org.el 940 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-wrap-region "org-table" (arg))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  166. (declare-function orgtbl-mode "org-table" (&optional arg))
  167. (declare-function org-export-get-backend "ox" (name))
  168. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  169. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  170. (defvar ffap-url-regexp)
  171. (defvar org-element-paragraph-separate)
  172. (defsubst org-uniquify (list)
  173. "Non-destructively remove duplicate elements from LIST."
  174. (let ((res (copy-sequence list))) (delete-dups res)))
  175. (defsubst org-get-at-bol (property)
  176. "Get text property PROPERTY at the beginning of line."
  177. (get-text-property (point-at-bol) property))
  178. (defsubst org-trim (s &optional keep-lead)
  179. "Remove whitespace at the beginning and the end of string S.
  180. When optional argument KEEP-LEAD is non-nil, removing blank lines
  181. at the beginning of the string does not affect leading indentation."
  182. (replace-regexp-in-string
  183. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  184. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  185. ;; load languages based on value of `org-babel-load-languages'
  186. (defvar org-babel-load-languages)
  187. ;;;###autoload
  188. (defun org-babel-do-load-languages (sym value)
  189. "Load the languages defined in `org-babel-load-languages'."
  190. (set-default sym value)
  191. (dolist (pair org-babel-load-languages)
  192. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  193. (if active
  194. (require (intern (concat "ob-" lang)))
  195. (funcall 'fmakunbound
  196. (intern (concat "org-babel-execute:" lang)))
  197. (funcall 'fmakunbound
  198. (intern (concat "org-babel-expand-body:" lang)))))))
  199. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  200. ;;;###autoload
  201. (defun org-babel-load-file (file &optional compile)
  202. "Load Emacs Lisp source code blocks in the Org FILE.
  203. This function exports the source code using `org-babel-tangle'
  204. and then loads the resulting file using `load-file'. With prefix
  205. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  206. file to byte-code before it is loaded."
  207. (interactive "fFile to load: \nP")
  208. (let* ((age (lambda (file)
  209. (float-time
  210. (time-subtract (current-time)
  211. (nth 5 (or (file-attributes (file-truename file))
  212. (file-attributes file)))))))
  213. (base-name (file-name-sans-extension file))
  214. (exported-file (concat base-name ".el")))
  215. ;; tangle if the Org file is newer than the elisp file
  216. (unless (and (file-exists-p exported-file)
  217. (> (funcall age file) (funcall age exported-file)))
  218. ;; Tangle-file traversal returns reversed list of tangled files
  219. ;; and we want to evaluate the first target.
  220. (setq exported-file
  221. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  222. (message "%s %s"
  223. (if compile
  224. (progn (byte-compile-file exported-file 'load)
  225. "Compiled and loaded")
  226. (progn (load-file exported-file) "Loaded"))
  227. exported-file)))
  228. (defcustom org-babel-load-languages '((emacs-lisp . t))
  229. "Languages which can be evaluated in Org buffers.
  230. This list can be used to load support for any of the languages
  231. below, note that each language will depend on a different set of
  232. system executables and/or Emacs modes. When a language is
  233. \"loaded\", then code blocks in that language can be evaluated
  234. with `org-babel-execute-src-block' bound by default to C-c
  235. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  236. be set to remove code block evaluation from the C-c C-c
  237. keybinding. By default only Emacs Lisp (which has no
  238. requirements) is loaded."
  239. :group 'org-babel
  240. :set 'org-babel-do-load-languages
  241. :version "24.1"
  242. :type '(alist :tag "Babel Languages"
  243. :key-type
  244. (choice
  245. (const :tag "Awk" awk)
  246. (const :tag "C" C)
  247. (const :tag "R" R)
  248. (const :tag "Asymptote" asymptote)
  249. (const :tag "Calc" calc)
  250. (const :tag "Clojure" clojure)
  251. (const :tag "CSS" css)
  252. (const :tag "Ditaa" ditaa)
  253. (const :tag "Dot" dot)
  254. (const :tag "Ebnf2ps" ebnf2ps)
  255. (const :tag "Emacs Lisp" emacs-lisp)
  256. (const :tag "Forth" forth)
  257. (const :tag "Fortran" fortran)
  258. (const :tag "Gnuplot" gnuplot)
  259. (const :tag "Haskell" haskell)
  260. (const :tag "hledger" hledger)
  261. (const :tag "IO" io)
  262. (const :tag "J" J)
  263. (const :tag "Java" java)
  264. (const :tag "Javascript" js)
  265. (const :tag "LaTeX" latex)
  266. (const :tag "Ledger" ledger)
  267. (const :tag "Lilypond" lilypond)
  268. (const :tag "Lisp" lisp)
  269. (const :tag "Makefile" makefile)
  270. (const :tag "Maxima" maxima)
  271. (const :tag "Matlab" matlab)
  272. (const :tag "Mscgen" mscgen)
  273. (const :tag "Ocaml" ocaml)
  274. (const :tag "Octave" octave)
  275. (const :tag "Org" org)
  276. (const :tag "Perl" perl)
  277. (const :tag "Pico Lisp" picolisp)
  278. (const :tag "PlantUML" plantuml)
  279. (const :tag "Python" python)
  280. (const :tag "Ruby" ruby)
  281. (const :tag "Sass" sass)
  282. (const :tag "Scala" scala)
  283. (const :tag "Scheme" scheme)
  284. (const :tag "Screen" screen)
  285. (const :tag "Shell Script" shell)
  286. (const :tag "Shen" shen)
  287. (const :tag "Sql" sql)
  288. (const :tag "Sqlite" sqlite)
  289. (const :tag "Stan" stan)
  290. (const :tag "Vala" vala))
  291. :value-type (boolean :tag "Activate" :value t)))
  292. ;;;; Customization variables
  293. (defcustom org-clone-delete-id nil
  294. "Remove ID property of clones of a subtree.
  295. When non-nil, clones of a subtree don't inherit the ID property.
  296. Otherwise they inherit the ID property with a new unique
  297. identifier."
  298. :type 'boolean
  299. :version "24.1"
  300. :group 'org-id)
  301. ;;; Version
  302. (org-check-version)
  303. ;;;###autoload
  304. (defun org-version (&optional here full message)
  305. "Show the Org version.
  306. Interactively, or when MESSAGE is non-nil, show it in echo area.
  307. With prefix argument, or when HERE is non-nil, insert it at point.
  308. In non-interactive uses, a reduced version string is output unless
  309. FULL is given."
  310. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  311. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  312. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  313. (load-suffixes (list ".el"))
  314. (org-install-dir
  315. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  316. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  317. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  318. (let* ((load-suffixes save-load-suffixes)
  319. (release (org-release))
  320. (git-version (org-git-version))
  321. (version (format "Org mode version %s (%s @ %s)"
  322. release
  323. git-version
  324. (if org-install-dir
  325. (if (string= org-dir org-install-dir)
  326. org-install-dir
  327. (concat "mixed installation! "
  328. org-install-dir
  329. " and "
  330. org-dir))
  331. "org-loaddefs.el can not be found!")))
  332. (version1 (if full version release)))
  333. (when here (insert version1))
  334. (when message (message "%s" version1))
  335. version1)))
  336. (defconst org-version (org-version))
  337. ;;; Syntax Constants
  338. ;;;; Block
  339. (defconst org-block-regexp
  340. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  341. "Regular expression for hiding blocks.")
  342. (defconst org-dblock-start-re
  343. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  344. "Matches the start line of a dynamic block, with parameters.")
  345. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  346. "Matches the end of a dynamic block.")
  347. ;;;; Clock and Planning
  348. (defconst org-clock-string "CLOCK:"
  349. "String used as prefix for timestamps clocking work hours on an item.")
  350. (defvar org-closed-string "CLOSED:"
  351. "String used as the prefix for timestamps logging closing a TODO entry.")
  352. (defvar org-deadline-string "DEADLINE:"
  353. "String to mark deadline entries.
  354. \\<org-mode-map>
  355. A deadline is this string, followed by a time stamp. It must be
  356. a word, terminated by a colon. You can insert a schedule keyword
  357. and a timestamp with `\\[org-deadline]'.")
  358. (defvar org-scheduled-string "SCHEDULED:"
  359. "String to mark scheduled TODO entries.
  360. \\<org-mode-map>
  361. A schedule is this string, followed by a time stamp. It must be
  362. a word, terminated by a colon. You can insert a schedule keyword
  363. and a timestamp with `\\[org-schedule]'.")
  364. (defconst org-ds-keyword-length
  365. (+ 2
  366. (apply #'max
  367. (mapcar #'length
  368. (list org-deadline-string org-scheduled-string
  369. org-clock-string org-closed-string))))
  370. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  371. (defconst org-planning-line-re
  372. (concat "^[ \t]*"
  373. (regexp-opt
  374. (list org-closed-string org-deadline-string org-scheduled-string)
  375. t))
  376. "Matches a line with planning info.
  377. Matched keyword is in group 1.")
  378. (defconst org-clock-line-re
  379. (concat "^[ \t]*" org-clock-string)
  380. "Matches a line with clock info.")
  381. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  382. "Matches the DEADLINE keyword.")
  383. (defconst org-deadline-time-regexp
  384. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  385. "Matches the DEADLINE keyword together with a time stamp.")
  386. (defconst org-deadline-time-hour-regexp
  387. (concat "\\<" org-deadline-string
  388. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  389. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  390. (defconst org-deadline-line-regexp
  391. (concat "\\<\\(" org-deadline-string "\\).*")
  392. "Matches the DEADLINE keyword and the rest of the line.")
  393. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  394. "Matches the SCHEDULED keyword.")
  395. (defconst org-scheduled-time-regexp
  396. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  397. "Matches the SCHEDULED keyword together with a time stamp.")
  398. (defconst org-scheduled-time-hour-regexp
  399. (concat "\\<" org-scheduled-string
  400. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  401. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  402. (defconst org-closed-time-regexp
  403. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  404. "Matches the CLOSED keyword together with a time stamp.")
  405. (defconst org-keyword-time-regexp
  406. (concat "\\<"
  407. (regexp-opt
  408. (list org-scheduled-string org-deadline-string org-closed-string
  409. org-clock-string)
  410. t)
  411. " *[[<]\\([^]>]+\\)[]>]")
  412. "Matches any of the 4 keywords, together with the time stamp.")
  413. (defconst org-keyword-time-not-clock-regexp
  414. (concat
  415. "\\<"
  416. (regexp-opt
  417. (list org-scheduled-string org-deadline-string org-closed-string) t)
  418. " *[[<]\\([^]>]+\\)[]>]")
  419. "Matches any of the 3 keywords, together with the time stamp.")
  420. (defconst org-maybe-keyword-time-regexp
  421. (concat "\\(\\<"
  422. (regexp-opt
  423. (list org-scheduled-string org-deadline-string org-closed-string
  424. org-clock-string)
  425. t)
  426. "\\)?"
  427. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  428. "\\|"
  429. "<%%([^\r\n>]*>\\)")
  430. "Matches a timestamp, possibly preceded by a keyword.")
  431. (defconst org-all-time-keywords
  432. (mapcar (lambda (w) (substring w 0 -1))
  433. (list org-scheduled-string org-deadline-string
  434. org-clock-string org-closed-string))
  435. "List of time keywords.")
  436. ;;;; Drawer
  437. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  438. "Matches first or last line of a hidden block.
  439. Group 1 contains drawer's name or \"END\".")
  440. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  441. "Regular expression matching the first line of a property drawer.")
  442. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  443. "Regular expression matching the last line of a property drawer.")
  444. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  445. "Regular expression matching the first line of a clock drawer.")
  446. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  447. "Regular expression matching the last line of a clock drawer.")
  448. (defconst org-property-drawer-re
  449. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  450. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  451. "[ \t]*:END:[ \t]*$")
  452. "Matches an entire property drawer.")
  453. (defconst org-clock-drawer-re
  454. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  455. org-clock-drawer-end-re "\\)\n?")
  456. "Matches an entire clock drawer.")
  457. ;;;; Headline
  458. (defconst org-heading-keyword-regexp-format
  459. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  460. "Printf format for a regexp matching a headline with some keyword.
  461. This regexp will match the headline of any node which has the
  462. exact keyword that is put into the format. The keyword isn't in
  463. any group by default, but the stars and the body are.")
  464. (defconst org-heading-keyword-maybe-regexp-format
  465. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  466. "Printf format for a regexp matching a headline, possibly with some keyword.
  467. This regexp can match any headline with the specified keyword, or
  468. without a keyword. The keyword isn't in any group by default,
  469. but the stars and the body are.")
  470. (defconst org-archive-tag "ARCHIVE"
  471. "The tag that marks a subtree as archived.
  472. An archived subtree does not open during visibility cycling, and does
  473. not contribute to the agenda listings.")
  474. (eval-and-compile
  475. (defconst org-comment-string "COMMENT"
  476. "Entries starting with this keyword will never be exported.
  477. \\<org-mode-map>
  478. An entry can be toggled between COMMENT and normal with
  479. `\\[org-toggle-comment]'."))
  480. ;;;; LaTeX Environments and Fragments
  481. (defconst org-latex-regexps
  482. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  483. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  484. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  485. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  486. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  487. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  488. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  489. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  490. "Regular expressions for matching embedded LaTeX.")
  491. ;;;; Node Property
  492. (defconst org-effort-property "Effort"
  493. "The property that is being used to keep track of effort estimates.
  494. Effort estimates given in this property need to have the format H:MM.")
  495. ;;;; Table
  496. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  497. "Detect an org-type or table-type table.")
  498. (defconst org-table-line-regexp "^[ \t]*|"
  499. "Detect an org-type table line.")
  500. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  501. "Detect an org-type table line.")
  502. (defconst org-table-hline-regexp "^[ \t]*|-"
  503. "Detect an org-type table hline.")
  504. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  505. "Detect a table-type table hline.")
  506. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  507. "Detect the first line outside a table when searching from within it.
  508. This works for both table types.")
  509. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  510. "Detect a #+TBLFM line.")
  511. ;;;; Timestamp
  512. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  513. "Regular expression for fast time stamp matching.")
  514. (defconst org-ts-regexp-inactive
  515. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  516. "Regular expression for fast inactive time stamp matching.")
  517. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  518. "Regular expression for fast time stamp matching.")
  519. (defconst org-ts-regexp0
  520. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  521. "Regular expression matching time strings for analysis.
  522. This one does not require the space after the date, so it can be used
  523. on a string that terminates immediately after the date.")
  524. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  525. "Regular expression matching time strings for analysis.")
  526. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  527. "Regular expression matching time stamps, with groups.")
  528. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  529. "Regular expression matching time stamps (also [..]), with groups.")
  530. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  531. "Regular expression matching a time stamp range.")
  532. (defconst org-tr-regexp-both
  533. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  534. "Regular expression matching a time stamp range.")
  535. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  536. org-ts-regexp "\\)?")
  537. "Regular expression matching a time stamp or time stamp range.")
  538. (defconst org-tsr-regexp-both
  539. (concat org-ts-regexp-both "\\(--?-?"
  540. org-ts-regexp-both "\\)?")
  541. "Regular expression matching a time stamp or time stamp range.
  542. The time stamps may be either active or inactive.")
  543. (defconst org-repeat-re
  544. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  545. "Regular expression for specifying repeated events.
  546. After a match, group 1 contains the repeat expression.")
  547. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  548. "Formats for `format-time-string' which are used for time stamps.")
  549. ;;; The custom variables
  550. (defgroup org nil
  551. "Outline-based notes management and organizer."
  552. :tag "Org"
  553. :group 'outlines
  554. :group 'calendar)
  555. (defcustom org-mode-hook nil
  556. "Mode hook for Org mode, run after the mode was turned on."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-load-hook nil
  560. "Hook that is run after org.el has been loaded."
  561. :group 'org
  562. :type 'hook)
  563. (defcustom org-log-buffer-setup-hook nil
  564. "Hook that is run after an Org log buffer is created."
  565. :group 'org
  566. :version "24.1"
  567. :type 'hook)
  568. (defvar org-modules) ; defined below
  569. (defvar org-modules-loaded nil
  570. "Have the modules been loaded already?")
  571. (defun org-load-modules-maybe (&optional force)
  572. "Load all extensions listed in `org-modules'."
  573. (when (or force (not org-modules-loaded))
  574. (dolist (ext org-modules)
  575. (condition-case nil (require ext)
  576. (error (message "Problems while trying to load feature `%s'" ext))))
  577. (setq org-modules-loaded t)))
  578. (defun org-set-modules (var value)
  579. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  580. (set var value)
  581. (when (featurep 'org)
  582. (org-load-modules-maybe 'force)
  583. (org-element-cache-reset 'all)))
  584. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  585. "Modules that should always be loaded together with org.el.
  586. If a description starts with <C>, the file is not part of Emacs
  587. and loading it will require that you have downloaded and properly
  588. installed the Org mode distribution.
  589. You can also use this system to load external packages (i.e. neither Org
  590. core modules, nor modules from the CONTRIB directory). Just add symbols
  591. to the end of the list. If the package is called org-xyz.el, then you need
  592. to add the symbol `xyz', and the package must have a call to:
  593. (provide \\='org-xyz)
  594. For export specific modules, see also `org-export-backends'."
  595. :group 'org
  596. :set 'org-set-modules
  597. :version "24.4"
  598. :package-version '(Org . "8.0")
  599. :type
  600. '(set :greedy t
  601. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  602. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  603. (const :tag " crypt: Encryption of subtrees" org-crypt)
  604. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  605. (const :tag " docview: Links to doc-view buffers" org-docview)
  606. (const :tag " eww: Store link to url of eww" org-eww)
  607. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  608. (const :tag " habit: Track your consistency with habits" org-habit)
  609. (const :tag " id: Global IDs for identifying entries" org-id)
  610. (const :tag " info: Links to Info nodes" org-info)
  611. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  612. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  613. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  614. (const :tag " mouse: Additional mouse support" org-mouse)
  615. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  616. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  617. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  618. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  619. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  620. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  621. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  622. (const :tag "C collector: Collect properties into tables" org-collector)
  623. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  624. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  625. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  626. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  627. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  628. (const :tag "C eval: Include command output as text" org-eval)
  629. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  630. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  631. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  632. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  633. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  634. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  635. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  636. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  637. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  638. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  639. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  640. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  641. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  642. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  643. (const :tag "C registry: A registry for Org links" org-registry)
  644. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  645. (const :tag "C secretary: Team management with Org" org-secretary)
  646. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  647. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  648. (const :tag "C track: Keep up with Org mode development" org-track)
  649. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  650. (const :tag "C vm: Links to VM folders/messages" org-vm)
  651. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  652. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  653. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  654. (defvar org-export-registered-backends) ; From ox.el.
  655. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  656. (declare-function org-export-backend-name "ox" (backend) t)
  657. (defcustom org-export-backends '(ascii html icalendar latex odt)
  658. "List of export back-ends that should be always available.
  659. If a description starts with <C>, the file is not part of Emacs
  660. and loading it will require that you have downloaded and properly
  661. installed the Org mode distribution.
  662. Unlike to `org-modules', libraries in this list will not be
  663. loaded along with Org, but only once the export framework is
  664. needed.
  665. This variable needs to be set before org.el is loaded. If you
  666. need to make a change while Emacs is running, use the customize
  667. interface or run the following code, where VAL stands for the new
  668. value of the variable, after updating it:
  669. (progn
  670. (setq org-export-registered-backends
  671. (cl-remove-if-not
  672. (lambda (backend)
  673. (let ((name (org-export-backend-name backend)))
  674. (or (memq name val)
  675. (catch \\='parentp
  676. (dolist (b val)
  677. (and (org-export-derived-backend-p b name)
  678. (throw \\='parentp t)))))))
  679. org-export-registered-backends))
  680. (let ((new-list (mapcar #\\='org-export-backend-name
  681. org-export-registered-backends)))
  682. (dolist (backend val)
  683. (cond
  684. ((not (load (format \"ox-%s\" backend) t t))
  685. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  686. backend))
  687. ((not (memq backend new-list)) (push backend new-list))))
  688. (set-default \\='org-export-backends new-list)))
  689. Adding a back-end to this list will also pull the back-end it
  690. depends on, if any."
  691. :group 'org
  692. :group 'org-export
  693. :version "26.1"
  694. :package-version '(Org . "9.0")
  695. :initialize 'custom-initialize-set
  696. :set (lambda (var val)
  697. (if (not (featurep 'ox)) (set-default var val)
  698. ;; Any back-end not required anymore (not present in VAL and not
  699. ;; a parent of any back-end in the new value) is removed from the
  700. ;; list of registered back-ends.
  701. (setq org-export-registered-backends
  702. (cl-remove-if-not
  703. (lambda (backend)
  704. (let ((name (org-export-backend-name backend)))
  705. (or (memq name val)
  706. (catch 'parentp
  707. (dolist (b val)
  708. (and (org-export-derived-backend-p b name)
  709. (throw 'parentp t)))))))
  710. org-export-registered-backends))
  711. ;; Now build NEW-LIST of both new back-ends and required
  712. ;; parents.
  713. (let ((new-list (mapcar #'org-export-backend-name
  714. org-export-registered-backends)))
  715. (dolist (backend val)
  716. (cond
  717. ((not (load (format "ox-%s" backend) t t))
  718. (message "Problems while trying to load export back-end `%s'"
  719. backend))
  720. ((not (memq backend new-list)) (push backend new-list))))
  721. ;; Set VAR to that list with fixed dependencies.
  722. (set-default var new-list))))
  723. :type '(set :greedy t
  724. (const :tag " ascii Export buffer to ASCII format" ascii)
  725. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  726. (const :tag " html Export buffer to HTML format" html)
  727. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  728. (const :tag " latex Export buffer to LaTeX format" latex)
  729. (const :tag " man Export buffer to MAN format" man)
  730. (const :tag " md Export buffer to Markdown format" md)
  731. (const :tag " odt Export buffer to ODT format" odt)
  732. (const :tag " org Export buffer to Org format" org)
  733. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  734. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  735. (const :tag "C deck Export buffer to deck.js presentations" deck)
  736. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  737. (const :tag "C groff Export buffer to Groff format" groff)
  738. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  739. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  740. (const :tag "C s5 Export buffer to s5 presentations" s5)
  741. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  742. (eval-after-load 'ox
  743. '(dolist (backend org-export-backends)
  744. (condition-case nil (require (intern (format "ox-%s" backend)))
  745. (error (message "Problems while trying to load export back-end `%s'"
  746. backend)))))
  747. (defcustom org-support-shift-select nil
  748. "Non-nil means make shift-cursor commands select text when possible.
  749. \\<org-mode-map>\
  750. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  751. start selecting a region, or enlarge regions started in this way.
  752. In Org mode, in special contexts, these same keys are used for
  753. other purposes, important enough to compete with shift selection.
  754. Org tries to balance these needs by supporting `shift-select-mode'
  755. outside these special contexts, under control of this variable.
  756. The default of this variable is nil, to avoid confusing behavior. Shifted
  757. cursor keys will then execute Org commands in the following contexts:
  758. - on a headline, changing TODO state (left/right) and priority (up/down)
  759. - on a time stamp, changing the time
  760. - in a plain list item, changing the bullet type
  761. - in a property definition line, switching between allowed values
  762. - in the BEGIN line of a clock table (changing the time block).
  763. Outside these contexts, the commands will throw an error.
  764. When this variable is t and the cursor is not in a special
  765. context, Org mode will support shift-selection for making and
  766. enlarging regions. To make this more effective, the bullet
  767. cycling will no longer happen anywhere in an item line, but only
  768. if the cursor is exactly on the bullet.
  769. If you set this variable to the symbol `always', then the keys
  770. will not be special in headlines, property lines, and item lines,
  771. to make shift selection work there as well. If this is what you
  772. want, you can use the following alternative commands:
  773. `\\[org-todo]' and `\\[org-priority]' \
  774. to change TODO state and priority,
  775. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  776. can be used to switch TODO sets,
  777. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  778. and properties can be edited by hand or in column view.
  779. However, when the cursor is on a timestamp, shift-cursor commands
  780. will still edit the time stamp - this is just too good to give up."
  781. :group 'org
  782. :type '(choice
  783. (const :tag "Never" nil)
  784. (const :tag "When outside special context" t)
  785. (const :tag "Everywhere except timestamps" always)))
  786. (defcustom org-loop-over-headlines-in-active-region nil
  787. "Shall some commands act upon headlines in the active region?
  788. When set to t, some commands will be performed in all headlines
  789. within the active region.
  790. When set to `start-level', some commands will be performed in all
  791. headlines within the active region, provided that these headlines
  792. are of the same level than the first one.
  793. When set to a string, those commands will be performed on the
  794. matching headlines within the active region. Such string must be
  795. a tags/property/todo match as it is used in the agenda tags view.
  796. The list of commands is: `org-schedule', `org-deadline',
  797. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  798. `org-archive-to-archive-sibling'. The archiving commands skip
  799. already archived entries."
  800. :type '(choice (const :tag "Don't loop" nil)
  801. (const :tag "All headlines in active region" t)
  802. (const :tag "In active region, headlines at the same level than the first one" start-level)
  803. (string :tag "Tags/Property/Todo matcher"))
  804. :version "24.1"
  805. :group 'org-todo
  806. :group 'org-archive)
  807. (defgroup org-startup nil
  808. "Options concerning startup of Org mode."
  809. :tag "Org Startup"
  810. :group 'org)
  811. (defcustom org-startup-folded t
  812. "Non-nil means entering Org mode will switch to OVERVIEW.
  813. This can also be configured on a per-file basis by adding one of
  814. the following lines anywhere in the buffer:
  815. #+STARTUP: fold (or `overview', this is equivalent)
  816. #+STARTUP: nofold (or `showall', this is equivalent)
  817. #+STARTUP: content
  818. #+STARTUP: showeverything
  819. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  820. to ignore this option when Org opens agenda files for the first
  821. time."
  822. :group 'org-startup
  823. :type '(choice
  824. (const :tag "nofold: show all" nil)
  825. (const :tag "fold: overview" t)
  826. (const :tag "content: all headlines" content)
  827. (const :tag "show everything, even drawers" showeverything)))
  828. (defcustom org-startup-truncated t
  829. "Non-nil means entering Org mode will set `truncate-lines'.
  830. This is useful since some lines containing links can be very long and
  831. uninteresting. Also tables look terrible when wrapped.
  832. The variable `org-startup-truncated' allows to configure
  833. truncation for Org mode different to the other modes that use the
  834. variable `truncate-lines' and as a shortcut instead of putting
  835. the variable `truncate-lines' into the `org-mode-hook'. If one
  836. wants to configure truncation for Org mode not statically but
  837. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  838. the variable `truncate-lines' has to be used because in such a
  839. case it is too late to set the variable `org-startup-truncated'."
  840. :group 'org-startup
  841. :type 'boolean)
  842. (defcustom org-startup-indented nil
  843. "Non-nil means turn on `org-indent-mode' on startup.
  844. This can also be configured on a per-file basis by adding one of
  845. the following lines anywhere in the buffer:
  846. #+STARTUP: indent
  847. #+STARTUP: noindent"
  848. :group 'org-structure
  849. :type '(choice
  850. (const :tag "Not" nil)
  851. (const :tag "Globally (slow on startup in large files)" t)))
  852. (defcustom org-use-sub-superscripts t
  853. "Non-nil means interpret \"_\" and \"^\" for display.
  854. If you want to control how Org exports those characters, see
  855. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  856. used to be an alias for `org-export-with-sub-superscripts' in
  857. Org <8.0, it is not anymore.
  858. When this option is turned on, you can use TeX-like syntax for
  859. sub- and superscripts within the buffer. Several characters after
  860. \"_\" or \"^\" will be considered as a single item - so grouping
  861. with {} is normally not needed. For example, the following things
  862. will be parsed as single sub- or superscripts:
  863. 10^24 or 10^tau several digits will be considered 1 item.
  864. 10^-12 or 10^-tau a leading sign with digits or a word
  865. x^2-y^3 will be read as x^2 - y^3, because items are
  866. terminated by almost any nonword/nondigit char.
  867. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  868. Still, ambiguity is possible. So when in doubt, use {} to enclose
  869. the sub/superscript. If you set this variable to the symbol `{}',
  870. the braces are *required* in order to trigger interpretations as
  871. sub/superscript. This can be helpful in documents that need \"_\"
  872. frequently in plain text."
  873. :group 'org-startup
  874. :version "24.4"
  875. :package-version '(Org . "8.0")
  876. :type '(choice
  877. (const :tag "Always interpret" t)
  878. (const :tag "Only with braces" {})
  879. (const :tag "Never interpret" nil)))
  880. (defcustom org-startup-with-beamer-mode nil
  881. "Non-nil means turn on `org-beamer-mode' on startup.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: beamer"
  885. :group 'org-startup
  886. :version "24.1"
  887. :type 'boolean)
  888. (defcustom org-startup-align-all-tables nil
  889. "Non-nil means align all tables when visiting a file.
  890. This is useful when the column width in tables is forced with <N> cookies
  891. in table fields. Such tables will look correct only after the first re-align.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: align
  895. #+STARTUP: noalign"
  896. :group 'org-startup
  897. :type 'boolean)
  898. (defcustom org-startup-with-inline-images nil
  899. "Non-nil means show inline images when loading a new Org file.
  900. This can also be configured on a per-file basis by adding one of
  901. the following lines anywhere in the buffer:
  902. #+STARTUP: inlineimages
  903. #+STARTUP: noinlineimages"
  904. :group 'org-startup
  905. :version "24.1"
  906. :type 'boolean)
  907. (defcustom org-startup-with-latex-preview nil
  908. "Non-nil means preview LaTeX fragments when loading a new Org file.
  909. This can also be configured on a per-file basis by adding one of
  910. the following lines anywhere in the buffer:
  911. #+STARTUP: latexpreview
  912. #+STARTUP: nolatexpreview"
  913. :group 'org-startup
  914. :version "24.4"
  915. :package-version '(Org . "8.0")
  916. :type 'boolean)
  917. (defcustom org-insert-mode-line-in-empty-file nil
  918. "Non-nil means insert the first line setting Org mode in empty files.
  919. When the function `org-mode' is called interactively in an empty file, this
  920. normally means that the file name does not automatically trigger Org mode.
  921. To ensure that the file will always be in Org mode in the future, a
  922. line enforcing Org mode will be inserted into the buffer, if this option
  923. has been set."
  924. :group 'org-startup
  925. :type 'boolean)
  926. (defcustom org-replace-disputed-keys nil
  927. "Non-nil means use alternative key bindings for some keys.
  928. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  929. These keys are also used by other packages like shift-selection-mode'
  930. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  931. If you want to use Org mode together with one of these other modes,
  932. or more generally if you would like to move some Org mode commands to
  933. other keys, set this variable and configure the keys with the variable
  934. `org-disputed-keys'.
  935. This option is only relevant at load-time of Org mode, and must be set
  936. *before* org.el is loaded. Changing it requires a restart of Emacs to
  937. become effective."
  938. :group 'org-startup
  939. :type 'boolean)
  940. (defcustom org-use-extra-keys nil
  941. "Non-nil means use extra key sequence definitions for certain commands.
  942. This happens automatically if `window-system' is nil. This
  943. variable lets you do the same manually. You must set it before
  944. loading Org."
  945. :group 'org-startup
  946. :type 'boolean)
  947. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  948. (defcustom org-disputed-keys
  949. '(([(shift up)] . [(meta p)])
  950. ([(shift down)] . [(meta n)])
  951. ([(shift left)] . [(meta -)])
  952. ([(shift right)] . [(meta +)])
  953. ([(control shift right)] . [(meta shift +)])
  954. ([(control shift left)] . [(meta shift -)]))
  955. "Keys for which Org mode and other modes compete.
  956. This is an alist, cars are the default keys, second element specifies
  957. the alternative to use when `org-replace-disputed-keys' is t.
  958. Keys can be specified in any syntax supported by `define-key'.
  959. The value of this option takes effect only at Org mode startup,
  960. therefore you'll have to restart Emacs to apply it after changing."
  961. :group 'org-startup
  962. :type 'alist)
  963. (defun org-key (key)
  964. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  965. Or return the original if not disputed."
  966. (when org-replace-disputed-keys
  967. (let* ((nkey (key-description key))
  968. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  969. org-disputed-keys)))
  970. (setq key (if x (cdr x) key))))
  971. key)
  972. (defun org-defkey (keymap key def)
  973. "Define a key, possibly translated, as returned by `org-key'."
  974. (define-key keymap (org-key key) def))
  975. (defcustom org-ellipsis nil
  976. "The ellipsis to use in the Org mode outline.
  977. When nil, just use the standard three dots. When a non-empty string,
  978. use that string instead.
  979. The change affects only Org mode (which will then use its own display table).
  980. Changing this requires executing `\\[org-mode]' in a buffer to become
  981. effective."
  982. :group 'org-startup
  983. :type '(choice (const :tag "Default" nil)
  984. (string :tag "String" :value "...#"))
  985. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  986. (defvar org-display-table nil
  987. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  988. (defgroup org-keywords nil
  989. "Keywords in Org mode."
  990. :tag "Org Keywords"
  991. :group 'org)
  992. (defcustom org-closed-keep-when-no-todo nil
  993. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  994. :group 'org-todo
  995. :group 'org-keywords
  996. :version "24.4"
  997. :package-version '(Org . "8.0")
  998. :type 'boolean)
  999. (defgroup org-structure nil
  1000. "Options concerning the general structure of Org files."
  1001. :tag "Org Structure"
  1002. :group 'org)
  1003. (defgroup org-reveal-location nil
  1004. "Options about how to make context of a location visible."
  1005. :tag "Org Reveal Location"
  1006. :group 'org-structure)
  1007. (defcustom org-show-context-detail '((agenda . local)
  1008. (bookmark-jump . lineage)
  1009. (isearch . lineage)
  1010. (default . ancestors))
  1011. "Alist between context and visibility span when revealing a location.
  1012. \\<org-mode-map>Some actions may move point into invisible
  1013. locations. As a consequence, Org always expose a neighborhood
  1014. around point. How much is shown depends on the initial action,
  1015. or context. Valid contexts are
  1016. agenda when exposing an entry from the agenda
  1017. org-goto when using the command `org-goto' (`\\[org-goto]')
  1018. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1019. tags-tree when constructing a sparse tree based on tags matches
  1020. link-search when exposing search matches associated with a link
  1021. mark-goto when exposing the jump goal of a mark
  1022. bookmark-jump when exposing a bookmark location
  1023. isearch when exiting from an incremental search
  1024. default default for all contexts not set explicitly
  1025. Allowed visibility spans are
  1026. minimal show current headline; if point is not on headline,
  1027. also show entry
  1028. local show current headline, entry and next headline
  1029. ancestors show current headline and its direct ancestors; if
  1030. point is not on headline, also show entry
  1031. lineage show current headline, its direct ancestors and all
  1032. their children; if point is not on headline, also show
  1033. entry and first child
  1034. tree show current headline, its direct ancestors and all
  1035. their children; if point is not on headline, also show
  1036. entry and all children
  1037. canonical show current headline, its direct ancestors along with
  1038. their entries and children; if point is not located on
  1039. the headline, also show current entry and all children
  1040. As special cases, a nil or t value means show all contexts in
  1041. `minimal' or `canonical' view, respectively.
  1042. Some views can make displayed information very compact, but also
  1043. make it harder to edit the location of the match. In such
  1044. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1045. more context."
  1046. :group 'org-reveal-location
  1047. :version "26.1"
  1048. :package-version '(Org . "9.0")
  1049. :type '(choice
  1050. (const :tag "Canonical" t)
  1051. (const :tag "Minimal" nil)
  1052. (repeat :greedy t :tag "Individual contexts"
  1053. (cons
  1054. (choice :tag "Context"
  1055. (const agenda)
  1056. (const org-goto)
  1057. (const occur-tree)
  1058. (const tags-tree)
  1059. (const link-search)
  1060. (const mark-goto)
  1061. (const bookmark-jump)
  1062. (const isearch)
  1063. (const default))
  1064. (choice :tag "Detail level"
  1065. (const minimal)
  1066. (const local)
  1067. (const ancestors)
  1068. (const lineage)
  1069. (const tree)
  1070. (const canonical))))))
  1071. (defcustom org-indirect-buffer-display 'other-window
  1072. "How should indirect tree buffers be displayed?
  1073. This applies to indirect buffers created with the commands
  1074. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1075. Valid values are:
  1076. current-window Display in the current window
  1077. other-window Just display in another window.
  1078. dedicated-frame Create one new frame, and re-use it each time.
  1079. new-frame Make a new frame each time. Note that in this case
  1080. previously-made indirect buffers are kept, and you need to
  1081. kill these buffers yourself."
  1082. :group 'org-structure
  1083. :group 'org-agenda-windows
  1084. :type '(choice
  1085. (const :tag "In current window" current-window)
  1086. (const :tag "In current frame, other window" other-window)
  1087. (const :tag "Each time a new frame" new-frame)
  1088. (const :tag "One dedicated frame" dedicated-frame)))
  1089. (defcustom org-use-speed-commands nil
  1090. "Non-nil means activate single letter commands at beginning of a headline.
  1091. This may also be a function to test for appropriate locations where speed
  1092. commands should be active.
  1093. For example, to activate speed commands when the point is on any
  1094. star at the beginning of the headline, you can do this:
  1095. (setq org-use-speed-commands
  1096. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1097. :group 'org-structure
  1098. :type '(choice
  1099. (const :tag "Never" nil)
  1100. (const :tag "At beginning of headline stars" t)
  1101. (function)))
  1102. (defcustom org-speed-commands-user nil
  1103. "Alist of additional speed commands.
  1104. This list will be checked before `org-speed-commands-default'
  1105. when the variable `org-use-speed-commands' is non-nil
  1106. and when the cursor is at the beginning of a headline.
  1107. The car of each entry is a string with a single letter, which must
  1108. be assigned to `self-insert-command' in the global map.
  1109. The cdr is either a command to be called interactively, a function
  1110. to be called, or a form to be evaluated.
  1111. An entry that is just a list with a single string will be interpreted
  1112. as a descriptive headline that will be added when listing the speed
  1113. commands in the Help buffer using the `?' speed command."
  1114. :group 'org-structure
  1115. :type '(repeat :value ("k" . ignore)
  1116. (choice :value ("k" . ignore)
  1117. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1118. (cons :tag "Letter and Command"
  1119. (string :tag "Command letter")
  1120. (choice
  1121. (function)
  1122. (sexp))))))
  1123. (defcustom org-bookmark-names-plist
  1124. '(:last-capture "org-capture-last-stored"
  1125. :last-refile "org-refile-last-stored"
  1126. :last-capture-marker "org-capture-last-stored-marker")
  1127. "Names for bookmarks automatically set by some Org commands.
  1128. This can provide strings as names for a number of bookmarks Org sets
  1129. automatically. The following keys are currently implemented:
  1130. :last-capture
  1131. :last-capture-marker
  1132. :last-refile
  1133. When a key does not show up in the property list, the corresponding bookmark
  1134. is not set."
  1135. :group 'org-structure
  1136. :type 'plist)
  1137. (defgroup org-cycle nil
  1138. "Options concerning visibility cycling in Org mode."
  1139. :tag "Org Cycle"
  1140. :group 'org-structure)
  1141. (defcustom org-cycle-skip-children-state-if-no-children t
  1142. "Non-nil means skip CHILDREN state in entries that don't have any."
  1143. :group 'org-cycle
  1144. :type 'boolean)
  1145. (defcustom org-cycle-max-level nil
  1146. "Maximum level which should still be subject to visibility cycling.
  1147. Levels higher than this will, for cycling, be treated as text, not a headline.
  1148. When `org-odd-levels-only' is set, a value of N in this variable actually
  1149. means 2N-1 stars as the limiting headline.
  1150. When nil, cycle all levels.
  1151. Note that the limiting level of cycling is also influenced by
  1152. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1153. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1154. than its value."
  1155. :group 'org-cycle
  1156. :type '(choice
  1157. (const :tag "No limit" nil)
  1158. (integer :tag "Maximum level")))
  1159. (defcustom org-hide-block-startup nil
  1160. "Non-nil means entering Org mode will fold all blocks.
  1161. This can also be set in on a per-file basis with
  1162. #+STARTUP: hideblocks
  1163. #+STARTUP: showblocks"
  1164. :group 'org-startup
  1165. :group 'org-cycle
  1166. :type 'boolean)
  1167. (defcustom org-cycle-global-at-bob nil
  1168. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1169. This makes it possible to do global cycling without having to use `S-TAB'
  1170. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1171. line of the buffer
  1172. must not be a headline -- it may be empty or some other text.
  1173. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1174. sure the cursor stays at the beginning of the buffer.
  1175. When this option is nil, don't do anything special at the beginning of
  1176. the buffer."
  1177. :group 'org-cycle
  1178. :type 'boolean)
  1179. (defcustom org-cycle-level-after-item/entry-creation t
  1180. "Non-nil means cycle entry level or item indentation in new empty entries.
  1181. When the cursor is at the end of an empty headline, i.e., with only stars
  1182. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1183. and then all possible ancestor states, before returning to the original state.
  1184. This makes data entry extremely fast: M-RET to create a new headline,
  1185. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1186. When the cursor is at the end of an empty plain list item, one TAB will
  1187. make it a subitem, two or more tabs will back up to make this an item
  1188. higher up in the item hierarchy."
  1189. :group 'org-cycle
  1190. :type 'boolean)
  1191. (defcustom org-cycle-emulate-tab t
  1192. "Where should `org-cycle' emulate TAB.
  1193. nil Never
  1194. white Only in completely white lines
  1195. whitestart Only at the beginning of lines, before the first non-white char
  1196. t Everywhere except in headlines
  1197. exc-hl-bol Everywhere except at the start of a headline
  1198. If TAB is used in a place where it does not emulate TAB, the current subtree
  1199. visibility is cycled."
  1200. :group 'org-cycle
  1201. :type '(choice (const :tag "Never" nil)
  1202. (const :tag "Only in completely white lines" white)
  1203. (const :tag "Before first char in a line" whitestart)
  1204. (const :tag "Everywhere except in headlines" t)
  1205. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1206. (defcustom org-cycle-separator-lines 2
  1207. "Number of empty lines needed to keep an empty line between collapsed trees.
  1208. If you leave an empty line between the end of a subtree and the following
  1209. headline, this empty line is hidden when the subtree is folded.
  1210. Org mode will leave (exactly) one empty line visible if the number of
  1211. empty lines is equal or larger to the number given in this variable.
  1212. So the default 2 means at least 2 empty lines after the end of a subtree
  1213. are needed to produce free space between a collapsed subtree and the
  1214. following headline.
  1215. If the number is negative, and the number of empty lines is at least -N,
  1216. all empty lines are shown.
  1217. Special case: when 0, never leave empty lines in collapsed view."
  1218. :group 'org-cycle
  1219. :type 'integer)
  1220. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1221. (defcustom org-pre-cycle-hook nil
  1222. "Hook that is run before visibility cycling is happening.
  1223. The function(s) in this hook must accept a single argument which indicates
  1224. the new state that will be set right after running this hook. The
  1225. argument is a symbol. Before a global state change, it can have the values
  1226. `overview', `content', or `all'. Before a local state change, it can have
  1227. the values `folded', `children', or `subtree'."
  1228. :group 'org-cycle
  1229. :type 'hook)
  1230. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1231. org-cycle-hide-drawers
  1232. org-cycle-show-empty-lines
  1233. org-optimize-window-after-visibility-change)
  1234. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1235. The function(s) in this hook must accept a single argument which indicates
  1236. the new state that was set by the most recent `org-cycle' command. The
  1237. argument is a symbol. After a global state change, it can have the values
  1238. `overview', `contents', or `all'. After a local state change, it can have
  1239. the values `folded', `children', or `subtree'."
  1240. :group 'org-cycle
  1241. :type 'hook
  1242. :version "26.1"
  1243. :package-version '(Org . "8.3"))
  1244. (defgroup org-edit-structure nil
  1245. "Options concerning structure editing in Org mode."
  1246. :tag "Org Edit Structure"
  1247. :group 'org-structure)
  1248. (defcustom org-odd-levels-only nil
  1249. "Non-nil means skip even levels and only use odd levels for the outline.
  1250. This has the effect that two stars are being added/taken away in
  1251. promotion/demotion commands. It also influences how levels are
  1252. handled by the exporters.
  1253. Changing it requires restart of `font-lock-mode' to become effective
  1254. for fontification also in regions already fontified.
  1255. You may also set this on a per-file basis by adding one of the following
  1256. lines to the buffer:
  1257. #+STARTUP: odd
  1258. #+STARTUP: oddeven"
  1259. :group 'org-edit-structure
  1260. :group 'org-appearance
  1261. :type 'boolean)
  1262. (defcustom org-adapt-indentation t
  1263. "Non-nil means adapt indentation to outline node level.
  1264. When this variable is set, Org assumes that you write outlines by
  1265. indenting text in each node to align with the headline (after the
  1266. stars). The following issues are influenced by this variable:
  1267. - The indentation is increased by one space in a demotion
  1268. command, and decreased by one in a promotion command. However,
  1269. in the latter case, if shifting some line in the entry body
  1270. would alter document structure (e.g., insert a new headline),
  1271. indentation is not changed at all.
  1272. - Property drawers and planning information is inserted indented
  1273. when this variable is set. When nil, they will not be indented.
  1274. - TAB indents a line relative to current level. The lines below
  1275. a headline will be indented when this variable is set.
  1276. Note that this is all about true indentation, by adding and
  1277. removing space characters. See also `org-indent.el' which does
  1278. level-dependent indentation in a virtual way, i.e. at display
  1279. time in Emacs."
  1280. :group 'org-edit-structure
  1281. :type 'boolean)
  1282. (defcustom org-special-ctrl-a/e nil
  1283. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1284. When t, `C-a' will bring back the cursor to the beginning of the
  1285. headline text, i.e. after the stars and after a possible TODO
  1286. keyword. In an item, this will be the position after bullet and
  1287. check-box, if any. When the cursor is already at that position,
  1288. another `C-a' will bring it to the beginning of the line.
  1289. `C-e' will jump to the end of the headline, ignoring the presence
  1290. of tags in the headline. A second `C-e' will then jump to the
  1291. true end of the line, after any tags. This also means that, when
  1292. this variable is non-nil, `C-e' also will never jump beyond the
  1293. end of the heading of a folded section, i.e. not after the
  1294. ellipses.
  1295. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1296. normally, going to the true line boundary first. Only a directly
  1297. following, identical keypress will bring the cursor to the
  1298. special positions.
  1299. This may also be a cons cell where the behavior for `C-a' and
  1300. `C-e' is set separately."
  1301. :group 'org-edit-structure
  1302. :type '(choice
  1303. (const :tag "off" nil)
  1304. (const :tag "on: after stars/bullet and before tags first" t)
  1305. (const :tag "reversed: true line boundary first" reversed)
  1306. (cons :tag "Set C-a and C-e separately"
  1307. (choice :tag "Special C-a"
  1308. (const :tag "off" nil)
  1309. (const :tag "on: after stars/bullet first" t)
  1310. (const :tag "reversed: before stars/bullet first" reversed))
  1311. (choice :tag "Special C-e"
  1312. (const :tag "off" nil)
  1313. (const :tag "on: before tags first" t)
  1314. (const :tag "reversed: after tags first" reversed)))))
  1315. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1316. (defcustom org-special-ctrl-k nil
  1317. "Non-nil means `C-k' will behave specially in headlines.
  1318. When nil, `C-k' will call the default `kill-line' command.
  1319. When t, the following will happen while the cursor is in the headline:
  1320. - When the cursor is at the beginning of a headline, kill the entire
  1321. line and possible the folded subtree below the line.
  1322. - When in the middle of the headline text, kill the headline up to the tags.
  1323. - When after the headline text, kill the tags."
  1324. :group 'org-edit-structure
  1325. :type 'boolean)
  1326. (defcustom org-ctrl-k-protect-subtree nil
  1327. "Non-nil means, do not delete a hidden subtree with C-k.
  1328. When set to the symbol `error', simply throw an error when C-k is
  1329. used to kill (part-of) a headline that has hidden text behind it.
  1330. Any other non-nil value will result in a query to the user, if it is
  1331. OK to kill that hidden subtree. When nil, kill without remorse."
  1332. :group 'org-edit-structure
  1333. :version "24.1"
  1334. :type '(choice
  1335. (const :tag "Do not protect hidden subtrees" nil)
  1336. (const :tag "Protect hidden subtrees with a security query" t)
  1337. (const :tag "Never kill a hidden subtree with C-k" error)))
  1338. (defcustom org-special-ctrl-o t
  1339. "Non-nil means, make `C-o' insert a row in tables."
  1340. :group 'org-edit-structure
  1341. :type 'boolean)
  1342. (defcustom org-catch-invisible-edits nil
  1343. "Check if in invisible region before inserting or deleting a character.
  1344. Valid values are:
  1345. nil Do not check, so just do invisible edits.
  1346. error Throw an error and do nothing.
  1347. show Make point visible, and do the requested edit.
  1348. show-and-error Make point visible, then throw an error and abort the edit.
  1349. smart Make point visible, and do insertion/deletion if it is
  1350. adjacent to visible text and the change feels predictable.
  1351. Never delete a previously invisible character or add in the
  1352. middle or right after an invisible region. Basically, this
  1353. allows insertion and backward-delete right before ellipses.
  1354. FIXME: maybe in this case we should not even show?"
  1355. :group 'org-edit-structure
  1356. :version "24.1"
  1357. :type '(choice
  1358. (const :tag "Do not check" nil)
  1359. (const :tag "Throw error when trying to edit" error)
  1360. (const :tag "Unhide, but do not do the edit" show-and-error)
  1361. (const :tag "Show invisible part and do the edit" show)
  1362. (const :tag "Be smart and do the right thing" smart)))
  1363. (defcustom org-yank-folded-subtrees t
  1364. "Non-nil means when yanking subtrees, fold them.
  1365. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1366. it starts with a heading and all other headings in it are either children
  1367. or siblings, then fold all the subtrees. However, do this only if no
  1368. text after the yank would be swallowed into a folded tree by this action."
  1369. :group 'org-edit-structure
  1370. :type 'boolean)
  1371. (defcustom org-yank-adjusted-subtrees nil
  1372. "Non-nil means when yanking subtrees, adjust the level.
  1373. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1374. this function for details."
  1375. :group 'org-edit-structure
  1376. :type 'boolean)
  1377. (defcustom org-M-RET-may-split-line '((default . t))
  1378. "Non-nil means M-RET will split the line at the cursor position.
  1379. When nil, it will go to the end of the line before making a
  1380. new line.
  1381. You may also set this option in a different way for different
  1382. contexts. Valid contexts are:
  1383. headline when creating a new headline
  1384. item when creating a new item
  1385. table in a table field
  1386. default the value to be used for all contexts not explicitly
  1387. customized"
  1388. :group 'org-structure
  1389. :group 'org-table
  1390. :type '(choice
  1391. (const :tag "Always" t)
  1392. (const :tag "Never" nil)
  1393. (repeat :greedy t :tag "Individual contexts"
  1394. (cons
  1395. (choice :tag "Context"
  1396. (const headline)
  1397. (const item)
  1398. (const table)
  1399. (const default))
  1400. (boolean)))))
  1401. (defcustom org-insert-heading-respect-content nil
  1402. "Non-nil means insert new headings after the current subtree.
  1403. \\<org-mode-map>
  1404. When nil, the new heading is created directly after the current line.
  1405. The commands `\\[org-insert-heading-respect-content]' and \
  1406. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1407. for the duration of the command."
  1408. :group 'org-structure
  1409. :type 'boolean)
  1410. (defcustom org-blank-before-new-entry '((heading . auto)
  1411. (plain-list-item . auto))
  1412. "Should `org-insert-heading' leave a blank line before new heading/item?
  1413. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1414. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1415. which case Org will look at the surrounding headings/items and try to
  1416. make an intelligent decision whether to insert a blank line or not."
  1417. :group 'org-edit-structure
  1418. :type '(list
  1419. (cons (const heading)
  1420. (choice (const :tag "Never" nil)
  1421. (const :tag "Always" t)
  1422. (const :tag "Auto" auto)))
  1423. (cons (const plain-list-item)
  1424. (choice (const :tag "Never" nil)
  1425. (const :tag "Always" t)
  1426. (const :tag "Auto" auto)))))
  1427. (defcustom org-insert-heading-hook nil
  1428. "Hook being run after inserting a new heading."
  1429. :group 'org-edit-structure
  1430. :type 'hook)
  1431. (defcustom org-enable-fixed-width-editor t
  1432. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1433. This currently only means they are never auto-wrapped.
  1434. When nil, such lines will be treated like ordinary lines."
  1435. :group 'org-edit-structure
  1436. :type 'boolean)
  1437. (defcustom org-goto-auto-isearch t
  1438. "Non-nil means typing characters in `org-goto' starts incremental search.
  1439. When nil, you can use these keybindings to navigate the buffer:
  1440. q Quit the org-goto interface
  1441. n Go to the next visible heading
  1442. p Go to the previous visible heading
  1443. f Go one heading forward on same level
  1444. b Go one heading backward on same level
  1445. u Go one heading up"
  1446. :group 'org-edit-structure
  1447. :type 'boolean)
  1448. (defgroup org-sparse-trees nil
  1449. "Options concerning sparse trees in Org mode."
  1450. :tag "Org Sparse Trees"
  1451. :group 'org-structure)
  1452. (defcustom org-highlight-sparse-tree-matches t
  1453. "Non-nil means highlight all matches that define a sparse tree.
  1454. The highlights will automatically disappear the next time the buffer is
  1455. changed by an edit command."
  1456. :group 'org-sparse-trees
  1457. :type 'boolean)
  1458. (defcustom org-remove-highlights-with-change t
  1459. "Non-nil means any change to the buffer will remove temporary highlights.
  1460. \\<org-mode-map>\
  1461. Such highlights are created by `org-occur' and `org-clock-display'.
  1462. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1463. to get rid of the highlights.
  1464. The highlights created by `org-toggle-latex-fragment' always need
  1465. `\\[org-toggle-latex-fragment]' to be removed."
  1466. :group 'org-sparse-trees
  1467. :group 'org-time
  1468. :type 'boolean)
  1469. (defcustom org-occur-case-fold-search t
  1470. "Non-nil means `org-occur' should be case-insensitive.
  1471. If set to `smart' the search will be case-insensitive only if it
  1472. doesn't specify any upper case character."
  1473. :group 'org-sparse-trees
  1474. :version "26.1"
  1475. :type '(choice
  1476. (const :tag "Case-sensitive" nil)
  1477. (const :tag "Case-insensitive" t)
  1478. (const :tag "Case-insensitive for lower case searches only" smart)))
  1479. (defcustom org-occur-hook '(org-first-headline-recenter)
  1480. "Hook that is run after `org-occur' has constructed a sparse tree.
  1481. This can be used to recenter the window to show as much of the structure
  1482. as possible."
  1483. :group 'org-sparse-trees
  1484. :type 'hook)
  1485. (defgroup org-imenu-and-speedbar nil
  1486. "Options concerning imenu and speedbar in Org mode."
  1487. :tag "Org Imenu and Speedbar"
  1488. :group 'org-structure)
  1489. (defcustom org-imenu-depth 2
  1490. "The maximum level for Imenu access to Org headlines.
  1491. This also applied for speedbar access."
  1492. :group 'org-imenu-and-speedbar
  1493. :type 'integer)
  1494. (defgroup org-table nil
  1495. "Options concerning tables in Org mode."
  1496. :tag "Org Table"
  1497. :group 'org)
  1498. (defcustom org-self-insert-cluster-for-undo nil
  1499. "Non-nil means cluster self-insert commands for undo when possible.
  1500. If this is set, then, like in the Emacs command loop, 20 consecutive
  1501. characters will be undone together.
  1502. This is configurable, because there is some impact on typing performance."
  1503. :group 'org-table
  1504. :type 'boolean)
  1505. (defcustom org-table-tab-recognizes-table.el t
  1506. "Non-nil means TAB will automatically notice a table.el table.
  1507. When it sees such a table, it moves point into it and - if necessary -
  1508. calls `table-recognize-table'."
  1509. :group 'org-table-editing
  1510. :type 'boolean)
  1511. (defgroup org-link nil
  1512. "Options concerning links in Org mode."
  1513. :tag "Org Link"
  1514. :group 'org)
  1515. (defvar-local org-link-abbrev-alist-local nil
  1516. "Buffer-local version of `org-link-abbrev-alist', which see.
  1517. The value of this is taken from the #+LINK lines.")
  1518. (defcustom org-link-parameters
  1519. '(("doi" :follow org--open-doi-link)
  1520. ("elisp" :follow org--open-elisp-link)
  1521. ("file" :complete org-file-complete-link)
  1522. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1523. ("help" :follow org--open-help-link)
  1524. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1525. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1526. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1527. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1528. ("shell" :follow org--open-shell-link))
  1529. "An alist of properties that defines all the links in Org mode.
  1530. The key in each association is a string of the link type.
  1531. Subsequent optional elements make up a p-list of link properties.
  1532. :follow - A function that takes the link path as an argument.
  1533. :export - A function that takes the link path, description and
  1534. export-backend as arguments.
  1535. :store - A function responsible for storing the link. See the
  1536. function `org-store-link-functions'.
  1537. :complete - A function that inserts a link with completion. The
  1538. function takes one optional prefix arg.
  1539. :face - A face for the link, or a function that returns a face.
  1540. The function takes one argument which is the link path. The
  1541. default face is `org-link'.
  1542. :mouse-face - The mouse-face. The default is `highlight'.
  1543. :display - `full' will not fold the link in descriptive
  1544. display. Default is `org-link'.
  1545. :help-echo - A string or function that takes (window object position)
  1546. as arguments and returns a string.
  1547. :keymap - A keymap that is active on the link. The default is
  1548. `org-mouse-map'.
  1549. :htmlize-link - A function for the htmlize-link. Defaults
  1550. to (list :uri \"type:path\")
  1551. :activate-func - A function to run at the end of font-lock
  1552. activation. The function must accept (link-start link-end path bracketp)
  1553. as arguments."
  1554. :group 'org-link
  1555. :type '(alist :tag "Link display parameters"
  1556. :value-type plist)
  1557. :version "26.1"
  1558. :package-version '(Org . "9.1"))
  1559. (defun org-link-get-parameter (type key)
  1560. "Get TYPE link property for KEY.
  1561. TYPE is a string and KEY is a plist keyword."
  1562. (plist-get
  1563. (cdr (assoc type org-link-parameters))
  1564. key))
  1565. (defun org-link-set-parameters (type &rest parameters)
  1566. "Set link TYPE properties to PARAMETERS.
  1567. PARAMETERS should be :key val pairs."
  1568. (let ((data (assoc type org-link-parameters)))
  1569. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1570. (push (cons type parameters) org-link-parameters)
  1571. (org-make-link-regexps)
  1572. (org-element-update-syntax))))
  1573. (defun org-link-types ()
  1574. "Return a list of known link types."
  1575. (mapcar #'car org-link-parameters))
  1576. (defcustom org-link-abbrev-alist nil
  1577. "Alist of link abbreviations.
  1578. The car of each element is a string, to be replaced at the start of a link.
  1579. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1580. links in Org buffers can have an optional tag after a double colon, e.g.,
  1581. [[linkkey:tag][description]]
  1582. The `linkkey' must be a single word, starting with a letter, followed
  1583. by letters, numbers, `-' or `_'.
  1584. If REPLACE is a string, the tag will simply be appended to create the link.
  1585. If the string contains \"%s\", the tag will be inserted there. If the string
  1586. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1587. at that point (see the function `url-hexify-string'). If the string contains
  1588. the specifier \"%(my-function)\", then the custom function `my-function' will
  1589. be invoked: this function takes the tag as its only argument and must return
  1590. a string.
  1591. REPLACE may also be a function that will be called with the tag as the
  1592. only argument to create the link, which should be returned as a string.
  1593. See the manual for examples."
  1594. :group 'org-link
  1595. :type '(repeat
  1596. (cons
  1597. (string :tag "Protocol")
  1598. (choice
  1599. (string :tag "Format")
  1600. (function)))))
  1601. (defcustom org-descriptive-links t
  1602. "Non-nil means Org will display descriptive links.
  1603. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1604. \"Org Website\", hiding the link itself and just displaying its
  1605. description. When set to nil, Org will display the full links
  1606. literally.
  1607. You can interactively set the value of this variable by calling
  1608. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1609. :group 'org-link
  1610. :type 'boolean)
  1611. (defcustom org-link-file-path-type 'adaptive
  1612. "How the path name in file links should be stored.
  1613. Valid values are:
  1614. relative Relative to the current directory, i.e. the directory of the file
  1615. into which the link is being inserted.
  1616. absolute Absolute path, if possible with ~ for home directory.
  1617. noabbrev Absolute path, no abbreviation of home directory.
  1618. adaptive Use relative path for files in the current directory and sub-
  1619. directories of it. For other files, use an absolute path."
  1620. :group 'org-link
  1621. :type '(choice
  1622. (const relative)
  1623. (const absolute)
  1624. (const noabbrev)
  1625. (const adaptive)))
  1626. (defvaralias 'org-activate-links 'org-highlight-links)
  1627. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1628. "Types of links that should be highlighted in Org files.
  1629. This is a list of symbols, each one of them leading to the
  1630. highlighting of a certain link type.
  1631. You can still open links that are not highlighted.
  1632. In principle, it does not hurt to turn on highlighting for all
  1633. link types. There may be a small gain when turning off unused
  1634. link types. The types are:
  1635. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1636. angle Links in angular brackets that may contain whitespace like
  1637. <bbdb:Carsten Dominik>.
  1638. plain Plain links in normal text, no whitespace, like http://google.com.
  1639. radio Text that is matched by a radio target, see manual for details.
  1640. tag Tag settings in a headline (link to tag search).
  1641. date Time stamps (link to calendar).
  1642. footnote Footnote labels.
  1643. If you set this variable during an Emacs session, use `org-mode-restart'
  1644. in the Org buffer so that the change takes effect."
  1645. :group 'org-link
  1646. :group 'org-appearance
  1647. :type '(set :greedy t
  1648. (const :tag "Double bracket links" bracket)
  1649. (const :tag "Angular bracket links" angle)
  1650. (const :tag "Plain text links" plain)
  1651. (const :tag "Radio target matches" radio)
  1652. (const :tag "Tags" tag)
  1653. (const :tag "Timestamps" date)
  1654. (const :tag "Footnotes" footnote)))
  1655. (defcustom org-make-link-description-function nil
  1656. "Function to use for generating link descriptions from links.
  1657. This function must take two parameters: the first one is the
  1658. link, the second one is the description generated by
  1659. `org-insert-link'. The function should return the description to
  1660. use."
  1661. :group 'org-link
  1662. :type '(choice (const nil) (function)))
  1663. (defgroup org-link-store nil
  1664. "Options concerning storing links in Org mode."
  1665. :tag "Org Store Link"
  1666. :group 'org-link)
  1667. (defcustom org-url-hexify-p t
  1668. "When non-nil, hexify URL when creating a link."
  1669. :type 'boolean
  1670. :version "24.3"
  1671. :group 'org-link-store)
  1672. (defcustom org-email-link-description-format "Email %c: %.30s"
  1673. "Format of the description part of a link to an email or usenet message.
  1674. The following %-escapes will be replaced by corresponding information:
  1675. %F full \"From\" field
  1676. %f name, taken from \"From\" field, address if no name
  1677. %T full \"To\" field
  1678. %t first name in \"To\" field, address if no name
  1679. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1680. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1681. %s subject
  1682. %d date
  1683. %m message-id.
  1684. You may use normal field width specification between the % and the letter.
  1685. This is for example useful to limit the length of the subject.
  1686. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1687. :group 'org-link-store
  1688. :type 'string)
  1689. (defcustom org-from-is-user-regexp
  1690. (let (r1 r2)
  1691. (when (and user-mail-address (not (string= user-mail-address "")))
  1692. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1693. (when (and user-full-name (not (string= user-full-name "")))
  1694. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1695. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1696. "Regexp matched against the \"From:\" header of an email or usenet message.
  1697. It should match if the message is from the user him/herself."
  1698. :group 'org-link-store
  1699. :type 'regexp)
  1700. (defcustom org-context-in-file-links t
  1701. "Non-nil means file links from `org-store-link' contain context.
  1702. \\<org-mode-map>
  1703. A search string will be added to the file name with :: as separator
  1704. and used to find the context when the link is activated by the command
  1705. `org-open-at-point'. When this option is t, the entire active region
  1706. will be placed in the search string of the file link. If set to a
  1707. positive integer, only the first n lines of context will be stored.
  1708. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1709. \\[org-store-link]')
  1710. negates this setting for the duration of the command."
  1711. :group 'org-link-store
  1712. :type '(choice boolean integer))
  1713. (defcustom org-keep-stored-link-after-insertion nil
  1714. "Non-nil means keep link in list for entire session.
  1715. \\<org-mode-map>
  1716. The command `org-store-link' adds a link pointing to the current
  1717. location to an internal list. These links accumulate during a session.
  1718. The command `org-insert-link' can be used to insert links into any
  1719. Org file (offering completion for all stored links).
  1720. When this option is nil, every link which has been inserted once using
  1721. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1722. unused
  1723. links more efficient."
  1724. :group 'org-link-store
  1725. :type 'boolean)
  1726. (defgroup org-link-follow nil
  1727. "Options concerning following links in Org mode."
  1728. :tag "Org Follow Link"
  1729. :group 'org-link)
  1730. (defcustom org-link-translation-function nil
  1731. "Function to translate links with different syntax to Org syntax.
  1732. This can be used to translate links created for example by the Planner
  1733. or emacs-wiki packages to Org syntax.
  1734. The function must accept two parameters, a TYPE containing the link
  1735. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1736. which is everything after the link protocol. It should return a cons
  1737. with possibly modified values of type and path.
  1738. Org contains a function for this, so if you set this variable to
  1739. `org-translate-link-from-planner', you should be able follow many
  1740. links created by planner."
  1741. :group 'org-link-follow
  1742. :type '(choice (const nil) (function)))
  1743. (defcustom org-follow-link-hook nil
  1744. "Hook that is run after a link has been followed."
  1745. :group 'org-link-follow
  1746. :type 'hook)
  1747. (defcustom org-tab-follows-link nil
  1748. "Non-nil means on links TAB will follow the link.
  1749. Needs to be set before org.el is loaded.
  1750. This really should not be used, it does not make sense, and the
  1751. implementation is bad."
  1752. :group 'org-link-follow
  1753. :type 'boolean)
  1754. (defcustom org-return-follows-link nil
  1755. "Non-nil means on links RET will follow the link.
  1756. In tables, the special behavior of RET has precedence."
  1757. :group 'org-link-follow
  1758. :type 'boolean)
  1759. (defcustom org-mouse-1-follows-link
  1760. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1761. "Non-nil means mouse-1 on a link will follow the link.
  1762. A longer mouse click will still set point. Needs to be set
  1763. before org.el is loaded."
  1764. :group 'org-link-follow
  1765. :version "26.1"
  1766. :package-version '(Org . "8.3")
  1767. :type '(choice
  1768. (const :tag "A double click follows the link" double)
  1769. (const :tag "Unconditionally follow the link with mouse-1" t)
  1770. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1771. (defcustom org-mark-ring-length 4
  1772. "Number of different positions to be recorded in the ring.
  1773. Changing this requires a restart of Emacs to work correctly."
  1774. :group 'org-link-follow
  1775. :type 'integer)
  1776. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1777. "Non-nil means internal fuzzy links can only match headlines.
  1778. When nil, the a fuzzy link may point to a target or a named
  1779. construct in the document. When set to the special value
  1780. `query-to-create', offer to create a new headline when none
  1781. matched.
  1782. Spaces and statistics cookies are ignored during heading searches."
  1783. :group 'org-link-follow
  1784. :version "24.1"
  1785. :type '(choice
  1786. (const :tag "Use fuzzy text search" nil)
  1787. (const :tag "Match only exact headline" t)
  1788. (const :tag "Match exact headline or query to create it"
  1789. query-to-create))
  1790. :safe #'symbolp)
  1791. (defcustom org-link-frame-setup
  1792. '((vm . vm-visit-folder-other-frame)
  1793. (vm-imap . vm-visit-imap-folder-other-frame)
  1794. (gnus . org-gnus-no-new-news)
  1795. (file . find-file-other-window)
  1796. (wl . wl-other-frame))
  1797. "Setup the frame configuration for following links.
  1798. When following a link with Emacs, it may often be useful to display
  1799. this link in another window or frame. This variable can be used to
  1800. set this up for the different types of links.
  1801. For VM, use any of
  1802. `vm-visit-folder'
  1803. `vm-visit-folder-other-window'
  1804. `vm-visit-folder-other-frame'
  1805. For Gnus, use any of
  1806. `gnus'
  1807. `gnus-other-frame'
  1808. `org-gnus-no-new-news'
  1809. For FILE, use any of
  1810. `find-file'
  1811. `find-file-other-window'
  1812. `find-file-other-frame'
  1813. For Wanderlust use any of
  1814. `wl'
  1815. `wl-other-frame'
  1816. For the calendar, use the variable `calendar-setup'.
  1817. For BBDB, it is currently only possible to display the matches in
  1818. another window."
  1819. :group 'org-link-follow
  1820. :type '(list
  1821. (cons (const vm)
  1822. (choice
  1823. (const vm-visit-folder)
  1824. (const vm-visit-folder-other-window)
  1825. (const vm-visit-folder-other-frame)))
  1826. (cons (const vm-imap)
  1827. (choice
  1828. (const vm-visit-imap-folder)
  1829. (const vm-visit-imap-folder-other-window)
  1830. (const vm-visit-imap-folder-other-frame)))
  1831. (cons (const gnus)
  1832. (choice
  1833. (const gnus)
  1834. (const gnus-other-frame)
  1835. (const org-gnus-no-new-news)))
  1836. (cons (const file)
  1837. (choice
  1838. (const find-file)
  1839. (const find-file-other-window)
  1840. (const find-file-other-frame)))
  1841. (cons (const wl)
  1842. (choice
  1843. (const wl)
  1844. (const wl-other-frame)))))
  1845. (defcustom org-display-internal-link-with-indirect-buffer nil
  1846. "Non-nil means use indirect buffer to display infile links.
  1847. Activating internal links (from one location in a file to another location
  1848. in the same file) normally just jumps to the location. When the link is
  1849. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1850. is displayed in
  1851. another window. When this option is set, the other window actually displays
  1852. an indirect buffer clone of the current buffer, to avoid any visibility
  1853. changes to the current buffer."
  1854. :group 'org-link-follow
  1855. :type 'boolean)
  1856. (defcustom org-open-non-existing-files nil
  1857. "Non-nil means `org-open-file' will open non-existing files.
  1858. When nil, an error will be generated.
  1859. This variable applies only to external applications because they
  1860. might choke on non-existing files. If the link is to a file that
  1861. will be opened in Emacs, the variable is ignored."
  1862. :group 'org-link-follow
  1863. :type 'boolean)
  1864. (defcustom org-open-directory-means-index-dot-org nil
  1865. "Non-nil means a link to a directory really means to index.org.
  1866. When nil, following a directory link will run dired or open a finder/explorer
  1867. window on that directory."
  1868. :group 'org-link-follow
  1869. :type 'boolean)
  1870. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1871. "Non-nil means ask for confirmation before executing shell links.
  1872. Shell links can be dangerous: just think about a link
  1873. [[shell:rm -rf ~/*][Google Search]]
  1874. This link would show up in your Org document as \"Google Search\",
  1875. but really it would remove your entire home directory.
  1876. Therefore we advise against setting this variable to nil.
  1877. Just change it to `y-or-n-p' if you want to confirm with a
  1878. single keystroke rather than having to type \"yes\"."
  1879. :group 'org-link-follow
  1880. :type '(choice
  1881. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1882. (const :tag "with y-or-n (faster)" y-or-n-p)
  1883. (const :tag "no confirmation (dangerous)" nil)))
  1884. (put 'org-confirm-shell-link-function
  1885. 'safe-local-variable
  1886. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1887. (defcustom org-confirm-shell-link-not-regexp ""
  1888. "A regexp to skip confirmation for shell links."
  1889. :group 'org-link-follow
  1890. :version "24.1"
  1891. :type 'regexp)
  1892. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1893. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1894. Elisp links can be dangerous: just think about a link
  1895. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1896. This link would show up in your Org document as \"Google Search\",
  1897. but really it would remove your entire home directory.
  1898. Therefore we advise against setting this variable to nil.
  1899. Just change it to `y-or-n-p' if you want to confirm with a
  1900. single keystroke rather than having to type \"yes\"."
  1901. :group 'org-link-follow
  1902. :type '(choice
  1903. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1904. (const :tag "with y-or-n (faster)" y-or-n-p)
  1905. (const :tag "no confirmation (dangerous)" nil)))
  1906. (put 'org-confirm-shell-link-function
  1907. 'safe-local-variable
  1908. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1909. (defcustom org-confirm-elisp-link-not-regexp ""
  1910. "A regexp to skip confirmation for Elisp links."
  1911. :group 'org-link-follow
  1912. :version "24.1"
  1913. :type 'regexp)
  1914. (defconst org-file-apps-defaults-gnu
  1915. '((remote . emacs)
  1916. (system . mailcap)
  1917. (t . mailcap))
  1918. "Default file applications on a UNIX or GNU/Linux system.
  1919. See `org-file-apps'.")
  1920. (defconst org-file-apps-defaults-macosx
  1921. '((remote . emacs)
  1922. (system . "open %s")
  1923. ("ps.gz" . "gv %s")
  1924. ("eps.gz" . "gv %s")
  1925. ("dvi" . "xdvi %s")
  1926. ("fig" . "xfig %s")
  1927. (t . "open %s"))
  1928. "Default file applications on a macOS system.
  1929. The system \"open\" is known as a default, but we use X11 applications
  1930. for some files for which the OS does not have a good default.
  1931. See `org-file-apps'.")
  1932. (defconst org-file-apps-defaults-windowsnt
  1933. (list '(remote . emacs)
  1934. (cons 'system (lambda (file _path)
  1935. (with-no-warnings (w32-shell-execute "open" file))))
  1936. (cons t (lambda (file _path)
  1937. (with-no-warnings (w32-shell-execute "open" file)))))
  1938. "Default file applications on a Windows NT system.
  1939. The system \"open\" is used for most files.
  1940. See `org-file-apps'.")
  1941. (defcustom org-file-apps
  1942. '((auto-mode . emacs)
  1943. ("\\.mm\\'" . default)
  1944. ("\\.x?html?\\'" . default)
  1945. ("\\.pdf\\'" . default))
  1946. "External applications for opening `file:path' items in a document.
  1947. \\<org-mode-map>\
  1948. Org mode uses system defaults for different file types, but
  1949. you can use this variable to set the application for a given file
  1950. extension. The entries in this list are cons cells where the car identifies
  1951. files and the cdr the corresponding command.
  1952. Possible values for the file identifier are:
  1953. \"string\" A string as a file identifier can be interpreted in different
  1954. ways, depending on its contents:
  1955. - Alphanumeric characters only:
  1956. Match links with this file extension.
  1957. Example: (\"pdf\" . \"evince %s\")
  1958. to open PDFs with evince.
  1959. - Regular expression: Match links where the
  1960. filename matches the regexp. If you want to
  1961. use groups here, use shy groups.
  1962. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1963. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1964. to open *.html and *.xhtml with firefox.
  1965. - Regular expression which contains (non-shy) groups:
  1966. Match links where the whole link, including \"::\", and
  1967. anything after that, matches the regexp.
  1968. In a custom command string, %1, %2, etc. are replaced with
  1969. the parts of the link that were matched by the groups.
  1970. For backwards compatibility, if a command string is given
  1971. that does not use any of the group matches, this case is
  1972. handled identically to the second one (i.e. match against
  1973. file name only).
  1974. In a custom function, you can access the group matches with
  1975. (match-string n link).
  1976. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1977. \"evince -p %1 %s\")
  1978. to open [[file:document.pdf::5]] with evince at page 5.
  1979. `directory' Matches a directory
  1980. `remote' Matches a remote file, accessible through tramp or efs.
  1981. Remote files most likely should be visited through Emacs
  1982. because external applications cannot handle such paths.
  1983. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1984. so all files Emacs knows how to handle. Using this with
  1985. command `emacs' will open most files in Emacs. Beware that this
  1986. will also open html files inside Emacs, unless you add
  1987. (\"html\" . default) to the list as well.
  1988. `system' The system command to open files, like `open' on Windows
  1989. and macOS, and mailcap under GNU/Linux. This is the command
  1990. that will be selected if you call `org-open-at-point' with a
  1991. double prefix argument (`\\[universal-argument] \
  1992. \\[universal-argument] \\[org-open-at-point]').
  1993. t Default for files not matched by any of the other options.
  1994. Possible values for the command are:
  1995. `emacs' The file will be visited by the current Emacs process.
  1996. `default' Use the default application for this file type, which is the
  1997. association for t in the list, most likely in the system-specific
  1998. part. This can be used to overrule an unwanted setting in the
  1999. system-specific variable.
  2000. `system' Use the system command for opening files, like \"open\".
  2001. This command is specified by the entry whose car is `system'.
  2002. Most likely, the system-specific version of this variable
  2003. does define this command, but you can overrule/replace it
  2004. here.
  2005. `mailcap' Use command specified in the mailcaps.
  2006. string A command to be executed by a shell; %s will be replaced
  2007. by the path to the file.
  2008. function A Lisp function, which will be called with two arguments:
  2009. the file path and the original link string, without the
  2010. \"file:\" prefix.
  2011. For more examples, see the system specific constants
  2012. `org-file-apps-defaults-macosx'
  2013. `org-file-apps-defaults-windowsnt'
  2014. `org-file-apps-defaults-gnu'."
  2015. :group 'org-link-follow
  2016. :type '(repeat
  2017. (cons (choice :value ""
  2018. (string :tag "Extension")
  2019. (const :tag "System command to open files" system)
  2020. (const :tag "Default for unrecognized files" t)
  2021. (const :tag "Remote file" remote)
  2022. (const :tag "Links to a directory" directory)
  2023. (const :tag "Any files that have Emacs modes"
  2024. auto-mode))
  2025. (choice :value ""
  2026. (const :tag "Visit with Emacs" emacs)
  2027. (const :tag "Use default" default)
  2028. (const :tag "Use the system command" system)
  2029. (string :tag "Command")
  2030. (function :tag "Function")))))
  2031. (defcustom org-doi-server-url "http://dx.doi.org/"
  2032. "The URL of the DOI server."
  2033. :type 'string
  2034. :version "24.3"
  2035. :group 'org-link-follow)
  2036. (defgroup org-refile nil
  2037. "Options concerning refiling entries in Org mode."
  2038. :tag "Org Refile"
  2039. :group 'org)
  2040. (defcustom org-directory "~/org"
  2041. "Directory with Org files.
  2042. This is just a default location to look for Org files. There is no need
  2043. at all to put your files into this directory. It is used in the
  2044. following situations:
  2045. 1. When a capture template specifies a target file that is not an
  2046. absolute path. The path will then be interpreted relative to
  2047. `org-directory'
  2048. 2. When the value of variable `org-agenda-files' is a single file, any
  2049. relative paths in this file will be taken as relative to
  2050. `org-directory'."
  2051. :group 'org-refile
  2052. :group 'org-capture
  2053. :type 'directory)
  2054. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2055. "Default target for storing notes.
  2056. Used as a fall back file for org-capture.el, for templates that
  2057. do not specify a target file."
  2058. :group 'org-refile
  2059. :group 'org-capture
  2060. :type 'file)
  2061. (defcustom org-goto-interface 'outline
  2062. "The default interface to be used for `org-goto'.
  2063. Allowed values are:
  2064. outline The interface shows an outline of the relevant file
  2065. and the correct heading is found by moving through
  2066. the outline or by searching with incremental search.
  2067. outline-path-completion Headlines in the current buffer are offered via
  2068. completion. This is the interface also used by
  2069. the refile command."
  2070. :group 'org-refile
  2071. :type '(choice
  2072. (const :tag "Outline" outline)
  2073. (const :tag "Outline-path-completion" outline-path-completion)))
  2074. (defcustom org-goto-max-level 5
  2075. "Maximum target level when running `org-goto' with refile interface."
  2076. :group 'org-refile
  2077. :type 'integer)
  2078. (defcustom org-reverse-note-order nil
  2079. "Non-nil means store new notes at the beginning of a file or entry.
  2080. When nil, new notes will be filed to the end of a file or entry.
  2081. This can also be a list with cons cells of regular expressions that
  2082. are matched against file names, and values."
  2083. :group 'org-capture
  2084. :group 'org-refile
  2085. :type '(choice
  2086. (const :tag "Reverse always" t)
  2087. (const :tag "Reverse never" nil)
  2088. (repeat :tag "By file name regexp"
  2089. (cons regexp boolean))))
  2090. (defcustom org-log-refile nil
  2091. "Information to record when a task is refiled.
  2092. Possible values are:
  2093. nil Don't add anything
  2094. time Add a time stamp to the task
  2095. note Prompt for a note and add it with template `org-log-note-headings'
  2096. This option can also be set with on a per-file-basis with
  2097. #+STARTUP: nologrefile
  2098. #+STARTUP: logrefile
  2099. #+STARTUP: lognoterefile
  2100. You can have local logging settings for a subtree by setting the LOGGING
  2101. property to one or more of these keywords.
  2102. When bulk-refiling from the agenda, the value `note' is forbidden and
  2103. will temporarily be changed to `time'."
  2104. :group 'org-refile
  2105. :group 'org-progress
  2106. :version "24.1"
  2107. :type '(choice
  2108. (const :tag "No logging" nil)
  2109. (const :tag "Record timestamp" time)
  2110. (const :tag "Record timestamp with note." note)))
  2111. (defcustom org-refile-targets nil
  2112. "Targets for refiling entries with `\\[org-refile]'.
  2113. This is a list of cons cells. Each cell contains:
  2114. - a specification of the files to be considered, either a list of files,
  2115. or a symbol whose function or variable value will be used to retrieve
  2116. a file name or a list of file names. If you use `org-agenda-files' for
  2117. that, all agenda files will be scanned for targets. Nil means consider
  2118. headings in the current buffer.
  2119. - A specification of how to find candidate refile targets. This may be
  2120. any of:
  2121. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2122. This tag has to be present in all target headlines, inheritance will
  2123. not be considered.
  2124. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2125. todo keyword.
  2126. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2127. headlines that are refiling targets.
  2128. - a cons cell (:level . N). Any headline of level N is considered a target.
  2129. Note that, when `org-odd-levels-only' is set, level corresponds to
  2130. order in hierarchy, not to the number of stars.
  2131. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2132. Note that, when `org-odd-levels-only' is set, level corresponds to
  2133. order in hierarchy, not to the number of stars.
  2134. Each element of this list generates a set of possible targets.
  2135. The union of these sets is presented (with completion) to
  2136. the user by `org-refile'.
  2137. You can set the variable `org-refile-target-verify-function' to a function
  2138. to verify each headline found by the simple criteria above.
  2139. When this variable is nil, all top-level headlines in the current buffer
  2140. are used, equivalent to the value `((nil . (:level . 1))'."
  2141. :group 'org-refile
  2142. :type '(repeat
  2143. (cons
  2144. (choice :value org-agenda-files
  2145. (const :tag "All agenda files" org-agenda-files)
  2146. (const :tag "Current buffer" nil)
  2147. (function) (variable) (file))
  2148. (choice :tag "Identify target headline by"
  2149. (cons :tag "Specific tag" (const :value :tag) (string))
  2150. (cons :tag "TODO keyword" (const :value :todo) (string))
  2151. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2152. (cons :tag "Level number" (const :value :level) (integer))
  2153. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2154. (defcustom org-refile-target-verify-function nil
  2155. "Function to verify if the headline at point should be a refile target.
  2156. The function will be called without arguments, with point at the
  2157. beginning of the headline. It should return t and leave point
  2158. where it is if the headline is a valid target for refiling.
  2159. If the target should not be selected, the function must return nil.
  2160. In addition to this, it may move point to a place from where the search
  2161. should be continued. For example, the function may decide that the entire
  2162. subtree of the current entry should be excluded and move point to the end
  2163. of the subtree."
  2164. :group 'org-refile
  2165. :type '(choice
  2166. (const nil)
  2167. (function)))
  2168. (defcustom org-refile-use-cache nil
  2169. "Non-nil means cache refile targets to speed up the process.
  2170. \\<org-mode-map>\
  2171. The cache for a particular file will be updated automatically when
  2172. the buffer has been killed, or when any of the marker used for flagging
  2173. refile targets no longer points at a live buffer.
  2174. If you have added new entries to a buffer that might themselves be targets,
  2175. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2176. if you find that easier, \
  2177. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2178. \\[org-refile]'."
  2179. :group 'org-refile
  2180. :version "24.1"
  2181. :type 'boolean)
  2182. (defcustom org-refile-use-outline-path nil
  2183. "Non-nil means provide refile targets as paths.
  2184. So a level 3 headline will be available as level1/level2/level3.
  2185. When the value is `file', also include the file name (without directory)
  2186. into the path. In this case, you can also stop the completion after
  2187. the file name, to get entries inserted as top level in the file.
  2188. When `full-file-path', include the full file path.
  2189. When `buffer-name', use the buffer name."
  2190. :group 'org-refile
  2191. :type '(choice
  2192. (const :tag "Not" nil)
  2193. (const :tag "Yes" t)
  2194. (const :tag "Start with file name" file)
  2195. (const :tag "Start with full file path" full-file-path)
  2196. (const :tag "Start with buffer name" buffer-name)))
  2197. (defcustom org-outline-path-complete-in-steps t
  2198. "Non-nil means complete the outline path in hierarchical steps.
  2199. When Org uses the refile interface to select an outline path (see
  2200. `org-refile-use-outline-path'), the completion of the path can be
  2201. done in a single go, or it can be done in steps down the headline
  2202. hierarchy. Going in steps is probably the best if you do not use
  2203. a special completion package like `ido' or `icicles'. However,
  2204. when using these packages, going in one step can be very fast,
  2205. while still showing the whole path to the entry."
  2206. :group 'org-refile
  2207. :type 'boolean)
  2208. (defcustom org-refile-allow-creating-parent-nodes nil
  2209. "Non-nil means allow the creation of new nodes as refile targets.
  2210. New nodes are then created by adding \"/new node name\" to the completion
  2211. of an existing node. When the value of this variable is `confirm',
  2212. new node creation must be confirmed by the user (recommended).
  2213. When nil, the completion must match an existing entry.
  2214. Note that, if the new heading is not seen by the criteria
  2215. listed in `org-refile-targets', multiple instances of the same
  2216. heading would be created by trying again to file under the new
  2217. heading."
  2218. :group 'org-refile
  2219. :type '(choice
  2220. (const :tag "Never" nil)
  2221. (const :tag "Always" t)
  2222. (const :tag "Prompt for confirmation" confirm)))
  2223. (defcustom org-refile-active-region-within-subtree nil
  2224. "Non-nil means also refile active region within a subtree.
  2225. By default `org-refile' doesn't allow refiling regions if they
  2226. don't contain a set of subtrees, but it might be convenient to
  2227. do so sometimes: in that case, the first line of the region is
  2228. converted to a headline before refiling."
  2229. :group 'org-refile
  2230. :version "24.1"
  2231. :type 'boolean)
  2232. (defgroup org-todo nil
  2233. "Options concerning TODO items in Org mode."
  2234. :tag "Org TODO"
  2235. :group 'org)
  2236. (defgroup org-progress nil
  2237. "Options concerning Progress logging in Org mode."
  2238. :tag "Org Progress"
  2239. :group 'org-time)
  2240. (defvar org-todo-interpretation-widgets
  2241. '((:tag "Sequence (cycling hits every state)" sequence)
  2242. (:tag "Type (cycling directly to DONE)" type))
  2243. "The available interpretation symbols for customizing `org-todo-keywords'.
  2244. Interested libraries should add to this list.")
  2245. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2246. "List of TODO entry keyword sequences and their interpretation.
  2247. \\<org-mode-map>This is a list of sequences.
  2248. Each sequence starts with a symbol, either `sequence' or `type',
  2249. indicating if the keywords should be interpreted as a sequence of
  2250. action steps, or as different types of TODO items. The first
  2251. keywords are states requiring action - these states will select a headline
  2252. for inclusion into the global TODO list Org produces. If one of the
  2253. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2254. signify that no further action is necessary. If \"|\" is not found,
  2255. the last keyword is treated as the only DONE state of the sequence.
  2256. The command `\\[org-todo]' cycles an entry through these states, and one
  2257. additional state where no keyword is present. For details about this
  2258. cycling, see the manual.
  2259. TODO keywords and interpretation can also be set on a per-file basis with
  2260. the special #+SEQ_TODO and #+TYP_TODO lines.
  2261. Each keyword can optionally specify a character for fast state selection
  2262. \(in combination with the variable `org-use-fast-todo-selection')
  2263. and specifiers for state change logging, using the same syntax that
  2264. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2265. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2266. indicates to record a time stamp each time this state is selected.
  2267. Each keyword may also specify if a timestamp or a note should be
  2268. recorded when entering or leaving the state, by adding additional
  2269. characters in the parenthesis after the keyword. This looks like this:
  2270. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2271. record only the time of the state change. With X and Y being either
  2272. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2273. Y when leaving the state if and only if the *target* state does not
  2274. define X. You may omit any of the fast-selection key or X or /Y,
  2275. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2276. For backward compatibility, this variable may also be just a list
  2277. of keywords. In this case the interpretation (sequence or type) will be
  2278. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2279. :group 'org-todo
  2280. :group 'org-keywords
  2281. :type '(choice
  2282. (repeat :tag "Old syntax, just keywords"
  2283. (string :tag "Keyword"))
  2284. (repeat :tag "New syntax"
  2285. (cons
  2286. (choice
  2287. :tag "Interpretation"
  2288. ;;Quick and dirty way to see
  2289. ;;`org-todo-interpretations'. This takes the
  2290. ;;place of item arguments
  2291. :convert-widget
  2292. (lambda (widget)
  2293. (widget-put widget
  2294. :args (mapcar
  2295. (lambda (x)
  2296. (widget-convert
  2297. (cons 'const x)))
  2298. org-todo-interpretation-widgets))
  2299. widget))
  2300. (repeat
  2301. (string :tag "Keyword"))))))
  2302. (defvar-local org-todo-keywords-1 nil
  2303. "All TODO and DONE keywords active in a buffer.")
  2304. (defvar org-todo-keywords-for-agenda nil)
  2305. (defvar org-done-keywords-for-agenda nil)
  2306. (defvar org-todo-keyword-alist-for-agenda nil)
  2307. (defvar org-tag-alist-for-agenda nil
  2308. "Alist of all tags from all agenda files.")
  2309. (defvar org-tag-groups-alist-for-agenda nil
  2310. "Alist of all groups tags from all current agenda files.")
  2311. (defvar-local org-tag-groups-alist nil)
  2312. (defvar org-agenda-contributing-files nil)
  2313. (defvar-local org-current-tag-alist nil
  2314. "Alist of all tag groups in current buffer.
  2315. This variable takes into consideration `org-tag-alist',
  2316. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2317. (defvar-local org-not-done-keywords nil)
  2318. (defvar-local org-done-keywords nil)
  2319. (defvar-local org-todo-heads nil)
  2320. (defvar-local org-todo-sets nil)
  2321. (defvar-local org-todo-log-states nil)
  2322. (defvar-local org-todo-kwd-alist nil)
  2323. (defvar-local org-todo-key-alist nil)
  2324. (defvar-local org-todo-key-trigger nil)
  2325. (defcustom org-todo-interpretation 'sequence
  2326. "Controls how TODO keywords are interpreted.
  2327. This variable is in principle obsolete and is only used for
  2328. backward compatibility, if the interpretation of todo keywords is
  2329. not given already in `org-todo-keywords'. See that variable for
  2330. more information."
  2331. :group 'org-todo
  2332. :group 'org-keywords
  2333. :type '(choice (const sequence)
  2334. (const type)))
  2335. (defcustom org-use-fast-todo-selection t
  2336. "\\<org-mode-map>\
  2337. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2338. This variable describes if and under what circumstances the cycling
  2339. mechanism for TODO keywords will be replaced by a single-key, direct
  2340. selection scheme.
  2341. When nil, fast selection is never used.
  2342. When the symbol `prefix', it will be used when `org-todo' is called
  2343. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2344. in an Org buffer, and
  2345. `\\[universal-argument] t' in an agenda buffer.
  2346. When t, fast selection is used by default. In this case, the prefix
  2347. argument forces cycling instead.
  2348. In all cases, the special interface is only used if access keys have
  2349. actually been assigned by the user, i.e. if keywords in the configuration
  2350. are followed by a letter in parenthesis, like TODO(t)."
  2351. :group 'org-todo
  2352. :type '(choice
  2353. (const :tag "Never" nil)
  2354. (const :tag "By default" t)
  2355. (const :tag "Only with C-u C-c C-t" prefix)))
  2356. (defcustom org-provide-todo-statistics t
  2357. "Non-nil means update todo statistics after insert and toggle.
  2358. ALL-HEADLINES means update todo statistics by including headlines
  2359. with no TODO keyword as well, counting them as not done.
  2360. A list of TODO keywords means the same, but skip keywords that are
  2361. not in this list.
  2362. When set to a list of two lists, the first list contains keywords
  2363. to consider as TODO keywords, the second list contains keywords
  2364. to consider as DONE keywords.
  2365. When this is set, todo statistics is updated in the parent of the
  2366. current entry each time a todo state is changed."
  2367. :group 'org-todo
  2368. :type '(choice
  2369. (const :tag "Yes, only for TODO entries" t)
  2370. (const :tag "Yes, including all entries" all-headlines)
  2371. (repeat :tag "Yes, for TODOs in this list"
  2372. (string :tag "TODO keyword"))
  2373. (list :tag "Yes, for TODOs and DONEs in these lists"
  2374. (repeat (string :tag "TODO keyword"))
  2375. (repeat (string :tag "DONE keyword")))
  2376. (other :tag "No TODO statistics" nil)))
  2377. (defcustom org-hierarchical-todo-statistics t
  2378. "Non-nil means TODO statistics covers just direct children.
  2379. When nil, all entries in the subtree are considered.
  2380. This has only an effect if `org-provide-todo-statistics' is set.
  2381. To set this to nil for only a single subtree, use a COOKIE_DATA
  2382. property and include the word \"recursive\" into the value."
  2383. :group 'org-todo
  2384. :type 'boolean)
  2385. (defcustom org-after-todo-state-change-hook nil
  2386. "Hook which is run after the state of a TODO item was changed.
  2387. The new state (a string with a TODO keyword, or nil) is available in the
  2388. Lisp variable `org-state'."
  2389. :group 'org-todo
  2390. :type 'hook)
  2391. (defvar org-blocker-hook nil
  2392. "Hook for functions that are allowed to block a state change.
  2393. Functions in this hook should not modify the buffer.
  2394. Each function gets as its single argument a property list,
  2395. see `org-trigger-hook' for more information about this list.
  2396. If any of the functions in this hook returns nil, the state change
  2397. is blocked.")
  2398. (defvar org-trigger-hook nil
  2399. "Hook for functions that are triggered by a state change.
  2400. Each function gets as its single argument a property list with at
  2401. least the following elements:
  2402. (:type type-of-change :position pos-at-entry-start
  2403. :from old-state :to new-state)
  2404. Depending on the type, more properties may be present.
  2405. This mechanism is currently implemented for:
  2406. TODO state changes
  2407. ------------------
  2408. :type todo-state-change
  2409. :from previous state (keyword as a string), or nil, or a symbol
  2410. `todo' or `done', to indicate the general type of state.
  2411. :to new state, like in :from")
  2412. (defcustom org-enforce-todo-dependencies nil
  2413. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2414. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2415. be blocked if any prior sibling is not yet done.
  2416. Finally, if the parent is blocked because of ordered siblings of its own,
  2417. the child will also be blocked."
  2418. :set (lambda (var val)
  2419. (set var val)
  2420. (if val
  2421. (add-hook 'org-blocker-hook
  2422. 'org-block-todo-from-children-or-siblings-or-parent)
  2423. (remove-hook 'org-blocker-hook
  2424. 'org-block-todo-from-children-or-siblings-or-parent)))
  2425. :group 'org-todo
  2426. :type 'boolean)
  2427. (defcustom org-enforce-todo-checkbox-dependencies nil
  2428. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2429. When this is nil, checkboxes have no influence on switching TODO states.
  2430. When non-nil, you first need to check off all check boxes before the TODO
  2431. entry can be switched to DONE.
  2432. This variable needs to be set before org.el is loaded, and you need to
  2433. restart Emacs after a change to make the change effective. The only way
  2434. to change is while Emacs is running is through the customize interface."
  2435. :set (lambda (var val)
  2436. (set var val)
  2437. (if val
  2438. (add-hook 'org-blocker-hook
  2439. 'org-block-todo-from-checkboxes)
  2440. (remove-hook 'org-blocker-hook
  2441. 'org-block-todo-from-checkboxes)))
  2442. :group 'org-todo
  2443. :type 'boolean)
  2444. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2445. "Non-nil means inserting a TODO heading is treated as state change.
  2446. So when the command `\\[org-insert-todo-heading]' is used, state change
  2447. logging will apply if appropriate. When nil, the new TODO item will
  2448. be inserted directly, and no logging will take place."
  2449. :group 'org-todo
  2450. :type 'boolean)
  2451. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2452. "Non-nil means switching TODO states with S-cursor counts as state change.
  2453. This is the default behavior. However, setting this to nil allows a
  2454. convenient way to select a TODO state and bypass any logging associated
  2455. with that."
  2456. :group 'org-todo
  2457. :type 'boolean)
  2458. (defcustom org-todo-state-tags-triggers nil
  2459. "Tag changes that should be triggered by TODO state changes.
  2460. This is a list. Each entry is
  2461. (state-change (tag . flag) .......)
  2462. State-change can be a string with a state, and empty string to indicate the
  2463. state that has no TODO keyword, or it can be one of the symbols `todo'
  2464. or `done', meaning any not-done or done state, respectively."
  2465. :group 'org-todo
  2466. :group 'org-tags
  2467. :type '(repeat
  2468. (cons (choice :tag "When changing to"
  2469. (const :tag "Not-done state" todo)
  2470. (const :tag "Done state" done)
  2471. (string :tag "State"))
  2472. (repeat
  2473. (cons :tag "Tag action"
  2474. (string :tag "Tag")
  2475. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2476. (defcustom org-log-done nil
  2477. "Information to record when a task moves to the DONE state.
  2478. Possible values are:
  2479. nil Don't add anything, just change the keyword
  2480. time Add a time stamp to the task
  2481. note Prompt for a note and add it with template `org-log-note-headings'
  2482. This option can also be set with on a per-file-basis with
  2483. #+STARTUP: nologdone
  2484. #+STARTUP: logdone
  2485. #+STARTUP: lognotedone
  2486. You can have local logging settings for a subtree by setting the LOGGING
  2487. property to one or more of these keywords."
  2488. :group 'org-todo
  2489. :group 'org-progress
  2490. :type '(choice
  2491. (const :tag "No logging" nil)
  2492. (const :tag "Record CLOSED timestamp" time)
  2493. (const :tag "Record CLOSED timestamp with note." note)))
  2494. ;; Normalize old uses of org-log-done.
  2495. (cond
  2496. ((eq org-log-done t) (setq org-log-done 'time))
  2497. ((and (listp org-log-done) (memq 'done org-log-done))
  2498. (setq org-log-done 'note)))
  2499. (defcustom org-log-reschedule nil
  2500. "Information to record when the scheduling date of a tasks is modified.
  2501. Possible values are:
  2502. nil Don't add anything, just change the date
  2503. time Add a time stamp to the task
  2504. note Prompt for a note and add it with template `org-log-note-headings'
  2505. This option can also be set with on a per-file-basis with
  2506. #+STARTUP: nologreschedule
  2507. #+STARTUP: logreschedule
  2508. #+STARTUP: lognotereschedule"
  2509. :group 'org-todo
  2510. :group 'org-progress
  2511. :type '(choice
  2512. (const :tag "No logging" nil)
  2513. (const :tag "Record timestamp" time)
  2514. (const :tag "Record timestamp with note." note)))
  2515. (defcustom org-log-redeadline nil
  2516. "Information to record when the deadline date of a tasks is modified.
  2517. Possible values are:
  2518. nil Don't add anything, just change the date
  2519. time Add a time stamp to the task
  2520. note Prompt for a note and add it with template `org-log-note-headings'
  2521. This option can also be set with on a per-file-basis with
  2522. #+STARTUP: nologredeadline
  2523. #+STARTUP: logredeadline
  2524. #+STARTUP: lognoteredeadline
  2525. You can have local logging settings for a subtree by setting the LOGGING
  2526. property to one or more of these keywords."
  2527. :group 'org-todo
  2528. :group 'org-progress
  2529. :type '(choice
  2530. (const :tag "No logging" nil)
  2531. (const :tag "Record timestamp" time)
  2532. (const :tag "Record timestamp with note." note)))
  2533. (defcustom org-log-note-clock-out nil
  2534. "Non-nil means record a note when clocking out of an item.
  2535. This can also be configured on a per-file basis by adding one of
  2536. the following lines anywhere in the buffer:
  2537. #+STARTUP: lognoteclock-out
  2538. #+STARTUP: nolognoteclock-out"
  2539. :group 'org-todo
  2540. :group 'org-progress
  2541. :type 'boolean)
  2542. (defcustom org-log-done-with-time t
  2543. "Non-nil means the CLOSED time stamp will contain date and time.
  2544. When nil, only the date will be recorded."
  2545. :group 'org-progress
  2546. :type 'boolean)
  2547. (defcustom org-log-note-headings
  2548. '((done . "CLOSING NOTE %t")
  2549. (state . "State %-12s from %-12S %t")
  2550. (note . "Note taken on %t")
  2551. (reschedule . "Rescheduled from %S on %t")
  2552. (delschedule . "Not scheduled, was %S on %t")
  2553. (redeadline . "New deadline from %S on %t")
  2554. (deldeadline . "Removed deadline, was %S on %t")
  2555. (refile . "Refiled on %t")
  2556. (clock-out . ""))
  2557. "Headings for notes added to entries.
  2558. The value is an alist, with the car being a symbol indicating the
  2559. note context, and the cdr is the heading to be used. The heading
  2560. may also be the empty string. The following placeholders can be
  2561. used:
  2562. %t a time stamp.
  2563. %T an active time stamp instead the default inactive one
  2564. %d a short-format time stamp.
  2565. %D an active short-format time stamp.
  2566. %s the new TODO state or time stamp (inactive), in double quotes.
  2567. %S the old TODO state or time stamp (inactive), in double quotes.
  2568. %u the user name.
  2569. %U full user name.
  2570. In fact, it is not a good idea to change the `state' entry,
  2571. because Agenda Log mode depends on the format of these entries."
  2572. :group 'org-todo
  2573. :group 'org-progress
  2574. :type '(list :greedy t
  2575. (cons (const :tag "Heading when closing an item" done) string)
  2576. (cons (const :tag
  2577. "Heading when changing todo state (todo sequence only)"
  2578. state) string)
  2579. (cons (const :tag "Heading when just taking a note" note) string)
  2580. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2581. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2582. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2583. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2584. (cons (const :tag "Heading when refiling" refile) string)
  2585. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2586. (unless (assq 'note org-log-note-headings)
  2587. (push '(note . "%t") org-log-note-headings))
  2588. (defcustom org-log-into-drawer nil
  2589. "Non-nil means insert state change notes and time stamps into a drawer.
  2590. When nil, state changes notes will be inserted after the headline and
  2591. any scheduling and clock lines, but not inside a drawer.
  2592. The value of this variable should be the name of the drawer to use.
  2593. LOGBOOK is proposed as the default drawer for this purpose, you can
  2594. also set this to a string to define the drawer of your choice.
  2595. A value of t is also allowed, representing \"LOGBOOK\".
  2596. A value of t or nil can also be set with on a per-file-basis with
  2597. #+STARTUP: logdrawer
  2598. #+STARTUP: nologdrawer
  2599. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2600. will be ignored.
  2601. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2602. a subtree.
  2603. Do not check directly this variable in a Lisp program. Call
  2604. function `org-log-into-drawer' instead."
  2605. :group 'org-todo
  2606. :group 'org-progress
  2607. :type '(choice
  2608. (const :tag "Not into a drawer" nil)
  2609. (const :tag "LOGBOOK" t)
  2610. (string :tag "Other")))
  2611. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2612. (defun org-log-into-drawer ()
  2613. "Name of the log drawer, as a string, or nil.
  2614. This is the value of `org-log-into-drawer'. However, if the
  2615. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2616. be used instead of the default value."
  2617. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2618. (cond ((equal p "nil") nil)
  2619. ((equal p "t") "LOGBOOK")
  2620. ((stringp p) p)
  2621. (p "LOGBOOK")
  2622. ((stringp org-log-into-drawer) org-log-into-drawer)
  2623. (org-log-into-drawer "LOGBOOK"))))
  2624. (defcustom org-log-state-notes-insert-after-drawers nil
  2625. "Non-nil means insert state change notes after any drawers in entry.
  2626. Only the drawers that *immediately* follow the headline and the
  2627. deadline/scheduled line are skipped.
  2628. When nil, insert notes right after the heading and perhaps the line
  2629. with deadline/scheduling if present.
  2630. This variable will have no effect if `org-log-into-drawer' is
  2631. set."
  2632. :group 'org-todo
  2633. :group 'org-progress
  2634. :type 'boolean)
  2635. (defcustom org-log-states-order-reversed t
  2636. "Non-nil means the latest state note will be directly after heading.
  2637. When nil, the state change notes will be ordered according to time.
  2638. This option can also be set with on a per-file-basis with
  2639. #+STARTUP: logstatesreversed
  2640. #+STARTUP: nologstatesreversed"
  2641. :group 'org-todo
  2642. :group 'org-progress
  2643. :type 'boolean)
  2644. (defcustom org-todo-repeat-to-state nil
  2645. "The TODO state to which a repeater should return the repeating task.
  2646. By default this is the first task in a TODO sequence, or the previous state
  2647. in a TODO_TYP set. But you can specify another task here.
  2648. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2649. :group 'org-todo
  2650. :version "24.1"
  2651. :type '(choice (const :tag "Head of sequence" nil)
  2652. (string :tag "Specific state")))
  2653. (defcustom org-log-repeat 'time
  2654. "Non-nil means record moving through the DONE state when triggering repeat.
  2655. An auto-repeating task is immediately switched back to TODO when
  2656. marked DONE. If you are not logging state changes (by adding \"@\"
  2657. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2658. record a closing note, there will be no record of the task moving
  2659. through DONE. This variable forces taking a note anyway.
  2660. nil Don't force a record
  2661. time Record a time stamp
  2662. note Prompt for a note and add it with template `org-log-note-headings'
  2663. This option can also be set with on a per-file-basis with
  2664. #+STARTUP: nologrepeat
  2665. #+STARTUP: logrepeat
  2666. #+STARTUP: lognoterepeat
  2667. You can have local logging settings for a subtree by setting the LOGGING
  2668. property to one or more of these keywords."
  2669. :group 'org-todo
  2670. :group 'org-progress
  2671. :type '(choice
  2672. (const :tag "Don't force a record" nil)
  2673. (const :tag "Force recording the DONE state" time)
  2674. (const :tag "Force recording a note with the DONE state" note)))
  2675. (defgroup org-priorities nil
  2676. "Priorities in Org mode."
  2677. :tag "Org Priorities"
  2678. :group 'org-todo)
  2679. (defcustom org-enable-priority-commands t
  2680. "Non-nil means priority commands are active.
  2681. When nil, these commands will be disabled, so that you never accidentally
  2682. set a priority."
  2683. :group 'org-priorities
  2684. :type 'boolean)
  2685. (defcustom org-highest-priority ?A
  2686. "The highest priority of TODO items. A character like ?A, ?B etc.
  2687. Must have a smaller ASCII number than `org-lowest-priority'."
  2688. :group 'org-priorities
  2689. :type 'character)
  2690. (defcustom org-lowest-priority ?C
  2691. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2692. Must have a larger ASCII number than `org-highest-priority'."
  2693. :group 'org-priorities
  2694. :type 'character)
  2695. (defcustom org-default-priority ?B
  2696. "The default priority of TODO items.
  2697. This is the priority an item gets if no explicit priority is given.
  2698. When starting to cycle on an empty priority the first step in the cycle
  2699. depends on `org-priority-start-cycle-with-default'. The resulting first
  2700. step priority must not exceed the range from `org-highest-priority' to
  2701. `org-lowest-priority' which means that `org-default-priority' has to be
  2702. in this range exclusive or inclusive the range boundaries. Else the
  2703. first step refuses to set the default and the second will fall back
  2704. to (depending on the command used) the highest or lowest priority."
  2705. :group 'org-priorities
  2706. :type 'character)
  2707. (defcustom org-priority-start-cycle-with-default t
  2708. "Non-nil means start with default priority when starting to cycle.
  2709. When this is nil, the first step in the cycle will be (depending on the
  2710. command used) one higher or lower than the default priority.
  2711. See also `org-default-priority'."
  2712. :group 'org-priorities
  2713. :type 'boolean)
  2714. (defcustom org-get-priority-function nil
  2715. "Function to extract the priority from a string.
  2716. The string is normally the headline. If this is nil Org computes the
  2717. priority from the priority cookie like [#A] in the headline. It returns
  2718. an integer, increasing by 1000 for each priority level.
  2719. The user can set a different function here, which should take a string
  2720. as an argument and return the numeric priority."
  2721. :group 'org-priorities
  2722. :version "24.1"
  2723. :type '(choice
  2724. (const nil)
  2725. (function)))
  2726. (defgroup org-time nil
  2727. "Options concerning time stamps and deadlines in Org mode."
  2728. :tag "Org Time"
  2729. :group 'org)
  2730. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2731. "Number of minutes to round time stamps to.
  2732. \\<org-mode-map>\
  2733. These are two values, the first applies when first creating a time stamp.
  2734. The second applies when changing it with the commands `S-up' and `S-down'.
  2735. When changing the time stamp, this means that it will change in steps
  2736. of N minutes, as given by the second value.
  2737. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2738. numbers should be factors of 60, so for example 5, 10, 15.
  2739. When this is larger than 1, you can still force an exact time stamp by using
  2740. a double prefix argument to a time stamp command like \
  2741. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2742. and by using a prefix arg to `S-up/down' to specify the exact number
  2743. of minutes to shift."
  2744. :group 'org-time
  2745. :get (lambda (var) ; Make sure both elements are there
  2746. (if (integerp (default-value var))
  2747. (list (default-value var) 5)
  2748. (default-value var)))
  2749. :type '(list
  2750. (integer :tag "when inserting times")
  2751. (integer :tag "when modifying times")))
  2752. ;; Normalize old customizations of this variable.
  2753. (when (integerp org-time-stamp-rounding-minutes)
  2754. (setq org-time-stamp-rounding-minutes
  2755. (list org-time-stamp-rounding-minutes
  2756. org-time-stamp-rounding-minutes)))
  2757. (defcustom org-display-custom-times nil
  2758. "Non-nil means overlay custom formats over all time stamps.
  2759. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2760. To turn this on on a per-file basis, insert anywhere in the file:
  2761. #+STARTUP: customtime"
  2762. :group 'org-time
  2763. :set 'set-default
  2764. :type 'sexp)
  2765. (make-variable-buffer-local 'org-display-custom-times)
  2766. (defcustom org-time-stamp-custom-formats
  2767. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2768. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2769. These are overlaid over the default ISO format if the variable
  2770. `org-display-custom-times' is set. Time like %H:%M should be at the
  2771. end of the second format. The custom formats are also honored by export
  2772. commands, if custom time display is turned on at the time of export."
  2773. :group 'org-time
  2774. :type 'sexp)
  2775. (defun org-time-stamp-format (&optional long inactive)
  2776. "Get the right format for a time string."
  2777. (let ((f (if long (cdr org-time-stamp-formats)
  2778. (car org-time-stamp-formats))))
  2779. (if inactive
  2780. (concat "[" (substring f 1 -1) "]")
  2781. f)))
  2782. (defcustom org-deadline-warning-days 14
  2783. "Number of days before expiration during which a deadline becomes active.
  2784. This variable governs the display in sparse trees and in the agenda.
  2785. When 0 or negative, it means use this number (the absolute value of it)
  2786. even if a deadline has a different individual lead time specified.
  2787. Custom commands can set this variable in the options section."
  2788. :group 'org-time
  2789. :group 'org-agenda-daily/weekly
  2790. :type 'integer)
  2791. (defcustom org-scheduled-delay-days 0
  2792. "Number of days before a scheduled item becomes active.
  2793. This variable governs the display in sparse trees and in the agenda.
  2794. The default value (i.e. 0) means: don't delay scheduled item.
  2795. When negative, it means use this number (the absolute value of it)
  2796. even if a scheduled item has a different individual delay time
  2797. specified.
  2798. Custom commands can set this variable in the options section."
  2799. :group 'org-time
  2800. :group 'org-agenda-daily/weekly
  2801. :version "24.4"
  2802. :package-version '(Org . "8.0")
  2803. :type 'integer)
  2804. (defcustom org-read-date-prefer-future t
  2805. "Non-nil means assume future for incomplete date input from user.
  2806. This affects the following situations:
  2807. 1. The user gives a month but not a year.
  2808. For example, if it is April and you enter \"feb 2\", this will be read
  2809. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2810. 2. The user gives a day, but no month.
  2811. For example, if today is the 15th, and you enter \"3\", Org will read
  2812. this as the third of *next* month. However, if you enter \"17\",
  2813. it will be considered as *this* month.
  2814. If you set this variable to the symbol `time', then also the following
  2815. will work:
  2816. 3. If the user gives a time.
  2817. If the time is before now, it will be interpreted as tomorrow.
  2818. Currently none of this works for ISO week specifications.
  2819. When this option is nil, the current day, month and year will always be
  2820. used as defaults.
  2821. See also `org-agenda-jump-prefer-future'."
  2822. :group 'org-time
  2823. :type '(choice
  2824. (const :tag "Never" nil)
  2825. (const :tag "Check month and day" t)
  2826. (const :tag "Check month, day, and time" time)))
  2827. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2828. "Should the agenda jump command prefer the future for incomplete dates?
  2829. The default is to do the same as configured in `org-read-date-prefer-future'.
  2830. But you can also set a deviating value here.
  2831. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2832. :group 'org-agenda
  2833. :group 'org-time
  2834. :version "24.1"
  2835. :type '(choice
  2836. (const :tag "Use org-read-date-prefer-future"
  2837. org-read-date-prefer-future)
  2838. (const :tag "Never" nil)
  2839. (const :tag "Always" t)))
  2840. (defcustom org-read-date-force-compatible-dates t
  2841. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2842. Depending on the system Emacs is running on, certain dates cannot
  2843. be represented with the type used internally to represent time.
  2844. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2845. correctly. Some systems allow for earlier dates, some for later,
  2846. some for both. One way to find out it to insert any date into an
  2847. Org buffer, putting the cursor on the year and hitting S-up and
  2848. S-down to test the range.
  2849. When this variable is set to t, the date/time prompt will not let
  2850. you specify dates outside the 1970-2037 range, so it is certain that
  2851. these dates will work in whatever version of Emacs you are
  2852. running, and also that you can move a file from one Emacs implementation
  2853. to another. WHenever Org is forcing the year for you, it will display
  2854. a message and beep.
  2855. When this variable is nil, Org will check if the date is
  2856. representable in the specific Emacs implementation you are using.
  2857. If not, it will force a year, usually the current year, and beep
  2858. to remind you. Currently this setting is not recommended because
  2859. the likelihood that you will open your Org files in an Emacs that
  2860. has limited date range is not negligible.
  2861. A workaround for this problem is to use diary sexp dates for time
  2862. stamps outside of this range."
  2863. :group 'org-time
  2864. :version "24.1"
  2865. :type 'boolean)
  2866. (defcustom org-read-date-display-live t
  2867. "Non-nil means display current interpretation of date prompt live.
  2868. This display will be in an overlay, in the minibuffer."
  2869. :group 'org-time
  2870. :type 'boolean)
  2871. (defcustom org-read-date-popup-calendar t
  2872. "Non-nil means pop up a calendar when prompting for a date.
  2873. In the calendar, the date can be selected with mouse-1. However, the
  2874. minibuffer will also be active, and you can simply enter the date as well.
  2875. When nil, only the minibuffer will be available."
  2876. :group 'org-time
  2877. :type 'boolean)
  2878. (defvaralias 'org-popup-calendar-for-date-prompt
  2879. 'org-read-date-popup-calendar)
  2880. (defcustom org-extend-today-until 0
  2881. "The hour when your day really ends. Must be an integer.
  2882. This has influence for the following applications:
  2883. - When switching the agenda to \"today\". It it is still earlier than
  2884. the time given here, the day recognized as TODAY is actually yesterday.
  2885. - When a date is read from the user and it is still before the time given
  2886. here, the current date and time will be assumed to be yesterday, 23:59.
  2887. Also, timestamps inserted in capture templates follow this rule.
  2888. IMPORTANT: This is a feature whose implementation is and likely will
  2889. remain incomplete. Really, it is only here because past midnight seems to
  2890. be the favorite working time of John Wiegley :-)"
  2891. :group 'org-time
  2892. :type 'integer)
  2893. (defcustom org-use-effective-time nil
  2894. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2895. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2896. \"effective time\" of any timestamps between midnight and 8am will be
  2897. 23:59 of the previous day."
  2898. :group 'org-time
  2899. :version "24.1"
  2900. :type 'boolean)
  2901. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2902. "When non-nil, use the last clock out time for `org-todo'.
  2903. Note that this option has precedence over the combined use of
  2904. `org-use-effective-time' and `org-extend-today-until'."
  2905. :group 'org-time
  2906. :version "24.4"
  2907. :package-version '(Org . "8.0")
  2908. :type 'boolean)
  2909. (defcustom org-edit-timestamp-down-means-later nil
  2910. "Non-nil means S-down will increase the time in a time stamp.
  2911. When nil, S-up will increase."
  2912. :group 'org-time
  2913. :type 'boolean)
  2914. (defcustom org-calendar-follow-timestamp-change t
  2915. "Non-nil means make the calendar window follow timestamp changes.
  2916. When a timestamp is modified and the calendar window is visible, it will be
  2917. moved to the new date."
  2918. :group 'org-time
  2919. :type 'boolean)
  2920. (defgroup org-tags nil
  2921. "Options concerning tags in Org mode."
  2922. :tag "Org Tags"
  2923. :group 'org)
  2924. (defcustom org-tag-alist nil
  2925. "Default tags available in Org files.
  2926. The value of this variable is an alist. Associations either:
  2927. (TAG)
  2928. (TAG . SELECT)
  2929. (SPECIAL)
  2930. where TAG is a tag as a string, SELECT is character, used to
  2931. select that tag through the fast tag selection interface, and
  2932. SPECIAL is one of the following keywords: `:startgroup',
  2933. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2934. `:newline'. These keywords are used to define a hierarchy of
  2935. tags. See manual for details.
  2936. When this variable is nil, Org mode bases tag input on what is
  2937. already in the buffer. The value can be overridden locally by
  2938. using a TAGS keyword, e.g.,
  2939. #+TAGS: tag1 tag2
  2940. See also `org-tag-persistent-alist' to sidestep this behavior."
  2941. :group 'org-tags
  2942. :type '(repeat
  2943. (choice
  2944. (cons :tag "Tag with key"
  2945. (string :tag "Tag name")
  2946. (character :tag "Access char"))
  2947. (list :tag "Tag" (string :tag "Tag name"))
  2948. (const :tag "Start radio group" (:startgroup))
  2949. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2950. (const :tag "Group tags delimiter" (:grouptags))
  2951. (const :tag "End radio group" (:endgroup))
  2952. (const :tag "End tag group, non distinct" (:endgrouptag))
  2953. (const :tag "New line" (:newline)))))
  2954. (defcustom org-tag-persistent-alist nil
  2955. "Tags always available in Org files.
  2956. The value of this variable is an alist. Associations either:
  2957. (TAG)
  2958. (TAG . SELECT)
  2959. (SPECIAL)
  2960. where TAG is a tag as a string, SELECT is a character, used to
  2961. select that tag through the fast tag selection interface, and
  2962. SPECIAL is one of the following keywords: `:startgroup',
  2963. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2964. `:newline'. These keywords are used to define a hierarchy of
  2965. tags. See manual for details.
  2966. Unlike to `org-tag-alist', tags defined in this variable do not
  2967. depend on a local TAGS keyword. Instead, to disable these tags
  2968. on a per-file basis, insert anywhere in the file:
  2969. #+STARTUP: noptag"
  2970. :group 'org-tags
  2971. :type '(repeat
  2972. (choice
  2973. (cons :tag "Tag with key"
  2974. (string :tag "Tag name")
  2975. (character :tag "Access char"))
  2976. (list :tag "Tag" (string :tag "Tag name"))
  2977. (const :tag "Start radio group" (:startgroup))
  2978. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2979. (const :tag "Group tags delimiter" (:grouptags))
  2980. (const :tag "End radio group" (:endgroup))
  2981. (const :tag "End tag group, non distinct" (:endgrouptag))
  2982. (const :tag "New line" (:newline)))))
  2983. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2984. "If non-nil, always offer completion for all tags of all agenda files.
  2985. Instead of customizing this variable directly, you might want to
  2986. set it locally for capture buffers, because there no list of
  2987. tags in that file can be created dynamically (there are none).
  2988. (add-hook \\='org-capture-mode-hook
  2989. (lambda ()
  2990. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2991. :group 'org-tags
  2992. :version "24.1"
  2993. :type 'boolean)
  2994. (defvar org-file-tags nil
  2995. "List of tags that can be inherited by all entries in the file.
  2996. The tags will be inherited if the variable `org-use-tag-inheritance'
  2997. says they should be.
  2998. This variable is populated from #+FILETAGS lines.")
  2999. (defcustom org-use-fast-tag-selection 'auto
  3000. "Non-nil means use fast tag selection scheme.
  3001. This is a special interface to select and deselect tags with single keys.
  3002. When nil, fast selection is never used.
  3003. When the symbol `auto', fast selection is used if and only if selection
  3004. characters for tags have been configured, either through the variable
  3005. `org-tag-alist' or through a #+TAGS line in the buffer.
  3006. When t, fast selection is always used and selection keys are assigned
  3007. automatically if necessary."
  3008. :group 'org-tags
  3009. :type '(choice
  3010. (const :tag "Always" t)
  3011. (const :tag "Never" nil)
  3012. (const :tag "When selection characters are configured" auto)))
  3013. (defcustom org-fast-tag-selection-single-key nil
  3014. "Non-nil means fast tag selection exits after first change.
  3015. When nil, you have to press RET to exit it.
  3016. During fast tag selection, you can toggle this flag with `C-c'.
  3017. This variable can also have the value `expert'. In this case, the window
  3018. displaying the tags menu is not even shown, until you press C-c again."
  3019. :group 'org-tags
  3020. :type '(choice
  3021. (const :tag "No" nil)
  3022. (const :tag "Yes" t)
  3023. (const :tag "Expert" expert)))
  3024. (defvar org-fast-tag-selection-include-todo nil
  3025. "Non-nil means fast tags selection interface will also offer TODO states.
  3026. This is an undocumented feature, you should not rely on it.")
  3027. (defcustom org-tags-column -77
  3028. "The column to which tags should be indented in a headline.
  3029. If this number is positive, it specifies the column. If it is negative,
  3030. it means that the tags should be flushright to that column. For example,
  3031. -80 works well for a normal 80 character screen.
  3032. When 0, place tags directly after headline text, with only one space in
  3033. between."
  3034. :group 'org-tags
  3035. :type 'integer)
  3036. (defcustom org-auto-align-tags t
  3037. "Non-nil keeps tags aligned when modifying headlines.
  3038. Some operations (i.e. demoting) change the length of a headline and
  3039. therefore shift the tags around. With this option turned on, after
  3040. each such operation the tags are again aligned to `org-tags-column'."
  3041. :group 'org-tags
  3042. :type 'boolean)
  3043. (defcustom org-use-tag-inheritance t
  3044. "Non-nil means tags in levels apply also for sublevels.
  3045. When nil, only the tags directly given in a specific line apply there.
  3046. This may also be a list of tags that should be inherited, or a regexp that
  3047. matches tags that should be inherited. Additional control is possible
  3048. with the variable `org-tags-exclude-from-inheritance' which gives an
  3049. explicit list of tags to be excluded from inheritance, even if the value of
  3050. `org-use-tag-inheritance' would select it for inheritance.
  3051. If this option is t, a match early-on in a tree can lead to a large
  3052. number of matches in the subtree when constructing the agenda or creating
  3053. a sparse tree. If you only want to see the first match in a tree during
  3054. a search, check out the variable `org-tags-match-list-sublevels'."
  3055. :group 'org-tags
  3056. :type '(choice
  3057. (const :tag "Not" nil)
  3058. (const :tag "Always" t)
  3059. (repeat :tag "Specific tags" (string :tag "Tag"))
  3060. (regexp :tag "Tags matched by regexp")))
  3061. (defcustom org-tags-exclude-from-inheritance nil
  3062. "List of tags that should never be inherited.
  3063. This is a way to exclude a few tags from inheritance. For way to do
  3064. the opposite, to actively allow inheritance for selected tags,
  3065. see the variable `org-use-tag-inheritance'."
  3066. :group 'org-tags
  3067. :type '(repeat (string :tag "Tag")))
  3068. (defun org-tag-inherit-p (tag)
  3069. "Check if TAG is one that should be inherited."
  3070. (cond
  3071. ((member tag org-tags-exclude-from-inheritance) nil)
  3072. ((eq org-use-tag-inheritance t) t)
  3073. ((not org-use-tag-inheritance) nil)
  3074. ((stringp org-use-tag-inheritance)
  3075. (string-match org-use-tag-inheritance tag))
  3076. ((listp org-use-tag-inheritance)
  3077. (member tag org-use-tag-inheritance))
  3078. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3079. (defcustom org-tags-match-list-sublevels t
  3080. "Non-nil means list also sublevels of headlines matching a search.
  3081. This variable applies to tags/property searches, and also to stuck
  3082. projects because this search is based on a tags match as well.
  3083. When set to the symbol `indented', sublevels are indented with
  3084. leading dots.
  3085. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3086. the sublevels of a headline matching a tag search often also match
  3087. the same search. Listing all of them can create very long lists.
  3088. Setting this variable to nil causes subtrees of a match to be skipped.
  3089. This variable is semi-obsolete and probably should always be true. It
  3090. is better to limit inheritance to certain tags using the variables
  3091. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3092. :group 'org-tags
  3093. :type '(choice
  3094. (const :tag "No, don't list them" nil)
  3095. (const :tag "Yes, do list them" t)
  3096. (const :tag "List them, indented with leading dots" indented)))
  3097. (defcustom org-tags-sort-function nil
  3098. "When set, tags are sorted using this function as a comparator."
  3099. :group 'org-tags
  3100. :type '(choice
  3101. (const :tag "No sorting" nil)
  3102. (const :tag "Alphabetical" string<)
  3103. (const :tag "Reverse alphabetical" string>)
  3104. (function :tag "Custom function" nil)))
  3105. (defvar org-tags-history nil
  3106. "History of minibuffer reads for tags.")
  3107. (defvar org-last-tags-completion-table nil
  3108. "The last used completion table for tags.")
  3109. (defvar org-after-tags-change-hook nil
  3110. "Hook that is run after the tags in a line have changed.")
  3111. (defgroup org-properties nil
  3112. "Options concerning properties in Org mode."
  3113. :tag "Org Properties"
  3114. :group 'org)
  3115. (defcustom org-property-format "%-10s %s"
  3116. "How property key/value pairs should be formatted by `indent-line'.
  3117. When `indent-line' hits a property definition, it will format the line
  3118. according to this format, mainly to make sure that the values are
  3119. lined-up with respect to each other."
  3120. :group 'org-properties
  3121. :type 'string)
  3122. (defcustom org-properties-postprocess-alist nil
  3123. "Alist of properties and functions to adjust inserted values.
  3124. Elements of this alist must be of the form
  3125. ([string] [function])
  3126. where [string] must be a property name and [function] must be a
  3127. lambda expression: this lambda expression must take one argument,
  3128. the value to adjust, and return the new value as a string.
  3129. For example, this element will allow the property \"Remaining\"
  3130. to be updated wrt the relation between the \"Effort\" property
  3131. and the clock summary:
  3132. ((\"Remaining\" (lambda(value)
  3133. (let ((clocksum (org-clock-sum-current-item))
  3134. (effort (org-duration-to-minutes
  3135. (org-entry-get (point) \"Effort\"))))
  3136. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3137. :group 'org-properties
  3138. :version "24.1"
  3139. :type '(alist :key-type (string :tag "Property")
  3140. :value-type (function :tag "Function")))
  3141. (defcustom org-use-property-inheritance nil
  3142. "Non-nil means properties apply also for sublevels.
  3143. This setting is chiefly used during property searches. Turning it on can
  3144. cause significant overhead when doing a search, which is why it is not
  3145. on by default.
  3146. When nil, only the properties directly given in the current entry count.
  3147. When t, every property is inherited. The value may also be a list of
  3148. properties that should have inheritance, or a regular expression matching
  3149. properties that should be inherited.
  3150. However, note that some special properties use inheritance under special
  3151. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3152. and the properties ending in \"_ALL\" when they are used as descriptor
  3153. for valid values of a property.
  3154. Note for programmers:
  3155. When querying an entry with `org-entry-get', you can control if inheritance
  3156. should be used. By default, `org-entry-get' looks only at the local
  3157. properties. You can request inheritance by setting the inherit argument
  3158. to t (to force inheritance) or to `selective' (to respect the setting
  3159. in this variable)."
  3160. :group 'org-properties
  3161. :type '(choice
  3162. (const :tag "Not" nil)
  3163. (const :tag "Always" t)
  3164. (repeat :tag "Specific properties" (string :tag "Property"))
  3165. (regexp :tag "Properties matched by regexp")))
  3166. (defun org-property-inherit-p (property)
  3167. "Return a non-nil value if PROPERTY should be inherited."
  3168. (cond
  3169. ((eq org-use-property-inheritance t) t)
  3170. ((not org-use-property-inheritance) nil)
  3171. ((stringp org-use-property-inheritance)
  3172. (string-match org-use-property-inheritance property))
  3173. ((listp org-use-property-inheritance)
  3174. (member-ignore-case property org-use-property-inheritance))
  3175. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3176. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3177. "The default column format, if no other format has been defined.
  3178. This variable can be set on the per-file basis by inserting a line
  3179. #+COLUMNS: %25ITEM ....."
  3180. :group 'org-properties
  3181. :type 'string)
  3182. (defcustom org-columns-ellipses ".."
  3183. "The ellipses to be used when a field in column view is truncated.
  3184. When this is the empty string, as many characters as possible are shown,
  3185. but then there will be no visual indication that the field has been truncated.
  3186. When this is a string of length N, the last N characters of a truncated
  3187. field are replaced by this string. If the column is narrower than the
  3188. ellipses string, only part of the ellipses string will be shown."
  3189. :group 'org-properties
  3190. :type 'string)
  3191. (defconst org-global-properties-fixed
  3192. '(("VISIBILITY_ALL" . "folded children content all")
  3193. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3194. "List of property/value pairs that can be inherited by any entry.
  3195. These are fixed values, for the preset properties. The user variable
  3196. that can be used to add to this list is `org-global-properties'.
  3197. The entries in this list are cons cells where the car is a property
  3198. name and cdr is a string with the value. If the value represents
  3199. multiple items like an \"_ALL\" property, separate the items by
  3200. spaces.")
  3201. (defcustom org-global-properties nil
  3202. "List of property/value pairs that can be inherited by any entry.
  3203. This list will be combined with the constant `org-global-properties-fixed'.
  3204. The entries in this list are cons cells where the car is a property
  3205. name and cdr is a string with the value.
  3206. You can set buffer-local values for the same purpose in the variable
  3207. `org-file-properties' this by adding lines like
  3208. #+PROPERTY: NAME VALUE"
  3209. :group 'org-properties
  3210. :type '(repeat
  3211. (cons (string :tag "Property")
  3212. (string :tag "Value"))))
  3213. (defvar-local org-file-properties nil
  3214. "List of property/value pairs that can be inherited by any entry.
  3215. Valid for the current buffer.
  3216. This variable is populated from #+PROPERTY lines.")
  3217. (defgroup org-agenda nil
  3218. "Options concerning agenda views in Org mode."
  3219. :tag "Org Agenda"
  3220. :group 'org)
  3221. (defvar-local org-category nil
  3222. "Variable used by org files to set a category for agenda display.
  3223. Such files should use a file variable to set it, for example
  3224. # -*- mode: org; org-category: \"ELisp\"
  3225. or contain a special line
  3226. #+CATEGORY: ELisp
  3227. If the file does not specify a category, then file's base name
  3228. is used instead.")
  3229. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3230. (defcustom org-agenda-files nil
  3231. "The files to be used for agenda display.
  3232. If an entry is a directory, all files in that directory that are matched
  3233. by `org-agenda-file-regexp' will be part of the file list.
  3234. If the value of the variable is not a list but a single file name, then
  3235. the list of agenda files is actually stored and maintained in that file,
  3236. one agenda file per line. In this file paths can be given relative to
  3237. `org-directory'. Tilde expansion and environment variable substitution
  3238. are also made.
  3239. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3240. and removed with `\\[org-remove-file]'."
  3241. :group 'org-agenda
  3242. :type '(choice
  3243. (repeat :tag "List of files and directories" file)
  3244. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3245. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3246. "Regular expression to match files for `org-agenda-files'.
  3247. If any element in the list in that variable contains a directory instead
  3248. of a normal file, all files in that directory that are matched by this
  3249. regular expression will be included."
  3250. :group 'org-agenda
  3251. :type 'regexp)
  3252. (defcustom org-agenda-text-search-extra-files nil
  3253. "List of extra files to be searched by text search commands.
  3254. These files will be searched in addition to the agenda files by the
  3255. commands `org-search-view' (`\\[org-agenda] s') \
  3256. and `org-occur-in-agenda-files'.
  3257. Note that these files will only be searched for text search commands,
  3258. not for the other agenda views like todo lists, tag searches or the weekly
  3259. agenda. This variable is intended to list notes and possibly archive files
  3260. that should also be searched by these two commands.
  3261. In fact, if the first element in the list is the symbol `agenda-archives',
  3262. then all archive files of all agenda files will be added to the search
  3263. scope."
  3264. :group 'org-agenda
  3265. :type '(set :greedy t
  3266. (const :tag "Agenda Archives" agenda-archives)
  3267. (repeat :inline t (file))))
  3268. (defvaralias 'org-agenda-multi-occur-extra-files
  3269. 'org-agenda-text-search-extra-files)
  3270. (defcustom org-agenda-skip-unavailable-files nil
  3271. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3272. A nil value means to remove them, after a query, from the list."
  3273. :group 'org-agenda
  3274. :type 'boolean)
  3275. (defcustom org-calendar-to-agenda-key [?c]
  3276. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3277. The command `org-calendar-goto-agenda' will be bound to this key. The
  3278. default is the character `c' because then `c' can be used to switch back and
  3279. forth between agenda and calendar."
  3280. :group 'org-agenda
  3281. :type 'sexp)
  3282. (defcustom org-calendar-insert-diary-entry-key [?i]
  3283. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3284. This option is irrelevant until `org-agenda-diary-file' has been configured
  3285. to point to an Org file. When that is the case, the command
  3286. `org-agenda-diary-entry' will be bound to the key given here, by default
  3287. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3288. if you want to continue doing this, you need to change this to a different
  3289. key."
  3290. :group 'org-agenda
  3291. :type 'sexp)
  3292. (defcustom org-agenda-diary-file 'diary-file
  3293. "File to which to add new entries with the `i' key in agenda and calendar.
  3294. When this is the symbol `diary-file', the functionality in the Emacs
  3295. calendar will be used to add entries to the `diary-file'. But when this
  3296. points to a file, `org-agenda-diary-entry' will be used instead."
  3297. :group 'org-agenda
  3298. :type '(choice
  3299. (const :tag "The standard Emacs diary file" diary-file)
  3300. (file :tag "Special Org file diary entries")))
  3301. (eval-after-load "calendar"
  3302. '(progn
  3303. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3304. 'org-calendar-goto-agenda)
  3305. (add-hook 'calendar-mode-hook
  3306. (lambda ()
  3307. (unless (eq org-agenda-diary-file 'diary-file)
  3308. (define-key calendar-mode-map
  3309. org-calendar-insert-diary-entry-key
  3310. 'org-agenda-diary-entry))))))
  3311. (defgroup org-latex nil
  3312. "Options for embedding LaTeX code into Org mode."
  3313. :tag "Org LaTeX"
  3314. :group 'org)
  3315. (defcustom org-format-latex-options
  3316. '(:foreground default :background default :scale 1.0
  3317. :html-foreground "Black" :html-background "Transparent"
  3318. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3319. "Options for creating images from LaTeX fragments.
  3320. This is a property list with the following properties:
  3321. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3322. `default' means use the foreground of the default face.
  3323. `auto' means use the foreground from the text face.
  3324. :background the background color, or \"Transparent\".
  3325. `default' means use the background of the default face.
  3326. `auto' means use the background from the text face.
  3327. :scale a scaling factor for the size of the images, to get more pixels
  3328. :html-foreground, :html-background, :html-scale
  3329. the same numbers for HTML export.
  3330. :matchers a list indicating which matchers should be used to
  3331. find LaTeX fragments. Valid members of this list are:
  3332. \"begin\" find environments
  3333. \"$1\" find single characters surrounded by $.$
  3334. \"$\" find math expressions surrounded by $...$
  3335. \"$$\" find math expressions surrounded by $$....$$
  3336. \"\\(\" find math expressions surrounded by \\(...\\)
  3337. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3338. :group 'org-latex
  3339. :type 'plist)
  3340. (defcustom org-format-latex-signal-error t
  3341. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3342. When nil, just push out a message."
  3343. :group 'org-latex
  3344. :version "24.1"
  3345. :type 'boolean)
  3346. (defcustom org-latex-to-mathml-jar-file nil
  3347. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3348. Use this to specify additional executable file say a jar file.
  3349. When using MathToWeb as the converter, specify the full-path to
  3350. your mathtoweb.jar file."
  3351. :group 'org-latex
  3352. :version "24.1"
  3353. :type '(choice
  3354. (const :tag "None" nil)
  3355. (file :tag "JAR file" :must-match t)))
  3356. (defcustom org-latex-to-mathml-convert-command nil
  3357. "Command to convert LaTeX fragments to MathML.
  3358. Replace format-specifiers in the command as noted below and use
  3359. `shell-command' to convert LaTeX to MathML.
  3360. %j: Executable file in fully expanded form as specified by
  3361. `org-latex-to-mathml-jar-file'.
  3362. %I: Input LaTeX file in fully expanded form.
  3363. %i: The latex fragment to be converted.
  3364. %o: Output MathML file.
  3365. This command is used by `org-create-math-formula'.
  3366. When using MathToWeb as the converter, set this option to
  3367. \"java -jar %j -unicode -force -df %o %I\".
  3368. When using LaTeXML set this option to
  3369. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3370. :group 'org-latex
  3371. :version "24.1"
  3372. :type '(choice
  3373. (const :tag "None" nil)
  3374. (string :tag "\nShell command")))
  3375. (defcustom org-preview-latex-default-process 'dvipng
  3376. "The default process to convert LaTeX fragments to image files.
  3377. All available processes and theirs documents can be found in
  3378. `org-preview-latex-process-alist', which see."
  3379. :group 'org-latex
  3380. :version "26.1"
  3381. :package-version '(Org . "9.0")
  3382. :type 'symbol)
  3383. (defcustom org-preview-latex-process-alist
  3384. '((dvipng
  3385. :programs ("latex" "dvipng")
  3386. :description "dvi > png"
  3387. :message "you need to install the programs: latex and dvipng."
  3388. :image-input-type "dvi"
  3389. :image-output-type "png"
  3390. :image-size-adjust (1.0 . 1.0)
  3391. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3392. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3393. (dvisvgm
  3394. :programs ("latex" "dvisvgm")
  3395. :description "dvi > svg"
  3396. :message "you need to install the programs: latex and dvisvgm."
  3397. :use-xcolor t
  3398. :image-input-type "dvi"
  3399. :image-output-type "svg"
  3400. :image-size-adjust (1.7 . 1.5)
  3401. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3402. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3403. (imagemagick
  3404. :programs ("latex" "convert")
  3405. :description "pdf > png"
  3406. :message "you need to install the programs: latex and imagemagick."
  3407. :use-xcolor t
  3408. :image-input-type "pdf"
  3409. :image-output-type "png"
  3410. :image-size-adjust (1.0 . 1.0)
  3411. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3412. :image-converter
  3413. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3414. "Definitions of external processes for LaTeX previewing.
  3415. Org mode can use some external commands to generate TeX snippet's images for
  3416. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3417. `org-create-formula-image' how to call them.
  3418. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3419. PROPERTIES accepts the following attributes:
  3420. :programs list of strings, required programs.
  3421. :description string, describe the process.
  3422. :message string, message it when required programs cannot be found.
  3423. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3424. :image-output-type string, output file type of image converter (e.g., \"png\").
  3425. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3426. deal with background and foreground color of image.
  3427. Otherwise, dvipng style background and foreground color
  3428. format are generated. You may then refer to them in
  3429. command options with \"%F\" and \"%B\".
  3430. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3431. image size showed in buffer and the cdr element is for
  3432. HTML file. This option is only useful for process
  3433. developers, users should use variable
  3434. `org-format-latex-options' instead.
  3435. :post-clean list of strings, files matched are to be cleaned up once
  3436. the image is generated. When nil, the files with \".dvi\",
  3437. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3438. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3439. be cleaned up.
  3440. :latex-header list of strings, the LaTeX header of the snippet file.
  3441. When nil, the fallback value is used instead, which is
  3442. controlled by `org-format-latex-header',
  3443. `org-latex-default-packages-alist' and
  3444. `org-latex-packages-alist', which see.
  3445. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3446. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3447. replaced with values defined below.
  3448. :image-converter list of image converter commands strings. Each of them is
  3449. given to the shell and supports any of the following
  3450. place-holders defined below.
  3451. Place-holders used by `:image-converter' and `:latex-compiler':
  3452. %f input file name
  3453. %b base name of input file
  3454. %o base directory of input file
  3455. %O absolute output file name
  3456. Place-holders only used by `:image-converter':
  3457. %F foreground of image
  3458. %B background of image
  3459. %D dpi, which is used to adjust image size by some processing commands.
  3460. %S the image size scale ratio, which is used to adjust image size by some
  3461. processing commands."
  3462. :group 'org-latex
  3463. :version "26.1"
  3464. :package-version '(Org . "9.0")
  3465. :type '(alist :tag "LaTeX to image backends"
  3466. :value-type (plist)))
  3467. (defcustom org-preview-latex-image-directory "ltximg/"
  3468. "Path to store latex preview images.
  3469. A relative path here creates many directories relative to the
  3470. processed org files paths. An absolute path puts all preview
  3471. images at the same place."
  3472. :group 'org-latex
  3473. :version "26.1"
  3474. :package-version '(Org . "9.0")
  3475. :type 'string)
  3476. (defun org-format-latex-mathml-available-p ()
  3477. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3478. (save-match-data
  3479. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3480. org-latex-to-mathml-convert-command)
  3481. (let ((executable (car (split-string
  3482. org-latex-to-mathml-convert-command))))
  3483. (when (executable-find executable)
  3484. (if (string-match
  3485. "%j" org-latex-to-mathml-convert-command)
  3486. (file-readable-p org-latex-to-mathml-jar-file)
  3487. t))))))
  3488. (defcustom org-format-latex-header "\\documentclass{article}
  3489. \\usepackage[usenames]{color}
  3490. \[PACKAGES]
  3491. \[DEFAULT-PACKAGES]
  3492. \\pagestyle{empty} % do not remove
  3493. % The settings below are copied from fullpage.sty
  3494. \\setlength{\\textwidth}{\\paperwidth}
  3495. \\addtolength{\\textwidth}{-3cm}
  3496. \\setlength{\\oddsidemargin}{1.5cm}
  3497. \\addtolength{\\oddsidemargin}{-2.54cm}
  3498. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3499. \\setlength{\\textheight}{\\paperheight}
  3500. \\addtolength{\\textheight}{-\\headheight}
  3501. \\addtolength{\\textheight}{-\\headsep}
  3502. \\addtolength{\\textheight}{-\\footskip}
  3503. \\addtolength{\\textheight}{-3cm}
  3504. \\setlength{\\topmargin}{1.5cm}
  3505. \\addtolength{\\topmargin}{-2.54cm}"
  3506. "The document header used for processing LaTeX fragments.
  3507. It is imperative that this header make sure that no page number
  3508. appears on the page. The package defined in the variables
  3509. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3510. will either replace the placeholder \"[PACKAGES]\" in this
  3511. header, or they will be appended."
  3512. :group 'org-latex
  3513. :type 'string)
  3514. (defun org-set-packages-alist (var val)
  3515. "Set the packages alist and make sure it has 3 elements per entry."
  3516. (set var (mapcar (lambda (x)
  3517. (if (and (consp x) (= (length x) 2))
  3518. (list (car x) (nth 1 x) t)
  3519. x))
  3520. val)))
  3521. (defun org-get-packages-alist (var)
  3522. "Get the packages alist and make sure it has 3 elements per entry."
  3523. (mapcar (lambda (x)
  3524. (if (and (consp x) (= (length x) 2))
  3525. (list (car x) (nth 1 x) t)
  3526. x))
  3527. (default-value var)))
  3528. (defcustom org-latex-default-packages-alist
  3529. '(("AUTO" "inputenc" t ("pdflatex"))
  3530. ("T1" "fontenc" t ("pdflatex"))
  3531. ("" "graphicx" t)
  3532. ("" "grffile" t)
  3533. ("" "longtable" nil)
  3534. ("" "wrapfig" nil)
  3535. ("" "rotating" nil)
  3536. ("normalem" "ulem" t)
  3537. ("" "amsmath" t)
  3538. ("" "textcomp" t)
  3539. ("" "amssymb" t)
  3540. ("" "capt-of" nil)
  3541. ("" "hyperref" nil))
  3542. "Alist of default packages to be inserted in the header.
  3543. Change this only if one of the packages here causes an
  3544. incompatibility with another package you are using.
  3545. The packages in this list are needed by one part or another of
  3546. Org mode to function properly:
  3547. - inputenc, fontenc: for basic font and character selection
  3548. - graphicx: for including images
  3549. - grffile: allow periods and spaces in graphics file names
  3550. - longtable: For multipage tables
  3551. - wrapfig: for figure placement
  3552. - rotating: for sideways figures and tables
  3553. - ulem: for underline and strike-through
  3554. - amsmath: for subscript and superscript and math environments
  3555. - textcomp, amssymb: for various symbols used
  3556. for interpreting the entities in `org-entities'. You can skip
  3557. some of these packages if you don't use any of their symbols.
  3558. - capt-of: for captions outside of floats
  3559. - hyperref: for cross references
  3560. Therefore you should not modify this variable unless you know
  3561. what you are doing. The one reason to change it anyway is that
  3562. you might be loading some other package that conflicts with one
  3563. of the default packages. Each element is either a cell or
  3564. a string.
  3565. A cell is of the format
  3566. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3567. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3568. when compiling LaTeX snippets into images for inclusion into
  3569. non-LaTeX output. COMPILERS is a list of compilers that should
  3570. include the package, see `org-latex-compiler'. If the document
  3571. compiler is not in the list, and the list is non-nil, the package
  3572. will not be inserted in the final document.
  3573. A string will be inserted as-is in the header of the document."
  3574. :group 'org-latex
  3575. :group 'org-export-latex
  3576. :set 'org-set-packages-alist
  3577. :get 'org-get-packages-alist
  3578. :version "26.1"
  3579. :package-version '(Org . "8.3")
  3580. :type '(repeat
  3581. (choice
  3582. (list :tag "options/package pair"
  3583. (string :tag "options")
  3584. (string :tag "package")
  3585. (boolean :tag "Snippet")
  3586. (choice
  3587. (const :tag "For all compilers" nil)
  3588. (repeat :tag "Allowed compiler" string)))
  3589. (string :tag "A line of LaTeX"))))
  3590. (defcustom org-latex-packages-alist nil
  3591. "Alist of packages to be inserted in every LaTeX header.
  3592. These will be inserted after `org-latex-default-packages-alist'.
  3593. Each element is either a cell or a string.
  3594. A cell is of the format:
  3595. (\"options\" \"package\" SNIPPET-FLAG)
  3596. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3597. needed when turning LaTeX snippets into images for inclusion into
  3598. non-LaTeX output.
  3599. A string will be inserted as-is in the header of the document.
  3600. Make sure that you only list packages here which:
  3601. - you want in every file;
  3602. - do not conflict with the setup in `org-format-latex-header';
  3603. - do not conflict with the default packages in
  3604. `org-latex-default-packages-alist'."
  3605. :group 'org-latex
  3606. :group 'org-export-latex
  3607. :set 'org-set-packages-alist
  3608. :get 'org-get-packages-alist
  3609. :type '(repeat
  3610. (choice
  3611. (list :tag "options/package pair"
  3612. (string :tag "options")
  3613. (string :tag "package")
  3614. (boolean :tag "Snippet"))
  3615. (string :tag "A line of LaTeX"))))
  3616. (defgroup org-appearance nil
  3617. "Settings for Org mode appearance."
  3618. :tag "Org Appearance"
  3619. :group 'org)
  3620. (defcustom org-level-color-stars-only nil
  3621. "Non-nil means fontify only the stars in each headline.
  3622. When nil, the entire headline is fontified.
  3623. Changing it requires restart of `font-lock-mode' to become effective
  3624. also in regions already fontified."
  3625. :group 'org-appearance
  3626. :type 'boolean)
  3627. (defcustom org-hide-leading-stars nil
  3628. "Non-nil means hide the first N-1 stars in a headline.
  3629. This works by using the face `org-hide' for these stars. This
  3630. face is white for a light background, and black for a dark
  3631. background. You may have to customize the face `org-hide' to
  3632. make this work.
  3633. Changing it requires restart of `font-lock-mode' to become effective
  3634. also in regions already fontified.
  3635. You may also set this on a per-file basis by adding one of the following
  3636. lines to the buffer:
  3637. #+STARTUP: hidestars
  3638. #+STARTUP: showstars"
  3639. :group 'org-appearance
  3640. :type 'boolean)
  3641. (defcustom org-hidden-keywords nil
  3642. "List of symbols corresponding to keywords to be hidden the org buffer.
  3643. For example, a value \\='(title) for this list will make the document's title
  3644. appear in the buffer without the initial #+TITLE: keyword."
  3645. :group 'org-appearance
  3646. :version "24.1"
  3647. :type '(set (const :tag "#+AUTHOR" author)
  3648. (const :tag "#+DATE" date)
  3649. (const :tag "#+EMAIL" email)
  3650. (const :tag "#+TITLE" title)))
  3651. (defcustom org-custom-properties nil
  3652. "List of properties (as strings) with a special meaning.
  3653. The default use of these custom properties is to let the user
  3654. hide them with `org-toggle-custom-properties-visibility'."
  3655. :group 'org-properties
  3656. :group 'org-appearance
  3657. :version "24.3"
  3658. :type '(repeat (string :tag "Property Name")))
  3659. (defcustom org-fontify-done-headline nil
  3660. "Non-nil means change the face of a headline if it is marked DONE.
  3661. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3662. When this is non-nil, the headline after the keyword is set to the
  3663. `org-headline-done' as an additional indication."
  3664. :group 'org-appearance
  3665. :type 'boolean)
  3666. (defcustom org-fontify-emphasized-text t
  3667. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3668. Changing this variable requires a restart of Emacs to take effect."
  3669. :group 'org-appearance
  3670. :type 'boolean)
  3671. (defcustom org-fontify-whole-heading-line nil
  3672. "Non-nil means fontify the whole line for headings.
  3673. This is useful when setting a background color for the
  3674. org-level-* faces."
  3675. :group 'org-appearance
  3676. :type 'boolean)
  3677. (defcustom org-highlight-latex-and-related nil
  3678. "Non-nil means highlight LaTeX related syntax in the buffer.
  3679. When non nil, the value should be a list containing any of the
  3680. following symbols:
  3681. `latex' Highlight LaTeX snippets and environments.
  3682. `script' Highlight subscript and superscript.
  3683. `entities' Highlight entities."
  3684. :group 'org-appearance
  3685. :version "24.4"
  3686. :package-version '(Org . "8.0")
  3687. :type '(choice
  3688. (const :tag "No highlighting" nil)
  3689. (set :greedy t :tag "Highlight"
  3690. (const :tag "LaTeX snippets and environments" latex)
  3691. (const :tag "Subscript and superscript" script)
  3692. (const :tag "Entities" entities))))
  3693. (defcustom org-hide-emphasis-markers nil
  3694. "Non-nil mean font-lock should hide the emphasis marker characters."
  3695. :group 'org-appearance
  3696. :type 'boolean)
  3697. (defcustom org-hide-macro-markers nil
  3698. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3699. :group 'org-appearance
  3700. :type 'boolean)
  3701. (defcustom org-pretty-entities nil
  3702. "Non-nil means show entities as UTF8 characters.
  3703. When nil, the \\name form remains in the buffer."
  3704. :group 'org-appearance
  3705. :version "24.1"
  3706. :type 'boolean)
  3707. (defcustom org-pretty-entities-include-sub-superscripts t
  3708. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3709. :group 'org-appearance
  3710. :version "24.1"
  3711. :type 'boolean)
  3712. (defvar org-emph-re nil
  3713. "Regular expression for matching emphasis.
  3714. After a match, the match groups contain these elements:
  3715. 0 The match of the full regular expression, including the characters
  3716. before and after the proper match
  3717. 1 The character before the proper match, or empty at beginning of line
  3718. 2 The proper match, including the leading and trailing markers
  3719. 3 The leading marker like * or /, indicating the type of highlighting
  3720. 4 The text between the emphasis markers, not including the markers
  3721. 5 The character after the match, empty at the end of a line")
  3722. (defvar org-verbatim-re nil
  3723. "Regular expression for matching verbatim text.")
  3724. (defvar org-emphasis-regexp-components) ; defined just below
  3725. (defvar org-emphasis-alist) ; defined just below
  3726. (defun org-set-emph-re (var val)
  3727. "Set variable and compute the emphasis regular expression."
  3728. (set var val)
  3729. (when (and (boundp 'org-emphasis-alist)
  3730. (boundp 'org-emphasis-regexp-components)
  3731. org-emphasis-alist org-emphasis-regexp-components)
  3732. (pcase-let*
  3733. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3734. (body (if (<= nl 0) body
  3735. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3736. (template
  3737. (format (concat "\\([%s]\\|^\\)" ;before markers
  3738. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3739. "\\([%s]\\|$\\)") ;after markers
  3740. pre border border body border post)))
  3741. (setq org-emph-re (format template "*/_+"))
  3742. (setq org-verbatim-re (format template "=~")))))
  3743. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3744. ;; set this option proved cumbersome. See this message/thread:
  3745. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3746. (defvar org-emphasis-regexp-components
  3747. '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3748. "Components used to build the regular expression for emphasis.
  3749. This is a list with five entries. Terminology: In an emphasis string
  3750. like \" *strong word* \", we call the initial space PREMATCH, the final
  3751. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3752. and \"trong wor\" is the body. The different components in this variable
  3753. specify what is allowed/forbidden in each part:
  3754. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3755. post Chars allowed as postmatch. End of line will be allowed too.
  3756. border The chars *forbidden* as border characters.
  3757. body-regexp A regexp like \".\" to match a body character. Don't use
  3758. non-shy groups here, and don't allow newline here.
  3759. newline The maximum number of newlines allowed in an emphasis exp.
  3760. You need to reload Org or to restart Emacs after customizing this.")
  3761. (defcustom org-emphasis-alist
  3762. '(("*" bold)
  3763. ("/" italic)
  3764. ("_" underline)
  3765. ("=" org-verbatim verbatim)
  3766. ("~" org-code verbatim)
  3767. ("+" (:strike-through t)))
  3768. "Alist of characters and faces to emphasize text.
  3769. Text starting and ending with a special character will be emphasized,
  3770. for example *bold*, _underlined_ and /italic/. This variable sets the
  3771. marker characters and the face to be used by font-lock for highlighting
  3772. in Org buffers.
  3773. You need to reload Org or to restart Emacs after customizing this."
  3774. :group 'org-appearance
  3775. :set 'org-set-emph-re
  3776. :version "24.4"
  3777. :package-version '(Org . "8.0")
  3778. :type '(repeat
  3779. (list
  3780. (string :tag "Marker character")
  3781. (choice
  3782. (face :tag "Font-lock-face")
  3783. (plist :tag "Face property list"))
  3784. (option (const verbatim)))))
  3785. (defvar org-protecting-blocks '("src" "example" "export")
  3786. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3787. This is needed for font-lock setup.")
  3788. ;;; Functions and variables from their packages
  3789. ;; Declared here to avoid compiler warnings
  3790. (defvar mark-active)
  3791. ;; Various packages
  3792. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3793. (declare-function calendar-forward-day "cal-move" (arg))
  3794. (declare-function calendar-goto-date "cal-move" (date))
  3795. (declare-function calendar-goto-today "cal-move" ())
  3796. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3797. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3798. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3799. (declare-function cdlatex-tab "ext:cdlatex" ())
  3800. (declare-function dired-get-filename
  3801. "dired"
  3802. (&optional localp no-error-if-not-filep))
  3803. (declare-function iswitchb-read-buffer
  3804. "iswitchb"
  3805. (prompt &optional
  3806. default require-match _predicate start matches-set))
  3807. (declare-function org-agenda-change-all-lines
  3808. "org-agenda"
  3809. (newhead hdmarker &optional fixface just-this))
  3810. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3811. "org-agenda"
  3812. (&optional end))
  3813. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3814. (declare-function org-agenda-format-item
  3815. "org-agenda"
  3816. (extra txt &optional level category tags dotime
  3817. remove-re habitp))
  3818. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3819. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3820. (declare-function org-agenda-save-markers-for-cut-and-paste
  3821. "org-agenda"
  3822. (beg end))
  3823. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3824. (declare-function org-agenda-skip "org-agenda" ())
  3825. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3826. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3827. (declare-function org-indent-mode "org-indent" (&optional arg))
  3828. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3829. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3830. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3831. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3832. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3833. (declare-function parse-time-string "parse-time" (string))
  3834. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3835. (defvar align-mode-rules-list)
  3836. (defvar calc-embedded-close-formula)
  3837. (defvar calc-embedded-open-formula)
  3838. (defvar calc-embedded-open-mode)
  3839. (defvar font-lock-unfontify-region-function)
  3840. (defvar iswitchb-temp-buflist)
  3841. (defvar org-agenda-tags-todo-honor-ignore-options)
  3842. (defvar remember-data-file)
  3843. (defvar texmathp-why)
  3844. ;;;###autoload
  3845. (defun turn-on-orgtbl ()
  3846. "Unconditionally turn on `orgtbl-mode'."
  3847. (require 'org-table)
  3848. (orgtbl-mode 1))
  3849. (defun org-at-table-p (&optional table-type)
  3850. "Non-nil if the cursor is inside an Org table.
  3851. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3852. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3853. (or (not (derived-mode-p 'org-mode))
  3854. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3855. (and e (or table-type
  3856. (eq 'org (org-element-property :type e))))))))
  3857. (defun org-at-table.el-p ()
  3858. "Non-nil when point is at a table.el table."
  3859. (and (org-match-line "[ \t]*[|+]")
  3860. (let ((element (org-element-at-point)))
  3861. (and (eq (org-element-type element) 'table)
  3862. (eq (org-element-property :type element) 'table.el)))))
  3863. (defun org-at-table-hline-p ()
  3864. "Non-nil when point is inside a hline in a table.
  3865. Assume point is already in a table."
  3866. (org-match-line org-table-hline-regexp))
  3867. (defun org-table-map-tables (function &optional quietly)
  3868. "Apply FUNCTION to the start of all tables in the buffer."
  3869. (org-with-wide-buffer
  3870. (goto-char (point-min))
  3871. (while (re-search-forward org-table-any-line-regexp nil t)
  3872. (unless quietly
  3873. (message "Mapping tables: %d%%"
  3874. (floor (* 100.0 (point)) (buffer-size))))
  3875. (beginning-of-line 1)
  3876. (when (and (looking-at org-table-line-regexp)
  3877. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3878. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3879. (save-excursion (funcall function))
  3880. (or (looking-at org-table-line-regexp)
  3881. (forward-char 1)))
  3882. (re-search-forward org-table-any-border-regexp nil 1)))
  3883. (unless quietly (message "Mapping tables: done")))
  3884. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3885. (declare-function org-clock-update-mode-line "org-clock" ())
  3886. (declare-function org-resolve-clocks "org-clock"
  3887. (&optional also-non-dangling-p prompt last-valid))
  3888. (defun org-at-TBLFM-p (&optional pos)
  3889. "Non-nil when point (or POS) is in #+TBLFM line."
  3890. (save-excursion
  3891. (goto-char (or pos (point)))
  3892. (beginning-of-line)
  3893. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3894. (eq (org-element-type (org-element-at-point)) 'table))))
  3895. (defvar org-clock-start-time)
  3896. (defvar org-clock-marker (make-marker)
  3897. "Marker recording the last clock-in.")
  3898. (defvar org-clock-hd-marker (make-marker)
  3899. "Marker recording the last clock-in, but the headline position.")
  3900. (defvar org-clock-heading ""
  3901. "The heading of the current clock entry.")
  3902. (defun org-clock-is-active ()
  3903. "Return the buffer where the clock is currently running.
  3904. Return nil if no clock is running."
  3905. (marker-buffer org-clock-marker))
  3906. (defun org-check-running-clock ()
  3907. "Check if the current buffer contains the running clock.
  3908. If yes, offer to stop it and to save the buffer with the changes."
  3909. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3910. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3911. (buffer-name))))
  3912. (org-clock-out)
  3913. (when (y-or-n-p "Save changed buffer?")
  3914. (save-buffer))))
  3915. (defun org-clocktable-try-shift (dir n)
  3916. "Check if this line starts a clock table, if yes, shift the time block."
  3917. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3918. (org-clocktable-shift dir n)))
  3919. ;;;###autoload
  3920. (defun org-clock-persistence-insinuate ()
  3921. "Set up hooks for clock persistence."
  3922. (require 'org-clock)
  3923. (add-hook 'org-mode-hook 'org-clock-load)
  3924. (add-hook 'kill-emacs-hook 'org-clock-save))
  3925. (defgroup org-archive nil
  3926. "Options concerning archiving in Org mode."
  3927. :tag "Org Archive"
  3928. :group 'org-structure)
  3929. (defcustom org-archive-location "%s_archive::"
  3930. "The location where subtrees should be archived.
  3931. The value of this variable is a string, consisting of two parts,
  3932. separated by a double-colon. The first part is a filename and
  3933. the second part is a headline.
  3934. When the filename is omitted, archiving happens in the same file.
  3935. %s in the filename will be replaced by the current file
  3936. name (without the directory part). Archiving to a different file
  3937. is useful to keep archived entries from contributing to the
  3938. Org Agenda.
  3939. The archived entries will be filed as subtrees of the specified
  3940. headline. When the headline is omitted, the subtrees are simply
  3941. filed away at the end of the file, as top-level entries. Also in
  3942. the heading you can use %s to represent the file name, this can be
  3943. useful when using the same archive for a number of different files.
  3944. Here are a few examples:
  3945. \"%s_archive::\"
  3946. If the current file is Projects.org, archive in file
  3947. Projects.org_archive, as top-level trees. This is the default.
  3948. \"::* Archived Tasks\"
  3949. Archive in the current file, under the top-level headline
  3950. \"* Archived Tasks\".
  3951. \"~/org/archive.org::\"
  3952. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3953. \"~/org/archive.org::* From %s\"
  3954. Archive in file ~/org/archive.org (absolute path), under headlines
  3955. \"From FILENAME\" where file name is the current file name.
  3956. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3957. The \"datetree/\" string is special, signifying to archive
  3958. items to the datetree. Items are placed in either the CLOSED
  3959. date of the item, or the current date if there is no CLOSED date.
  3960. The heading will be a subentry to the current date. There doesn't
  3961. need to be a heading, but there always needs to be a slash after
  3962. datetree. For example, to store archived items directly in the
  3963. datetree, use \"~/org/datetree.org::datetree/\".
  3964. \"basement::** Finished Tasks\"
  3965. Archive in file ./basement (relative path), as level 3 trees
  3966. below the level 2 heading \"** Finished Tasks\".
  3967. You may set this option on a per-file basis by adding to the buffer a
  3968. line like
  3969. #+ARCHIVE: basement::** Finished Tasks
  3970. You may also define it locally for a subtree by setting an ARCHIVE property
  3971. in the entry. If such a property is found in an entry, or anywhere up
  3972. the hierarchy, it will be used."
  3973. :group 'org-archive
  3974. :type 'string)
  3975. (defcustom org-agenda-skip-archived-trees t
  3976. "Non-nil means the agenda will skip any items located in archived trees.
  3977. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3978. variable is no longer recommended, you should leave it at the value t.
  3979. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3980. :group 'org-archive
  3981. :group 'org-agenda-skip
  3982. :type 'boolean)
  3983. (defcustom org-columns-skip-archived-trees t
  3984. "Non-nil means ignore archived trees when creating column view."
  3985. :group 'org-archive
  3986. :group 'org-properties
  3987. :type 'boolean)
  3988. (defcustom org-cycle-open-archived-trees nil
  3989. "Non-nil means `org-cycle' will open archived trees.
  3990. An archived tree is a tree marked with the tag ARCHIVE.
  3991. When nil, archived trees will stay folded. You can still open them with
  3992. normal outline commands like `show-all', but not with the cycling commands."
  3993. :group 'org-archive
  3994. :group 'org-cycle
  3995. :type 'boolean)
  3996. (defcustom org-sparse-tree-open-archived-trees nil
  3997. "Non-nil means sparse tree construction shows matches in archived trees.
  3998. When nil, matches in these trees are highlighted, but the trees are kept in
  3999. collapsed state."
  4000. :group 'org-archive
  4001. :group 'org-sparse-trees
  4002. :type 'boolean)
  4003. (defcustom org-sparse-tree-default-date-type nil
  4004. "The default date type when building a sparse tree.
  4005. When this is nil, a date is a scheduled or a deadline timestamp.
  4006. Otherwise, these types are allowed:
  4007. all: all timestamps
  4008. active: only active timestamps (<...>)
  4009. inactive: only inactive timestamps ([...])
  4010. scheduled: only scheduled timestamps
  4011. deadline: only deadline timestamps"
  4012. :type '(choice (const :tag "Scheduled or deadline" nil)
  4013. (const :tag "All timestamps" all)
  4014. (const :tag "Only active timestamps" active)
  4015. (const :tag "Only inactive timestamps" inactive)
  4016. (const :tag "Only scheduled timestamps" scheduled)
  4017. (const :tag "Only deadline timestamps" deadline)
  4018. (const :tag "Only closed timestamps" closed))
  4019. :version "26.1"
  4020. :package-version '(Org . "8.3")
  4021. :group 'org-sparse-trees)
  4022. (defun org-cycle-hide-archived-subtrees (state)
  4023. "Re-hide all archived subtrees after a visibility state change.
  4024. STATE should be one of the symbols listed in the docstring of
  4025. `org-cycle-hook'."
  4026. (when (and (not org-cycle-open-archived-trees)
  4027. (not (memq state '(overview folded))))
  4028. (save-excursion
  4029. (let* ((globalp (memq state '(contents all)))
  4030. (beg (if globalp (point-min) (point)))
  4031. (end (if globalp (point-max) (org-end-of-subtree t))))
  4032. (org-hide-archived-subtrees beg end)
  4033. (goto-char beg)
  4034. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4035. (message "%s" (substitute-command-keys
  4036. "Subtree is archived and stays closed. Use \
  4037. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4038. (defun org-force-cycle-archived ()
  4039. "Cycle subtree even if it is archived."
  4040. (interactive)
  4041. (setq this-command 'org-cycle)
  4042. (let ((org-cycle-open-archived-trees t))
  4043. (call-interactively 'org-cycle)))
  4044. (defun org-hide-archived-subtrees (beg end)
  4045. "Re-hide all archived subtrees after a visibility state change."
  4046. (org-with-wide-buffer
  4047. (let ((case-fold-search nil)
  4048. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4049. (goto-char beg)
  4050. ;; Include headline point is currently on.
  4051. (beginning-of-line)
  4052. (while (and (< (point) end) (re-search-forward re end t))
  4053. (when (member org-archive-tag (org-get-tags))
  4054. (org-flag-subtree t)
  4055. (org-end-of-subtree t))))))
  4056. (declare-function outline-end-of-heading "outline" ())
  4057. (declare-function outline-flag-region "outline" (from to flag))
  4058. (defun org-flag-subtree (flag)
  4059. (save-excursion
  4060. (org-back-to-heading t)
  4061. (outline-end-of-heading)
  4062. (outline-flag-region (point)
  4063. (progn (org-end-of-subtree t) (point))
  4064. flag)))
  4065. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4066. ;; Declare Column View Code
  4067. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4068. (declare-function org-columns-compute "org-colview" (property))
  4069. ;; Declare ID code
  4070. (declare-function org-id-store-link "org-id")
  4071. (declare-function org-id-locations-load "org-id")
  4072. (declare-function org-id-locations-save "org-id")
  4073. (defvar org-id-track-globally)
  4074. ;;; Variables for pre-computed regular expressions, all buffer local
  4075. (defvar-local org-todo-regexp nil
  4076. "Matches any of the TODO state keywords.
  4077. Since TODO keywords are case-sensitive, `case-fold-search' is
  4078. expected to be bound to nil when matching against this regexp.")
  4079. (defvar-local org-not-done-regexp nil
  4080. "Matches any of the TODO state keywords except the last one.
  4081. Since TODO keywords are case-sensitive, `case-fold-search' is
  4082. expected to be bound to nil when matching against this regexp.")
  4083. (defvar-local org-not-done-heading-regexp nil
  4084. "Matches a TODO headline that is not done.
  4085. Since TODO keywords are case-sensitive, `case-fold-search' is
  4086. expected to be bound to nil when matching against this regexp.")
  4087. (defvar-local org-todo-line-regexp nil
  4088. "Matches a headline and puts TODO state into group 2 if present.
  4089. Since TODO keywords are case-sensitive, `case-fold-search' is
  4090. expected to be bound to nil when matching against this regexp.")
  4091. (defvar-local org-complex-heading-regexp nil
  4092. "Matches a headline and puts everything into groups:
  4093. group 1: Stars
  4094. group 2: The TODO keyword, maybe
  4095. group 3: Priority cookie
  4096. group 4: True headline
  4097. group 5: Tags
  4098. Since TODO keywords are case-sensitive, `case-fold-search' is
  4099. expected to be bound to nil when matching against this regexp.")
  4100. (defvar-local org-complex-heading-regexp-format nil
  4101. "Printf format to make regexp to match an exact headline.
  4102. This regexp will match the headline of any node which has the
  4103. exact headline text that is put into the format, but may have any
  4104. TODO state, priority and tags.")
  4105. (defvar-local org-todo-line-tags-regexp nil
  4106. "Matches a headline and puts TODO state into group 2 if present.
  4107. Also put tags into group 4 if tags are present.")
  4108. (defconst org-plain-time-of-day-regexp
  4109. (concat
  4110. "\\(\\<[012]?[0-9]"
  4111. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4112. "\\(--?"
  4113. "\\(\\<[012]?[0-9]"
  4114. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4115. "\\)?")
  4116. "Regular expression to match a plain time or time range.
  4117. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4118. groups carry important information:
  4119. 0 the full match
  4120. 1 the first time, range or not
  4121. 8 the second time, if it is a range.")
  4122. (defconst org-plain-time-extension-regexp
  4123. (concat
  4124. "\\(\\<[012]?[0-9]"
  4125. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4126. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4127. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4128. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4129. groups carry important information:
  4130. 0 the full match
  4131. 7 hours of duration
  4132. 9 minutes of duration")
  4133. (defconst org-stamp-time-of-day-regexp
  4134. (concat
  4135. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4136. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4137. "\\(--?"
  4138. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4139. "Regular expression to match a timestamp time or time range.
  4140. After a match, the following groups carry important information:
  4141. 0 the full match
  4142. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4143. 2 the first time, range or not
  4144. 4 the second time, if it is a range.")
  4145. (defconst org-startup-options
  4146. '(("fold" org-startup-folded t)
  4147. ("overview" org-startup-folded t)
  4148. ("nofold" org-startup-folded nil)
  4149. ("showall" org-startup-folded nil)
  4150. ("showeverything" org-startup-folded showeverything)
  4151. ("content" org-startup-folded content)
  4152. ("indent" org-startup-indented t)
  4153. ("noindent" org-startup-indented nil)
  4154. ("hidestars" org-hide-leading-stars t)
  4155. ("showstars" org-hide-leading-stars nil)
  4156. ("odd" org-odd-levels-only t)
  4157. ("oddeven" org-odd-levels-only nil)
  4158. ("align" org-startup-align-all-tables t)
  4159. ("noalign" org-startup-align-all-tables nil)
  4160. ("inlineimages" org-startup-with-inline-images t)
  4161. ("noinlineimages" org-startup-with-inline-images nil)
  4162. ("latexpreview" org-startup-with-latex-preview t)
  4163. ("nolatexpreview" org-startup-with-latex-preview nil)
  4164. ("customtime" org-display-custom-times t)
  4165. ("logdone" org-log-done time)
  4166. ("lognotedone" org-log-done note)
  4167. ("nologdone" org-log-done nil)
  4168. ("lognoteclock-out" org-log-note-clock-out t)
  4169. ("nolognoteclock-out" org-log-note-clock-out nil)
  4170. ("logrepeat" org-log-repeat state)
  4171. ("lognoterepeat" org-log-repeat note)
  4172. ("logdrawer" org-log-into-drawer t)
  4173. ("nologdrawer" org-log-into-drawer nil)
  4174. ("logstatesreversed" org-log-states-order-reversed t)
  4175. ("nologstatesreversed" org-log-states-order-reversed nil)
  4176. ("nologrepeat" org-log-repeat nil)
  4177. ("logreschedule" org-log-reschedule time)
  4178. ("lognotereschedule" org-log-reschedule note)
  4179. ("nologreschedule" org-log-reschedule nil)
  4180. ("logredeadline" org-log-redeadline time)
  4181. ("lognoteredeadline" org-log-redeadline note)
  4182. ("nologredeadline" org-log-redeadline nil)
  4183. ("logrefile" org-log-refile time)
  4184. ("lognoterefile" org-log-refile note)
  4185. ("nologrefile" org-log-refile nil)
  4186. ("fninline" org-footnote-define-inline t)
  4187. ("nofninline" org-footnote-define-inline nil)
  4188. ("fnlocal" org-footnote-section nil)
  4189. ("fnauto" org-footnote-auto-label t)
  4190. ("fnprompt" org-footnote-auto-label nil)
  4191. ("fnconfirm" org-footnote-auto-label confirm)
  4192. ("fnplain" org-footnote-auto-label plain)
  4193. ("fnadjust" org-footnote-auto-adjust t)
  4194. ("nofnadjust" org-footnote-auto-adjust nil)
  4195. ("constcgs" constants-unit-system cgs)
  4196. ("constSI" constants-unit-system SI)
  4197. ("noptag" org-tag-persistent-alist nil)
  4198. ("hideblocks" org-hide-block-startup t)
  4199. ("nohideblocks" org-hide-block-startup nil)
  4200. ("beamer" org-startup-with-beamer-mode t)
  4201. ("entitiespretty" org-pretty-entities t)
  4202. ("entitiesplain" org-pretty-entities nil))
  4203. "Variable associated with STARTUP options for Org.
  4204. Each element is a list of three items: the startup options (as written
  4205. in the #+STARTUP line), the corresponding variable, and the value to set
  4206. this variable to if the option is found. An optional forth element PUSH
  4207. means to push this value onto the list in the variable.")
  4208. (defcustom org-group-tags t
  4209. "When non-nil (the default), use group tags.
  4210. This can be turned on/off through `org-toggle-tags-groups'."
  4211. :group 'org-tags
  4212. :group 'org-startup
  4213. :type 'boolean)
  4214. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4215. (defun org-toggle-tags-groups ()
  4216. "Toggle support for group tags.
  4217. Support for group tags is controlled by the option
  4218. `org-group-tags', which is non-nil by default."
  4219. (interactive)
  4220. (setq org-group-tags (not org-group-tags))
  4221. (cond ((and (derived-mode-p 'org-agenda-mode)
  4222. org-group-tags)
  4223. (org-agenda-redo))
  4224. ((derived-mode-p 'org-mode)
  4225. (let ((org-inhibit-startup t)) (org-mode))))
  4226. (message "Groups tags support has been turned %s"
  4227. (if org-group-tags "on" "off")))
  4228. (defun org-set-regexps-and-options (&optional tags-only)
  4229. "Precompute regular expressions used in the current buffer.
  4230. When optional argument TAGS-ONLY is non-nil, only compute tags
  4231. related expressions."
  4232. (when (derived-mode-p 'org-mode)
  4233. (let ((alist (org--setup-collect-keywords
  4234. (org-make-options-regexp
  4235. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4236. (and (not tags-only)
  4237. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4238. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4239. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4240. ;; Startup options. Get this early since it does change
  4241. ;; behavior for other options (e.g., tags).
  4242. (let ((startup (cdr (assq 'startup alist))))
  4243. (dolist (option startup)
  4244. (let ((entry (assoc-string option org-startup-options t)))
  4245. (when entry
  4246. (let ((var (nth 1 entry))
  4247. (val (nth 2 entry)))
  4248. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4249. (unless (listp (symbol-value var))
  4250. (set (make-local-variable var) nil))
  4251. (add-to-list var val)))))))
  4252. (setq-local org-file-tags
  4253. (mapcar #'org-add-prop-inherited
  4254. (cdr (assq 'filetags alist))))
  4255. (setq org-current-tag-alist
  4256. (append org-tag-persistent-alist
  4257. (let ((tags (cdr (assq 'tags alist))))
  4258. (if tags (org-tag-string-to-alist tags)
  4259. org-tag-alist))))
  4260. (setq org-tag-groups-alist
  4261. (org-tag-alist-to-groups org-current-tag-alist))
  4262. (unless tags-only
  4263. ;; File properties.
  4264. (setq-local org-file-properties (cdr (assq 'property alist)))
  4265. ;; Archive location.
  4266. (let ((archive (cdr (assq 'archive alist))))
  4267. (when archive (setq-local org-archive-location archive)))
  4268. ;; Category.
  4269. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4270. (when cat
  4271. (setq-local org-category (intern cat))
  4272. (setq-local org-file-properties
  4273. (org--update-property-plist
  4274. "CATEGORY" cat org-file-properties))))
  4275. ;; Columns.
  4276. (let ((column (cdr (assq 'columns alist))))
  4277. (when column (setq-local org-columns-default-format column)))
  4278. ;; Constants.
  4279. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4280. ;; Link abbreviations.
  4281. (let ((links (cdr (assq 'link alist))))
  4282. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4283. ;; Priorities.
  4284. (let ((priorities (cdr (assq 'priorities alist))))
  4285. (when priorities
  4286. (setq-local org-highest-priority (nth 0 priorities))
  4287. (setq-local org-lowest-priority (nth 1 priorities))
  4288. (setq-local org-default-priority (nth 2 priorities))))
  4289. ;; Scripts.
  4290. (let ((scripts (assq 'scripts alist)))
  4291. (when scripts
  4292. (setq-local org-use-sub-superscripts (cdr scripts))))
  4293. ;; TODO keywords.
  4294. (setq-local org-todo-kwd-alist nil)
  4295. (setq-local org-todo-key-alist nil)
  4296. (setq-local org-todo-key-trigger nil)
  4297. (setq-local org-todo-keywords-1 nil)
  4298. (setq-local org-done-keywords nil)
  4299. (setq-local org-todo-heads nil)
  4300. (setq-local org-todo-sets nil)
  4301. (setq-local org-todo-log-states nil)
  4302. (let ((todo-sequences
  4303. (or (nreverse (cdr (assq 'todo alist)))
  4304. (let ((d (default-value 'org-todo-keywords)))
  4305. (if (not (stringp (car d))) d
  4306. ;; XXX: Backward compatibility code.
  4307. (list (cons org-todo-interpretation d)))))))
  4308. (dolist (sequence todo-sequences)
  4309. (let* ((sequence (or (run-hook-with-args-until-success
  4310. 'org-todo-setup-filter-hook sequence)
  4311. sequence))
  4312. (sequence-type (car sequence))
  4313. (keywords (cdr sequence))
  4314. (sep (member "|" keywords))
  4315. names alist)
  4316. (dolist (k (remove "|" keywords))
  4317. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4318. k)
  4319. (error "Invalid TODO keyword %s" k))
  4320. (let ((name (match-string 1 k))
  4321. (key (match-string 2 k))
  4322. (log (org-extract-log-state-settings k)))
  4323. (push name names)
  4324. (push (cons name (and key (string-to-char key))) alist)
  4325. (when log (push log org-todo-log-states))))
  4326. (let* ((names (nreverse names))
  4327. (done (if sep (org-remove-keyword-keys (cdr sep))
  4328. (last names)))
  4329. (head (car names))
  4330. (tail (list sequence-type head (car done) (org-last done))))
  4331. (add-to-list 'org-todo-heads head 'append)
  4332. (push names org-todo-sets)
  4333. (setq org-done-keywords (append org-done-keywords done nil))
  4334. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4335. (setq org-todo-key-alist
  4336. (append org-todo-key-alist
  4337. (and alist
  4338. (append '((:startgroup))
  4339. (nreverse alist)
  4340. '((:endgroup))))))
  4341. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4342. (setq org-todo-sets (nreverse org-todo-sets)
  4343. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4344. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4345. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4346. ;; Compute the regular expressions and other local variables.
  4347. ;; Using `org-outline-regexp-bol' would complicate them much,
  4348. ;; because of the fixed white space at the end of that string.
  4349. (unless org-done-keywords
  4350. (setq org-done-keywords
  4351. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4352. (setq org-not-done-keywords
  4353. (org-delete-all org-done-keywords
  4354. (copy-sequence org-todo-keywords-1))
  4355. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4356. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4357. org-not-done-heading-regexp
  4358. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4359. org-todo-line-regexp
  4360. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4361. org-complex-heading-regexp
  4362. (concat "^\\(\\*+\\)"
  4363. "\\(?: +" org-todo-regexp "\\)?"
  4364. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4365. "\\(?: +\\(.*?\\)\\)??"
  4366. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4367. "[ \t]*$")
  4368. org-complex-heading-regexp-format
  4369. (concat "^\\(\\*+\\)"
  4370. "\\(?: +" org-todo-regexp "\\)?"
  4371. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4372. "\\(?: +"
  4373. ;; Stats cookies can be stuck to body.
  4374. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4375. "\\(%s\\)"
  4376. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4377. "\\)"
  4378. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4379. "[ \t]*$")
  4380. org-todo-line-tags-regexp
  4381. (concat "^\\(\\*+\\)"
  4382. "\\(?: +" org-todo-regexp "\\)?"
  4383. "\\(?: +\\(.*?\\)\\)??"
  4384. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4385. "[ \t]*$"))
  4386. (org-compute-latex-and-related-regexp)))))
  4387. (defun org--setup-collect-keywords (regexp &optional files alist)
  4388. "Return setup keywords values as an alist.
  4389. REGEXP matches a subset of setup keywords. FILES is a list of
  4390. file names already visited. It is used to avoid circular setup
  4391. files. ALIST, when non-nil, is the alist computed so far.
  4392. Return value contains the following keys: `archive', `category',
  4393. `columns', `constants', `filetags', `link', `priorities',
  4394. `property', `scripts', `startup', `tags' and `todo'."
  4395. (org-with-wide-buffer
  4396. (goto-char (point-min))
  4397. (let ((case-fold-search t))
  4398. (while (re-search-forward regexp nil t)
  4399. (let ((element (org-element-at-point)))
  4400. (when (eq (org-element-type element) 'keyword)
  4401. (let ((key (org-element-property :key element))
  4402. (value (org-element-property :value element)))
  4403. (cond
  4404. ((equal key "ARCHIVE")
  4405. (when (org-string-nw-p value)
  4406. (push (cons 'archive value) alist)))
  4407. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4408. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4409. ((equal key "CONSTANTS")
  4410. (let* ((constants (assq 'constants alist))
  4411. (store (cdr constants)))
  4412. (dolist (pair (split-string value))
  4413. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4414. pair)
  4415. (let* ((name (match-string 1 pair))
  4416. (value (match-string 2 pair))
  4417. (old (assoc name store)))
  4418. (if old (setcdr old value)
  4419. (push (cons name value) store)))))
  4420. (if constants (setcdr constants store)
  4421. (push (cons 'constants store) alist))))
  4422. ((equal key "FILETAGS")
  4423. (when (org-string-nw-p value)
  4424. (let ((old (assq 'filetags alist))
  4425. (new (apply #'nconc
  4426. (mapcar (lambda (x) (org-split-string x ":"))
  4427. (split-string value)))))
  4428. (if old (setcdr old (append new (cdr old)))
  4429. (push (cons 'filetags new) alist)))))
  4430. ((equal key "LINK")
  4431. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4432. (let ((links (assq 'link alist))
  4433. (pair (cons (match-string-no-properties 1 value)
  4434. (match-string-no-properties 2 value))))
  4435. (if links (push pair (cdr links))
  4436. (push (list 'link pair) alist)))))
  4437. ((equal key "OPTIONS")
  4438. (when (and (org-string-nw-p value)
  4439. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4440. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4441. ((equal key "PRIORITIES")
  4442. (push (cons 'priorities
  4443. (let ((prio (split-string value)))
  4444. (if (< (length prio) 3) '(?A ?C ?B)
  4445. (mapcar #'string-to-char prio))))
  4446. alist))
  4447. ((equal key "PROPERTY")
  4448. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4449. (let* ((property (assq 'property alist))
  4450. (value (org--update-property-plist
  4451. (match-string-no-properties 1 value)
  4452. (match-string-no-properties 2 value)
  4453. (cdr property))))
  4454. (if property (setcdr property value)
  4455. (push (cons 'property value) alist)))))
  4456. ((equal key "STARTUP")
  4457. (let ((startup (assq 'startup alist)))
  4458. (if startup
  4459. (setcdr startup
  4460. (append (cdr startup) (split-string value)))
  4461. (push (cons 'startup (split-string value)) alist))))
  4462. ((equal key "TAGS")
  4463. (let ((tag-cell (assq 'tags alist)))
  4464. (if tag-cell
  4465. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4466. (push (cons 'tags value) alist))))
  4467. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4468. (let ((todo (assq 'todo alist))
  4469. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4470. (split-string value))))
  4471. (if todo (push value (cdr todo))
  4472. (push (list 'todo value) alist))))
  4473. ((equal key "SETUPFILE")
  4474. (unless buffer-read-only ; Do not check in Gnus messages.
  4475. (let ((f (and (org-string-nw-p value)
  4476. (expand-file-name
  4477. (org-unbracket-string "\"" "\"" value)))))
  4478. (when (and f (file-readable-p f) (not (member f files)))
  4479. (with-temp-buffer
  4480. (setq default-directory (file-name-directory f))
  4481. (insert-file-contents f)
  4482. (setq alist
  4483. ;; Fake Org mode to benefit from cache
  4484. ;; without recurring needlessly.
  4485. (let ((major-mode 'org-mode))
  4486. (org--setup-collect-keywords
  4487. regexp (cons f files) alist)))))))))))))))
  4488. alist)
  4489. (defun org-tag-string-to-alist (s)
  4490. "Return tag alist associated to string S.
  4491. S is a value for TAGS keyword or produced with
  4492. `org-tag-alist-to-string'. Return value is an alist suitable for
  4493. `org-tag-alist' or `org-tag-persistent-alist'."
  4494. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4495. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4496. "\\|{.+?}\\)" ; regular expression
  4497. "\\(?:(\\(.\\))\\)?\\'"))
  4498. alist group-flag)
  4499. (dolist (tokens lines (cdr (nreverse alist)))
  4500. (push '(:newline) alist)
  4501. (while tokens
  4502. (let ((token (pop tokens)))
  4503. (pcase token
  4504. ("{"
  4505. (push '(:startgroup) alist)
  4506. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4507. ("}"
  4508. (push '(:endgroup) alist)
  4509. (setq group-flag nil))
  4510. ("["
  4511. (push '(:startgrouptag) alist)
  4512. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4513. ("]"
  4514. (push '(:endgrouptag) alist)
  4515. (setq group-flag nil))
  4516. (":"
  4517. (push '(:grouptags) alist))
  4518. ((guard (string-match tag-re token))
  4519. (let ((tag (match-string 1 token))
  4520. (key (and (match-beginning 2)
  4521. (string-to-char (match-string 2 token)))))
  4522. ;; Push all tags in groups, no matter if they already
  4523. ;; appear somewhere else in the list.
  4524. (when (or group-flag (not (assoc tag alist)))
  4525. (push (cons tag key) alist))))))))))
  4526. (defun org-tag-alist-to-string (alist &optional skip-key)
  4527. "Return tag string associated to ALIST.
  4528. ALIST is an alist, as defined in `org-tag-alist' or
  4529. `org-tag-persistent-alist', or produced with
  4530. `org-tag-string-to-alist'.
  4531. Return value is a string suitable as a value for \"TAGS\"
  4532. keyword.
  4533. When optional argument SKIP-KEY is non-nil, skip selection keys
  4534. next to tags."
  4535. (mapconcat (lambda (token)
  4536. (pcase token
  4537. (`(:startgroup) "{")
  4538. (`(:endgroup) "}")
  4539. (`(:startgrouptag) "[")
  4540. (`(:endgrouptag) "]")
  4541. (`(:grouptags) ":")
  4542. (`(:newline) "\\n")
  4543. ((and
  4544. (guard (not skip-key))
  4545. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4546. (format "%s(%c)" tag key))
  4547. (`(,(and tag (pred stringp)) . ,_) tag)
  4548. (_ (user-error "Invalid tag token: %S" token))))
  4549. alist
  4550. " "))
  4551. (defun org-tag-alist-to-groups (alist)
  4552. "Return group alist from tag ALIST.
  4553. ALIST is an alist, as defined in `org-tag-alist' or
  4554. `org-tag-persistent-alist', or produced with
  4555. `org-tag-string-to-alist'. Return value is an alist following
  4556. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4557. a string, summarizing TAGS, as a list of strings."
  4558. (let (groups group-status current-group)
  4559. (dolist (token alist (nreverse groups))
  4560. (pcase token
  4561. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4562. (`(,(or :endgroup :endgrouptag))
  4563. (when (eq group-status 'append)
  4564. (push (nreverse current-group) groups))
  4565. (setq group-status nil))
  4566. (`(:grouptags) (setq group-status 'append))
  4567. ((and `(,tag . ,_) (guard group-status))
  4568. (if (eq group-status 'append) (push tag current-group)
  4569. (setq current-group (list tag))))
  4570. (_ nil)))))
  4571. (defvar org--file-cache (make-hash-table :test #'equal)
  4572. "Hash table to store contents of files referenced via a URL.
  4573. This is the cache of file URLs read using `org-file-contents'.")
  4574. (defun org-reset-file-cache ()
  4575. "Reset the cache of files downloaded by `org-file-contents'."
  4576. (clrhash org--file-cache))
  4577. (defun org-file-url-p (file)
  4578. "Non-nil if FILE is a URL."
  4579. (require 'ffap)
  4580. (string-match-p ffap-url-regexp file))
  4581. (defun org-file-contents (file &optional noerror nocache)
  4582. "Return the contents of FILE, as a string.
  4583. FILE can be a file name or URL.
  4584. If FILE is a URL, download the contents. If the URL contents are
  4585. already cached in the `org--file-cache' hash table, the download step
  4586. is skipped.
  4587. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4588. from file or URL.
  4589. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4590. is available. This option applies only if FILE is a URL."
  4591. (let* ((is-url (org-file-url-p file))
  4592. (cache (and is-url
  4593. (not nocache)
  4594. (gethash file org--file-cache))))
  4595. (cond
  4596. (cache)
  4597. (is-url
  4598. (with-current-buffer (url-retrieve-synchronously file)
  4599. (goto-char (point-min))
  4600. ;; Move point to after the url-retrieve header.
  4601. (search-forward "\n\n" nil :move)
  4602. ;; Search for the success code only in the url-retrieve header.
  4603. (if (save-excursion
  4604. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4605. ;; Update the cache `org--file-cache' and return contents.
  4606. (puthash file
  4607. (buffer-substring-no-properties (point) (point-max))
  4608. org--file-cache)
  4609. (funcall (if noerror #'message #'user-error)
  4610. "Unable to fetch file from %S"
  4611. file))))
  4612. (t
  4613. (with-temp-buffer
  4614. (condition-case nil
  4615. (progn
  4616. (insert-file-contents file)
  4617. (buffer-string))
  4618. (file-error
  4619. (funcall (if noerror #'message #'user-error)
  4620. "Unable to read file %S"
  4621. file))))))))
  4622. (defun org-extract-log-state-settings (x)
  4623. "Extract the log state setting from a TODO keyword string.
  4624. This will extract info from a string like \"WAIT(w@/!)\"."
  4625. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4626. (let ((kw (match-string 1 x))
  4627. (log1 (and (match-end 3) (match-string 3 x)))
  4628. (log2 (and (match-end 4) (match-string 4 x))))
  4629. (and (or log1 log2)
  4630. (list kw
  4631. (and log1 (if (equal log1 "!") 'time 'note))
  4632. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4633. (defun org-remove-keyword-keys (list)
  4634. "Remove a pair of parenthesis at the end of each string in LIST."
  4635. (mapcar (lambda (x)
  4636. (if (string-match "(.*)$" x)
  4637. (substring x 0 (match-beginning 0))
  4638. x))
  4639. list))
  4640. (defun org-assign-fast-keys (alist)
  4641. "Assign fast keys to a keyword-key alist.
  4642. Respect keys that are already there."
  4643. (let (new e (alt ?0))
  4644. (while (setq e (pop alist))
  4645. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4646. (cdr e)) ;; Key already assigned.
  4647. (push e new)
  4648. (let ((clist (string-to-list (downcase (car e))))
  4649. (used (append new alist)))
  4650. (when (= (car clist) ?@)
  4651. (pop clist))
  4652. (while (and clist (rassoc (car clist) used))
  4653. (pop clist))
  4654. (unless clist
  4655. (while (rassoc alt used)
  4656. (cl-incf alt)))
  4657. (push (cons (car e) (or (car clist) alt)) new))))
  4658. (nreverse new)))
  4659. ;;; Some variables used in various places
  4660. (defvar org-window-configuration nil
  4661. "Used in various places to store a window configuration.")
  4662. (defvar org-selected-window nil
  4663. "Used in various places to store a window configuration.")
  4664. (defvar org-finish-function nil
  4665. "Function to be called when `C-c C-c' is used.
  4666. This is for getting out of special buffers like capture.")
  4667. (defvar org-last-state)
  4668. ;; Defined somewhere in this file, but used before definition.
  4669. (defvar org-entities) ;; defined in org-entities.el
  4670. (defvar org-struct-menu)
  4671. (defvar org-org-menu)
  4672. (defvar org-tbl-menu)
  4673. ;;;; Define the Org mode
  4674. ;; We use a before-change function to check if a table might need
  4675. ;; an update.
  4676. (defvar org-table-may-need-update t
  4677. "Indicates that a table might need an update.
  4678. This variable is set by `org-before-change-function'.
  4679. `org-table-align' sets it back to nil.")
  4680. (defun org-before-change-function (_beg _end)
  4681. "Every change indicates that a table might need an update."
  4682. (setq org-table-may-need-update t))
  4683. (defvar org-mode-map)
  4684. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4685. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4686. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4687. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4688. (defvar org-table-buffer-is-an nil)
  4689. (defvar bidi-paragraph-direction)
  4690. (defvar buffer-face-mode-face)
  4691. (require 'outline)
  4692. ;; Other stuff we need.
  4693. (require 'time-date)
  4694. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4695. (require 'easymenu)
  4696. (autoload 'easy-menu-add "easymenu")
  4697. (require 'overlay)
  4698. ;; (require 'org-macs) moved higher up in the file before it is first used
  4699. (require 'org-entities)
  4700. ;; (require 'org-compat) moved higher up in the file before it is first used
  4701. (require 'org-faces)
  4702. (require 'org-list)
  4703. (require 'org-pcomplete)
  4704. (require 'org-src)
  4705. (require 'org-footnote)
  4706. (require 'org-macro)
  4707. ;; babel
  4708. (require 'ob)
  4709. ;;;###autoload
  4710. (define-derived-mode org-mode outline-mode "Org"
  4711. "Outline-based notes management and organizer, alias
  4712. \"Carsten's outline-mode for keeping track of everything.\"
  4713. Org mode develops organizational tasks around a NOTES file which
  4714. contains information about projects as plain text. Org mode is
  4715. implemented on top of Outline mode, which is ideal to keep the content
  4716. of large files well structured. It supports ToDo items, deadlines and
  4717. time stamps, which magically appear in the diary listing of the Emacs
  4718. calendar. Tables are easily created with a built-in table editor.
  4719. Plain text URL-like links connect to websites, emails (VM), Usenet
  4720. messages (Gnus), BBDB entries, and any files related to the project.
  4721. For printing and sharing of notes, an Org file (or a part of it)
  4722. can be exported as a structured ASCII or HTML file.
  4723. The following commands are available:
  4724. \\{org-mode-map}"
  4725. ;; Get rid of Outline menus, they are not needed
  4726. ;; Need to do this here because define-derived-mode sets up
  4727. ;; the keymap so late. Still, it is a waste to call this each time
  4728. ;; we switch another buffer into Org mode.
  4729. (define-key org-mode-map [menu-bar headings] 'undefined)
  4730. (define-key org-mode-map [menu-bar hide] 'undefined)
  4731. (define-key org-mode-map [menu-bar show] 'undefined)
  4732. (org-load-modules-maybe)
  4733. (org-install-agenda-files-menu)
  4734. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4735. (add-to-invisibility-spec '(org-cwidth))
  4736. (add-to-invisibility-spec '(org-hide-block . t))
  4737. (setq-local outline-regexp org-outline-regexp)
  4738. (setq-local outline-level 'org-outline-level)
  4739. (setq bidi-paragraph-direction 'left-to-right)
  4740. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4741. (unless org-display-table
  4742. (setq org-display-table (make-display-table)))
  4743. (set-display-table-slot
  4744. org-display-table 4
  4745. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4746. org-ellipsis)))
  4747. (setq buffer-display-table org-display-table))
  4748. (org-set-regexps-and-options)
  4749. (org-set-font-lock-defaults)
  4750. (when (and org-tag-faces (not org-tags-special-faces-re))
  4751. ;; tag faces set outside customize.... force initialization.
  4752. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4753. ;; Calc embedded
  4754. (setq-local calc-embedded-open-mode "# ")
  4755. ;; Modify a few syntax entries
  4756. (modify-syntax-entry ?@ "w")
  4757. (modify-syntax-entry ?\" "\"")
  4758. (modify-syntax-entry ?\\ "_")
  4759. (modify-syntax-entry ?~ "_")
  4760. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4761. ;; Activate before-change-function
  4762. (setq-local org-table-may-need-update t)
  4763. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4764. ;; Check for running clock before killing a buffer
  4765. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4766. ;; Initialize macros templates.
  4767. (org-macro-initialize-templates)
  4768. ;; Initialize radio targets.
  4769. (org-update-radio-target-regexp)
  4770. ;; Indentation.
  4771. (setq-local indent-line-function 'org-indent-line)
  4772. (setq-local indent-region-function 'org-indent-region)
  4773. ;; Filling and auto-filling.
  4774. (org-setup-filling)
  4775. ;; Comments.
  4776. (org-setup-comments-handling)
  4777. ;; Initialize cache.
  4778. (org-element-cache-reset)
  4779. ;; Beginning/end of defun
  4780. (setq-local beginning-of-defun-function 'org-backward-element)
  4781. (setq-local end-of-defun-function
  4782. (lambda ()
  4783. (if (not (org-at-heading-p))
  4784. (org-forward-element)
  4785. (org-forward-element)
  4786. (forward-char -1))))
  4787. ;; Next error for sparse trees
  4788. (setq-local next-error-function 'org-occur-next-match)
  4789. ;; Make sure dependence stuff works reliably, even for users who set it
  4790. ;; too late :-(
  4791. (if org-enforce-todo-dependencies
  4792. (add-hook 'org-blocker-hook
  4793. 'org-block-todo-from-children-or-siblings-or-parent)
  4794. (remove-hook 'org-blocker-hook
  4795. 'org-block-todo-from-children-or-siblings-or-parent))
  4796. (if org-enforce-todo-checkbox-dependencies
  4797. (add-hook 'org-blocker-hook
  4798. 'org-block-todo-from-checkboxes)
  4799. (remove-hook 'org-blocker-hook
  4800. 'org-block-todo-from-checkboxes))
  4801. ;; Align options lines
  4802. (setq-local
  4803. align-mode-rules-list
  4804. '((org-in-buffer-settings
  4805. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4806. (modes . '(org-mode)))))
  4807. ;; Imenu
  4808. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4809. ;; Make isearch reveal context
  4810. (setq-local outline-isearch-open-invisible-function
  4811. (lambda (&rest _) (org-show-context 'isearch)))
  4812. ;; Setup the pcomplete hooks
  4813. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4814. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4815. (setq-local pcomplete-default-completion-function 'ignore)
  4816. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4817. (setq-local pcomplete-termination-string "")
  4818. (setq-local buffer-face-mode-face 'org-default)
  4819. ;; If empty file that did not turn on Org mode automatically, make
  4820. ;; it to.
  4821. (when (and org-insert-mode-line-in-empty-file
  4822. (called-interactively-p 'any)
  4823. (= (point-min) (point-max)))
  4824. (insert "# -*- mode: org -*-\n\n"))
  4825. (unless org-inhibit-startup
  4826. (org-unmodified
  4827. (when org-startup-with-beamer-mode (org-beamer-mode))
  4828. (when org-startup-align-all-tables
  4829. (org-table-map-tables #'org-table-align t))
  4830. (when org-startup-with-inline-images (org-display-inline-images))
  4831. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4832. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4833. (when org-startup-truncated (setq truncate-lines t))
  4834. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4835. (org-refresh-effort-properties)))
  4836. ;; Try to set `org-hide' face correctly.
  4837. (let ((foreground (org-find-invisible-foreground)))
  4838. (when foreground
  4839. (set-face-foreground 'org-hide foreground))))
  4840. ;; Update `customize-package-emacs-version-alist'
  4841. (add-to-list 'customize-package-emacs-version-alist
  4842. '(Org ("8.0" . "24.4")
  4843. ("8.1" . "24.4")
  4844. ("8.2" . "24.4")
  4845. ("8.2.7" . "24.4")
  4846. ("8.3" . "26.1")
  4847. ("9.0" . "26.1")
  4848. ("9.1" . "26.1")))
  4849. (defvar org-mode-transpose-word-syntax-table
  4850. (let ((st (make-syntax-table text-mode-syntax-table)))
  4851. (dolist (c org-emphasis-alist st)
  4852. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4853. (when (fboundp 'abbrev-table-put)
  4854. (abbrev-table-put org-mode-abbrev-table
  4855. :parents (list text-mode-abbrev-table)))
  4856. (defun org-find-invisible-foreground ()
  4857. (let ((candidates (remove
  4858. "unspecified-bg"
  4859. (nconc
  4860. (list (face-background 'default)
  4861. (face-background 'org-default))
  4862. (mapcar
  4863. (lambda (alist)
  4864. (when (boundp alist)
  4865. (cdr (assq 'background-color (symbol-value alist)))))
  4866. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4867. (list (face-foreground 'org-hide))))))
  4868. (car (remove nil candidates))))
  4869. (defun org-current-time (&optional rounding-minutes past)
  4870. "Current time, possibly rounded to ROUNDING-MINUTES.
  4871. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4872. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4873. the rounding returns a past time."
  4874. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4875. (car org-time-stamp-rounding-minutes)))
  4876. (time (decode-time)) res)
  4877. (if (< r 1)
  4878. (current-time)
  4879. (setq res
  4880. (apply 'encode-time
  4881. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4882. (nthcdr 2 time))))
  4883. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4884. (seconds-to-time (- (float-time res) (* r 60)))
  4885. res))))
  4886. (defun org-today ()
  4887. "Return today date, considering `org-extend-today-until'."
  4888. (time-to-days
  4889. (time-subtract (current-time)
  4890. (list 0 (* 3600 org-extend-today-until) 0))))
  4891. ;;;; Font-Lock stuff, including the activators
  4892. (defvar org-mouse-map (make-sparse-keymap))
  4893. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4894. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4895. (when org-mouse-1-follows-link
  4896. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4897. (when org-tab-follows-link
  4898. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4899. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4900. (require 'font-lock)
  4901. (defconst org-non-link-chars "]\t\n\r<>")
  4902. (defvar org-link-types-re nil
  4903. "Matches a link that has a url-like prefix like \"http:\"")
  4904. (defvar org-link-re-with-space nil
  4905. "Matches a link with spaces, optional angular brackets around it.")
  4906. (defvar org-link-re-with-space2 nil
  4907. "Matches a link with spaces, optional angular brackets around it.")
  4908. (defvar org-link-re-with-space3 nil
  4909. "Matches a link with spaces, only for internal part in bracket links.")
  4910. (defvar org-angle-link-re nil
  4911. "Matches link with angular brackets, spaces are allowed.")
  4912. (defvar org-plain-link-re nil
  4913. "Matches plain link, without spaces.")
  4914. (defvar org-bracket-link-regexp nil
  4915. "Matches a link in double brackets.")
  4916. (defvar org-bracket-link-analytic-regexp nil
  4917. "Regular expression used to analyze links.
  4918. Here is what the match groups contain after a match:
  4919. 1: http:
  4920. 2: http
  4921. 3: path
  4922. 4: [desc]
  4923. 5: desc")
  4924. (defvar org-bracket-link-analytic-regexp++ nil
  4925. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4926. (defvar org-any-link-re nil
  4927. "Regular expression matching any link.")
  4928. (defconst org-match-sexp-depth 3
  4929. "Number of stacked braces for sub/superscript matching.")
  4930. (defun org-create-multibrace-regexp (left right n)
  4931. "Create a regular expression which will match a balanced sexp.
  4932. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4933. as single character strings.
  4934. The regexp returned will match the entire expression including the
  4935. delimiters. It will also define a single group which contains the
  4936. match except for the outermost delimiters. The maximum depth of
  4937. stacked delimiters is N. Escaping delimiters is not possible."
  4938. (let* ((nothing (concat "[^" left right "]*?"))
  4939. (or "\\|")
  4940. (re nothing)
  4941. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4942. (while (> n 1)
  4943. (setq n (1- n)
  4944. re (concat re or next)
  4945. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4946. (concat left "\\(" re "\\)" right)))
  4947. (defconst org-match-substring-regexp
  4948. (concat
  4949. "\\(\\S-\\)\\([_^]\\)\\("
  4950. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4951. "\\|"
  4952. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4953. "\\|"
  4954. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4955. "The regular expression matching a sub- or superscript.")
  4956. (defconst org-match-substring-with-braces-regexp
  4957. (concat
  4958. "\\(\\S-\\)\\([_^]\\)"
  4959. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4960. "The regular expression matching a sub- or superscript, forcing braces.")
  4961. (defun org-make-link-regexps ()
  4962. "Update the link regular expressions.
  4963. This should be called after the variable `org-link-parameters' has changed."
  4964. (let ((types-re (regexp-opt (org-link-types) t)))
  4965. (setq org-link-types-re
  4966. (concat "\\`" types-re ":")
  4967. org-link-re-with-space
  4968. (concat "<?" types-re ":"
  4969. "\\([^" org-non-link-chars " ]"
  4970. "[^" org-non-link-chars "]*"
  4971. "[^" org-non-link-chars " ]\\)>?")
  4972. org-link-re-with-space2
  4973. (concat "<?" types-re ":"
  4974. "\\([^" org-non-link-chars " ]"
  4975. "[^\t\n\r]*"
  4976. "[^" org-non-link-chars " ]\\)>?")
  4977. org-link-re-with-space3
  4978. (concat "<?" types-re ":"
  4979. "\\([^" org-non-link-chars " ]"
  4980. "[^\t\n\r]*\\)")
  4981. org-angle-link-re
  4982. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4983. types-re)
  4984. org-plain-link-re
  4985. (concat
  4986. "\\<" types-re ":"
  4987. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4988. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4989. org-bracket-link-regexp
  4990. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4991. org-bracket-link-analytic-regexp
  4992. (concat
  4993. "\\[\\["
  4994. "\\(" types-re ":\\)?"
  4995. "\\([^]]+\\)"
  4996. "\\]"
  4997. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4998. "\\]")
  4999. org-bracket-link-analytic-regexp++
  5000. (concat
  5001. "\\[\\["
  5002. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5003. "\\([^]]+\\)"
  5004. "\\]"
  5005. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5006. "\\]")
  5007. org-any-link-re
  5008. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5009. org-angle-link-re "\\)\\|\\("
  5010. org-plain-link-re "\\)"))))
  5011. (org-make-link-regexps)
  5012. (defvar org-emph-face nil)
  5013. (defun org-do-emphasis-faces (limit)
  5014. "Run through the buffer and emphasize strings."
  5015. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5016. (car org-emphasis-regexp-components))))
  5017. (catch :exit
  5018. (while (re-search-forward quick-re limit t)
  5019. (let* ((marker (match-string 2))
  5020. (verbatim? (member marker '("~" "="))))
  5021. (when (save-excursion
  5022. (goto-char (match-beginning 0))
  5023. (and
  5024. ;; Do not match table hlines.
  5025. (not (and (equal marker "+")
  5026. (org-match-line
  5027. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5028. ;; Do not match headline stars. Do not consider
  5029. ;; stars of a headline as closing marker for bold
  5030. ;; markup either.
  5031. (not (and (equal marker "*")
  5032. (save-excursion
  5033. (forward-char)
  5034. (skip-chars-backward "*")
  5035. (looking-at-p org-outline-regexp-bol))))
  5036. ;; Match full emphasis markup regexp.
  5037. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5038. ;; Do not span over paragraph boundaries.
  5039. (not (string-match-p org-element-paragraph-separate
  5040. (match-string 2)))
  5041. ;; Do not span over cells in table rows.
  5042. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5043. (string-match-p "|" (match-string 4))))))
  5044. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5045. (font-lock-prepend-text-property
  5046. (match-beginning 2) (match-end 2) 'face face)
  5047. (when verbatim?
  5048. (org-remove-flyspell-overlays-in
  5049. (match-beginning 0) (match-end 0)))
  5050. (add-text-properties (match-beginning 2) (match-end 2)
  5051. '(font-lock-multiline t org-emphasis t))
  5052. (when org-hide-emphasis-markers
  5053. (add-text-properties (match-end 4) (match-beginning 5)
  5054. '(invisible org-link))
  5055. (add-text-properties (match-beginning 3) (match-end 3)
  5056. '(invisible org-link)))
  5057. (throw :exit t))))))))
  5058. (defun org-emphasize (&optional char)
  5059. "Insert or change an emphasis, i.e. a font like bold or italic.
  5060. If there is an active region, change that region to a new emphasis.
  5061. If there is no region, just insert the marker characters and position
  5062. the cursor between them.
  5063. CHAR should be the marker character. If it is a space, it means to
  5064. remove the emphasis of the selected region.
  5065. If CHAR is not given (for example in an interactive call) it will be
  5066. prompted for."
  5067. (interactive)
  5068. (let ((erc org-emphasis-regexp-components)
  5069. (string "") beg end move s)
  5070. (if (org-region-active-p)
  5071. (setq beg (region-beginning)
  5072. end (region-end)
  5073. string (buffer-substring beg end))
  5074. (setq move t))
  5075. (unless char
  5076. (message "Emphasis marker or tag: [%s]"
  5077. (mapconcat #'car org-emphasis-alist ""))
  5078. (setq char (read-char-exclusive)))
  5079. (if (equal char ?\s)
  5080. (setq s ""
  5081. move nil)
  5082. (unless (assoc (char-to-string char) org-emphasis-alist)
  5083. (user-error "No such emphasis marker: \"%c\"" char))
  5084. (setq s (char-to-string char)))
  5085. (while (and (> (length string) 1)
  5086. (equal (substring string 0 1) (substring string -1))
  5087. (assoc (substring string 0 1) org-emphasis-alist))
  5088. (setq string (substring string 1 -1)))
  5089. (setq string (concat s string s))
  5090. (when beg (delete-region beg end))
  5091. (unless (or (bolp)
  5092. (string-match (concat "[" (nth 0 erc) "\n]")
  5093. (char-to-string (char-before (point)))))
  5094. (insert " "))
  5095. (unless (or (eobp)
  5096. (string-match (concat "[" (nth 1 erc) "\n]")
  5097. (char-to-string (char-after (point)))))
  5098. (insert " ") (backward-char 1))
  5099. (insert string)
  5100. (and move (backward-char 1))))
  5101. (defconst org-nonsticky-props
  5102. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5103. (defsubst org-rear-nonsticky-at (pos)
  5104. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5105. (defun org-activate-links (limit)
  5106. "Add link properties to links.
  5107. This includes angle, plain, and bracket links."
  5108. (catch :exit
  5109. (while (re-search-forward org-any-link-re limit t)
  5110. (let* ((start (match-beginning 0))
  5111. (end (match-end 0))
  5112. (style (cond ((eq ?< (char-after start)) 'angle)
  5113. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5114. (t 'plain))))
  5115. (when (and (memq style org-highlight-links)
  5116. ;; Do not confuse plain links with tags.
  5117. (not (and (eq style 'plain)
  5118. (let ((face (get-text-property
  5119. (max (1- start) (point-min)) 'face)))
  5120. (if (consp face) (memq 'org-tag face)
  5121. (eq 'org-tag face))))))
  5122. (let* ((link-object (save-excursion
  5123. (goto-char start)
  5124. (save-match-data (org-element-link-parser))))
  5125. (link (org-element-property :raw-link link-object))
  5126. (type (org-element-property :type link-object))
  5127. (path (org-element-property :path link-object))
  5128. (properties ;for link's visible part
  5129. (list
  5130. 'face (pcase (org-link-get-parameter type :face)
  5131. ((and (pred functionp) face) (funcall face path))
  5132. ((and (pred facep) face) face)
  5133. ((and (pred consp) face) face) ;anonymous
  5134. (_ 'org-link))
  5135. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5136. 'highlight)
  5137. 'keymap (or (org-link-get-parameter type :keymap)
  5138. org-mouse-map)
  5139. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5140. ((and (pred stringp) echo) echo)
  5141. ((and (pred functionp) echo) echo)
  5142. (_ (concat "LINK: " link)))
  5143. 'htmlize-link (pcase (org-link-get-parameter type
  5144. :htmlize-link)
  5145. ((and (pred functionp) f) (funcall f))
  5146. (_ `(:uri ,link)))
  5147. 'font-lock-multiline t)))
  5148. (org-remove-flyspell-overlays-in start end)
  5149. (org-rear-nonsticky-at end)
  5150. (if (not (eq 'bracket style))
  5151. (add-text-properties start end properties)
  5152. ;; Handle invisible parts in bracket links.
  5153. (remove-text-properties start end '(invisible nil))
  5154. (let ((hidden
  5155. (append `(invisible
  5156. ,(or (org-link-get-parameter type :display)
  5157. 'org-link))
  5158. properties))
  5159. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5160. (visible-end (or (match-end 4) (match-end 2))))
  5161. (add-text-properties start visible-start hidden)
  5162. (add-text-properties visible-start visible-end properties)
  5163. (add-text-properties visible-end end hidden)
  5164. (org-rear-nonsticky-at visible-start)
  5165. (org-rear-nonsticky-at visible-end)))
  5166. (let ((f (org-link-get-parameter type :activate-func)))
  5167. (when (functionp f)
  5168. (funcall f start end path (eq style 'bracket))))
  5169. (throw :exit t))))) ;signal success
  5170. nil))
  5171. (defun org-activate-code (limit)
  5172. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5173. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5174. (remove-text-properties (match-beginning 0) (match-end 0)
  5175. '(display t invisible t intangible t))
  5176. t))
  5177. (defcustom org-src-fontify-natively t
  5178. "When non-nil, fontify code in code blocks.
  5179. See also the `org-block' face."
  5180. :type 'boolean
  5181. :version "26.1"
  5182. :package-version '(Org . "8.3")
  5183. :group 'org-appearance
  5184. :group 'org-babel)
  5185. (defcustom org-allow-promoting-top-level-subtree nil
  5186. "When non-nil, allow promoting a top level subtree.
  5187. The leading star of the top level headline will be replaced
  5188. by a #."
  5189. :type 'boolean
  5190. :version "24.1"
  5191. :group 'org-appearance)
  5192. (defun org-fontify-meta-lines-and-blocks (limit)
  5193. (condition-case nil
  5194. (org-fontify-meta-lines-and-blocks-1 limit)
  5195. (error (message "Org mode fontification error in %S at %d"
  5196. (current-buffer)
  5197. (line-number-at-pos)))))
  5198. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5199. "Fontify #+ lines and blocks."
  5200. (let ((case-fold-search t))
  5201. (when (re-search-forward
  5202. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5203. limit t)
  5204. (let ((beg (match-beginning 0))
  5205. (block-start (match-end 0))
  5206. (block-end nil)
  5207. (lang (match-string 7))
  5208. (beg1 (line-beginning-position 2))
  5209. (dc1 (downcase (match-string 2)))
  5210. (dc3 (downcase (match-string 3)))
  5211. end end1 quoting block-type)
  5212. (cond
  5213. ((and (match-end 4) (equal dc3 "+begin"))
  5214. ;; Truly a block
  5215. (setq block-type (downcase (match-string 5))
  5216. quoting (member block-type org-protecting-blocks))
  5217. (when (re-search-forward
  5218. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5219. nil t) ;; on purpose, we look further than LIMIT
  5220. (setq end (min (point-max) (match-end 0))
  5221. end1 (min (point-max) (1- (match-beginning 0))))
  5222. (setq block-end (match-beginning 0))
  5223. (when quoting
  5224. (org-remove-flyspell-overlays-in beg1 end1)
  5225. (remove-text-properties beg end
  5226. '(display t invisible t intangible t)))
  5227. (add-text-properties
  5228. beg end '(font-lock-fontified t font-lock-multiline t))
  5229. (add-text-properties beg beg1 '(face org-meta-line))
  5230. (org-remove-flyspell-overlays-in beg beg1)
  5231. (add-text-properties ; For end_src
  5232. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5233. (org-remove-flyspell-overlays-in end1 end)
  5234. (cond
  5235. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5236. (org-src-font-lock-fontify-block lang block-start block-end)
  5237. (add-text-properties beg1 block-end '(src-block t)))
  5238. (quoting
  5239. (add-text-properties beg1 (min (point-max) (1+ end1))
  5240. (list 'face
  5241. (list :inherit
  5242. (let ((face-name
  5243. (intern (format "org-block-%s" lang))))
  5244. (append (and (facep face-name) (list face-name))
  5245. '(org-block))))))) ; end of source block
  5246. ((not org-fontify-quote-and-verse-blocks))
  5247. ((string= block-type "quote")
  5248. (add-face-text-property
  5249. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5250. ((string= block-type "verse")
  5251. (add-face-text-property
  5252. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5253. (add-text-properties beg beg1 '(face org-block-begin-line))
  5254. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5255. '(face org-block-end-line))
  5256. t))
  5257. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5258. (org-remove-flyspell-overlays-in
  5259. (match-beginning 0)
  5260. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5261. (add-text-properties
  5262. beg (match-end 3)
  5263. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5264. '(font-lock-fontified t invisible t)
  5265. '(font-lock-fontified t face org-document-info-keyword)))
  5266. (add-text-properties
  5267. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5268. (if (string-equal dc1 "+title:")
  5269. '(font-lock-fontified t face org-document-title)
  5270. '(font-lock-fontified t face org-document-info))))
  5271. ((string-prefix-p "+caption" dc1)
  5272. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5273. (remove-text-properties (match-beginning 0) (match-end 0)
  5274. '(display t invisible t intangible t))
  5275. ;; Handle short captions.
  5276. (save-excursion
  5277. (beginning-of-line)
  5278. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5279. (add-text-properties (line-beginning-position) (match-end 1)
  5280. '(font-lock-fontified t face org-meta-line))
  5281. (add-text-properties (match-end 0) (line-end-position)
  5282. '(font-lock-fontified t face org-block))
  5283. t)
  5284. ((member dc3 '(" " ""))
  5285. (org-remove-flyspell-overlays-in beg (match-end 0))
  5286. (add-text-properties
  5287. beg (match-end 0)
  5288. '(font-lock-fontified t face font-lock-comment-face)))
  5289. (t ;; just any other in-buffer setting, but not indented
  5290. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5291. (remove-text-properties (match-beginning 0) (match-end 0)
  5292. '(display t invisible t intangible t))
  5293. (add-text-properties beg (match-end 0)
  5294. '(font-lock-fontified t face org-meta-line))
  5295. t))))))
  5296. (defun org-fontify-drawers (limit)
  5297. "Fontify drawers."
  5298. (when (re-search-forward org-drawer-regexp limit t)
  5299. (add-text-properties
  5300. (match-beginning 0) (match-end 0)
  5301. '(font-lock-fontified t face org-special-keyword))
  5302. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5303. t))
  5304. (defun org-fontify-macros (limit)
  5305. "Fontify macros."
  5306. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5307. (add-text-properties
  5308. (match-beginning 0) (match-end 0)
  5309. '(font-lock-fontified t face org-macro))
  5310. (when org-hide-macro-markers
  5311. (add-text-properties (match-end 2) (match-beginning 2)
  5312. '(invisible t))
  5313. (add-text-properties (match-beginning 1) (match-end 1)
  5314. '(invisible t)))
  5315. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5316. t))
  5317. (defun org-activate-footnote-links (limit)
  5318. "Add text properties for footnotes."
  5319. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5320. (when fn
  5321. (let* ((beg (nth 1 fn))
  5322. (end (nth 2 fn))
  5323. (label (car fn))
  5324. (referencep (/= (line-beginning-position) beg)))
  5325. (when (and referencep (nth 3 fn))
  5326. (save-excursion
  5327. (goto-char beg)
  5328. (search-forward (or label "fn:"))
  5329. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5330. (add-text-properties beg end
  5331. (list 'mouse-face 'highlight
  5332. 'keymap org-mouse-map
  5333. 'help-echo
  5334. (if referencep "Footnote reference"
  5335. "Footnote definition")
  5336. 'font-lock-fontified t
  5337. 'font-lock-multiline t
  5338. 'face 'org-footnote))))))
  5339. (defun org-activate-dates (limit)
  5340. "Add text properties for dates."
  5341. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5342. (not (equal (char-before (match-beginning 0)) 91)))
  5343. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5344. (add-text-properties (match-beginning 0) (match-end 0)
  5345. (list 'mouse-face 'highlight
  5346. 'keymap org-mouse-map))
  5347. (org-rear-nonsticky-at (match-end 0))
  5348. (when org-display-custom-times
  5349. ;; If it's a date range, activate custom time for second date.
  5350. (when (match-end 3)
  5351. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5352. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5353. t))
  5354. (defvar-local org-target-link-regexp nil
  5355. "Regular expression matching radio targets in plain text.")
  5356. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5357. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5358. border border border))
  5359. "Regular expression matching a link target.")
  5360. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5361. "Regular expression matching a radio target.")
  5362. (defconst org-any-target-regexp
  5363. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5364. "Regular expression matching any target.")
  5365. (defun org-activate-target-links (limit)
  5366. "Add text properties for target matches."
  5367. (when org-target-link-regexp
  5368. (let ((case-fold-search t))
  5369. (when (re-search-forward org-target-link-regexp limit t)
  5370. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5371. (add-text-properties (match-beginning 1) (match-end 1)
  5372. (list 'mouse-face 'highlight
  5373. 'keymap org-mouse-map
  5374. 'help-echo "Radio target link"
  5375. 'org-linked-text t))
  5376. (org-rear-nonsticky-at (match-end 1))
  5377. t))))
  5378. (defun org-update-radio-target-regexp ()
  5379. "Find all radio targets in this file and update the regular expression.
  5380. Also refresh fontification if needed."
  5381. (interactive)
  5382. (let ((old-regexp org-target-link-regexp)
  5383. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5384. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5385. (targets
  5386. (org-with-wide-buffer
  5387. (goto-char (point-min))
  5388. (let (rtn)
  5389. (while (re-search-forward org-radio-target-regexp nil t)
  5390. ;; Make sure point is really within the object.
  5391. (backward-char)
  5392. (let ((obj (org-element-context)))
  5393. (when (eq (org-element-type obj) 'radio-target)
  5394. (cl-pushnew (org-element-property :value obj) rtn
  5395. :test #'equal))))
  5396. rtn))))
  5397. (setq org-target-link-regexp
  5398. (and targets
  5399. (concat before-re
  5400. (mapconcat
  5401. (lambda (x)
  5402. (replace-regexp-in-string
  5403. " +" "\\s-+" (regexp-quote x) t t))
  5404. targets
  5405. "\\|")
  5406. after-re)))
  5407. (unless (equal old-regexp org-target-link-regexp)
  5408. ;; Clean-up cache.
  5409. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5410. ((not org-target-link-regexp) old-regexp)
  5411. (t
  5412. (concat before-re
  5413. (mapconcat
  5414. (lambda (re)
  5415. (substring re (length before-re)
  5416. (- (length after-re))))
  5417. (list old-regexp org-target-link-regexp)
  5418. "\\|")
  5419. after-re)))))
  5420. (org-with-wide-buffer
  5421. (goto-char (point-min))
  5422. (while (re-search-forward regexp nil t)
  5423. (org-element-cache-refresh (match-beginning 1)))))
  5424. ;; Re fontify buffer.
  5425. (when (memq 'radio org-highlight-links)
  5426. (org-restart-font-lock)))))
  5427. (defun org-hide-wide-columns (limit)
  5428. (let (s e)
  5429. (setq s (text-property-any (point) (or limit (point-max))
  5430. 'org-cwidth t))
  5431. (when s
  5432. (setq e (next-single-property-change s 'org-cwidth))
  5433. (add-text-properties s e '(invisible org-cwidth))
  5434. (goto-char e)
  5435. t)))
  5436. (defvar org-latex-and-related-regexp nil
  5437. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5438. (defun org-compute-latex-and-related-regexp ()
  5439. "Compute regular expression for LaTeX, entities and sub/superscript.
  5440. Result depends on variable `org-highlight-latex-and-related'."
  5441. (setq-local
  5442. org-latex-and-related-regexp
  5443. (let* ((re-sub
  5444. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5445. ((eq org-use-sub-superscripts '{})
  5446. (list org-match-substring-with-braces-regexp))
  5447. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5448. (re-latex
  5449. (when (memq 'latex org-highlight-latex-and-related)
  5450. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5451. (delq nil
  5452. (mapcar (lambda (x)
  5453. (and (member (car x) matchers) (nth 1 x)))
  5454. org-latex-regexps)))))
  5455. (re-entities
  5456. (when (memq 'entities org-highlight-latex-and-related)
  5457. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5458. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5459. (defun org-do-latex-and-related (limit)
  5460. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5461. LIMIT bounds the search for syntax to highlight. Stop at first
  5462. highlighted object, if any. Return t if some highlighting was
  5463. done, nil otherwise."
  5464. (when (org-string-nw-p org-latex-and-related-regexp)
  5465. (catch 'found
  5466. (while (re-search-forward org-latex-and-related-regexp limit t)
  5467. (unless
  5468. (cl-some
  5469. (lambda (f)
  5470. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5471. (save-excursion
  5472. (goto-char (1+ (match-beginning 0)))
  5473. (face-at-point nil t)))
  5474. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5475. '(?_ ?^))
  5476. 1
  5477. 0)))
  5478. (font-lock-prepend-text-property
  5479. (+ offset (match-beginning 0)) (match-end 0)
  5480. 'face 'org-latex-and-related)
  5481. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5482. '(font-lock-multiline t)))
  5483. (throw 'found t)))
  5484. nil)))
  5485. (defun org-restart-font-lock ()
  5486. "Restart `font-lock-mode', to force refontification."
  5487. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5488. (font-lock-mode -1)
  5489. (font-lock-mode 1)))
  5490. (defun org-activate-tags (limit)
  5491. (when (re-search-forward
  5492. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5493. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5494. (add-text-properties (match-beginning 1) (match-end 1)
  5495. (list 'mouse-face 'highlight
  5496. 'keymap org-mouse-map))
  5497. (org-rear-nonsticky-at (match-end 1))
  5498. t))
  5499. (defun org-outline-level ()
  5500. "Compute the outline level of the heading at point.
  5501. If this is called at a normal headline, the level is the number
  5502. of stars. Use `org-reduced-level' to remove the effect of
  5503. `org-odd-levels'. Unlike to `org-current-level', this function
  5504. takes into consideration inlinetasks."
  5505. (org-with-wide-buffer
  5506. (end-of-line)
  5507. (if (re-search-backward org-outline-regexp-bol nil t)
  5508. (1- (- (match-end 0) (match-beginning 0)))
  5509. 0)))
  5510. (defvar org-font-lock-keywords nil)
  5511. (defsubst org-re-property (property &optional literal allow-null value)
  5512. "Return a regexp matching a PROPERTY line.
  5513. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5514. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5515. non-nil, match properties even without a value.
  5516. Match group 3 is set to the value when it exists. If there is no
  5517. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5518. With optional argument VALUE, match only property lines with
  5519. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5520. unless LITERAL is non-nil."
  5521. (concat
  5522. "^\\(?4:[ \t]*\\)"
  5523. (format "\\(?1::\\(?2:%s\\):\\)"
  5524. (if literal property (regexp-quote property)))
  5525. (cond (value
  5526. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5527. (if literal value (regexp-quote value))))
  5528. (allow-null
  5529. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5530. (t
  5531. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5532. (defconst org-property-re
  5533. (org-re-property "\\S-+" 'literal t)
  5534. "Regular expression matching a property line.
  5535. There are four matching groups:
  5536. 1: :PROPKEY: including the leading and trailing colon,
  5537. 2: PROPKEY without the leading and trailing colon,
  5538. 3: PROPVAL without leading or trailing spaces,
  5539. 4: the indentation of the current line,
  5540. 5: trailing whitespace.")
  5541. (defvar org-font-lock-hook nil
  5542. "Functions to be called for special font lock stuff.")
  5543. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5544. (defvar org-font-lock-set-keywords-hook nil
  5545. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5546. This is called after `org-font-lock-extra-keywords' is defined, but before
  5547. it is installed to be used by font lock. This can be useful if something
  5548. needs to be inserted at a specific position in the font-lock sequence.")
  5549. (defun org-font-lock-hook (limit)
  5550. "Run `org-font-lock-hook' within LIMIT."
  5551. (run-hook-with-args 'org-font-lock-hook limit))
  5552. (defun org-set-font-lock-defaults ()
  5553. "Set font lock defaults for the current buffer."
  5554. (let* ((em org-fontify-emphasized-text)
  5555. (lk org-highlight-links)
  5556. (org-font-lock-extra-keywords
  5557. (list
  5558. ;; Call the hook
  5559. '(org-font-lock-hook)
  5560. ;; Headlines
  5561. `(,(if org-fontify-whole-heading-line
  5562. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5563. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5564. (1 (org-get-level-face 1))
  5565. (2 (org-get-level-face 2))
  5566. (3 (org-get-level-face 3)))
  5567. ;; Table lines
  5568. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5569. (1 'org-table t))
  5570. ;; Table internals
  5571. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5572. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5573. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5574. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5575. ;; Drawers
  5576. '(org-fontify-drawers)
  5577. ;; Properties
  5578. (list org-property-re
  5579. '(1 'org-special-keyword t)
  5580. '(3 'org-property-value t))
  5581. ;; Link related fontification.
  5582. '(org-activate-links)
  5583. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5584. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5585. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5586. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5587. ;; Targets.
  5588. (list org-any-target-regexp '(0 'org-target t))
  5589. ;; Diary sexps.
  5590. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5591. ;; Macro
  5592. '(org-fontify-macros)
  5593. '(org-hide-wide-columns (0 nil append))
  5594. ;; TODO keyword
  5595. (list (format org-heading-keyword-regexp-format
  5596. org-todo-regexp)
  5597. '(2 (org-get-todo-face 2) t))
  5598. ;; DONE
  5599. (if org-fontify-done-headline
  5600. (list (format org-heading-keyword-regexp-format
  5601. (concat
  5602. "\\(?:"
  5603. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5604. "\\)"))
  5605. '(2 'org-headline-done t))
  5606. nil)
  5607. ;; Priorities
  5608. '(org-font-lock-add-priority-faces)
  5609. ;; Tags
  5610. '(org-font-lock-add-tag-faces)
  5611. ;; Tags groups
  5612. (when (and org-group-tags org-tag-groups-alist)
  5613. (list (concat org-outline-regexp-bol ".+\\(:"
  5614. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5615. ":\\).*$")
  5616. '(1 'org-tag-group prepend)))
  5617. ;; Special keywords
  5618. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5619. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5620. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5621. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5622. ;; Emphasis
  5623. (when em '(org-do-emphasis-faces))
  5624. ;; Checkboxes
  5625. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5626. 1 'org-checkbox prepend)
  5627. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5628. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5629. (0 (org-get-checkbox-statistics-face) t)))
  5630. ;; Description list items
  5631. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5632. 1 'org-list-dt prepend)
  5633. ;; ARCHIVEd headings
  5634. (list (concat
  5635. org-outline-regexp-bol
  5636. "\\(.*:" org-archive-tag ":.*\\)")
  5637. '(1 'org-archived prepend))
  5638. ;; Specials
  5639. '(org-do-latex-and-related)
  5640. '(org-fontify-entities)
  5641. '(org-raise-scripts)
  5642. ;; Code
  5643. '(org-activate-code (1 'org-code t))
  5644. ;; COMMENT
  5645. (list (format
  5646. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5647. org-todo-regexp
  5648. org-comment-string)
  5649. '(9 'org-special-keyword t))
  5650. ;; Blocks and meta lines
  5651. '(org-fontify-meta-lines-and-blocks))))
  5652. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5653. (run-hooks 'org-font-lock-set-keywords-hook)
  5654. ;; Now set the full font-lock-keywords
  5655. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5656. (setq-local font-lock-defaults
  5657. '(org-font-lock-keywords t nil nil backward-paragraph))
  5658. (kill-local-variable 'font-lock-keywords)
  5659. nil))
  5660. (defun org-toggle-pretty-entities ()
  5661. "Toggle the composition display of entities as UTF8 characters."
  5662. (interactive)
  5663. (setq-local org-pretty-entities (not org-pretty-entities))
  5664. (org-restart-font-lock)
  5665. (if org-pretty-entities
  5666. (message "Entities are now displayed as UTF8 characters")
  5667. (save-restriction
  5668. (widen)
  5669. (decompose-region (point-min) (point-max))
  5670. (message "Entities are now displayed as plain text"))))
  5671. (defvar-local org-custom-properties-overlays nil
  5672. "List of overlays used for custom properties.")
  5673. (defun org-toggle-custom-properties-visibility ()
  5674. "Display or hide properties in `org-custom-properties'."
  5675. (interactive)
  5676. (if org-custom-properties-overlays
  5677. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5678. (setq org-custom-properties-overlays nil))
  5679. (when org-custom-properties
  5680. (org-with-wide-buffer
  5681. (goto-char (point-min))
  5682. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5683. (while (re-search-forward regexp nil t)
  5684. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5685. (when (and end (< (point) end))
  5686. ;; Hide first custom property in current drawer.
  5687. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5688. (overlay-put o 'invisible t)
  5689. (overlay-put o 'org-custom-property t)
  5690. (push o org-custom-properties-overlays))
  5691. ;; Hide additional custom properties in the same drawer.
  5692. (while (re-search-forward regexp end t)
  5693. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5694. (overlay-put o 'invisible t)
  5695. (overlay-put o 'org-custom-property t)
  5696. (push o org-custom-properties-overlays)))))
  5697. ;; Each entry is limited to a single property drawer.
  5698. (outline-next-heading)))))))
  5699. (defun org-fontify-entities (limit)
  5700. "Find an entity to fontify."
  5701. (let (ee)
  5702. (when org-pretty-entities
  5703. (catch 'match
  5704. ;; "\_ "-family is left out on purpose. Only the first one,
  5705. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5706. ;; confusing when adding a second white space character.
  5707. (while (re-search-forward
  5708. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5709. limit t)
  5710. (when (and (not (org-at-comment-p))
  5711. (setq ee (org-entity-get (match-string 1)))
  5712. (= (length (nth 6 ee)) 1))
  5713. (let* ((end (if (equal (match-string 2) "{}")
  5714. (match-end 2)
  5715. (match-end 1))))
  5716. (add-text-properties
  5717. (match-beginning 0) end
  5718. (list 'font-lock-fontified t))
  5719. (compose-region (match-beginning 0) end
  5720. (nth 6 ee) nil)
  5721. (backward-char 1)
  5722. (throw 'match t))))
  5723. nil))))
  5724. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5725. "Fontify string S like in Org mode."
  5726. (with-temp-buffer
  5727. (insert s)
  5728. (let ((org-odd-levels-only odd-levels))
  5729. (org-mode)
  5730. (org-font-lock-ensure)
  5731. (buffer-string))))
  5732. (defvar org-m nil)
  5733. (defvar org-l nil)
  5734. (defvar org-f nil)
  5735. (defun org-get-level-face (n)
  5736. "Get the right face for match N in font-lock matching of headlines."
  5737. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5738. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5739. (if org-cycle-level-faces
  5740. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5741. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5742. (cond
  5743. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5744. ((eq n 2) org-f)
  5745. (t (unless org-level-color-stars-only org-f))))
  5746. (defun org-face-from-face-or-color (context inherit face-or-color)
  5747. "Create a face list that inherits INHERIT, but sets the foreground color.
  5748. When FACE-OR-COLOR is not a string, just return it."
  5749. (if (stringp face-or-color)
  5750. (list :inherit inherit
  5751. (cdr (assoc context org-faces-easy-properties))
  5752. face-or-color)
  5753. face-or-color))
  5754. (defun org-get-todo-face (kwd)
  5755. "Get the right face for a TODO keyword KWD.
  5756. If KWD is a number, get the corresponding match group."
  5757. (when (numberp kwd) (setq kwd (match-string kwd)))
  5758. (or (org-face-from-face-or-color
  5759. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5760. (and (member kwd org-done-keywords) 'org-done)
  5761. 'org-todo))
  5762. (defun org-get-priority-face (priority)
  5763. "Get the right face for PRIORITY.
  5764. PRIORITY is a character."
  5765. (or (org-face-from-face-or-color
  5766. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5767. 'org-priority))
  5768. (defun org-get-tag-face (tag)
  5769. "Get the right face for TAG.
  5770. If TAG is a number, get the corresponding match group."
  5771. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5772. (or (org-face-from-face-or-color
  5773. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5774. 'org-tag)))
  5775. (defun org-font-lock-add-priority-faces (limit)
  5776. "Add the special priority faces."
  5777. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5778. (add-text-properties
  5779. (match-beginning 1) (match-end 1)
  5780. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5781. 'font-lock-fontified t))))
  5782. (defun org-font-lock-add-tag-faces (limit)
  5783. "Add the special tag faces."
  5784. (when (and org-tag-faces org-tags-special-faces-re)
  5785. (while (re-search-forward org-tags-special-faces-re limit t)
  5786. (add-text-properties (match-beginning 1) (match-end 1)
  5787. (list 'face (org-get-tag-face 1)
  5788. 'font-lock-fontified t))
  5789. (backward-char 1))))
  5790. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5791. "Remove fontification and activation overlays from links."
  5792. (font-lock-default-unfontify-region beg end)
  5793. (let* ((buffer-undo-list t)
  5794. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5795. (inhibit-modification-hooks t)
  5796. deactivate-mark buffer-file-name buffer-file-truename)
  5797. (decompose-region beg end)
  5798. (remove-text-properties beg end
  5799. '(mouse-face t keymap t org-linked-text t
  5800. invisible t intangible t
  5801. org-emphasis t))
  5802. (org-remove-font-lock-display-properties beg end)))
  5803. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5804. ((raise 0.3) (height 0.7))
  5805. ((raise -0.5))
  5806. ((raise 0.5)))
  5807. "Display properties for showing superscripts and subscripts.")
  5808. (defun org-remove-font-lock-display-properties (beg end)
  5809. "Remove specific display properties that have been added by font lock.
  5810. The will remove the raise properties that are used to show superscripts
  5811. and subscripts."
  5812. (let (next prop)
  5813. (while (< beg end)
  5814. (setq next (next-single-property-change beg 'display nil end)
  5815. prop (get-text-property beg 'display))
  5816. (when (member prop org-script-display)
  5817. (put-text-property beg next 'display nil))
  5818. (setq beg next))))
  5819. (defun org-raise-scripts (limit)
  5820. "Add raise properties to sub/superscripts."
  5821. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5822. (re-search-forward
  5823. (if (eq org-use-sub-superscripts t)
  5824. org-match-substring-regexp
  5825. org-match-substring-with-braces-regexp)
  5826. limit t))
  5827. (let* ((pos (point)) table-p comment-p
  5828. (mpos (match-beginning 3))
  5829. (emph-p (get-text-property mpos 'org-emphasis))
  5830. (link-p (get-text-property mpos 'mouse-face))
  5831. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5832. (goto-char (point-at-bol))
  5833. (setq table-p (looking-at-p org-table-dataline-regexp)
  5834. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5835. (goto-char pos)
  5836. ;; Handle a_b^c
  5837. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5838. (unless (or comment-p emph-p link-p keyw-p)
  5839. (put-text-property (match-beginning 3) (match-end 0)
  5840. 'display
  5841. (if (equal (char-after (match-beginning 2)) ?^)
  5842. (nth (if table-p 3 1) org-script-display)
  5843. (nth (if table-p 2 0) org-script-display)))
  5844. (add-text-properties (match-beginning 2) (match-end 2)
  5845. (list 'invisible t))
  5846. (when (and (eq (char-after (match-beginning 3)) ?{)
  5847. (eq (char-before (match-end 3)) ?}))
  5848. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5849. (list 'invisible t))
  5850. (add-text-properties (1- (match-end 3)) (match-end 3)
  5851. (list 'invisible t))))
  5852. t)))
  5853. ;;;; Visibility cycling, including org-goto and indirect buffer
  5854. ;;; Cycling
  5855. (defvar-local org-cycle-global-status nil)
  5856. (put 'org-cycle-global-status 'org-state t)
  5857. (defvar-local org-cycle-subtree-status nil)
  5858. (put 'org-cycle-subtree-status 'org-state t)
  5859. (defvar org-inlinetask-min-level)
  5860. (defun org-unlogged-message (&rest args)
  5861. "Display a message, but avoid logging it in the *Messages* buffer."
  5862. (let ((message-log-max nil))
  5863. (apply 'message args)))
  5864. ;;;###autoload
  5865. (defun org-cycle (&optional arg)
  5866. "TAB-action and visibility cycling for Org mode.
  5867. This is the command invoked in Org mode by the `TAB' key. Its main
  5868. purpose is outline visibility cycling, but it also invokes other actions
  5869. in special contexts.
  5870. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5871. the entire
  5872. buffer through 3 states (global cycling)
  5873. 1. OVERVIEW: Show only top-level headlines.
  5874. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5875. 3. SHOW ALL: Show everything.
  5876. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5877. switch to the startup visibility,
  5878. determined by the variable `org-startup-folded', and by any VISIBILITY
  5879. properties in the buffer.
  5880. With a `\\[universal-argument] \\[universal-argument] \
  5881. \\[universal-argument]' prefix argument, show the entire buffer, including
  5882. any drawers.
  5883. When inside a table, re-align the table and move to the next field.
  5884. When point is at the beginning of a headline, rotate the subtree started
  5885. by this line through 3 different states (local cycling)
  5886. 1. FOLDED: Only the main headline is shown.
  5887. 2. CHILDREN: The main headline and the direct children are shown.
  5888. From this state, you can move to one of the children
  5889. and zoom in further.
  5890. 3. SUBTREE: Show the entire subtree, including body text.
  5891. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5892. When point is at the beginning of an empty headline and the variable
  5893. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5894. of the headline by demoting and promoting it to likely levels. This
  5895. speeds up creation document structure by pressing `TAB' once or several
  5896. times right after creating a new headline.
  5897. When there is a numeric prefix, go up to a heading with level ARG, do
  5898. a `show-subtree' and return to the previous cursor position. If ARG
  5899. is negative, go up that many levels.
  5900. When point is not at the beginning of a headline, execute the global
  5901. binding for `TAB', which is re-indenting the line. See the option
  5902. `org-cycle-emulate-tab' for details.
  5903. As a special case, if point is at the beginning of the buffer and there is
  5904. no headline in line 1, this function will act as if called with prefix arg
  5905. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5906. prefix arg, but only
  5907. if the variable `org-cycle-global-at-bob' is t."
  5908. (interactive "P")
  5909. (org-load-modules-maybe)
  5910. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5911. (and org-cycle-level-after-item/entry-creation
  5912. (or (org-cycle-level)
  5913. (org-cycle-item-indentation))))
  5914. (let* ((limit-level
  5915. (or org-cycle-max-level
  5916. (and (boundp 'org-inlinetask-min-level)
  5917. org-inlinetask-min-level
  5918. (1- org-inlinetask-min-level))))
  5919. (nstars (and limit-level
  5920. (if org-odd-levels-only
  5921. (and limit-level (1- (* limit-level 2)))
  5922. limit-level)))
  5923. (org-outline-regexp
  5924. (if (not (derived-mode-p 'org-mode))
  5925. outline-regexp
  5926. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5927. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5928. (not (looking-at org-outline-regexp))))
  5929. (org-cycle-hook
  5930. (if bob-special
  5931. (delq 'org-optimize-window-after-visibility-change
  5932. (copy-sequence org-cycle-hook))
  5933. org-cycle-hook))
  5934. (pos (point)))
  5935. (cond
  5936. ((equal arg '(16))
  5937. (setq last-command 'dummy)
  5938. (org-set-startup-visibility)
  5939. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5940. ((equal arg '(64))
  5941. (outline-show-all)
  5942. (org-unlogged-message "Entire buffer visible, including drawers"))
  5943. ((equal arg '(4)) (org-cycle-internal-global))
  5944. ;; Try hiding block at point.
  5945. ((org-hide-block-toggle-maybe))
  5946. ;; Try cdlatex TAB completion
  5947. ((org-try-cdlatex-tab))
  5948. ;; Table: enter it or move to the next field.
  5949. ((org-at-table-p 'any)
  5950. (if (org-at-table.el-p)
  5951. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5952. Use `\\[org-edit-special]' to edit table.el tables"))
  5953. (if arg (org-table-edit-field t)
  5954. (org-table-justify-field-maybe)
  5955. (call-interactively 'org-table-next-field))))
  5956. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5957. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5958. (bob-special (org-cycle-internal-global))
  5959. ;; Drawers: delegate to `org-flag-drawer'.
  5960. ((save-excursion
  5961. (beginning-of-line 1)
  5962. (looking-at org-drawer-regexp))
  5963. (org-flag-drawer ; toggle block visibility
  5964. (not (get-char-property (match-end 0) 'invisible))))
  5965. ;; Show-subtree, ARG levels up from here.
  5966. ((integerp arg)
  5967. (save-excursion
  5968. (org-back-to-heading)
  5969. (outline-up-heading (if (< arg 0) (- arg)
  5970. (- (funcall outline-level) arg)))
  5971. (org-show-subtree)))
  5972. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5973. ((and (featurep 'org-inlinetask)
  5974. (org-inlinetask-at-task-p)
  5975. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5976. (org-inlinetask-toggle-visibility))
  5977. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5978. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5979. (save-excursion (move-beginning-of-line 1)
  5980. (looking-at org-outline-regexp)))
  5981. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5982. (org-cycle-internal-local))
  5983. ;; From there: TAB emulation and template completion.
  5984. (buffer-read-only (org-back-to-heading))
  5985. ((run-hook-with-args-until-success
  5986. 'org-tab-after-check-for-cycling-hook))
  5987. ((org-try-structure-completion))
  5988. ((run-hook-with-args-until-success
  5989. 'org-tab-before-tab-emulation-hook))
  5990. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5991. (or (not (bolp))
  5992. (not (looking-at org-outline-regexp))))
  5993. (call-interactively (global-key-binding "\t")))
  5994. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5995. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5996. (or (and (eq org-cycle-emulate-tab 'white)
  5997. (= (match-end 0) (point-at-eol)))
  5998. (and (eq org-cycle-emulate-tab 'whitestart)
  5999. (>= (match-end 0) pos))))
  6000. t
  6001. (eq org-cycle-emulate-tab t))
  6002. (call-interactively (global-key-binding "\t")))
  6003. (t (save-excursion
  6004. (org-back-to-heading)
  6005. (org-cycle)))))))
  6006. (defun org-cycle-internal-global ()
  6007. "Do the global cycling action."
  6008. ;; Hack to avoid display of messages for .org attachments in Gnus
  6009. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6010. (cond
  6011. ((and (eq last-command this-command)
  6012. (eq org-cycle-global-status 'overview))
  6013. ;; We just created the overview - now do table of contents
  6014. ;; This can be slow in very large buffers, so indicate action
  6015. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6016. (unless ga (org-unlogged-message "CONTENTS..."))
  6017. (org-content)
  6018. (unless ga (org-unlogged-message "CONTENTS...done"))
  6019. (setq org-cycle-global-status 'contents)
  6020. (run-hook-with-args 'org-cycle-hook 'contents))
  6021. ((and (eq last-command this-command)
  6022. (eq org-cycle-global-status 'contents))
  6023. ;; We just showed the table of contents - now show everything
  6024. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6025. (outline-show-all)
  6026. (unless ga (org-unlogged-message "SHOW ALL"))
  6027. (setq org-cycle-global-status 'all)
  6028. (run-hook-with-args 'org-cycle-hook 'all))
  6029. (t
  6030. ;; Default action: go to overview
  6031. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6032. (org-overview)
  6033. (unless ga (org-unlogged-message "OVERVIEW"))
  6034. (setq org-cycle-global-status 'overview)
  6035. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6036. (defvar org-called-with-limited-levels nil
  6037. "Non-nil when `org-with-limited-levels' is currently active.")
  6038. (defun org-invisible-p (&optional pos)
  6039. "Non-nil if the character after POS is invisible.
  6040. If POS is nil, use `point' instead."
  6041. (get-char-property (or pos (point)) 'invisible))
  6042. (defun org-cycle-internal-local ()
  6043. "Do the local cycling action."
  6044. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6045. ;; First, determine end of headline (EOH), end of subtree or item
  6046. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6047. (save-excursion
  6048. (if (org-at-item-p)
  6049. (progn
  6050. (beginning-of-line)
  6051. (setq struct (org-list-struct))
  6052. (setq eoh (point-at-eol))
  6053. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6054. (setq has-children (org-list-has-child-p (point) struct)))
  6055. (org-back-to-heading)
  6056. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6057. (setq eos (save-excursion (org-end-of-subtree t t)
  6058. (when (bolp) (backward-char)) (point)))
  6059. (setq has-children
  6060. (or (save-excursion
  6061. (let ((level (funcall outline-level)))
  6062. (outline-next-heading)
  6063. (and (org-at-heading-p t)
  6064. (> (funcall outline-level) level))))
  6065. (save-excursion
  6066. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6067. ;; Determine end invisible part of buffer (EOL)
  6068. (beginning-of-line 2)
  6069. (while (and (not (eobp)) ;This is like `next-line'.
  6070. (get-char-property (1- (point)) 'invisible))
  6071. (goto-char (next-single-char-property-change (point) 'invisible))
  6072. (and (eolp) (beginning-of-line 2)))
  6073. (setq eol (point)))
  6074. ;; Find out what to do next and set `this-command'
  6075. (cond
  6076. ((= eos eoh)
  6077. ;; Nothing is hidden behind this heading
  6078. (unless (org-before-first-heading-p)
  6079. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6080. (org-unlogged-message "EMPTY ENTRY")
  6081. (setq org-cycle-subtree-status nil)
  6082. (save-excursion
  6083. (goto-char eos)
  6084. (outline-next-heading)
  6085. (when (org-invisible-p) (org-flag-heading nil))))
  6086. ((and (or (>= eol eos)
  6087. (not (string-match "\\S-" (buffer-substring eol eos))))
  6088. (or has-children
  6089. (not (setq children-skipped
  6090. org-cycle-skip-children-state-if-no-children))))
  6091. ;; Entire subtree is hidden in one line: children view
  6092. (unless (org-before-first-heading-p)
  6093. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6094. (if (org-at-item-p)
  6095. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6096. (org-show-entry)
  6097. (org-with-limited-levels (org-show-children))
  6098. (org-show-set-visibility 'canonical)
  6099. ;; FIXME: This slows down the func way too much.
  6100. ;; How keep drawers hidden in subtree anyway?
  6101. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6102. ;; (org-cycle-hide-drawers 'subtree))
  6103. ;; Fold every list in subtree to top-level items.
  6104. (when (eq org-cycle-include-plain-lists 'integrate)
  6105. (save-excursion
  6106. (org-back-to-heading)
  6107. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6108. (beginning-of-line 1)
  6109. (let* ((struct (org-list-struct))
  6110. (prevs (org-list-prevs-alist struct))
  6111. (end (org-list-get-bottom-point struct)))
  6112. (dolist (e (org-list-get-all-items (point) struct prevs))
  6113. (org-list-set-item-visibility e struct 'folded))
  6114. (goto-char (if (< end eos) end eos)))))))
  6115. (org-unlogged-message "CHILDREN")
  6116. (save-excursion
  6117. (goto-char eos)
  6118. (outline-next-heading)
  6119. (when (org-invisible-p) (org-flag-heading nil)))
  6120. (setq org-cycle-subtree-status 'children)
  6121. (unless (org-before-first-heading-p)
  6122. (run-hook-with-args 'org-cycle-hook 'children)))
  6123. ((or children-skipped
  6124. (and (eq last-command this-command)
  6125. (eq org-cycle-subtree-status 'children)))
  6126. ;; We just showed the children, or no children are there,
  6127. ;; now show everything.
  6128. (unless (org-before-first-heading-p)
  6129. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6130. (outline-flag-region eoh eos nil)
  6131. (org-unlogged-message
  6132. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6133. (setq org-cycle-subtree-status 'subtree)
  6134. (unless (org-before-first-heading-p)
  6135. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6136. (t
  6137. ;; Default action: hide the subtree.
  6138. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6139. (outline-flag-region eoh eos t)
  6140. (org-unlogged-message "FOLDED")
  6141. (setq org-cycle-subtree-status 'folded)
  6142. (unless (org-before-first-heading-p)
  6143. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6144. ;;;###autoload
  6145. (defun org-global-cycle (&optional arg)
  6146. "Cycle the global visibility. For details see `org-cycle'.
  6147. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6148. With a numeric prefix, show all headlines up to that level."
  6149. (interactive "P")
  6150. (let ((org-cycle-include-plain-lists
  6151. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6152. (cond
  6153. ((integerp arg)
  6154. (outline-show-all)
  6155. (outline-hide-sublevels arg)
  6156. (setq org-cycle-global-status 'contents))
  6157. ((equal arg '(4))
  6158. (org-set-startup-visibility)
  6159. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6160. (t
  6161. (org-cycle '(4))))))
  6162. (defun org-set-startup-visibility ()
  6163. "Set the visibility required by startup options and properties."
  6164. (cond
  6165. ((eq org-startup-folded t)
  6166. (org-overview))
  6167. ((eq org-startup-folded 'content)
  6168. (org-content))
  6169. ((or (eq org-startup-folded 'showeverything)
  6170. (eq org-startup-folded nil))
  6171. (outline-show-all)))
  6172. (unless (eq org-startup-folded 'showeverything)
  6173. (when org-hide-block-startup (org-hide-block-all))
  6174. (org-set-visibility-according-to-property 'no-cleanup)
  6175. (org-cycle-hide-archived-subtrees 'all)
  6176. (org-cycle-hide-drawers 'all)
  6177. (org-cycle-show-empty-lines t)))
  6178. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6179. "Switch subtree visibilities according to :VISIBILITY: property."
  6180. (interactive)
  6181. (org-with-wide-buffer
  6182. (goto-char (point-min))
  6183. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6184. (if (not (org-at-property-p)) (outline-next-heading)
  6185. (let ((state (match-string 3)))
  6186. (save-excursion
  6187. (org-back-to-heading t)
  6188. (outline-hide-subtree)
  6189. (org-reveal))
  6190. (cond
  6191. ((equal state "folded")
  6192. (outline-hide-subtree)
  6193. (org-end-of-subtree t t))
  6194. ((equal state "children")
  6195. (org-show-hidden-entry)
  6196. (org-show-children))
  6197. ((equal state "content")
  6198. (save-excursion
  6199. (save-restriction
  6200. (org-narrow-to-subtree)
  6201. (org-content)))
  6202. (org-end-of-subtree t t))
  6203. ((member state '("all" "showall"))
  6204. (outline-show-subtree))))))
  6205. (unless no-cleanup
  6206. (org-cycle-hide-archived-subtrees 'all)
  6207. (org-cycle-hide-drawers 'all)
  6208. (org-cycle-show-empty-lines 'all))))
  6209. ;; This function uses outline-regexp instead of the more fundamental
  6210. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6211. ;; buffers, where outline-regexp is needed.
  6212. (defun org-overview ()
  6213. "Switch to overview mode, showing only top-level headlines.
  6214. This shows all headlines with a level equal or greater than the level
  6215. of the first headline in the buffer. This is important, because if the
  6216. first headline is not level one, then (hide-sublevels 1) gives confusing
  6217. results."
  6218. (interactive)
  6219. (save-excursion
  6220. (let ((level
  6221. (save-excursion
  6222. (goto-char (point-min))
  6223. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6224. (goto-char (match-beginning 0))
  6225. (funcall outline-level)))))
  6226. (and level (outline-hide-sublevels level)))))
  6227. (defun org-content (&optional arg)
  6228. "Show all headlines in the buffer, like a table of contents.
  6229. With numerical argument N, show content up to level N."
  6230. (interactive "P")
  6231. (org-overview)
  6232. (save-excursion
  6233. ;; Visit all headings and show their offspring
  6234. (and (integerp arg) (org-overview))
  6235. (goto-char (point-max))
  6236. (catch 'exit
  6237. (while (and (progn (condition-case nil
  6238. (outline-previous-visible-heading 1)
  6239. (error (goto-char (point-min))))
  6240. t)
  6241. (looking-at org-outline-regexp))
  6242. (if (integerp arg)
  6243. (org-show-children (1- arg))
  6244. (outline-show-branches))
  6245. (when (bobp) (throw 'exit nil))))))
  6246. (defun org-optimize-window-after-visibility-change (state)
  6247. "Adjust the window after a change in outline visibility.
  6248. This function is the default value of the hook `org-cycle-hook'."
  6249. (when (get-buffer-window (current-buffer))
  6250. (cond
  6251. ((eq state 'content) nil)
  6252. ((eq state 'all) nil)
  6253. ((eq state 'folded) nil)
  6254. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6255. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6256. (defun org-remove-empty-overlays-at (pos)
  6257. "Remove outline overlays that do not contain non-white stuff."
  6258. (dolist (o (overlays-at pos))
  6259. (and (eq 'outline (overlay-get o 'invisible))
  6260. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6261. (overlay-end o))))
  6262. (delete-overlay o))))
  6263. (defun org-clean-visibility-after-subtree-move ()
  6264. "Fix visibility issues after moving a subtree."
  6265. ;; First, find a reasonable region to look at:
  6266. ;; Start two siblings above, end three below
  6267. (let* ((beg (save-excursion
  6268. (and (org-get-last-sibling)
  6269. (org-get-last-sibling))
  6270. (point)))
  6271. (end (save-excursion
  6272. (and (org-get-next-sibling)
  6273. (org-get-next-sibling)
  6274. (org-get-next-sibling))
  6275. (if (org-at-heading-p)
  6276. (point-at-eol)
  6277. (point))))
  6278. (level (looking-at "\\*+"))
  6279. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6280. (save-excursion
  6281. (save-restriction
  6282. (narrow-to-region beg end)
  6283. (when re
  6284. ;; Properly fold already folded siblings
  6285. (goto-char (point-min))
  6286. (while (re-search-forward re nil t)
  6287. (when (and (not (org-invisible-p))
  6288. (save-excursion
  6289. (goto-char (point-at-eol)) (org-invisible-p)))
  6290. (outline-hide-entry))))
  6291. (org-cycle-show-empty-lines 'overview)
  6292. (org-cycle-hide-drawers 'overview)))))
  6293. (defun org-cycle-show-empty-lines (state)
  6294. "Show empty lines above all visible headlines.
  6295. The region to be covered depends on STATE when called through
  6296. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6297. entire buffer covered. Note that an empty line is only shown if there
  6298. are at least `org-cycle-separator-lines' empty lines before the headline."
  6299. (when (/= org-cycle-separator-lines 0)
  6300. (save-excursion
  6301. (let* ((n (abs org-cycle-separator-lines))
  6302. (re (cond
  6303. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6304. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6305. (t (let ((ns (number-to-string (- n 2))))
  6306. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6307. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6308. beg end)
  6309. (cond
  6310. ((memq state '(overview contents t))
  6311. (setq beg (point-min) end (point-max)))
  6312. ((memq state '(children folded))
  6313. (setq beg (point)
  6314. end (progn (org-end-of-subtree t t)
  6315. (line-beginning-position 2)))))
  6316. (when beg
  6317. (goto-char beg)
  6318. (while (re-search-forward re end t)
  6319. (unless (get-char-property (match-end 1) 'invisible)
  6320. (let ((e (match-end 1))
  6321. (b (if (>= org-cycle-separator-lines 0)
  6322. (match-beginning 1)
  6323. (save-excursion
  6324. (goto-char (match-beginning 0))
  6325. (skip-chars-backward " \t\n")
  6326. (line-end-position)))))
  6327. (outline-flag-region b e nil))))))))
  6328. ;; Never hide empty lines at the end of the file.
  6329. (save-excursion
  6330. (goto-char (point-max))
  6331. (outline-previous-heading)
  6332. (outline-end-of-heading)
  6333. (when (and (looking-at "[ \t\n]+")
  6334. (= (match-end 0) (point-max)))
  6335. (outline-flag-region (point) (match-end 0) nil))))
  6336. (defun org-show-empty-lines-in-parent ()
  6337. "Move to the parent and re-show empty lines before visible headlines."
  6338. (save-excursion
  6339. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6340. (org-cycle-show-empty-lines context))))
  6341. (defun org-files-list ()
  6342. "Return `org-agenda-files' list, plus all open Org files.
  6343. This is useful for operations that need to scan all of a user's
  6344. open and agenda-wise Org files."
  6345. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  6346. (dolist (buf (buffer-list))
  6347. (with-current-buffer buf
  6348. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6349. (cl-pushnew (expand-file-name (buffer-file-name)) files
  6350. :test #'equal))))
  6351. files))
  6352. (defsubst org-entry-beginning-position ()
  6353. "Return the beginning position of the current entry."
  6354. (save-excursion (org-back-to-heading t) (point)))
  6355. (defsubst org-entry-end-position ()
  6356. "Return the end position of the current entry."
  6357. (save-excursion (outline-next-heading) (point)))
  6358. (defun org-cycle-hide-drawers (state &optional exceptions)
  6359. "Re-hide all drawers after a visibility state change.
  6360. STATE should be one of the symbols listed in the docstring of
  6361. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6362. a list of strings specifying which drawers should not be hidden."
  6363. (when (and (derived-mode-p 'org-mode)
  6364. (not (memq state '(overview folded contents))))
  6365. (save-excursion
  6366. (let* ((globalp (eq state 'all))
  6367. (beg (if globalp (point-min) (point)))
  6368. (end (if globalp (point-max)
  6369. (if (eq state 'children)
  6370. (save-excursion (outline-next-heading) (point))
  6371. (org-end-of-subtree t)))))
  6372. (goto-char beg)
  6373. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6374. (unless (member-ignore-case (match-string 1) exceptions)
  6375. (let ((drawer (org-element-at-point)))
  6376. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6377. (org-flag-drawer t drawer)
  6378. ;; Make sure to skip drawer entirely or we might flag
  6379. ;; it another time when matching its ending line with
  6380. ;; `org-drawer-regexp'.
  6381. (goto-char (org-element-property :end drawer))))))))))
  6382. (defun org-flag-drawer (flag &optional element)
  6383. "When FLAG is non-nil, hide the drawer we are at.
  6384. Otherwise make it visible. When optional argument ELEMENT is
  6385. a parsed drawer, as returned by `org-element-at-point', hide or
  6386. show that drawer instead."
  6387. (let ((drawer (or element
  6388. (and (save-excursion
  6389. (beginning-of-line)
  6390. (looking-at-p org-drawer-regexp))
  6391. (org-element-at-point)))))
  6392. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6393. (let ((post (org-element-property :post-affiliated drawer)))
  6394. (save-excursion
  6395. (outline-flag-region
  6396. (progn (goto-char post) (line-end-position))
  6397. (progn (goto-char (org-element-property :end drawer))
  6398. (skip-chars-backward " \r\t\n")
  6399. (line-end-position))
  6400. flag))
  6401. ;; When the drawer is hidden away, make sure point lies in
  6402. ;; a visible part of the buffer.
  6403. (when (and flag (> (line-beginning-position) post))
  6404. (goto-char post))))))
  6405. (defun org-subtree-end-visible-p ()
  6406. "Is the end of the current subtree visible?"
  6407. (pos-visible-in-window-p
  6408. (save-excursion (org-end-of-subtree t) (point))))
  6409. (defun org-first-headline-recenter ()
  6410. "Move cursor to the first headline and recenter the headline."
  6411. (let ((window (get-buffer-window)))
  6412. (when window
  6413. (goto-char (point-min))
  6414. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6415. (set-window-start window (line-beginning-position))))))
  6416. ;;; Saving and restoring visibility
  6417. (defun org-outline-overlay-data (&optional use-markers)
  6418. "Return a list of the locations of all outline overlays.
  6419. These are overlays with the `invisible' property value `outline'.
  6420. The return value is a list of cons cells, with start and stop
  6421. positions for each overlay.
  6422. If USE-MARKERS is set, return the positions as markers."
  6423. (let (beg end)
  6424. (org-with-wide-buffer
  6425. (delq nil
  6426. (mapcar (lambda (o)
  6427. (when (eq (overlay-get o 'invisible) 'outline)
  6428. (setq beg (overlay-start o)
  6429. end (overlay-end o))
  6430. (and beg end (> end beg)
  6431. (if use-markers
  6432. (cons (copy-marker beg)
  6433. (copy-marker end t))
  6434. (cons beg end)))))
  6435. (overlays-in (point-min) (point-max)))))))
  6436. (defun org-set-outline-overlay-data (data)
  6437. "Create visibility overlays for all positions in DATA.
  6438. DATA should have been made by `org-outline-overlay-data'."
  6439. (org-with-wide-buffer
  6440. (outline-show-all)
  6441. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6442. ;;; Folding of blocks
  6443. (defvar-local org-hide-block-overlays nil
  6444. "Overlays hiding blocks.")
  6445. (defun org-block-map (function &optional start end)
  6446. "Call FUNCTION at the head of all source blocks in the current buffer.
  6447. Optional arguments START and END can be used to limit the range."
  6448. (let ((start (or start (point-min)))
  6449. (end (or end (point-max))))
  6450. (save-excursion
  6451. (goto-char start)
  6452. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6453. (save-excursion
  6454. (save-match-data
  6455. (goto-char (match-beginning 0))
  6456. (funcall function)))))))
  6457. (defun org-hide-block-toggle-all ()
  6458. "Toggle the visibility of all blocks in the current buffer."
  6459. (org-block-map 'org-hide-block-toggle))
  6460. (defun org-hide-block-all ()
  6461. "Fold all blocks in the current buffer."
  6462. (interactive)
  6463. (org-show-block-all)
  6464. (org-block-map 'org-hide-block-toggle-maybe))
  6465. (defun org-show-block-all ()
  6466. "Unfold all blocks in the current buffer."
  6467. (interactive)
  6468. (mapc #'delete-overlay org-hide-block-overlays)
  6469. (setq org-hide-block-overlays nil))
  6470. (defun org-hide-block-toggle-maybe ()
  6471. "Toggle visibility of block at point.
  6472. Unlike to `org-hide-block-toggle', this function does not throw
  6473. an error. Return a non-nil value when toggling is successful."
  6474. (interactive)
  6475. (ignore-errors (org-hide-block-toggle)))
  6476. (defun org-hide-block-toggle (&optional force)
  6477. "Toggle the visibility of the current block.
  6478. When optional argument FORCE is `off', make block visible. If it
  6479. is non-nil, hide it unconditionally. Throw an error when not at
  6480. a block. Return a non-nil value when toggling is successful."
  6481. (interactive)
  6482. (let ((element (org-element-at-point)))
  6483. (unless (memq (org-element-type element)
  6484. '(center-block comment-block dynamic-block example-block
  6485. export-block quote-block special-block
  6486. src-block verse-block))
  6487. (user-error "Not at a block"))
  6488. (let* ((start (save-excursion
  6489. (goto-char (org-element-property :post-affiliated element))
  6490. (line-end-position)))
  6491. (end (save-excursion
  6492. (goto-char (org-element-property :end element))
  6493. (skip-chars-backward " \r\t\n")
  6494. (line-end-position)))
  6495. (overlays (overlays-at start)))
  6496. (cond
  6497. ;; Do nothing when not before or at the block opening line or
  6498. ;; at the block closing line.
  6499. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6500. ((and (not (eq force 'off))
  6501. (not (memq t (mapcar
  6502. (lambda (o)
  6503. (eq (overlay-get o 'invisible) 'org-hide-block))
  6504. overlays))))
  6505. (let ((ov (make-overlay start end)))
  6506. (overlay-put ov 'invisible 'org-hide-block)
  6507. ;; Make the block accessible to `isearch'.
  6508. (overlay-put
  6509. ov 'isearch-open-invisible
  6510. (lambda (ov)
  6511. (when (memq ov org-hide-block-overlays)
  6512. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6513. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6514. (delete-overlay ov))))
  6515. (push ov org-hide-block-overlays)
  6516. ;; When the block is hidden away, make sure point is left in
  6517. ;; a visible part of the buffer.
  6518. (when (> (line-beginning-position) start)
  6519. (goto-char start)
  6520. (beginning-of-line))
  6521. ;; Signal successful toggling.
  6522. t))
  6523. ((or (not force) (eq force 'off))
  6524. (dolist (ov overlays t)
  6525. (when (memq ov org-hide-block-overlays)
  6526. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6527. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6528. (delete-overlay ov))))))))
  6529. ;; Remove overlays when changing major mode
  6530. (add-hook 'org-mode-hook
  6531. (lambda () (add-hook 'change-major-mode-hook
  6532. 'org-show-block-all 'append 'local)))
  6533. ;;; Org-goto
  6534. (defvar org-goto-window-configuration nil)
  6535. (defvar org-goto-marker nil)
  6536. (defvar org-goto-map)
  6537. (defun org-goto-map ()
  6538. "Set the keymap `org-goto'."
  6539. (setq org-goto-map
  6540. (let ((map (make-sparse-keymap)))
  6541. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6542. mouse-drag-region universal-argument org-occur)))
  6543. (dolist (cmd cmds)
  6544. (substitute-key-definition cmd cmd map global-map)))
  6545. (suppress-keymap map)
  6546. (org-defkey map "\C-m" 'org-goto-ret)
  6547. (org-defkey map [(return)] 'org-goto-ret)
  6548. (org-defkey map [(left)] 'org-goto-left)
  6549. (org-defkey map [(right)] 'org-goto-right)
  6550. (org-defkey map [(control ?g)] 'org-goto-quit)
  6551. (org-defkey map "\C-i" 'org-cycle)
  6552. (org-defkey map [(tab)] 'org-cycle)
  6553. (org-defkey map [(down)] 'outline-next-visible-heading)
  6554. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6555. (if org-goto-auto-isearch
  6556. (if (fboundp 'define-key-after)
  6557. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6558. nil)
  6559. (org-defkey map "q" 'org-goto-quit)
  6560. (org-defkey map "n" 'outline-next-visible-heading)
  6561. (org-defkey map "p" 'outline-previous-visible-heading)
  6562. (org-defkey map "f" 'outline-forward-same-level)
  6563. (org-defkey map "b" 'outline-backward-same-level)
  6564. (org-defkey map "u" 'outline-up-heading))
  6565. (org-defkey map "/" 'org-occur)
  6566. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6567. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6568. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6569. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6570. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6571. map)))
  6572. (defconst org-goto-help
  6573. "Browse buffer copy, to find location or copy text.%s
  6574. RET=jump to location C-g=quit and return to previous location
  6575. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6576. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6577. (defun org-goto (&optional alternative-interface)
  6578. "Look up a different location in the current file, keeping current visibility.
  6579. When you want look-up or go to a different location in a
  6580. document, the fastest way is often to fold the entire buffer and
  6581. then dive into the tree. This method has the disadvantage, that
  6582. the previous location will be folded, which may not be what you
  6583. want.
  6584. This command works around this by showing a copy of the current
  6585. buffer in an indirect buffer, in overview mode. You can dive
  6586. into the tree in that copy, use org-occur and incremental search
  6587. to find a location. When pressing RET or `Q', the command
  6588. returns to the original buffer in which the visibility is still
  6589. unchanged. After RET it will also jump to the location selected
  6590. in the indirect buffer and expose the headline hierarchy above.
  6591. With a prefix argument, use the alternative interface: e.g., if
  6592. `org-goto-interface' is `outline' use `outline-path-completion'."
  6593. (interactive "P")
  6594. (org-goto-map)
  6595. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6596. (org-refile-use-outline-path t)
  6597. (org-refile-target-verify-function nil)
  6598. (interface
  6599. (if (not alternative-interface)
  6600. org-goto-interface
  6601. (if (eq org-goto-interface 'outline)
  6602. 'outline-path-completion
  6603. 'outline)))
  6604. (org-goto-start-pos (point))
  6605. (selected-point
  6606. (if (eq interface 'outline)
  6607. (car (org-get-location (current-buffer) org-goto-help))
  6608. (let ((pa (org-refile-get-location "Goto")))
  6609. (org-refile-check-position pa)
  6610. (nth 3 pa)))))
  6611. (if selected-point
  6612. (progn
  6613. (org-mark-ring-push org-goto-start-pos)
  6614. (goto-char selected-point)
  6615. (when (or (org-invisible-p) (org-invisible-p2))
  6616. (org-show-context 'org-goto)))
  6617. (message "Quit"))))
  6618. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6619. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6620. (defvar org-goto-local-auto-isearch-map) ; defined below
  6621. (defun org-get-location (_buf help)
  6622. "Let the user select a location in current buffer.
  6623. This function uses a recursive edit. It returns the selected position
  6624. or nil."
  6625. (org-no-popups
  6626. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6627. (isearch-hide-immediately nil)
  6628. (isearch-search-fun-function
  6629. (lambda () 'org-goto-local-search-headings))
  6630. (org-goto-selected-point org-goto-exit-command))
  6631. (save-excursion
  6632. (save-window-excursion
  6633. (delete-other-windows)
  6634. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6635. (pop-to-buffer-same-window
  6636. (condition-case nil
  6637. (make-indirect-buffer (current-buffer) "*org-goto*")
  6638. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6639. (with-output-to-temp-buffer "*Org Help*"
  6640. (princ (format help (if org-goto-auto-isearch
  6641. " Just type for auto-isearch."
  6642. " n/p/f/b/u to navigate, q to quit."))))
  6643. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6644. (setq buffer-read-only nil)
  6645. (let ((org-startup-truncated t)
  6646. (org-startup-folded nil)
  6647. (org-startup-align-all-tables nil))
  6648. (org-mode)
  6649. (org-overview))
  6650. (setq buffer-read-only t)
  6651. (if (and (boundp 'org-goto-start-pos)
  6652. (integer-or-marker-p org-goto-start-pos))
  6653. (progn (goto-char org-goto-start-pos)
  6654. (when (org-invisible-p)
  6655. (org-show-set-visibility 'lineage)))
  6656. (goto-char (point-min)))
  6657. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6658. (message "Select location and press RET")
  6659. (use-local-map org-goto-map)
  6660. (recursive-edit)))
  6661. (kill-buffer "*org-goto*")
  6662. (cons org-goto-selected-point org-goto-exit-command))))
  6663. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6664. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6665. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6666. (if (fboundp 'isearch-other-control-char)
  6667. (progn
  6668. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6669. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6670. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6671. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6672. (define-key org-goto-local-auto-isearch-map [return] nil))
  6673. (defun org-goto-local-search-headings (string bound noerror)
  6674. "Search and make sure that any matches are in headlines."
  6675. (catch 'return
  6676. (while (if isearch-forward
  6677. (search-forward string bound noerror)
  6678. (search-backward string bound noerror))
  6679. (when (save-match-data
  6680. (and (save-excursion
  6681. (beginning-of-line)
  6682. (looking-at org-complex-heading-regexp))
  6683. (or (not (match-beginning 5))
  6684. (< (point) (match-beginning 5)))))
  6685. (throw 'return (point))))))
  6686. (defun org-goto-local-auto-isearch ()
  6687. "Start isearch."
  6688. (interactive)
  6689. (goto-char (point-min))
  6690. (let ((keys (this-command-keys)))
  6691. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6692. (isearch-mode t)
  6693. (isearch-process-search-char (string-to-char keys)))))
  6694. (defun org-goto-ret (&optional _arg)
  6695. "Finish `org-goto' by going to the new location."
  6696. (interactive "P")
  6697. (setq org-goto-selected-point (point))
  6698. (setq org-goto-exit-command 'return)
  6699. (throw 'exit nil))
  6700. (defun org-goto-left ()
  6701. "Finish `org-goto' by going to the new location."
  6702. (interactive)
  6703. (if (org-at-heading-p)
  6704. (progn
  6705. (beginning-of-line 1)
  6706. (setq org-goto-selected-point (point)
  6707. org-goto-exit-command 'left)
  6708. (throw 'exit nil))
  6709. (user-error "Not on a heading")))
  6710. (defun org-goto-right ()
  6711. "Finish `org-goto' by going to the new location."
  6712. (interactive)
  6713. (if (org-at-heading-p)
  6714. (progn
  6715. (setq org-goto-selected-point (point)
  6716. org-goto-exit-command 'right)
  6717. (throw 'exit nil))
  6718. (user-error "Not on a heading")))
  6719. (defun org-goto-quit ()
  6720. "Finish `org-goto' without cursor motion."
  6721. (interactive)
  6722. (setq org-goto-selected-point nil)
  6723. (setq org-goto-exit-command 'quit)
  6724. (throw 'exit nil))
  6725. ;;; Indirect buffer display of subtrees
  6726. (defvar org-indirect-dedicated-frame nil
  6727. "This is the frame being used for indirect tree display.")
  6728. (defvar org-last-indirect-buffer nil)
  6729. (defun org-tree-to-indirect-buffer (&optional arg)
  6730. "Create indirect buffer and narrow it to current subtree.
  6731. With a numerical prefix ARG, go up to this level and then take that tree.
  6732. If ARG is negative, go up that many levels.
  6733. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6734. indirect buffer previously made with this command, to avoid proliferation of
  6735. indirect buffers. However, when you call the command with a \
  6736. `\\[universal-argument]' prefix, or
  6737. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6738. so that you can work with several indirect buffers at the same time. If
  6739. `org-indirect-buffer-display' is `dedicated-frame', the \
  6740. `\\[universal-argument]' prefix also
  6741. requests that a new frame be made for the new buffer, so that the dedicated
  6742. frame is not changed."
  6743. (interactive "P")
  6744. (let ((cbuf (current-buffer))
  6745. (cwin (selected-window))
  6746. (pos (point))
  6747. beg end level heading ibuf)
  6748. (save-excursion
  6749. (org-back-to-heading t)
  6750. (when (numberp arg)
  6751. (setq level (org-outline-level))
  6752. (when (< arg 0) (setq arg (+ level arg)))
  6753. (while (> (setq level (org-outline-level)) arg)
  6754. (org-up-heading-safe)))
  6755. (setq beg (point)
  6756. heading (org-get-heading 'no-tags))
  6757. (org-end-of-subtree t t)
  6758. (when (org-at-heading-p) (backward-char 1))
  6759. (setq end (point)))
  6760. (when (and (buffer-live-p org-last-indirect-buffer)
  6761. (not (eq org-indirect-buffer-display 'new-frame))
  6762. (not arg))
  6763. (kill-buffer org-last-indirect-buffer))
  6764. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6765. org-last-indirect-buffer ibuf)
  6766. (cond
  6767. ((or (eq org-indirect-buffer-display 'new-frame)
  6768. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6769. (select-frame (make-frame))
  6770. (delete-other-windows)
  6771. (pop-to-buffer-same-window ibuf)
  6772. (org-set-frame-title heading))
  6773. ((eq org-indirect-buffer-display 'dedicated-frame)
  6774. (raise-frame
  6775. (select-frame (or (and org-indirect-dedicated-frame
  6776. (frame-live-p org-indirect-dedicated-frame)
  6777. org-indirect-dedicated-frame)
  6778. (setq org-indirect-dedicated-frame (make-frame)))))
  6779. (delete-other-windows)
  6780. (pop-to-buffer-same-window ibuf)
  6781. (org-set-frame-title (concat "Indirect: " heading)))
  6782. ((eq org-indirect-buffer-display 'current-window)
  6783. (pop-to-buffer-same-window ibuf))
  6784. ((eq org-indirect-buffer-display 'other-window)
  6785. (pop-to-buffer ibuf))
  6786. (t (error "Invalid value")))
  6787. (narrow-to-region beg end)
  6788. (outline-show-all)
  6789. (goto-char pos)
  6790. (run-hook-with-args 'org-cycle-hook 'all)
  6791. (and (window-live-p cwin) (select-window cwin))))
  6792. (defun org-get-indirect-buffer (&optional buffer heading)
  6793. (setq buffer (or buffer (current-buffer)))
  6794. (let ((n 1) (base (buffer-name buffer)) bname)
  6795. (while (buffer-live-p
  6796. (get-buffer
  6797. (setq bname
  6798. (concat base "-"
  6799. (if heading (concat heading "-" (number-to-string n))
  6800. (number-to-string n))))))
  6801. (setq n (1+ n)))
  6802. (condition-case nil
  6803. (make-indirect-buffer buffer bname 'clone)
  6804. (error (make-indirect-buffer buffer bname)))))
  6805. (defun org-set-frame-title (title)
  6806. "Set the title of the current frame to the string TITLE."
  6807. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6808. ;;;; Structure editing
  6809. ;;; Inserting headlines
  6810. (defun org--line-empty-p (n)
  6811. "Is the Nth next line empty?
  6812. Counts the current line as N = 1 and the previous line as N = 0;
  6813. see `beginning-of-line'."
  6814. (save-excursion
  6815. (and (not (bobp))
  6816. (or (beginning-of-line n) t)
  6817. (save-match-data
  6818. (looking-at "[ \t]*$")))))
  6819. (defun org-previous-line-empty-p ()
  6820. "Is the previous line a blank line?
  6821. When NEXT is non-nil, check the next line instead."
  6822. (org--line-empty-p 0))
  6823. (defun org-next-line-empty-p ()
  6824. "Is the previous line a blank line?
  6825. When NEXT is non-nil, check the next line instead."
  6826. (org--line-empty-p 2))
  6827. (defun org--blank-before-heading-p (&optional parent)
  6828. "Non-nil when an empty line should precede a new heading here.
  6829. When optional argument PARENT is non-nil, consider parent
  6830. headline instead of current one."
  6831. (pcase (assq 'heading org-blank-before-new-entry)
  6832. (`(heading . auto)
  6833. (save-excursion
  6834. (org-with-limited-levels
  6835. (unless (and (org-before-first-heading-p)
  6836. (not (outline-next-heading)))
  6837. (org-back-to-heading t)
  6838. (when parent (org-up-heading-safe))
  6839. (cond ((not (bobp))
  6840. (org-previous-line-empty-p))
  6841. ((outline-next-heading)
  6842. (org-previous-line-empty-p))
  6843. ;; Ignore trailing spaces on last buffer line.
  6844. ((progn (skip-chars-backward " \t") (bolp))
  6845. (org-previous-line-empty-p))
  6846. (t nil))))))
  6847. (`(heading . ,value) value)
  6848. (_ nil)))
  6849. (defun org-insert-heading (&optional arg invisible-ok top)
  6850. "Insert a new heading or an item with the same depth at point.
  6851. If point is at the beginning of a heading, insert a new heading
  6852. or a new headline above the current one. When at the beginning
  6853. of a regular line of text, turn it into a heading.
  6854. If point is in the middle of a line, split it and create a new
  6855. headline with the text in the current line after point (see
  6856. `org-M-RET-may-split-line' on how to modify this behavior). As
  6857. a special case, on a headline, splitting can only happen on the
  6858. title itself. E.g., this excludes breaking stars or tags.
  6859. With a `\\[universal-argument]' prefix, set \
  6860. `org-insert-heading-respect-content' to
  6861. a non-nil value for the duration of the command. This forces the
  6862. insertion of a heading after the current subtree, independently
  6863. on the location of point.
  6864. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6865. insert the heading at the end of the tree
  6866. above the current heading. For example, if point is within a
  6867. 2nd-level heading, then it will insert a 2nd-level heading at
  6868. the end of the 1st-level parent subtree.
  6869. When INVISIBLE-OK is set, stop at invisible headlines when going
  6870. back. This is important for non-interactive uses of the
  6871. command.
  6872. When optional argument TOP is non-nil, insert a level 1 heading,
  6873. unconditionally."
  6874. (interactive "P")
  6875. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6876. (level (org-current-level))
  6877. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6878. (cond
  6879. ((or org-insert-heading-respect-content
  6880. (member arg '((4) (16)))
  6881. (and (not invisible-ok)
  6882. (invisible-p (max (1- (point)) (point-min)))))
  6883. ;; Position point at the location of insertion.
  6884. (if (not level) ;before first headline
  6885. (org-with-limited-levels (outline-next-heading))
  6886. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6887. ;; is nil.
  6888. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6889. (cond ((equal arg '(16))
  6890. (org-up-heading-safe)
  6891. (org-end-of-subtree t t))
  6892. (t
  6893. (org-end-of-subtree t t))))
  6894. (unless (bolp) (insert "\n")) ;ensure final newline
  6895. (unless (and blank? (org-previous-line-empty-p))
  6896. (org-N-empty-lines-before-current (if blank? 1 0)))
  6897. (insert stars " \n")
  6898. (forward-char -1))
  6899. ;; At a headline...
  6900. ((org-at-heading-p)
  6901. (cond ((bolp)
  6902. (when blank? (save-excursion (insert "\n")))
  6903. (save-excursion (insert stars " \n"))
  6904. (unless (and blank? (org-previous-line-empty-p))
  6905. (org-N-empty-lines-before-current (if blank? 1 0)))
  6906. (end-of-line))
  6907. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6908. (org-match-line org-complex-heading-regexp)
  6909. (org-pos-in-match-range (point) 4))
  6910. ;; Grab the text that should moved to the new headline.
  6911. ;; Preserve tags.
  6912. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6913. (if (looking-at "[ \t]*$") (replace-match "")
  6914. (org-set-tags nil t))
  6915. (end-of-line)
  6916. (when blank? (insert "\n"))
  6917. (insert "\n" stars " ")
  6918. (when (org-string-nw-p split) (insert split))
  6919. (when (eobp) (save-excursion (insert "\n")))))
  6920. (t
  6921. (end-of-line)
  6922. (when blank? (insert "\n"))
  6923. (insert "\n" stars " ")
  6924. (when (eobp) (save-excursion (insert "\n"))))))
  6925. ;; On regular text, turn line into a headline or split, if
  6926. ;; appropriate.
  6927. ((bolp)
  6928. (insert stars " ")
  6929. (unless (and blank? (org-previous-line-empty-p))
  6930. (org-N-empty-lines-before-current (if blank? 1 0))))
  6931. (t
  6932. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6933. (end-of-line))
  6934. (insert "\n" stars " ")
  6935. (unless (and blank? (org-previous-line-empty-p))
  6936. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6937. (run-hooks 'org-insert-heading-hook))
  6938. (defun org-N-empty-lines-before-current (n)
  6939. "Make the number of empty lines before current exactly N.
  6940. So this will delete or add empty lines."
  6941. (let ((column (current-column)))
  6942. (beginning-of-line)
  6943. (unless (bobp)
  6944. (let ((start (save-excursion
  6945. (skip-chars-backward " \r\t\n")
  6946. (line-end-position))))
  6947. (delete-region start (line-end-position 0))))
  6948. (insert (make-string n ?\n))
  6949. (move-to-column column)))
  6950. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6951. "Return the heading of the current entry, without the stars.
  6952. When NO-TAGS is non-nil, don't include tags.
  6953. When NO-TODO is non-nil, don't include TODO keywords.
  6954. When NO-PRIORITY is non-nil, don't include priority cookie.
  6955. When NO-COMMENT is non-nil, don't include COMMENT string."
  6956. (save-excursion
  6957. (org-back-to-heading t)
  6958. (let ((case-fold-search nil))
  6959. (looking-at org-complex-heading-regexp)
  6960. (let ((todo (and (not no-todo) (match-string 2)))
  6961. (priority (and (not no-priority) (match-string 3)))
  6962. (headline (pcase (match-string 4)
  6963. (`nil "")
  6964. ((and (guard no-comment) h)
  6965. (replace-regexp-in-string
  6966. (eval-when-compile
  6967. (format "\\`%s[ \t]+" org-comment-string))
  6968. "" h))
  6969. (h h)))
  6970. (tags (and (not no-tags) (match-string 5))))
  6971. (mapconcat #'identity
  6972. (delq nil (list todo priority headline tags))
  6973. " ")))))
  6974. (defvar orgstruct-mode) ; defined below
  6975. (defun org-heading-components ()
  6976. "Return the components of the current heading.
  6977. This is a list with the following elements:
  6978. - the level as an integer
  6979. - the reduced level, different if `org-odd-levels-only' is set.
  6980. - the TODO keyword, or nil
  6981. - the priority character, like ?A, or nil if no priority is given
  6982. - the headline text itself, or the tags string if no headline text
  6983. - the tags string, or nil."
  6984. (save-excursion
  6985. (org-back-to-heading t)
  6986. (when (let (case-fold-search)
  6987. (looking-at
  6988. (if orgstruct-mode
  6989. org-heading-regexp
  6990. org-complex-heading-regexp)))
  6991. (if orgstruct-mode
  6992. (list (length (match-string 1))
  6993. (org-reduced-level (length (match-string 1)))
  6994. nil
  6995. nil
  6996. (match-string 2)
  6997. nil)
  6998. (list (length (match-string 1))
  6999. (org-reduced-level (length (match-string 1)))
  7000. (match-string-no-properties 2)
  7001. (and (match-end 3) (aref (match-string 3) 2))
  7002. (match-string-no-properties 4)
  7003. (match-string-no-properties 5))))))
  7004. (defun org-get-entry ()
  7005. "Get the entry text, after heading, entire subtree."
  7006. (save-excursion
  7007. (org-back-to-heading t)
  7008. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7009. (defun org-edit-headline (&optional heading)
  7010. "Edit the current headline.
  7011. Set it to HEADING when provided."
  7012. (interactive)
  7013. (org-with-wide-buffer
  7014. (org-back-to-heading t)
  7015. (let ((case-fold-search nil))
  7016. (when (looking-at org-complex-heading-regexp)
  7017. (let* ((old (match-string-no-properties 4))
  7018. (new (save-match-data
  7019. (org-trim (or heading (read-string "Edit: " old))))))
  7020. (unless (equal old new)
  7021. (if old (replace-match new t t nil 4)
  7022. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7023. (insert " " new))
  7024. (org-set-tags nil t)
  7025. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7026. (defun org-insert-heading-after-current ()
  7027. "Insert a new heading with same level as current, after current subtree."
  7028. (interactive)
  7029. (org-back-to-heading)
  7030. (org-insert-heading)
  7031. (org-move-subtree-down)
  7032. (end-of-line 1))
  7033. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7034. "Insert heading with `org-insert-heading-respect-content' set to t."
  7035. (interactive)
  7036. (org-insert-heading '(4) invisible-ok))
  7037. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7038. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7039. (interactive)
  7040. (org-insert-todo-heading force-state '(4)))
  7041. (defun org-insert-todo-heading (arg &optional force-heading)
  7042. "Insert a new heading with the same level and TODO state as current heading.
  7043. If the heading has no TODO state, or if the state is DONE, use
  7044. the first state (TODO by default). Also with one prefix arg,
  7045. force first state. With two prefix args, force inserting at the
  7046. end of the parent subtree.
  7047. When called at a plain list item, insert a new item with an
  7048. unchecked check box."
  7049. (interactive "P")
  7050. (when (or force-heading (not (org-insert-item 'checkbox)))
  7051. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7052. force-heading))
  7053. (save-excursion
  7054. (org-forward-heading-same-level -1)
  7055. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7056. (let* ((new-mark-x
  7057. (if (or (equal arg '(4))
  7058. (not (match-beginning 2))
  7059. (member (match-string 2) org-done-keywords))
  7060. (car org-todo-keywords-1)
  7061. (match-string 2)))
  7062. (new-mark
  7063. (or
  7064. (run-hook-with-args-until-success
  7065. 'org-todo-get-default-hook new-mark-x nil)
  7066. new-mark-x)))
  7067. (beginning-of-line 1)
  7068. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7069. (if org-treat-insert-todo-heading-as-state-change
  7070. (org-todo new-mark)
  7071. (insert new-mark " "))))
  7072. (when org-provide-todo-statistics
  7073. (org-update-parent-todo-statistics))))
  7074. (defun org-insert-subheading (arg)
  7075. "Insert a new subheading and demote it.
  7076. Works for outline headings and for plain lists alike."
  7077. (interactive "P")
  7078. (org-insert-heading arg)
  7079. (cond
  7080. ((org-at-heading-p) (org-do-demote))
  7081. ((org-at-item-p) (org-indent-item))))
  7082. (defun org-insert-todo-subheading (arg)
  7083. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7084. Works for outline headings and for plain lists alike."
  7085. (interactive "P")
  7086. (org-insert-todo-heading arg)
  7087. (cond
  7088. ((org-at-heading-p) (org-do-demote))
  7089. ((org-at-item-p) (org-indent-item))))
  7090. ;;; Promotion and Demotion
  7091. (defvar org-after-demote-entry-hook nil
  7092. "Hook run after an entry has been demoted.
  7093. The cursor will be at the beginning of the entry.
  7094. When a subtree is being demoted, the hook will be called for each node.")
  7095. (defvar org-after-promote-entry-hook nil
  7096. "Hook run after an entry has been promoted.
  7097. The cursor will be at the beginning of the entry.
  7098. When a subtree is being promoted, the hook will be called for each node.")
  7099. (defun org-promote-subtree ()
  7100. "Promote the entire subtree.
  7101. See also `org-promote'."
  7102. (interactive)
  7103. (save-excursion
  7104. (org-with-limited-levels (org-map-tree 'org-promote)))
  7105. (org-fix-position-after-promote))
  7106. (defun org-demote-subtree ()
  7107. "Demote the entire subtree.
  7108. See `org-demote' and `org-promote'."
  7109. (interactive)
  7110. (save-excursion
  7111. (org-with-limited-levels (org-map-tree 'org-demote)))
  7112. (org-fix-position-after-promote))
  7113. (defun org-do-promote ()
  7114. "Promote the current heading higher up the tree.
  7115. If the region is active in `transient-mark-mode', promote all
  7116. headings in the region."
  7117. (interactive)
  7118. (save-excursion
  7119. (if (org-region-active-p)
  7120. (org-map-region 'org-promote (region-beginning) (region-end))
  7121. (org-promote)))
  7122. (org-fix-position-after-promote))
  7123. (defun org-do-demote ()
  7124. "Demote the current heading lower down the tree.
  7125. If the region is active in `transient-mark-mode', demote all
  7126. headings in the region."
  7127. (interactive)
  7128. (save-excursion
  7129. (if (org-region-active-p)
  7130. (org-map-region 'org-demote (region-beginning) (region-end))
  7131. (org-demote)))
  7132. (org-fix-position-after-promote))
  7133. (defun org-fix-position-after-promote ()
  7134. "Fix cursor position and indentation after demoting/promoting."
  7135. (let ((pos (point)))
  7136. (when (save-excursion
  7137. (beginning-of-line)
  7138. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7139. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7140. (cond ((eobp) (insert " "))
  7141. ((eolp) (insert " "))
  7142. ((equal (char-after) ?\s) (forward-char 1))))))
  7143. (defun org-current-level ()
  7144. "Return the level of the current entry, or nil if before the first headline.
  7145. The level is the number of stars at the beginning of the
  7146. headline. Use `org-reduced-level' to remove the effect of
  7147. `org-odd-levels'. Unlike to `org-outline-level', this function
  7148. ignores inlinetasks."
  7149. (let ((level (org-with-limited-levels (org-outline-level))))
  7150. (and (> level 0) level)))
  7151. (defun org-get-previous-line-level ()
  7152. "Return the outline depth of the last headline before the current line.
  7153. Returns 0 for the first headline in the buffer, and nil if before the
  7154. first headline."
  7155. (and (org-current-level)
  7156. (or (and (/= (line-beginning-position) (point-min))
  7157. (save-excursion (beginning-of-line 0) (org-current-level)))
  7158. 0)))
  7159. (defun org-reduced-level (l)
  7160. "Compute the effective level of a heading.
  7161. This takes into account the setting of `org-odd-levels-only'."
  7162. (cond
  7163. ((zerop l) 0)
  7164. (org-odd-levels-only (1+ (floor (/ l 2))))
  7165. (t l)))
  7166. (defun org-level-increment ()
  7167. "Return the number of stars that will be added or removed at a
  7168. time to headlines when structure editing, based on the value of
  7169. `org-odd-levels-only'."
  7170. (if org-odd-levels-only 2 1))
  7171. (defun org-get-valid-level (level &optional change)
  7172. "Rectify a level change under the influence of `org-odd-levels-only'.
  7173. LEVEL is a current level, CHANGE is by how much the level should
  7174. be modified. Even if CHANGE is nil, LEVEL may be returned
  7175. modified because even level numbers will become the next higher
  7176. odd number. Returns values greater than 0."
  7177. (if org-odd-levels-only
  7178. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7179. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7180. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7181. (max 1 (+ level (or change 0)))))
  7182. (defun org-promote ()
  7183. "Promote the current heading higher up the tree."
  7184. (org-with-wide-buffer
  7185. (org-back-to-heading t)
  7186. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7187. after-change-functions))
  7188. (level (save-match-data (funcall outline-level)))
  7189. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7190. (diff (abs (- level (length up-head) -1))))
  7191. (cond
  7192. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7193. (replace-match "# " nil t))
  7194. ((= level 1)
  7195. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7196. (t (replace-match up-head nil t)))
  7197. (unless (= level 1)
  7198. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7199. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7200. (run-hooks 'org-after-promote-entry-hook))))
  7201. (defun org-demote ()
  7202. "Demote the current heading lower down the tree."
  7203. (org-with-wide-buffer
  7204. (org-back-to-heading t)
  7205. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7206. after-change-functions))
  7207. (level (save-match-data (funcall outline-level)))
  7208. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7209. (diff (abs (- level (length down-head) -1))))
  7210. (replace-match down-head nil t)
  7211. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7212. (when org-adapt-indentation (org-fixup-indentation diff))
  7213. (run-hooks 'org-after-demote-entry-hook))))
  7214. (defun org-cycle-level ()
  7215. "Cycle the level of an empty headline through possible states.
  7216. This goes first to child, then to parent, level, then up the hierarchy.
  7217. After top level, it switches back to sibling level."
  7218. (interactive)
  7219. (let ((org-adapt-indentation nil))
  7220. (when (org-point-at-end-of-empty-headline)
  7221. (setq this-command 'org-cycle-level) ; Only needed for caching
  7222. (let ((cur-level (org-current-level))
  7223. (prev-level (org-get-previous-line-level)))
  7224. (cond
  7225. ;; If first headline in file, promote to top-level.
  7226. ((= prev-level 0)
  7227. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7228. do (org-do-promote)))
  7229. ;; If same level as prev, demote one.
  7230. ((= prev-level cur-level)
  7231. (org-do-demote))
  7232. ;; If parent is top-level, promote to top level if not already.
  7233. ((= prev-level 1)
  7234. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7235. do (org-do-promote)))
  7236. ;; If top-level, return to prev-level.
  7237. ((= cur-level 1)
  7238. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7239. do (org-do-demote)))
  7240. ;; If less than prev-level, promote one.
  7241. ((< cur-level prev-level)
  7242. (org-do-promote))
  7243. ;; If deeper than prev-level, promote until higher than
  7244. ;; prev-level.
  7245. ((> cur-level prev-level)
  7246. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7247. do (org-do-promote))))
  7248. t))))
  7249. (defun org-map-tree (fun)
  7250. "Call FUN for every heading underneath the current one."
  7251. (org-back-to-heading t)
  7252. (let ((level (funcall outline-level)))
  7253. (save-excursion
  7254. (funcall fun)
  7255. (while (and (progn
  7256. (outline-next-heading)
  7257. (> (funcall outline-level) level))
  7258. (not (eobp)))
  7259. (funcall fun)))))
  7260. (defun org-map-region (fun beg end)
  7261. "Call FUN for every heading between BEG and END."
  7262. (let ((org-ignore-region t))
  7263. (save-excursion
  7264. (setq end (copy-marker end))
  7265. (goto-char beg)
  7266. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7267. (< (point) end))
  7268. (funcall fun))
  7269. (while (and (progn
  7270. (outline-next-heading)
  7271. (< (point) end))
  7272. (not (eobp)))
  7273. (funcall fun)))))
  7274. (defun org-fixup-indentation (diff)
  7275. "Change the indentation in the current entry by DIFF.
  7276. DIFF is an integer. Indentation is done according to the
  7277. following rules:
  7278. - Planning information and property drawers are always indented
  7279. according to the new level of the headline;
  7280. - Footnote definitions and their contents are ignored;
  7281. - Inlinetasks' boundaries are not shifted;
  7282. - Empty lines are ignored;
  7283. - Other lines' indentation are shifted by DIFF columns, unless
  7284. it would introduce a structural change in the document, in
  7285. which case no shifting is done at all.
  7286. Assume point is at a heading or an inlinetask beginning."
  7287. (org-with-wide-buffer
  7288. (narrow-to-region (line-beginning-position)
  7289. (save-excursion
  7290. (if (org-with-limited-levels (org-at-heading-p))
  7291. (org-with-limited-levels (outline-next-heading))
  7292. (org-inlinetask-goto-end))
  7293. (point)))
  7294. (forward-line)
  7295. ;; Indent properly planning info and property drawer.
  7296. (when (looking-at-p org-planning-line-re)
  7297. (org-indent-line)
  7298. (forward-line))
  7299. (when (looking-at org-property-drawer-re)
  7300. (goto-char (match-end 0))
  7301. (forward-line)
  7302. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7303. (catch 'no-shift
  7304. (when (zerop diff) (throw 'no-shift nil))
  7305. ;; If DIFF is negative, first check if a shift is possible at all
  7306. ;; (e.g., it doesn't break structure). This can only happen if
  7307. ;; some contents are not properly indented.
  7308. (let ((case-fold-search t))
  7309. (when (< diff 0)
  7310. (let ((diff (- diff))
  7311. (forbidden-re (concat org-outline-regexp
  7312. "\\|"
  7313. (substring org-footnote-definition-re 1))))
  7314. (save-excursion
  7315. (while (not (eobp))
  7316. (cond
  7317. ((looking-at-p "[ \t]*$") (forward-line))
  7318. ((and (looking-at-p org-footnote-definition-re)
  7319. (let ((e (org-element-at-point)))
  7320. (and (eq (org-element-type e) 'footnote-definition)
  7321. (goto-char (org-element-property :end e))))))
  7322. ((looking-at-p org-outline-regexp) (forward-line))
  7323. ;; Give up if shifting would move before column 0 or
  7324. ;; if it would introduce a headline or a footnote
  7325. ;; definition.
  7326. (t
  7327. (skip-chars-forward " \t")
  7328. (let ((ind (current-column)))
  7329. (when (or (< ind diff)
  7330. (and (= ind diff) (looking-at-p forbidden-re)))
  7331. (throw 'no-shift nil)))
  7332. ;; Ignore contents of example blocks and source
  7333. ;; blocks if their indentation is meant to be
  7334. ;; preserved. Jump to block's closing line.
  7335. (beginning-of-line)
  7336. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7337. (let ((e (org-element-at-point)))
  7338. (and (memq (org-element-type e)
  7339. '(example-block src-block))
  7340. (or org-src-preserve-indentation
  7341. (org-element-property :preserve-indent e))
  7342. (goto-char (org-element-property :end e))
  7343. (progn (skip-chars-backward " \r\t\n")
  7344. (beginning-of-line)
  7345. t))))
  7346. (forward-line))))))))
  7347. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7348. ;; by DIFF. Also skip contents of source or example blocks
  7349. ;; when indentation is meant to be preserved.
  7350. (while (not (eobp))
  7351. (cond
  7352. ((and (looking-at-p org-footnote-definition-re)
  7353. (let ((e (org-element-at-point)))
  7354. (and (eq (org-element-type e) 'footnote-definition)
  7355. (goto-char (org-element-property :end e))))))
  7356. ((looking-at-p org-outline-regexp) (forward-line))
  7357. ((looking-at-p "[ \t]*$") (forward-line))
  7358. (t
  7359. (indent-line-to (+ (org-get-indentation) diff))
  7360. (beginning-of-line)
  7361. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7362. (let ((e (org-element-at-point)))
  7363. (and (memq (org-element-type e)
  7364. '(example-block src-block))
  7365. (or org-src-preserve-indentation
  7366. (org-element-property :preserve-indent e))
  7367. (goto-char (org-element-property :end e))
  7368. (progn (skip-chars-backward " \r\t\n")
  7369. (beginning-of-line)
  7370. t))))
  7371. (forward-line)))))))))
  7372. (defun org-convert-to-odd-levels ()
  7373. "Convert an Org file with all levels allowed to one with odd levels.
  7374. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7375. level 5 etc."
  7376. (interactive)
  7377. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7378. (let ((outline-level 'org-outline-level)
  7379. (org-odd-levels-only nil) n)
  7380. (save-excursion
  7381. (goto-char (point-min))
  7382. (while (re-search-forward "^\\*\\*+ " nil t)
  7383. (setq n (- (length (match-string 0)) 2))
  7384. (while (>= (setq n (1- n)) 0)
  7385. (org-demote))
  7386. (end-of-line 1))))))
  7387. (defun org-convert-to-oddeven-levels ()
  7388. "Convert an Org file with only odd levels to one with odd/even levels.
  7389. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7390. file contains a section with an even level, conversion would
  7391. destroy the structure of the file. An error is signaled in this
  7392. case."
  7393. (interactive)
  7394. (goto-char (point-min))
  7395. ;; First check if there are no even levels
  7396. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7397. (org-show-set-visibility 'canonical)
  7398. (error "Not all levels are odd in this file. Conversion not possible"))
  7399. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7400. (let ((outline-regexp org-outline-regexp)
  7401. (outline-level 'org-outline-level)
  7402. (org-odd-levels-only nil) n)
  7403. (save-excursion
  7404. (goto-char (point-min))
  7405. (while (re-search-forward "^\\*\\*+ " nil t)
  7406. (setq n (/ (1- (length (match-string 0))) 2))
  7407. (while (>= (setq n (1- n)) 0)
  7408. (org-promote))
  7409. (end-of-line 1))))))
  7410. (defun org-tr-level (n)
  7411. "Make N odd if required."
  7412. (if org-odd-levels-only (1+ (/ n 2)) n))
  7413. ;;; Vertical tree motion, cutting and pasting of subtrees
  7414. (defun org-move-subtree-up (&optional arg)
  7415. "Move the current subtree up past ARG headlines of the same level."
  7416. (interactive "p")
  7417. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7418. (defun org-move-subtree-down (&optional arg)
  7419. "Move the current subtree down past ARG headlines of the same level."
  7420. (interactive "p")
  7421. (setq arg (prefix-numeric-value arg))
  7422. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7423. 'org-get-last-sibling))
  7424. (ins-point (make-marker))
  7425. (cnt (abs arg))
  7426. (col (current-column))
  7427. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7428. ;; Select the tree
  7429. (org-back-to-heading)
  7430. (setq beg0 (point))
  7431. (save-excursion
  7432. (setq ne-beg (org-back-over-empty-lines))
  7433. (setq beg (point)))
  7434. (save-match-data
  7435. (save-excursion (outline-end-of-heading)
  7436. (setq folded (org-invisible-p)))
  7437. (progn (org-end-of-subtree nil t)
  7438. (unless (eobp) (backward-char))))
  7439. (outline-next-heading)
  7440. (setq ne-end (org-back-over-empty-lines))
  7441. (setq end (point))
  7442. (goto-char beg0)
  7443. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7444. ;; include less whitespace
  7445. (save-excursion
  7446. (goto-char beg)
  7447. (forward-line (- ne-beg ne-end))
  7448. (setq beg (point))))
  7449. ;; Find insertion point, with error handling
  7450. (while (> cnt 0)
  7451. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7452. (progn (goto-char beg0)
  7453. (user-error "Cannot move past superior level or buffer limit")))
  7454. (setq cnt (1- cnt)))
  7455. (when (> arg 0)
  7456. ;; Moving forward - still need to move over subtree
  7457. (org-end-of-subtree t t)
  7458. (save-excursion
  7459. (org-back-over-empty-lines)
  7460. (or (bolp) (newline))))
  7461. (setq ne-ins (org-back-over-empty-lines))
  7462. (move-marker ins-point (point))
  7463. (setq txt (buffer-substring beg end))
  7464. (org-save-markers-in-region beg end)
  7465. (delete-region beg end)
  7466. (org-remove-empty-overlays-at beg)
  7467. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7468. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7469. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7470. (let ((bbb (point)))
  7471. (insert-before-markers txt)
  7472. (org-reinstall-markers-in-region bbb)
  7473. (move-marker ins-point bbb))
  7474. (or (bolp) (insert "\n"))
  7475. (setq ins-end (point))
  7476. (goto-char ins-point)
  7477. (org-skip-whitespace)
  7478. (when (and (< arg 0)
  7479. (org-first-sibling-p)
  7480. (> ne-ins ne-beg))
  7481. ;; Move whitespace back to beginning
  7482. (save-excursion
  7483. (goto-char ins-end)
  7484. (let ((kill-whole-line t))
  7485. (kill-line (- ne-ins ne-beg)) (point)))
  7486. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7487. (move-marker ins-point nil)
  7488. (if folded
  7489. (outline-hide-subtree)
  7490. (org-show-entry)
  7491. (org-show-children)
  7492. (org-cycle-hide-drawers 'children))
  7493. (org-clean-visibility-after-subtree-move)
  7494. ;; move back to the initial column we were at
  7495. (move-to-column col)))
  7496. (defvar org-subtree-clip ""
  7497. "Clipboard for cut and paste of subtrees.
  7498. This is actually only a copy of the kill, because we use the normal kill
  7499. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7500. (defvar org-subtree-clip-folded nil
  7501. "Was the last copied subtree folded?
  7502. This is used to fold the tree back after pasting.")
  7503. (defun org-cut-subtree (&optional n)
  7504. "Cut the current subtree into the clipboard.
  7505. With prefix arg N, cut this many sequential subtrees.
  7506. This is a short-hand for marking the subtree and then cutting it."
  7507. (interactive "p")
  7508. (org-copy-subtree n 'cut))
  7509. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7510. "Copy the current subtree into the clipboard.
  7511. With prefix arg N, copy this many sequential subtrees.
  7512. This is a short-hand for marking the subtree and then copying it.
  7513. If CUT is non-nil, actually cut the subtree.
  7514. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7515. of some markers in the region, even if CUT is non-nil. This is
  7516. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7517. (interactive "p")
  7518. (let (beg end folded (beg0 (point)))
  7519. (if (called-interactively-p 'any)
  7520. (org-back-to-heading nil) ; take what looks like a subtree
  7521. (org-back-to-heading t)) ; take what is really there
  7522. (setq beg (point))
  7523. (skip-chars-forward " \t\r\n")
  7524. (save-match-data
  7525. (if nosubtrees
  7526. (outline-next-heading)
  7527. (save-excursion (outline-end-of-heading)
  7528. (setq folded (org-invisible-p)))
  7529. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7530. (org-end-of-subtree t t)))
  7531. ;; Include the end of an inlinetask
  7532. (when (and (featurep 'org-inlinetask)
  7533. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7534. "END[ \t]*$")))
  7535. (end-of-line))
  7536. (setq end (point))
  7537. (goto-char beg0)
  7538. (when (> end beg)
  7539. (setq org-subtree-clip-folded folded)
  7540. (when (or cut force-store-markers)
  7541. (org-save-markers-in-region beg end))
  7542. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7543. (setq org-subtree-clip (current-kill 0))
  7544. (message "%s: Subtree(s) with %d characters"
  7545. (if cut "Cut" "Copied")
  7546. (length org-subtree-clip)))))
  7547. (defun org-paste-subtree (&optional level tree for-yank remove)
  7548. "Paste the clipboard as a subtree, with modification of headline level.
  7549. The entire subtree is promoted or demoted in order to match a new headline
  7550. level.
  7551. If the cursor is at the beginning of a headline, the same level as
  7552. that headline is used to paste the tree.
  7553. If not, the new level is derived from the *visible* headings
  7554. before and after the insertion point, and taken to be the inferior headline
  7555. level of the two. So if the previous visible heading is level 3 and the
  7556. next is level 4 (or vice versa), level 4 will be used for insertion.
  7557. This makes sure that the subtree remains an independent subtree and does
  7558. not swallow low level entries.
  7559. You can also force a different level, either by using a numeric prefix
  7560. argument, or by inserting the heading marker by hand. For example, if the
  7561. cursor is after \"*****\", then the tree will be shifted to level 5.
  7562. If optional TREE is given, use this text instead of the kill ring.
  7563. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7564. move back over whitespace before inserting, and move point to the end of
  7565. the inserted text when done.
  7566. When REMOVE is non-nil, remove the subtree from the clipboard."
  7567. (interactive "P")
  7568. (setq tree (or tree (and kill-ring (current-kill 0))))
  7569. (unless (org-kill-is-subtree-p tree)
  7570. (user-error "%s"
  7571. (substitute-command-keys
  7572. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7573. (org-with-limited-levels
  7574. (let* ((visp (not (org-invisible-p)))
  7575. (txt tree)
  7576. (^re_ "\\(\\*+\\)[ \t]*")
  7577. (old-level (if (string-match org-outline-regexp-bol txt)
  7578. (- (match-end 0) (match-beginning 0) 1)
  7579. -1))
  7580. (force-level (cond (level (prefix-numeric-value level))
  7581. ((and (looking-at "[ \t]*$")
  7582. (string-match
  7583. "^\\*+$" (buffer-substring
  7584. (point-at-bol) (point))))
  7585. (- (match-end 0) (match-beginning 0)))
  7586. ((and (bolp)
  7587. (looking-at org-outline-regexp))
  7588. (- (match-end 0) (point) 1))))
  7589. (previous-level (save-excursion
  7590. (condition-case nil
  7591. (progn
  7592. (outline-previous-visible-heading 1)
  7593. (if (looking-at ^re_)
  7594. (- (match-end 0) (match-beginning 0) 1)
  7595. 1))
  7596. (error 1))))
  7597. (next-level (save-excursion
  7598. (condition-case nil
  7599. (progn
  7600. (or (looking-at org-outline-regexp)
  7601. (outline-next-visible-heading 1))
  7602. (if (looking-at ^re_)
  7603. (- (match-end 0) (match-beginning 0) 1)
  7604. 1))
  7605. (error 1))))
  7606. (new-level (or force-level (max previous-level next-level)))
  7607. (shift (if (or (= old-level -1)
  7608. (= new-level -1)
  7609. (= old-level new-level))
  7610. 0
  7611. (- new-level old-level)))
  7612. (delta (if (> shift 0) -1 1))
  7613. (func (if (> shift 0) 'org-demote 'org-promote))
  7614. (org-odd-levels-only nil)
  7615. beg end newend)
  7616. ;; Remove the forced level indicator
  7617. (when force-level
  7618. (delete-region (point-at-bol) (point)))
  7619. ;; Paste
  7620. (beginning-of-line (if (bolp) 1 2))
  7621. (setq beg (point))
  7622. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7623. (insert-before-markers txt)
  7624. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7625. (setq newend (point))
  7626. (org-reinstall-markers-in-region beg)
  7627. (setq end (point))
  7628. (goto-char beg)
  7629. (skip-chars-forward " \t\n\r")
  7630. (setq beg (point))
  7631. (when (and (org-invisible-p) visp)
  7632. (save-excursion (outline-show-heading)))
  7633. ;; Shift if necessary
  7634. (unless (= shift 0)
  7635. (save-restriction
  7636. (narrow-to-region beg end)
  7637. (while (not (= shift 0))
  7638. (org-map-region func (point-min) (point-max))
  7639. (setq shift (+ delta shift)))
  7640. (goto-char (point-min))
  7641. (setq newend (point-max))))
  7642. (when (or (called-interactively-p 'interactive) for-yank)
  7643. (message "Clipboard pasted as level %d subtree" new-level))
  7644. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7645. kill-ring
  7646. (eq org-subtree-clip (current-kill 0))
  7647. org-subtree-clip-folded)
  7648. ;; The tree was folded before it was killed/copied
  7649. (outline-hide-subtree))
  7650. (and for-yank (goto-char newend))
  7651. (and remove (setq kill-ring (cdr kill-ring))))))
  7652. (defun org-kill-is-subtree-p (&optional txt)
  7653. "Check if the current kill is an outline subtree, or a set of trees.
  7654. Returns nil if kill does not start with a headline, or if the first
  7655. headline level is not the largest headline level in the tree.
  7656. So this will actually accept several entries of equal levels as well,
  7657. which is OK for `org-paste-subtree'.
  7658. If optional TXT is given, check this string instead of the current kill."
  7659. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7660. (re (org-get-limited-outline-regexp))
  7661. (^re (concat "^" re))
  7662. (start-level (and kill
  7663. (string-match
  7664. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7665. kill)
  7666. (- (match-end 2) (match-beginning 2) 1)))
  7667. (start (1+ (or (match-beginning 2) -1))))
  7668. (if (not start-level)
  7669. (progn
  7670. nil) ;; does not even start with a heading
  7671. (catch 'exit
  7672. (while (setq start (string-match ^re kill (1+ start)))
  7673. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7674. (throw 'exit nil)))
  7675. t))))
  7676. (defvar org-markers-to-move nil
  7677. "Markers that should be moved with a cut-and-paste operation.
  7678. Those markers are stored together with their positions relative to
  7679. the start of the region.")
  7680. (defun org-save-markers-in-region (beg end)
  7681. "Check markers in region.
  7682. If these markers are between BEG and END, record their position relative
  7683. to BEG, so that after moving the block of text, we can put the markers back
  7684. into place.
  7685. This function gets called just before an entry or tree gets cut from the
  7686. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7687. called immediately, to move the markers with the entries."
  7688. (setq org-markers-to-move nil)
  7689. (when (featurep 'org-clock)
  7690. (org-clock-save-markers-for-cut-and-paste beg end))
  7691. (when (featurep 'org-agenda)
  7692. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7693. (defun org-check-and-save-marker (marker beg end)
  7694. "Check if MARKER is between BEG and END.
  7695. If yes, remember the marker and the distance to BEG."
  7696. (when (and (marker-buffer marker)
  7697. (equal (marker-buffer marker) (current-buffer))
  7698. (>= marker beg) (< marker end))
  7699. (push (cons marker (- marker beg)) org-markers-to-move)))
  7700. (defun org-reinstall-markers-in-region (beg)
  7701. "Move all remembered markers to their position relative to BEG."
  7702. (dolist (x org-markers-to-move)
  7703. (move-marker (car x) (+ beg (cdr x))))
  7704. (setq org-markers-to-move nil))
  7705. (defun org-narrow-to-subtree ()
  7706. "Narrow buffer to the current subtree."
  7707. (interactive)
  7708. (save-excursion
  7709. (save-match-data
  7710. (org-with-limited-levels
  7711. (narrow-to-region
  7712. (progn (org-back-to-heading t) (point))
  7713. (progn (org-end-of-subtree t t)
  7714. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7715. (point)))))))
  7716. (defun org-narrow-to-block ()
  7717. "Narrow buffer to the current block."
  7718. (interactive)
  7719. (let* ((case-fold-search t)
  7720. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7721. "^[ \t]*#\\+end_.*")))
  7722. (if blockp
  7723. (narrow-to-region (car blockp) (cdr blockp))
  7724. (user-error "Not in a block"))))
  7725. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7726. "Clone the task (subtree) at point N times.
  7727. The clones will be inserted as siblings.
  7728. In interactive use, the user will be prompted for the number of
  7729. clones to be produced. If the entry has a timestamp, the user
  7730. will also be prompted for a time shift, which may be a repeater
  7731. as used in time stamps, for example `+3d'. To disable this,
  7732. you can call the function with a universal prefix argument.
  7733. When a valid repeater is given and the entry contains any time
  7734. stamps, the clones will become a sequence in time, with time
  7735. stamps in the subtree shifted for each clone produced. If SHIFT
  7736. is nil or the empty string, time stamps will be left alone. The
  7737. ID property of the original subtree is removed.
  7738. In each clone, all the CLOCK entries will be removed. This
  7739. prevents Org from considering that the clocked times overlap.
  7740. If the original subtree did contain time stamps with a repeater,
  7741. the following will happen:
  7742. - the repeater will be removed in each clone
  7743. - an additional clone will be produced, with the current, unshifted
  7744. date(s) in the entry.
  7745. - the original entry will be placed *after* all the clones, with
  7746. repeater intact.
  7747. - the start days in the repeater in the original entry will be shifted
  7748. to past the last clone.
  7749. In this way you can spell out a number of instances of a repeating task,
  7750. and still retain the repeater to cover future instances of the task.
  7751. As described above, N+1 clones are produced when the original
  7752. subtree has a repeater. Setting N to 0, then, can be used to
  7753. remove the repeater from a subtree and create a shifted clone
  7754. with the original repeater."
  7755. (interactive "nNumber of clones to produce: ")
  7756. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7757. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7758. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7759. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7760. (shift
  7761. (or shift
  7762. (if (and (not (equal current-prefix-arg '(4)))
  7763. (save-excursion
  7764. (goto-char beg)
  7765. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7766. (read-from-minibuffer
  7767. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7768. ""))) ;No time shift
  7769. (doshift
  7770. (and (org-string-nw-p shift)
  7771. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7772. shift)
  7773. (user-error "Invalid shift specification %s" shift)))))
  7774. (goto-char end-of-tree)
  7775. (unless (bolp) (insert "\n"))
  7776. (let* ((end (point))
  7777. (template (buffer-substring beg end))
  7778. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7779. (shift-what (pcase (and doshift (match-string 2 shift))
  7780. (`nil nil)
  7781. ("d" 'day)
  7782. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7783. ("m" 'month)
  7784. ("y" 'year)
  7785. (_ (error "Unsupported time unit"))))
  7786. (nmin 1)
  7787. (nmax n)
  7788. (n-no-remove -1)
  7789. (idprop (org-entry-get nil "ID")))
  7790. (when (and doshift
  7791. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7792. template))
  7793. (delete-region beg end)
  7794. (setq end beg)
  7795. (setq nmin 0)
  7796. (setq nmax (1+ nmax))
  7797. (setq n-no-remove nmax))
  7798. (goto-char end)
  7799. (cl-loop for n from nmin to nmax do
  7800. (insert
  7801. ;; Prepare clone.
  7802. (with-temp-buffer
  7803. (insert template)
  7804. (org-mode)
  7805. (goto-char (point-min))
  7806. (org-show-subtree)
  7807. (and idprop (if org-clone-delete-id
  7808. (org-entry-delete nil "ID")
  7809. (org-id-get-create t)))
  7810. (unless (= n 0)
  7811. (while (re-search-forward org-clock-line-re nil t)
  7812. (delete-region (line-beginning-position)
  7813. (line-beginning-position 2)))
  7814. (goto-char (point-min))
  7815. (while (re-search-forward org-drawer-regexp nil t)
  7816. (org-remove-empty-drawer-at (point))))
  7817. (goto-char (point-min))
  7818. (when doshift
  7819. (while (re-search-forward org-ts-regexp-both nil t)
  7820. (org-timestamp-change (* n shift-n) shift-what))
  7821. (unless (= n n-no-remove)
  7822. (goto-char (point-min))
  7823. (while (re-search-forward org-ts-regexp nil t)
  7824. (save-excursion
  7825. (goto-char (match-beginning 0))
  7826. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7827. (delete-region (match-beginning 1) (match-end 1)))))))
  7828. (buffer-string)))))
  7829. (goto-char beg)))
  7830. ;;; Outline Sorting
  7831. (defun org-sort (&optional with-case)
  7832. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7833. Optional argument WITH-CASE means sort case-sensitively."
  7834. (interactive "P")
  7835. (org-call-with-arg
  7836. (cond ((org-at-table-p) #'org-table-sort-lines)
  7837. ((org-at-item-p) #'org-sort-list)
  7838. (t #'org-sort-entries))
  7839. with-case))
  7840. (defun org-sort-remove-invisible (s)
  7841. "Remove invisible part of links and emphasis markers from string S."
  7842. (remove-text-properties 0 (length s) org-rm-props s)
  7843. (replace-regexp-in-string
  7844. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7845. (replace-regexp-in-string
  7846. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7847. (org-link-display-format s)
  7848. t t) t t))
  7849. (defvar org-priority-regexp) ; defined later in the file
  7850. (defvar org-after-sorting-entries-or-items-hook nil
  7851. "Hook that is run after a bunch of entries or items have been sorted.
  7852. When children are sorted, the cursor is in the parent line when this
  7853. hook gets called. When a region or a plain list is sorted, the cursor
  7854. will be in the first entry of the sorted region/list.")
  7855. (defun org-sort-entries
  7856. (&optional with-case sorting-type getkey-func compare-func property
  7857. interactive?)
  7858. "Sort entries on a certain level of an outline tree.
  7859. If there is an active region, the entries in the region are sorted.
  7860. Else, if the cursor is before the first entry, sort the top-level items.
  7861. Else, the children of the entry at point are sorted.
  7862. Sorting can be alphabetically, numerically, by date/time as given by
  7863. a time stamp, by a property, by priority order, or by a custom function.
  7864. The command prompts for the sorting type unless it has been given to the
  7865. function through the SORTING-TYPE argument, which needs to be a character,
  7866. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7867. the precise meaning of each character:
  7868. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7869. c By creation time, which is assumed to be the first inactive time stamp
  7870. at the beginning of a line.
  7871. d By deadline date/time.
  7872. k By clocking time.
  7873. n Numerically, by converting the beginning of the entry/item to a number.
  7874. o By order of TODO keywords.
  7875. p By priority according to the cookie.
  7876. r By the value of a property.
  7877. s By scheduled date/time.
  7878. t By date/time, either the first active time stamp in the entry, or, if
  7879. none exist, by the first inactive one.
  7880. Capital letters will reverse the sort order.
  7881. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7882. called with point at the beginning of the record. It must return a
  7883. value that is compatible with COMPARE-FUNC, the function used to
  7884. compare entries.
  7885. Comparing entries ignores case by default. However, with an optional argument
  7886. WITH-CASE, the sorting considers case as well.
  7887. Sorting is done against the visible part of the headlines, it ignores hidden
  7888. links.
  7889. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7890. A non-nil value for INTERACTIVE? is used to signal that this
  7891. function is being called interactively."
  7892. (interactive (list current-prefix-arg nil nil nil nil t))
  7893. (let ((case-func (if with-case 'identity 'downcase))
  7894. start beg end stars re re2
  7895. txt what tmp)
  7896. ;; Find beginning and end of region to sort
  7897. (cond
  7898. ((org-region-active-p)
  7899. ;; we will sort the region
  7900. (setq end (region-end)
  7901. what "region")
  7902. (goto-char (region-beginning))
  7903. (unless (org-at-heading-p) (outline-next-heading))
  7904. (setq start (point)))
  7905. ((or (org-at-heading-p)
  7906. (ignore-errors (progn (org-back-to-heading) t)))
  7907. ;; we will sort the children of the current headline
  7908. (org-back-to-heading)
  7909. (setq start (point)
  7910. end (progn (org-end-of-subtree t t)
  7911. (or (bolp) (insert "\n"))
  7912. (when (>= (org-back-over-empty-lines) 1)
  7913. (forward-line 1))
  7914. (point))
  7915. what "children")
  7916. (goto-char start)
  7917. (outline-show-subtree)
  7918. (outline-next-heading))
  7919. (t
  7920. ;; we will sort the top-level entries in this file
  7921. (goto-char (point-min))
  7922. (or (org-at-heading-p) (outline-next-heading))
  7923. (setq start (point))
  7924. (goto-char (point-max))
  7925. (beginning-of-line 1)
  7926. (when (looking-at ".*?\\S-")
  7927. ;; File ends in a non-white line
  7928. (end-of-line 1)
  7929. (insert "\n"))
  7930. (setq end (point-max))
  7931. (setq what "top-level")
  7932. (goto-char start)
  7933. (outline-show-all)))
  7934. (setq beg (point))
  7935. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7936. (looking-at "\\(\\*+\\)")
  7937. (setq stars (match-string 1)
  7938. re (concat "^" (regexp-quote stars) " +")
  7939. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7940. txt (buffer-substring beg end))
  7941. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7942. (when (and (not (equal stars "*")) (string-match re2 txt))
  7943. (user-error "Region to sort contains a level above the first entry"))
  7944. (unless sorting-type
  7945. (message
  7946. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7947. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7948. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7949. what)
  7950. (setq sorting-type (read-char-exclusive)))
  7951. (unless getkey-func
  7952. (and (= (downcase sorting-type) ?f)
  7953. (setq getkey-func
  7954. (or (and interactive?
  7955. (org-read-function
  7956. "Function for extracting keys: "))
  7957. (error "Missing key extractor")))))
  7958. (and (= (downcase sorting-type) ?r)
  7959. (not property)
  7960. (setq property
  7961. (completing-read "Property: "
  7962. (mapcar #'list (org-buffer-property-keys t))
  7963. nil t)))
  7964. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7965. (message "Sorting entries...")
  7966. (save-restriction
  7967. (narrow-to-region start end)
  7968. (let ((restore-clock?
  7969. ;; The clock marker is lost when using `sort-subr'; mark
  7970. ;; the clock with temporary `:org-clock-marker-backup'
  7971. ;; text property.
  7972. (when (and (eq (org-clock-is-active) (current-buffer))
  7973. (<= start (marker-position org-clock-marker))
  7974. (>= end (marker-position org-clock-marker)))
  7975. (org-with-silent-modifications
  7976. (put-text-property (1- org-clock-marker) org-clock-marker
  7977. :org-clock-marker-backup t))
  7978. t))
  7979. (dcst (downcase sorting-type))
  7980. (case-fold-search nil)
  7981. (now (current-time)))
  7982. (sort-subr
  7983. (/= dcst sorting-type)
  7984. ;; This function moves to the beginning character of the "record" to
  7985. ;; be sorted.
  7986. (lambda nil
  7987. (if (re-search-forward re nil t)
  7988. (goto-char (match-beginning 0))
  7989. (goto-char (point-max))))
  7990. ;; This function moves to the last character of the "record" being
  7991. ;; sorted.
  7992. (lambda nil
  7993. (save-match-data
  7994. (condition-case nil
  7995. (outline-forward-same-level 1)
  7996. (error
  7997. (goto-char (point-max))))))
  7998. ;; This function returns the value that gets sorted against.
  7999. (lambda nil
  8000. (cond
  8001. ((= dcst ?n)
  8002. (if (looking-at org-complex-heading-regexp)
  8003. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8004. nil))
  8005. ((= dcst ?a)
  8006. (if (looking-at org-complex-heading-regexp)
  8007. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8008. nil))
  8009. ((= dcst ?k)
  8010. (or (get-text-property (point) :org-clock-minutes) 0))
  8011. ((= dcst ?t)
  8012. (let ((end (save-excursion (outline-next-heading) (point))))
  8013. (if (or (re-search-forward org-ts-regexp end t)
  8014. (re-search-forward org-ts-regexp-both end t))
  8015. (org-time-string-to-seconds (match-string 0))
  8016. (float-time now))))
  8017. ((= dcst ?c)
  8018. (let ((end (save-excursion (outline-next-heading) (point))))
  8019. (if (re-search-forward
  8020. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8021. end t)
  8022. (org-time-string-to-seconds (match-string 0))
  8023. (float-time now))))
  8024. ((= dcst ?s)
  8025. (let ((end (save-excursion (outline-next-heading) (point))))
  8026. (if (re-search-forward org-scheduled-time-regexp end t)
  8027. (org-time-string-to-seconds (match-string 1))
  8028. (float-time now))))
  8029. ((= dcst ?d)
  8030. (let ((end (save-excursion (outline-next-heading) (point))))
  8031. (if (re-search-forward org-deadline-time-regexp end t)
  8032. (org-time-string-to-seconds (match-string 1))
  8033. (float-time now))))
  8034. ((= dcst ?p)
  8035. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8036. (string-to-char (match-string 2))
  8037. org-default-priority))
  8038. ((= dcst ?r)
  8039. (or (org-entry-get nil property) ""))
  8040. ((= dcst ?o)
  8041. (when (looking-at org-complex-heading-regexp)
  8042. (let* ((m (match-string 2))
  8043. (s (if (member m org-done-keywords) '- '+)))
  8044. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8045. ((= dcst ?f)
  8046. (if getkey-func
  8047. (progn
  8048. (setq tmp (funcall getkey-func))
  8049. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8050. tmp)
  8051. (error "Invalid key function `%s'" getkey-func)))
  8052. (t (error "Invalid sorting type `%c'" sorting-type))))
  8053. nil
  8054. (cond
  8055. ((= dcst ?a) 'string<)
  8056. ((= dcst ?f)
  8057. (or compare-func
  8058. (and interactive?
  8059. (org-read-function
  8060. (concat "Function for comparing keys "
  8061. "(empty for default `sort-subr' predicate): ")
  8062. 'allow-empty))))
  8063. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  8064. (when restore-clock?
  8065. (move-marker org-clock-marker
  8066. (1+ (next-single-property-change
  8067. start :org-clock-marker-backup)))
  8068. (remove-text-properties (1- org-clock-marker) org-clock-marker
  8069. '(:org-clock-marker-backup t)))))
  8070. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8071. (message "Sorting entries...done")))
  8072. ;;; The orgstruct minor mode
  8073. ;; Define a minor mode which can be used in other modes in order to
  8074. ;; integrate the Org mode structure editing commands.
  8075. ;; This is really a hack, because the Org mode structure commands use
  8076. ;; keys which normally belong to the major mode. Here is how it
  8077. ;; works: The minor mode defines all the keys necessary to operate the
  8078. ;; structure commands, but wraps the commands into a function which
  8079. ;; tests if the cursor is currently at a headline or a plain list
  8080. ;; item. If that is the case, the structure command is used,
  8081. ;; temporarily setting many Org mode variables like regular
  8082. ;; expressions for filling etc. However, when any of those keys is
  8083. ;; used at a different location, function uses `key-binding' to look
  8084. ;; up if the key has an associated command in another currently active
  8085. ;; keymap (minor modes, major mode, global), and executes that
  8086. ;; command. There might be problems if any of the keys is otherwise
  8087. ;; used as a prefix key.
  8088. (defcustom orgstruct-heading-prefix-regexp ""
  8089. "Regexp that matches the custom prefix of Org headlines in
  8090. orgstruct(++)-mode."
  8091. :group 'org
  8092. :version "26.1"
  8093. :package-version '(Org . "8.3")
  8094. :type 'regexp)
  8095. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8096. (defcustom orgstruct-setup-hook nil
  8097. "Hook run after orgstruct-mode-map is filled."
  8098. :group 'org
  8099. :version "24.4"
  8100. :package-version '(Org . "8.0")
  8101. :type 'hook)
  8102. (defvar orgstruct-initialized nil)
  8103. (defvar org-local-vars nil
  8104. "List of local variables, for use by `orgstruct-mode'.")
  8105. ;;;###autoload
  8106. (define-minor-mode orgstruct-mode
  8107. "Toggle the minor mode `orgstruct-mode'.
  8108. This mode is for using Org mode structure commands in other
  8109. modes. The following keys behave as if Org mode were active, if
  8110. the cursor is on a headline, or on a plain list item (both as
  8111. defined by Org mode)."
  8112. nil " OrgStruct" (make-sparse-keymap)
  8113. (funcall (if orgstruct-mode
  8114. 'add-to-invisibility-spec
  8115. 'remove-from-invisibility-spec)
  8116. '(outline . t))
  8117. (when orgstruct-mode
  8118. (org-load-modules-maybe)
  8119. (unless orgstruct-initialized
  8120. (orgstruct-setup)
  8121. (setq orgstruct-initialized t))))
  8122. ;;;###autoload
  8123. (defun turn-on-orgstruct ()
  8124. "Unconditionally turn on `orgstruct-mode'."
  8125. (orgstruct-mode 1))
  8126. (defvar-local orgstruct-is-++ nil
  8127. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8128. (defvar-local org-fb-vars nil)
  8129. (defun orgstruct++-mode (&optional arg)
  8130. "Toggle `orgstruct-mode', the enhanced version of it.
  8131. In addition to setting orgstruct-mode, this also exports all
  8132. indentation and autofilling variables from Org mode into the
  8133. buffer. It will also recognize item context in multiline items."
  8134. (interactive "P")
  8135. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8136. (if (< arg 1)
  8137. (progn (orgstruct-mode -1)
  8138. (dolist (v org-fb-vars)
  8139. (set (make-local-variable (car v))
  8140. (if (eq (car-safe (cadr v)) 'quote)
  8141. (cl-cadadr v)
  8142. (nth 1 v)))))
  8143. (orgstruct-mode 1)
  8144. (setq org-fb-vars nil)
  8145. (unless org-local-vars
  8146. (setq org-local-vars (org-get-local-variables)))
  8147. (let (var val)
  8148. (dolist (x org-local-vars)
  8149. (when (string-match
  8150. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8151. \\|fill-prefix\\|indent-\\)"
  8152. (symbol-name (car x)))
  8153. (setq var (car x) val (nth 1 x))
  8154. (push (list var `(quote ,(eval var))) org-fb-vars)
  8155. (set (make-local-variable var)
  8156. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8157. (setq-local orgstruct-is-++ t))))
  8158. ;;;###autoload
  8159. (defun turn-on-orgstruct++ ()
  8160. "Unconditionally turn on `orgstruct++-mode'."
  8161. (orgstruct++-mode 1))
  8162. (defun orgstruct-error ()
  8163. "Error when there is no default binding for a structure key."
  8164. (interactive)
  8165. (funcall (if (fboundp 'user-error)
  8166. 'user-error
  8167. 'error)
  8168. "This key has no function outside structure elements"))
  8169. (defun orgstruct-setup ()
  8170. "Setup orgstruct keymap."
  8171. (dolist (cell '((org-demote . t)
  8172. (org-metaleft . t)
  8173. (org-metaright . t)
  8174. (org-promote . t)
  8175. (org-shiftmetaleft . t)
  8176. (org-shiftmetaright . t)
  8177. org-backward-element
  8178. org-backward-heading-same-level
  8179. org-ctrl-c-ret
  8180. org-ctrl-c-minus
  8181. org-ctrl-c-star
  8182. org-cycle
  8183. org-force-cycle-archived
  8184. org-forward-heading-same-level
  8185. org-insert-heading
  8186. org-insert-heading-respect-content
  8187. org-kill-note-or-show-branches
  8188. org-mark-subtree
  8189. org-meta-return
  8190. org-metadown
  8191. org-metaup
  8192. org-narrow-to-subtree
  8193. org-promote-subtree
  8194. org-reveal
  8195. org-shiftdown
  8196. org-shiftleft
  8197. org-shiftmetadown
  8198. org-shiftmetaup
  8199. org-shiftright
  8200. org-shifttab
  8201. org-shifttab
  8202. org-shiftup
  8203. org-show-children
  8204. org-show-subtree
  8205. org-sort
  8206. org-up-element
  8207. outline-demote
  8208. outline-next-visible-heading
  8209. outline-previous-visible-heading
  8210. outline-promote
  8211. outline-up-heading))
  8212. (let ((f (or (car-safe cell) cell))
  8213. (disable-when-heading-prefix (cdr-safe cell)))
  8214. (when (fboundp f)
  8215. (let ((new-bindings))
  8216. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8217. (where-is-internal f outline-mode-map)))
  8218. (push binding new-bindings)
  8219. ;; TODO use local-function-key-map
  8220. (dolist (rep '(("<tab>" . "TAB")
  8221. ("<return>" . "RET")
  8222. ("<escape>" . "ESC")
  8223. ("<delete>" . "DEL")))
  8224. (setq binding (read-kbd-macro
  8225. (let ((case-fold-search))
  8226. (replace-regexp-in-string
  8227. (regexp-quote (cdr rep))
  8228. (car rep)
  8229. (key-description binding)))))
  8230. (cl-pushnew binding new-bindings :test 'equal)))
  8231. (dolist (binding new-bindings)
  8232. (let ((key (lookup-key orgstruct-mode-map binding)))
  8233. (when (or (not key) (numberp key))
  8234. (ignore-errors
  8235. (org-defkey orgstruct-mode-map
  8236. binding
  8237. (orgstruct-make-binding
  8238. f binding disable-when-heading-prefix))))))))))
  8239. (run-hooks 'orgstruct-setup-hook))
  8240. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8241. "Create a function for binding in the structure minor mode.
  8242. FUN is the command to call inside a table. KEY is the key that
  8243. should be checked in for a command to execute outside of tables.
  8244. Non-nil `disable-when-heading-prefix' means to disable the command
  8245. if `orgstruct-heading-prefix-regexp' is not empty."
  8246. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8247. (let ((nname name)
  8248. (i 0))
  8249. (while (fboundp (intern nname))
  8250. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8251. (setq name (intern nname)))
  8252. (eval
  8253. (let ((bindings '((org-heading-regexp
  8254. (concat "^"
  8255. orgstruct-heading-prefix-regexp
  8256. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8257. (org-outline-regexp
  8258. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8259. (org-outline-regexp-bol
  8260. (concat "^" org-outline-regexp))
  8261. (outline-regexp org-outline-regexp)
  8262. (outline-heading-end-regexp "\n")
  8263. (outline-level 'org-outline-level)
  8264. (outline-heading-alist))))
  8265. `(defun ,name (arg)
  8266. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8267. "Outside of structure, run the binding of `"
  8268. (key-description key) "'."
  8269. (when disable-when-heading-prefix
  8270. (concat
  8271. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8272. "back to the default binding due to limitations of Org's implementation of\n"
  8273. "`" (symbol-name fun) "'.")))
  8274. (interactive "p")
  8275. (let* ((disable
  8276. ,(and disable-when-heading-prefix
  8277. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8278. (fallback
  8279. (or disable
  8280. (not
  8281. (let* ,bindings
  8282. (org-context-p 'headline 'item
  8283. ,(when (memq fun
  8284. '(org-insert-heading
  8285. org-insert-heading-respect-content
  8286. org-meta-return))
  8287. '(when orgstruct-is-++
  8288. 'item-body))))))))
  8289. (if fallback
  8290. (let* ((orgstruct-mode)
  8291. (binding
  8292. (let ((key ,key))
  8293. (catch 'exit
  8294. (dolist
  8295. (rep
  8296. '(nil
  8297. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8298. ("<\\([^>]*\\)return>" . "\\1RET")
  8299. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8300. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8301. nil)
  8302. (when rep
  8303. (setq key (read-kbd-macro
  8304. (let ((case-fold-search))
  8305. (replace-regexp-in-string
  8306. (car rep)
  8307. (cdr rep)
  8308. (key-description key))))))
  8309. (when (key-binding key)
  8310. (throw 'exit (key-binding key))))))))
  8311. (if (keymapp binding)
  8312. (org-set-transient-map binding)
  8313. (let ((func (or binding
  8314. (unless disable
  8315. 'orgstruct-error))))
  8316. (when func
  8317. (call-interactively func)))))
  8318. (org-run-like-in-org-mode
  8319. (lambda ()
  8320. (interactive)
  8321. (let* ,bindings
  8322. (call-interactively ',fun)))))))))
  8323. name))
  8324. (defun org-contextualize-keys (alist contexts)
  8325. "Return valid elements in ALIST depending on CONTEXTS.
  8326. `org-agenda-custom-commands' or `org-capture-templates' are the
  8327. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8328. or `org-capture-templates-contexts' are the associated contexts
  8329. definitions."
  8330. (let ((contexts
  8331. ;; normalize contexts
  8332. (mapcar
  8333. (lambda(c) (cond ((listp (cadr c))
  8334. (list (car c) (car c) (nth 1 c)))
  8335. ((string= "" (cadr c))
  8336. (list (car c) (car c) (nth 2 c)))
  8337. (t c)))
  8338. contexts))
  8339. (a alist) r s)
  8340. ;; loop over all commands or templates
  8341. (dolist (c a)
  8342. (let (vrules repl)
  8343. (cond
  8344. ((not (assoc (car c) contexts))
  8345. (push c r))
  8346. ((and (assoc (car c) contexts)
  8347. (setq vrules (org-contextualize-validate-key
  8348. (car c) contexts)))
  8349. (mapc (lambda (vr)
  8350. (unless (equal (car vr) (cadr vr))
  8351. (setq repl vr)))
  8352. vrules)
  8353. (if (not repl) (push c r)
  8354. (push (cadr repl) s)
  8355. (push
  8356. (cons (car c)
  8357. (cdr (or (assoc (cadr repl) alist)
  8358. (error "Undefined key `%s' as contextual replacement for `%s'"
  8359. (cadr repl) (car c)))))
  8360. r))))))
  8361. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8362. (delq
  8363. nil
  8364. (delete-dups
  8365. (mapcar (lambda (x)
  8366. (let ((tpl (car x)))
  8367. (unless (delq
  8368. nil
  8369. (mapcar (lambda (y)
  8370. (equal y tpl))
  8371. s))
  8372. x)))
  8373. (reverse r))))))
  8374. (defun org-contextualize-validate-key (key contexts)
  8375. "Check CONTEXTS for agenda or capture KEY."
  8376. (let (res)
  8377. (dolist (r contexts)
  8378. (dolist (rr (car (last r)))
  8379. (when
  8380. (and (equal key (car r))
  8381. (if (functionp rr) (funcall rr)
  8382. (or (and (eq (car rr) 'in-file)
  8383. (buffer-file-name)
  8384. (string-match (cdr rr) (buffer-file-name)))
  8385. (and (eq (car rr) 'in-mode)
  8386. (string-match (cdr rr) (symbol-name major-mode)))
  8387. (and (eq (car rr) 'in-buffer)
  8388. (string-match (cdr rr) (buffer-name)))
  8389. (when (and (eq (car rr) 'not-in-file)
  8390. (buffer-file-name))
  8391. (not (string-match (cdr rr) (buffer-file-name))))
  8392. (when (eq (car rr) 'not-in-mode)
  8393. (not (string-match (cdr rr) (symbol-name major-mode))))
  8394. (when (eq (car rr) 'not-in-buffer)
  8395. (not (string-match (cdr rr) (buffer-name)))))))
  8396. (push r res))))
  8397. (delete-dups (delq nil res))))
  8398. (defun org-context-p (&rest contexts)
  8399. "Check if local context is any of CONTEXTS.
  8400. Possible values in the list of contexts are `table', `headline', and `item'."
  8401. (let ((pos (point)))
  8402. (goto-char (point-at-bol))
  8403. (prog1 (or (and (memq 'table contexts)
  8404. (looking-at "[ \t]*|"))
  8405. (and (memq 'headline contexts)
  8406. (looking-at org-outline-regexp))
  8407. (and (memq 'item contexts)
  8408. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8409. (and (memq 'item-body contexts)
  8410. (org-in-item-p)))
  8411. (goto-char pos))))
  8412. ;;;###autoload
  8413. (defun org-run-like-in-org-mode (cmd)
  8414. "Run a command, pretending that the current buffer is in Org mode.
  8415. This will temporarily bind local variables that are typically bound in
  8416. Org mode to the values they have in Org mode, and then interactively
  8417. call CMD."
  8418. (org-load-modules-maybe)
  8419. (unless org-local-vars
  8420. (setq org-local-vars (org-get-local-variables)))
  8421. (let (binds)
  8422. (dolist (var org-local-vars)
  8423. (when (or (not (boundp (car var)))
  8424. (eq (symbol-value (car var))
  8425. (default-value (car var))))
  8426. (push (list (car var) `(quote ,(cadr var))) binds)))
  8427. (eval `(let ,binds
  8428. (call-interactively (quote ,cmd))))))
  8429. (defun org-get-category (&optional pos force-refresh)
  8430. "Get the category applying to position POS."
  8431. (save-match-data
  8432. (when force-refresh (org-refresh-category-properties))
  8433. (let ((pos (or pos (point))))
  8434. (or (get-text-property pos 'org-category)
  8435. (progn (org-refresh-category-properties)
  8436. (get-text-property pos 'org-category))))))
  8437. ;;; Refresh properties
  8438. (defun org-refresh-properties (dprop tprop)
  8439. "Refresh buffer text properties.
  8440. DPROP is the drawer property and TPROP is either the
  8441. corresponding text property to set, or an alist with each element
  8442. being a text property (as a symbol) and a function to apply to
  8443. the value of the drawer property."
  8444. (let* ((case-fold-search t)
  8445. (inhibit-read-only t)
  8446. (inherit? (org-property-inherit-p dprop))
  8447. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8448. (global (and inherit? (org--property-global-value dprop nil))))
  8449. (org-with-silent-modifications
  8450. (org-with-point-at 1
  8451. ;; Set global values (e.g., values defined through
  8452. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8453. (when global (put-text-property (point-min) (point-max) tprop global))
  8454. ;; Set local values.
  8455. (while (re-search-forward property-re nil t)
  8456. (when (org-at-property-p)
  8457. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8458. (outline-next-heading))))))
  8459. (defun org-refresh-property (tprop p &optional inherit)
  8460. "Refresh the buffer text property TPROP from the drawer property P.
  8461. The refresh happens only for the current headline, or the whole
  8462. sub-tree if optional argument INHERIT is non-nil."
  8463. (unless (org-before-first-heading-p)
  8464. (save-excursion
  8465. (org-back-to-heading t)
  8466. (let ((start (point))
  8467. (end (save-excursion
  8468. (if inherit (org-end-of-subtree t t)
  8469. (or (outline-next-heading) (point-max))))))
  8470. (if (symbolp tprop)
  8471. ;; TPROP is a text property symbol.
  8472. (put-text-property start end tprop p)
  8473. ;; TPROP is an alist with (property . function) elements.
  8474. (pcase-dolist (`(,prop . ,f) tprop)
  8475. (put-text-property start end prop (funcall f p))))))))
  8476. (defun org-refresh-category-properties ()
  8477. "Refresh category text properties in the buffer."
  8478. (let ((case-fold-search t)
  8479. (inhibit-read-only t)
  8480. (default-category
  8481. (cond ((null org-category)
  8482. (if buffer-file-name
  8483. (file-name-sans-extension
  8484. (file-name-nondirectory buffer-file-name))
  8485. "???"))
  8486. ((symbolp org-category) (symbol-name org-category))
  8487. (t org-category))))
  8488. (org-with-silent-modifications
  8489. (org-with-wide-buffer
  8490. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8491. ;; This is the default category for the buffer. If none is
  8492. ;; found, fall-back to `org-category' or buffer file name.
  8493. (put-text-property
  8494. (point-min) (point-max)
  8495. 'org-category
  8496. (catch 'buffer-category
  8497. (goto-char (point-max))
  8498. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8499. (let ((element (org-element-at-point)))
  8500. (when (eq (org-element-type element) 'keyword)
  8501. (throw 'buffer-category
  8502. (org-element-property :value element)))))
  8503. default-category))
  8504. ;; Set sub-tree specific categories.
  8505. (goto-char (point-min))
  8506. (let ((regexp (org-re-property "CATEGORY")))
  8507. (while (re-search-forward regexp nil t)
  8508. (let ((value (match-string-no-properties 3)))
  8509. (when (org-at-property-p)
  8510. (put-text-property
  8511. (save-excursion (org-back-to-heading t) (point))
  8512. (save-excursion (org-end-of-subtree t t) (point))
  8513. 'org-category
  8514. value)))))))))
  8515. (defun org-refresh-stats-properties ()
  8516. "Refresh stats text properties in the buffer."
  8517. (org-with-silent-modifications
  8518. (org-with-point-at 1
  8519. (let ((regexp (concat org-outline-regexp-bol
  8520. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8521. (while (re-search-forward regexp nil t)
  8522. (let* ((numerator (string-to-number (match-string 1)))
  8523. (denominator (and (match-end 2)
  8524. (string-to-number (match-string 2))))
  8525. (stats (cond ((not denominator) numerator) ;percent
  8526. ((= denominator 0) 0)
  8527. (t (/ (* numerator 100) denominator)))))
  8528. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8529. 'org-stats stats)))))))
  8530. (defun org-refresh-effort-properties ()
  8531. "Refresh effort properties"
  8532. (org-refresh-properties
  8533. org-effort-property
  8534. '((effort . identity)
  8535. (effort-minutes . org-duration-to-minutes))))
  8536. ;;;; Link Stuff
  8537. ;;; Link abbreviations
  8538. (defun org-link-expand-abbrev (link)
  8539. "Apply replacements as defined in `org-link-abbrev-alist'."
  8540. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8541. (let* ((key (match-string 1 link))
  8542. (as (or (assoc key org-link-abbrev-alist-local)
  8543. (assoc key org-link-abbrev-alist)))
  8544. (tag (and (match-end 2) (match-string 3 link)))
  8545. rpl)
  8546. (if (not as)
  8547. link
  8548. (setq rpl (cdr as))
  8549. (cond
  8550. ((symbolp rpl) (funcall rpl tag))
  8551. ((string-match "%(\\([^)]+\\))" rpl)
  8552. (replace-match
  8553. (save-match-data
  8554. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8555. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8556. ((string-match "%h" rpl)
  8557. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8558. (t (concat rpl tag)))))
  8559. link))
  8560. ;;; Storing and inserting links
  8561. (defvar org-insert-link-history nil
  8562. "Minibuffer history for links inserted with `org-insert-link'.")
  8563. (defvar org-stored-links nil
  8564. "Contains the links stored with `org-store-link'.")
  8565. (defvar org-store-link-plist nil
  8566. "Plist with info about the most recently link created with `org-store-link'.")
  8567. (defun org-store-link-functions ()
  8568. "Return a list of functions that are called to create and store a link.
  8569. The functions defined in the :store property of
  8570. `org-link-parameters'.
  8571. Each function will be called in turn until one returns a non-nil
  8572. value. Each function should check if it is responsible for
  8573. creating this link (for example by looking at the major mode).
  8574. If not, it must exit and return nil. If yes, it should return
  8575. a non-nil value after calling `org-store-link-props' with a list
  8576. of properties and values. Special properties are:
  8577. :type The link prefix, like \"http\". This must be given.
  8578. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8579. This is obligatory as well.
  8580. :description Optional default description for the second pair
  8581. of brackets in an Org mode link. The user can still change
  8582. this when inserting this link into an Org mode buffer.
  8583. In addition to these, any additional properties can be specified
  8584. and then used in capture templates."
  8585. (cl-loop for link in org-link-parameters
  8586. with store-func
  8587. do (setq store-func (org-link-get-parameter (car link) :store))
  8588. if store-func
  8589. collect store-func))
  8590. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8591. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8592. ;;;###autoload
  8593. (defun org-store-link (arg)
  8594. "Store an org-link to the current location.
  8595. \\<org-mode-map>
  8596. This link is added to `org-stored-links' and can later be inserted
  8597. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8598. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8599. A single
  8600. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8601. `org-gnus-prefer-web-links' for links to Usenet articles.
  8602. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8603. skipping storing functions that are not
  8604. part of Org core.
  8605. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8606. prefix ARG forces storing a link for each line in the
  8607. active region."
  8608. (interactive "P")
  8609. (org-load-modules-maybe)
  8610. (if (and (equal arg '(64)) (org-region-active-p))
  8611. (save-excursion
  8612. (let ((end (region-end)))
  8613. (goto-char (region-beginning))
  8614. (set-mark (point))
  8615. (while (< (point-at-eol) end)
  8616. (move-end-of-line 1) (activate-mark)
  8617. (let (current-prefix-arg)
  8618. (call-interactively 'org-store-link))
  8619. (move-beginning-of-line 2)
  8620. (set-mark (point)))))
  8621. (setq org-store-link-plist nil)
  8622. (let (link cpltxt desc description search txt custom-id agenda-link)
  8623. (cond
  8624. ;; Store a link using an external link type, if any function is
  8625. ;; available. If more than one can generate a link from current
  8626. ;; location, ask which one to use.
  8627. ((and (not (equal arg '(16)))
  8628. (let ((results-alist nil))
  8629. (dolist (f (org-store-link-functions))
  8630. (when (funcall f)
  8631. ;; XXX: return value is not link's plist, so we
  8632. ;; store the new value before it is modified. It
  8633. ;; would be cleaner to ask store link functions to
  8634. ;; return the plist instead.
  8635. (push (cons f (copy-sequence org-store-link-plist))
  8636. results-alist)))
  8637. (pcase results-alist
  8638. (`nil nil)
  8639. (`((,_ . ,_)) t) ;single choice: nothing to do
  8640. (`((,name . ,_) . ,_)
  8641. ;; Reinstate link plist associated to the chosen
  8642. ;; function.
  8643. (apply #'org-store-link-props
  8644. (cdr (assoc-string
  8645. (completing-read
  8646. "Which function for creating the link? "
  8647. (mapcar #'car results-alist)
  8648. nil t (symbol-name name))
  8649. results-alist)))
  8650. t))))
  8651. (setq link (plist-get org-store-link-plist :link))
  8652. (setq desc (or (plist-get org-store-link-plist :description)
  8653. link)))
  8654. ;; Store a link from a source code buffer.
  8655. ((org-src-edit-buffer-p)
  8656. (let ((coderef-format (org-src-coderef-format)))
  8657. (cond ((save-excursion
  8658. (beginning-of-line)
  8659. (looking-at (org-src-coderef-regexp coderef-format)))
  8660. (setq link (format "(%s)" (match-string-no-properties 3))))
  8661. ((called-interactively-p 'any)
  8662. (let ((label (read-string "Code line label: ")))
  8663. (end-of-line)
  8664. (setq link (format coderef-format label))
  8665. (let ((gc (- 79 (length link))))
  8666. (if (< (current-column) gc)
  8667. (org-move-to-column gc t)
  8668. (insert " ")))
  8669. (insert link)
  8670. (setq link (concat "(" label ")"))
  8671. (setq desc nil)))
  8672. (t (setq link nil)))))
  8673. ;; We are in the agenda, link to referenced location
  8674. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8675. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8676. (get-text-property (point) 'org-marker))))
  8677. (when m
  8678. (org-with-point-at m
  8679. (setq agenda-link
  8680. (if (called-interactively-p 'any)
  8681. (call-interactively 'org-store-link)
  8682. (org-store-link nil)))))))
  8683. ((eq major-mode 'calendar-mode)
  8684. (let ((cd (calendar-cursor-to-date)))
  8685. (setq link
  8686. (format-time-string
  8687. (car org-time-stamp-formats)
  8688. (apply 'encode-time
  8689. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8690. nil nil nil))))
  8691. (org-store-link-props :type "calendar" :date cd)))
  8692. ((eq major-mode 'help-mode)
  8693. (setq link (concat "help:" (save-excursion
  8694. (goto-char (point-min))
  8695. (looking-at "^[^ ]+")
  8696. (match-string 0))))
  8697. (org-store-link-props :type "help"))
  8698. ((eq major-mode 'w3-mode)
  8699. (setq cpltxt (if (and (buffer-name)
  8700. (not (string-match "Untitled" (buffer-name))))
  8701. (buffer-name)
  8702. (url-view-url t))
  8703. link (url-view-url t))
  8704. (org-store-link-props :type "w3" :url (url-view-url t)))
  8705. ((eq major-mode 'image-mode)
  8706. (setq cpltxt (concat "file:"
  8707. (abbreviate-file-name buffer-file-name))
  8708. link cpltxt)
  8709. (org-store-link-props :type "image" :file buffer-file-name))
  8710. ;; In dired, store a link to the file of the current line
  8711. ((derived-mode-p 'dired-mode)
  8712. (let ((file (dired-get-filename nil t)))
  8713. (setq file (if file
  8714. (abbreviate-file-name
  8715. (expand-file-name (dired-get-filename nil t)))
  8716. ;; otherwise, no file so use current directory.
  8717. default-directory))
  8718. (setq cpltxt (concat "file:" file)
  8719. link cpltxt)))
  8720. ((setq search (run-hook-with-args-until-success
  8721. 'org-create-file-search-functions))
  8722. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8723. "::" search))
  8724. (setq cpltxt (or description link)))
  8725. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8726. (org-with-limited-levels
  8727. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8728. (cond
  8729. ;; Store a link using the target at point
  8730. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8731. (setq cpltxt
  8732. (concat "file:"
  8733. (abbreviate-file-name
  8734. (buffer-file-name (buffer-base-buffer)))
  8735. "::" (match-string 1))
  8736. link cpltxt))
  8737. ((and (featurep 'org-id)
  8738. (or (eq org-id-link-to-org-use-id t)
  8739. (and (called-interactively-p 'any)
  8740. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8741. (and (eq org-id-link-to-org-use-id
  8742. 'create-if-interactive-and-no-custom-id)
  8743. (not custom-id))))
  8744. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8745. ;; Store a link using the ID at point
  8746. (setq link (condition-case nil
  8747. (prog1 (org-id-store-link)
  8748. (setq desc (or (plist-get org-store-link-plist
  8749. :description)
  8750. "")))
  8751. (error
  8752. ;; Probably before first headline, link only to file
  8753. (concat "file:"
  8754. (abbreviate-file-name
  8755. (buffer-file-name (buffer-base-buffer))))))))
  8756. (t
  8757. ;; Just link to current headline
  8758. (setq cpltxt (concat "file:"
  8759. (abbreviate-file-name
  8760. (buffer-file-name (buffer-base-buffer)))))
  8761. ;; Add a context search string
  8762. (when (org-xor org-context-in-file-links
  8763. (equal arg '(4)))
  8764. (let* ((element (org-element-at-point))
  8765. (name (org-element-property :name element)))
  8766. (setq txt (cond
  8767. ((org-at-heading-p) nil)
  8768. (name)
  8769. ((org-region-active-p)
  8770. (buffer-substring (region-beginning) (region-end)))))
  8771. (when (or (null txt) (string-match "\\S-" txt))
  8772. (setq cpltxt
  8773. (concat cpltxt "::"
  8774. (condition-case nil
  8775. (org-make-org-heading-search-string txt)
  8776. (error "")))
  8777. desc (or name
  8778. (nth 4 (ignore-errors (org-heading-components)))
  8779. "NONE")))))
  8780. (when (string-match "::\\'" cpltxt)
  8781. (setq cpltxt (substring cpltxt 0 -2)))
  8782. (setq link cpltxt)))))
  8783. ((buffer-file-name (buffer-base-buffer))
  8784. ;; Just link to this file here.
  8785. (setq cpltxt (concat "file:"
  8786. (abbreviate-file-name
  8787. (buffer-file-name (buffer-base-buffer)))))
  8788. ;; Add a context string.
  8789. (when (org-xor org-context-in-file-links
  8790. (equal arg '(4)))
  8791. (setq txt (if (org-region-active-p)
  8792. (buffer-substring (region-beginning) (region-end))
  8793. (buffer-substring (point-at-bol) (point-at-eol))))
  8794. ;; Only use search option if there is some text.
  8795. (when (string-match "\\S-" txt)
  8796. (setq cpltxt
  8797. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8798. desc "NONE")))
  8799. (setq link cpltxt))
  8800. ((called-interactively-p 'interactive)
  8801. (user-error "No method for storing a link from this buffer"))
  8802. (t (setq link nil)))
  8803. ;; We're done setting link and desc, clean up
  8804. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8805. (setq link (or link cpltxt)
  8806. desc (or desc cpltxt))
  8807. (cond ((not desc))
  8808. ((equal desc "NONE") (setq desc nil))
  8809. (t (setq desc
  8810. (replace-regexp-in-string
  8811. org-bracket-link-analytic-regexp
  8812. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8813. desc))))
  8814. ;; Return the link
  8815. (if (not (and (or (called-interactively-p 'any)
  8816. executing-kbd-macro)
  8817. link))
  8818. (or agenda-link (and link (org-make-link-string link desc)))
  8819. (push (list link desc) org-stored-links)
  8820. (message "Stored: %s" (or desc link))
  8821. (when custom-id
  8822. (setq link (concat "file:" (abbreviate-file-name
  8823. (buffer-file-name)) "::#" custom-id))
  8824. (push (list link desc) org-stored-links))
  8825. (car org-stored-links)))))
  8826. (defun org-store-link-props (&rest plist)
  8827. "Store link properties.
  8828. The properties are pre-processed by extracting names, addresses
  8829. and dates."
  8830. (let ((x (plist-get plist :from)))
  8831. (when x
  8832. (let ((adr (mail-extract-address-components x)))
  8833. (setq plist (plist-put plist :fromname (car adr)))
  8834. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8835. (let ((x (plist-get plist :to)))
  8836. (when x
  8837. (let ((adr (mail-extract-address-components x)))
  8838. (setq plist (plist-put plist :toname (car adr)))
  8839. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8840. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8841. (when x
  8842. (setq plist (plist-put plist :date-timestamp
  8843. (format-time-string
  8844. (org-time-stamp-format t) x)))
  8845. (setq plist (plist-put plist :date-timestamp-inactive
  8846. (format-time-string
  8847. (org-time-stamp-format t t) x)))))
  8848. (let ((from (plist-get plist :from))
  8849. (to (plist-get plist :to)))
  8850. (when (and from to org-from-is-user-regexp)
  8851. (setq plist
  8852. (plist-put plist :fromto
  8853. (if (string-match org-from-is-user-regexp from)
  8854. (concat "to %t")
  8855. (concat "from %f"))))))
  8856. (setq org-store-link-plist plist))
  8857. (defun org-add-link-props (&rest plist)
  8858. "Add these properties to the link property list."
  8859. (let (key value)
  8860. (while plist
  8861. (setq key (pop plist) value (pop plist))
  8862. (setq org-store-link-plist
  8863. (plist-put org-store-link-plist key value)))))
  8864. (defun org-email-link-description (&optional fmt)
  8865. "Return the description part of an email link.
  8866. This takes information from `org-store-link-plist' and formats it
  8867. according to FMT (default from `org-email-link-description-format')."
  8868. (setq fmt (or fmt org-email-link-description-format))
  8869. (let* ((p org-store-link-plist)
  8870. (to (plist-get p :toaddress))
  8871. (from (plist-get p :fromaddress))
  8872. (table
  8873. (list
  8874. (cons "%c" (plist-get p :fromto))
  8875. (cons "%F" (plist-get p :from))
  8876. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8877. (cons "%T" (plist-get p :to))
  8878. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8879. (cons "%s" (plist-get p :subject))
  8880. (cons "%d" (plist-get p :date))
  8881. (cons "%m" (plist-get p :message-id)))))
  8882. (when (string-match "%c" fmt)
  8883. ;; Check if the user wrote this message
  8884. (if (and org-from-is-user-regexp from to
  8885. (save-match-data (string-match org-from-is-user-regexp from)))
  8886. (setq fmt (replace-match "to %t" t t fmt))
  8887. (setq fmt (replace-match "from %f" t t fmt))))
  8888. (org-replace-escapes fmt table)))
  8889. (defun org-make-org-heading-search-string (&optional string)
  8890. "Make search string for the current headline or STRING."
  8891. (let ((s (or string
  8892. (and (derived-mode-p 'org-mode)
  8893. (save-excursion
  8894. (org-back-to-heading t)
  8895. (org-element-property :raw-value (org-element-at-point))))))
  8896. (lines org-context-in-file-links))
  8897. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8898. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8899. (when (and string (integerp lines) (> lines 0))
  8900. (let ((slines (org-split-string s "\n")))
  8901. (when (< lines (length slines))
  8902. (setq s (mapconcat
  8903. 'identity
  8904. (reverse (nthcdr (- (length slines) lines)
  8905. (reverse slines))) "\n")))))
  8906. (mapconcat #'identity (split-string s) " ")))
  8907. (defconst org-link-escape-chars
  8908. ;;%20 %5B %5D %25
  8909. '(?\s ?\[ ?\] ?%)
  8910. "List of characters that should be escaped in a link when stored to Org.
  8911. This is the list that is used for internal purposes.")
  8912. (defun org-make-link-string (link &optional description)
  8913. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8914. (unless (org-string-nw-p link) (error "Empty link"))
  8915. (let ((uri (cond ((string-match org-link-types-re link)
  8916. (concat (match-string 1 link)
  8917. (org-link-escape (substring link (match-end 1)))))
  8918. ((or (file-name-absolute-p link)
  8919. (string-match-p "\\`\\.\\.?/" link))
  8920. (org-link-escape link))
  8921. ;; For readability, do not encode space characters
  8922. ;; in fuzzy links.
  8923. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8924. (description
  8925. (and (org-string-nw-p description)
  8926. ;; Remove brackets from description, as they are fatal.
  8927. (replace-regexp-in-string
  8928. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8929. (org-trim description)))))
  8930. (format "[[%s]%s]"
  8931. uri
  8932. (if description (format "[%s]" description) ""))))
  8933. (defun org-link-escape (text &optional table merge)
  8934. "Return percent escaped representation of TEXT.
  8935. TEXT is a string with the text to escape.
  8936. Optional argument TABLE is a list with characters that should be
  8937. escaped. When nil, `org-link-escape-chars' is used.
  8938. If optional argument MERGE is set, merge TABLE into
  8939. `org-link-escape-chars'."
  8940. (let ((characters-to-encode
  8941. (cond ((null table) org-link-escape-chars)
  8942. (merge (append org-link-escape-chars table))
  8943. (t table))))
  8944. (mapconcat
  8945. (lambda (c)
  8946. (if (or (memq c characters-to-encode)
  8947. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8948. (mapconcat (lambda (e) (format "%%%.2X" e))
  8949. (or (encode-coding-char c 'utf-8)
  8950. (error "Unable to percent escape character: %c" c))
  8951. "")
  8952. (char-to-string c)))
  8953. text "")))
  8954. (defun org-link-unescape (str)
  8955. "Unhex hexified Unicode parts in string STR.
  8956. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8957. reciprocal of `org-link-escape', which see."
  8958. (if (org-string-nw-p str)
  8959. (replace-regexp-in-string
  8960. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8961. str))
  8962. (defun org-link-unescape-compound (hex)
  8963. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8964. Note: this function also decodes single byte encodings like
  8965. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8966. (save-match-data
  8967. (let* ((bytes (cdr (split-string hex "%")))
  8968. (ret "")
  8969. (eat 0)
  8970. (sum 0))
  8971. (while bytes
  8972. (let* ((val (string-to-number (pop bytes) 16))
  8973. (shift-xor
  8974. (if (= 0 eat)
  8975. (cond
  8976. ((>= val 252) (cons 6 252))
  8977. ((>= val 248) (cons 5 248))
  8978. ((>= val 240) (cons 4 240))
  8979. ((>= val 224) (cons 3 224))
  8980. ((>= val 192) (cons 2 192))
  8981. (t (cons 0 0)))
  8982. (cons 6 128))))
  8983. (when (>= val 192) (setq eat (car shift-xor)))
  8984. (setq val (logxor val (cdr shift-xor)))
  8985. (setq sum (+ (lsh sum (car shift-xor)) val))
  8986. (when (> eat 0) (setq eat (- eat 1)))
  8987. (cond
  8988. ((= 0 eat) ;multi byte
  8989. (setq ret (concat ret (char-to-string sum)))
  8990. (setq sum 0))
  8991. ((not bytes) ; single byte(s)
  8992. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8993. ret)))
  8994. (defun org-link-unescape-single-byte-sequence (hex)
  8995. "Unhexify hex-encoded single byte character sequences."
  8996. (mapconcat (lambda (byte)
  8997. (char-to-string (string-to-number byte 16)))
  8998. (cdr (split-string hex "%")) ""))
  8999. (defun org-xor (a b)
  9000. "Exclusive or."
  9001. (if a (not b) b))
  9002. (defun org-fixup-message-id-for-http (s)
  9003. "Replace special characters in a message id, so it can be used in an http query."
  9004. (when (string-match "%" s)
  9005. (setq s (mapconcat (lambda (c)
  9006. (if (eq c ?%)
  9007. "%25"
  9008. (char-to-string c)))
  9009. s "")))
  9010. (while (string-match "<" s)
  9011. (setq s (replace-match "%3C" t t s)))
  9012. (while (string-match ">" s)
  9013. (setq s (replace-match "%3E" t t s)))
  9014. (while (string-match "@" s)
  9015. (setq s (replace-match "%40" t t s)))
  9016. s)
  9017. (defun org-link-prettify (link)
  9018. "Return a human-readable representation of LINK.
  9019. The car of LINK must be a raw link.
  9020. The cdr of LINK must be either a link description or nil."
  9021. (let ((desc (or (cadr link) "<no description>")))
  9022. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9023. "<" (car link) ">")))
  9024. ;;;###autoload
  9025. (defun org-insert-link-global ()
  9026. "Insert a link like Org mode does.
  9027. This command can be called in any mode to insert a link in Org syntax."
  9028. (interactive)
  9029. (org-load-modules-maybe)
  9030. (org-run-like-in-org-mode 'org-insert-link))
  9031. (defun org-insert-all-links (arg &optional pre post)
  9032. "Insert all links in `org-stored-links'.
  9033. When a universal prefix, do not delete the links from `org-stored-links'.
  9034. When `ARG' is a number, insert the last N link(s).
  9035. `PRE' and `POST' are optional arguments to define a string to
  9036. prepend or to append."
  9037. (interactive "P")
  9038. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9039. (links (copy-sequence org-stored-links))
  9040. (pr (or pre "- "))
  9041. (po (or post "\n"))
  9042. (cnt 1) l)
  9043. (if (null org-stored-links)
  9044. (message "No link to insert")
  9045. (while (and (or (listp arg) (>= arg cnt))
  9046. (setq l (if (listp arg)
  9047. (pop links)
  9048. (pop org-stored-links))))
  9049. (setq cnt (1+ cnt))
  9050. (insert pr)
  9051. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9052. (insert po)))))
  9053. (defun org-insert-last-stored-link (arg)
  9054. "Insert the last link stored in `org-stored-links'."
  9055. (interactive "p")
  9056. (org-insert-all-links arg "" "\n"))
  9057. (defun org-link-fontify-links-to-this-file ()
  9058. "Fontify links to the current file in `org-stored-links'."
  9059. (let ((f (buffer-file-name)) a b)
  9060. (setq a (mapcar (lambda(l)
  9061. (let ((ll (car l)))
  9062. (when (and (string-match "^file:\\(.+\\)::" ll)
  9063. (equal f (expand-file-name (match-string 1 ll))))
  9064. ll)))
  9065. org-stored-links))
  9066. (when (featurep 'org-id)
  9067. (setq b (mapcar (lambda(l)
  9068. (let ((ll (car l)))
  9069. (when (and (string-match "^id:\\(.+\\)$" ll)
  9070. (equal f (expand-file-name
  9071. (or (org-id-find-id-file
  9072. (match-string 1 ll)) ""))))
  9073. ll)))
  9074. org-stored-links)))
  9075. (mapcar (lambda(l)
  9076. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9077. (delq nil (append a b)))))
  9078. (defvar org--links-history nil)
  9079. (defun org-insert-link (&optional complete-file link-location default-description)
  9080. "Insert a link. At the prompt, enter the link.
  9081. Completion can be used to insert any of the link protocol prefixes in use.
  9082. The history can be used to select a link previously stored with
  9083. `org-store-link'. When the empty string is entered (i.e. if you just
  9084. press `RET' at the prompt), the link defaults to the most recently
  9085. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9086. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9087. You will also be prompted for a description, and if one is given, it will
  9088. be displayed in the buffer instead of the link.
  9089. If there is already a link at point, this command will allow you to edit
  9090. link and description parts.
  9091. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9092. file name can be
  9093. selected using completion. The path to the file will be relative to the
  9094. current directory if the file is in the current directory or a subdirectory.
  9095. Otherwise, the link will be the absolute path as completed in the minibuffer
  9096. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9097. option `org-link-file-path-type'.
  9098. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9099. absolute path even if the file is in
  9100. the current directory or below.
  9101. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9102. prefix negates `org-keep-stored-link-after-insertion'.
  9103. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9104. the link location instead of reading one interactively.
  9105. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9106. be used as the default description. Otherwise, if
  9107. `org-make-link-description-function' is non-nil, this function
  9108. will be called with the link target, and the result will be the
  9109. default link description."
  9110. (interactive "P")
  9111. (let* ((wcf (current-window-configuration))
  9112. (origbuf (current-buffer))
  9113. (region (when (org-region-active-p)
  9114. (buffer-substring (region-beginning) (region-end))))
  9115. (remove (and region (list (region-beginning) (region-end))))
  9116. (desc region)
  9117. (link link-location)
  9118. (abbrevs org-link-abbrev-alist-local)
  9119. entry all-prefixes auto-desc)
  9120. (cond
  9121. (link-location) ; specified by arg, just use it.
  9122. ((org-in-regexp org-bracket-link-regexp 1)
  9123. ;; We do have a link at point, and we are going to edit it.
  9124. (setq remove (list (match-beginning 0) (match-end 0)))
  9125. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9126. (setq link (read-string "Link: "
  9127. (org-link-unescape
  9128. (match-string-no-properties 1)))))
  9129. ((or (org-in-regexp org-angle-link-re)
  9130. (org-in-regexp org-plain-link-re))
  9131. ;; Convert to bracket link
  9132. (setq remove (list (match-beginning 0) (match-end 0))
  9133. link (read-string "Link: "
  9134. (org-unbracket-string "<" ">" (match-string 0)))))
  9135. ((member complete-file '((4) (16)))
  9136. ;; Completing read for file names.
  9137. (setq link (org-file-complete-link complete-file)))
  9138. (t
  9139. ;; Read link, with completion for stored links.
  9140. (org-link-fontify-links-to-this-file)
  9141. (org-switch-to-buffer-other-window "*Org Links*")
  9142. (with-current-buffer "*Org Links*"
  9143. (erase-buffer)
  9144. (insert "Insert a link.
  9145. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9146. (when org-stored-links
  9147. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9148. (insert (mapconcat 'org-link-prettify
  9149. (reverse org-stored-links) "\n")))
  9150. (goto-char (point-min)))
  9151. (let ((cw (selected-window)))
  9152. (select-window (get-buffer-window "*Org Links*" 'visible))
  9153. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9154. (unless (pos-visible-in-window-p (point-max))
  9155. (org-fit-window-to-buffer))
  9156. (and (window-live-p cw) (select-window cw)))
  9157. (setq all-prefixes (append (mapcar 'car abbrevs)
  9158. (mapcar 'car org-link-abbrev-alist)
  9159. (org-link-types)))
  9160. (unwind-protect
  9161. ;; Fake a link history, containing the stored links.
  9162. (let ((org--links-history
  9163. (append (mapcar #'car org-stored-links)
  9164. org-insert-link-history)))
  9165. (setq link
  9166. (org-completing-read
  9167. "Link: "
  9168. (append
  9169. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9170. (mapcar #'car org-stored-links))
  9171. nil nil nil
  9172. 'org--links-history
  9173. (caar org-stored-links)))
  9174. (unless (org-string-nw-p link) (user-error "No link selected"))
  9175. (dolist (l org-stored-links)
  9176. (when (equal link (cadr l))
  9177. (setq link (car l))
  9178. (setq auto-desc t)))
  9179. (when (or (member link all-prefixes)
  9180. (and (equal ":" (substring link -1))
  9181. (member (substring link 0 -1) all-prefixes)
  9182. (setq link (substring link 0 -1))))
  9183. (setq link (with-current-buffer origbuf
  9184. (org-link-try-special-completion link)))))
  9185. (set-window-configuration wcf)
  9186. (kill-buffer "*Org Links*"))
  9187. (setq entry (assoc link org-stored-links))
  9188. (or entry (push link org-insert-link-history))
  9189. (setq desc (or desc (nth 1 entry)))))
  9190. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9191. (not org-keep-stored-link-after-insertion))
  9192. (setq org-stored-links (delq (assoc link org-stored-links)
  9193. org-stored-links)))
  9194. (when (and (string-match org-plain-link-re link)
  9195. (not (string-match org-ts-regexp link)))
  9196. ;; URL-like link, normalize the use of angular brackets.
  9197. (setq link (org-unbracket-string "<" ">" link)))
  9198. ;; Check if we are linking to the current file with a search
  9199. ;; option If yes, simplify the link by using only the search
  9200. ;; option.
  9201. (when (and buffer-file-name
  9202. (let ((case-fold-search nil))
  9203. (string-match "\\`file:\\(.+?\\)::" link)))
  9204. (let ((path (match-string-no-properties 1 link))
  9205. (search (substring-no-properties link (match-end 0))))
  9206. (save-match-data
  9207. (when (equal (file-truename buffer-file-name) (file-truename path))
  9208. ;; We are linking to this same file, with a search option
  9209. (setq link search)))))
  9210. ;; Check if we can/should use a relative path. If yes, simplify
  9211. ;; the link.
  9212. (let ((case-fold-search nil))
  9213. (when (string-match "\\`\\(file\\|docview\\):" link)
  9214. (let* ((type (match-string-no-properties 0 link))
  9215. (path-start (match-end 0))
  9216. (search (and (string-match "::\\(.*\\)\\'" link)
  9217. (match-string 1 link)))
  9218. (path
  9219. (if search
  9220. (substring-no-properties
  9221. link path-start (match-beginning 0))
  9222. (substring-no-properties link (match-end 0))))
  9223. (origpath path))
  9224. (cond
  9225. ((or (eq org-link-file-path-type 'absolute)
  9226. (equal complete-file '(16)))
  9227. (setq path (abbreviate-file-name (expand-file-name path))))
  9228. ((eq org-link-file-path-type 'noabbrev)
  9229. (setq path (expand-file-name path)))
  9230. ((eq org-link-file-path-type 'relative)
  9231. (setq path (file-relative-name path)))
  9232. (t
  9233. (save-match-data
  9234. (if (string-match (concat "^" (regexp-quote
  9235. (expand-file-name
  9236. (file-name-as-directory
  9237. default-directory))))
  9238. (expand-file-name path))
  9239. ;; We are linking a file with relative path name.
  9240. (setq path (substring (expand-file-name path)
  9241. (match-end 0)))
  9242. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9243. (setq link (concat type path (and search (concat "::" search))))
  9244. (when (equal desc origpath)
  9245. (setq desc path)))))
  9246. (unless auto-desc
  9247. (let ((initial-input
  9248. (cond
  9249. (default-description)
  9250. ((not org-make-link-description-function) desc)
  9251. (t (condition-case nil
  9252. (funcall org-make-link-description-function link desc)
  9253. (error
  9254. (message "Can't get link description from `%s'"
  9255. (symbol-name org-make-link-description-function))
  9256. (sit-for 2)
  9257. nil))))))
  9258. (setq desc (read-string "Description: " initial-input))))
  9259. (unless (string-match "\\S-" desc) (setq desc nil))
  9260. (when remove (apply 'delete-region remove))
  9261. (insert (org-make-link-string link desc))
  9262. ;; Redisplay so as the new link has proper invisible characters.
  9263. (sit-for 0)))
  9264. (defun org-link-try-special-completion (type)
  9265. "If there is completion support for link type TYPE, offer it."
  9266. (let ((fun (org-link-get-parameter type :complete)))
  9267. (if (functionp fun)
  9268. (funcall fun)
  9269. (read-string "Link (no completion support): " (concat type ":")))))
  9270. (defun org-file-complete-link (&optional arg)
  9271. "Create a file link using completion."
  9272. (let ((file (read-file-name "File: "))
  9273. (pwd (file-name-as-directory (expand-file-name ".")))
  9274. (pwd1 (file-name-as-directory (abbreviate-file-name
  9275. (expand-file-name ".")))))
  9276. (cond ((equal arg '(16))
  9277. (concat "file:"
  9278. (abbreviate-file-name (expand-file-name file))))
  9279. ((string-match
  9280. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9281. (concat "file:" (match-string 1 file)))
  9282. ((string-match
  9283. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9284. (expand-file-name file))
  9285. (concat "file:"
  9286. (match-string 1 (expand-file-name file))))
  9287. (t (concat "file:" file)))))
  9288. (defun org-completing-read (&rest args)
  9289. "Completing-read with SPACE being a normal character."
  9290. (let ((enable-recursive-minibuffers t)
  9291. (minibuffer-local-completion-map
  9292. (copy-keymap minibuffer-local-completion-map)))
  9293. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9294. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9295. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9296. 'org-time-stamp-inactive)
  9297. (apply #'completing-read args)))
  9298. ;;; Opening/following a link
  9299. (defvar org-link-search-failed nil)
  9300. (defvar org-open-link-functions nil
  9301. "Hook for functions finding a plain text link.
  9302. These functions must take a single argument, the link content.
  9303. They will be called for links that look like [[link text][description]]
  9304. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9305. like a filename (e.g. \"./blue.png\").
  9306. These functions will be called *before* Org attempts to resolve the
  9307. link by doing text searches in the current buffer - so if you want a
  9308. link \"[[target]]\" to still find \"<<target>>\", your function should
  9309. handle this as a special case.
  9310. When the function does handle the link, it must return a non-nil value.
  9311. If it decides that it is not responsible for this link, it must return
  9312. nil to indicate that that Org can continue with other options like
  9313. exact and fuzzy text search.")
  9314. (defun org-next-link (&optional search-backward)
  9315. "Move forward to the next link.
  9316. If the link is in hidden text, expose it."
  9317. (interactive "P")
  9318. (when (and org-link-search-failed (eq this-command last-command))
  9319. (goto-char (point-min))
  9320. (message "Link search wrapped back to beginning of buffer"))
  9321. (setq org-link-search-failed nil)
  9322. (let* ((pos (point))
  9323. (ct (org-context))
  9324. (a (assq :link ct))
  9325. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9326. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9327. ((looking-at org-any-link-re)
  9328. ;; Don't stay stuck at link without an org-link face
  9329. (forward-char (if search-backward -1 1))))
  9330. (if (funcall srch-fun org-any-link-re nil t)
  9331. (progn
  9332. (goto-char (match-beginning 0))
  9333. (when (org-invisible-p) (org-show-context)))
  9334. (goto-char pos)
  9335. (setq org-link-search-failed t)
  9336. (message "No further link found"))))
  9337. (defun org-previous-link ()
  9338. "Move backward to the previous link.
  9339. If the link is in hidden text, expose it."
  9340. (interactive)
  9341. (funcall 'org-next-link t))
  9342. (defun org-translate-link (s)
  9343. "Translate a link string if a translation function has been defined."
  9344. (with-temp-buffer
  9345. (insert (org-trim s))
  9346. (org-trim (org-element-interpret-data (org-element-context)))))
  9347. (defun org-translate-link-from-planner (type path)
  9348. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9349. This is still an experimental function, your mileage may vary."
  9350. (cond
  9351. ((member type '("http" "https" "news" "ftp"))
  9352. ;; standard Internet links are the same.
  9353. nil)
  9354. ((and (equal type "irc") (string-match "^//" path))
  9355. ;; Planner has two / at the beginning of an irc link, we have 1.
  9356. ;; We should have zero, actually....
  9357. (setq path (substring path 1)))
  9358. ((and (equal type "lisp") (string-match "^/" path))
  9359. ;; Planner has a slash, we do not.
  9360. (setq type "elisp" path (substring path 1)))
  9361. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9362. ;; A typical message link. Planner has the id after the final slash,
  9363. ;; we separate it with a hash mark
  9364. (setq path (concat (match-string 1 path) "#"
  9365. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9366. (cons type path))
  9367. (defun org-find-file-at-mouse (ev)
  9368. "Open file link or URL at mouse."
  9369. (interactive "e")
  9370. (mouse-set-point ev)
  9371. (org-open-at-point 'in-emacs))
  9372. (defun org-open-at-mouse (ev)
  9373. "Open file link or URL at mouse.
  9374. See the docstring of `org-open-file' for details."
  9375. (interactive "e")
  9376. (mouse-set-point ev)
  9377. (when (eq major-mode 'org-agenda-mode)
  9378. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9379. (org-open-at-point))
  9380. (defvar org-window-config-before-follow-link nil
  9381. "The window configuration before following a link.
  9382. This is saved in case the need arises to restore it.")
  9383. ;;;###autoload
  9384. (defun org-open-at-point-global ()
  9385. "Follow a link or time-stamp like Org mode does.
  9386. This command can be called in any mode to follow an external link
  9387. or a time-stamp that has Org mode syntax. Its behavior is
  9388. undefined when called on internal links (e.g., fuzzy links).
  9389. Raise an error when there is nothing to follow. "
  9390. (interactive)
  9391. (cond ((org-in-regexp org-any-link-re)
  9392. (org-open-link-from-string (match-string-no-properties 0)))
  9393. ((or (org-in-regexp org-ts-regexp-both nil t)
  9394. (org-in-regexp org-tsr-regexp-both nil t))
  9395. (org-follow-timestamp-link))
  9396. (t (user-error "No link found"))))
  9397. ;;;###autoload
  9398. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9399. "Open a link in the string S, as if it was in Org mode."
  9400. (interactive "sLink: \nP")
  9401. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9402. (with-temp-buffer
  9403. (let ((org-inhibit-startup (not reference-buffer)))
  9404. (org-mode)
  9405. (insert s)
  9406. (goto-char (point-min))
  9407. (when reference-buffer
  9408. (setq org-link-abbrev-alist-local
  9409. (with-current-buffer reference-buffer
  9410. org-link-abbrev-alist-local)))
  9411. (org-open-at-point arg reference-buffer)))))
  9412. (defvar org-open-at-point-functions nil
  9413. "Hook that is run when following a link at point.
  9414. Functions in this hook must return t if they identify and follow
  9415. a link at point. If they don't find anything interesting at point,
  9416. they must return nil.")
  9417. (defvar org-link-search-inhibit-query nil)
  9418. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9419. (defun org--open-doi-link (path)
  9420. "Open a \"doi\" type link.
  9421. PATH is a the path to search for, as a string."
  9422. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9423. (defun org--open-elisp-link (path)
  9424. "Open a \"elisp\" type link.
  9425. PATH is the sexp to evaluate, as a string."
  9426. (let ((cmd path))
  9427. (if (or (and (org-string-nw-p
  9428. org-confirm-elisp-link-not-regexp)
  9429. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9430. (not org-confirm-elisp-link-function)
  9431. (funcall org-confirm-elisp-link-function
  9432. (format "Execute \"%s\" as elisp? "
  9433. (org-add-props cmd nil 'face 'org-warning))))
  9434. (message "%s => %s" cmd
  9435. (if (eq (string-to-char cmd) ?\()
  9436. (eval (read cmd))
  9437. (call-interactively (read cmd))))
  9438. (user-error "Abort"))))
  9439. (defun org--open-help-link (path)
  9440. "Open a \"help\" type link.
  9441. PATH is a symbol name, as a string."
  9442. (pcase (intern path)
  9443. ((and (pred fboundp) variable) (describe-function variable))
  9444. ((and (pred boundp) function) (describe-variable function))
  9445. (name (user-error "Unknown function or variable: %s" name))))
  9446. (defun org--open-shell-link (path)
  9447. "Open a \"shell\" type link.
  9448. PATH is the command to execute, as a string."
  9449. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9450. (cmd path))
  9451. (if (or (and (org-string-nw-p
  9452. org-confirm-shell-link-not-regexp)
  9453. (string-match
  9454. org-confirm-shell-link-not-regexp cmd))
  9455. (not org-confirm-shell-link-function)
  9456. (funcall org-confirm-shell-link-function
  9457. (format "Execute \"%s\" in shell? "
  9458. (org-add-props cmd nil
  9459. 'face 'org-warning))))
  9460. (progn
  9461. (message "Executing %s" cmd)
  9462. (shell-command cmd buf)
  9463. (when (featurep 'midnight)
  9464. (setq clean-buffer-list-kill-buffer-names
  9465. (cons (buffer-name buf)
  9466. clean-buffer-list-kill-buffer-names))))
  9467. (user-error "Abort"))))
  9468. (defun org-open-at-point (&optional arg reference-buffer)
  9469. "Open link, timestamp, footnote or tags at point.
  9470. When point is on a link, follow it. Normally, files will be
  9471. opened by an appropriate application. If the optional prefix
  9472. argument ARG is non-nil, Emacs will visit the file. With
  9473. a double prefix argument, try to open outside of Emacs, in the
  9474. application the system uses for this file type.
  9475. When point is on a timestamp, open the agenda at the day
  9476. specified.
  9477. When point is a footnote definition, move to the first reference
  9478. found. If it is on a reference, move to the associated
  9479. definition.
  9480. When point is on a headline, display a list of every link in the
  9481. entry, so it is possible to pick one, or all, of them. If point
  9482. is on a tag, call `org-tags-view' instead.
  9483. When optional argument REFERENCE-BUFFER is non-nil, it should
  9484. specify a buffer from where the link search should happen. This
  9485. is used internally by `org-open-link-from-string'.
  9486. On top of syntactically correct links, this function will also
  9487. try to open links and time-stamps in comments, example
  9488. blocks... i.e., whenever point is on something looking like
  9489. a timestamp or a link."
  9490. (interactive "P")
  9491. ;; On a code block, open block's results.
  9492. (unless (call-interactively 'org-babel-open-src-block-result)
  9493. (org-load-modules-maybe)
  9494. (setq org-window-config-before-follow-link (current-window-configuration))
  9495. (org-remove-occur-highlights nil nil t)
  9496. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9497. (let* ((context
  9498. ;; Only consider supported types, even if they are not
  9499. ;; the closest one.
  9500. (org-element-lineage
  9501. (org-element-context)
  9502. '(clock footnote-definition footnote-reference headline
  9503. inlinetask link timestamp)
  9504. t))
  9505. (type (org-element-type context))
  9506. (value (org-element-property :value context)))
  9507. (cond
  9508. ;; On a headline or an inlinetask, but not on a timestamp,
  9509. ;; a link, a footnote reference.
  9510. ((memq type '(headline inlinetask))
  9511. (org-match-line org-complex-heading-regexp)
  9512. (if (and (match-beginning 5)
  9513. (>= (point) (match-beginning 5))
  9514. (< (point) (match-end 5)))
  9515. ;; On tags.
  9516. (org-tags-view arg (substring (match-string 5) 0 -1))
  9517. ;; Not on tags.
  9518. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9519. (`(nil . ,_)
  9520. (require 'org-attach)
  9521. (org-attach-reveal 'if-exists))
  9522. (`(,links . ,links-end)
  9523. (dolist (link (if (stringp links) (list links) links))
  9524. (search-forward link nil links-end)
  9525. (goto-char (match-beginning 0))
  9526. (org-open-at-point))))))
  9527. ;; On a footnote reference or at definition's label.
  9528. ((or (eq type 'footnote-reference)
  9529. (and (eq type 'footnote-definition)
  9530. (save-excursion
  9531. ;; Do not validate action when point is on the
  9532. ;; spaces right after the footnote label, in
  9533. ;; order to be on par with behaviour on links.
  9534. (skip-chars-forward " \t")
  9535. (let ((begin
  9536. (org-element-property :contents-begin context)))
  9537. (if begin (< (point) begin)
  9538. (= (org-element-property :post-affiliated context)
  9539. (line-beginning-position)))))))
  9540. (org-footnote-action))
  9541. ;; No valid context. Ignore catch-all types like `headline'.
  9542. ;; If point is on something looking like a link or
  9543. ;; a time-stamp, try opening it. It may be useful in
  9544. ;; comments, example blocks...
  9545. ((memq type '(footnote-definition headline inlinetask nil))
  9546. (call-interactively #'org-open-at-point-global))
  9547. ;; On a clock line, make sure point is on the timestamp
  9548. ;; before opening it.
  9549. ((and (eq type 'clock)
  9550. value
  9551. (>= (point) (org-element-property :begin value))
  9552. (<= (point) (org-element-property :end value)))
  9553. (org-follow-timestamp-link))
  9554. ;; Do nothing on white spaces after an object.
  9555. ((>= (point)
  9556. (save-excursion
  9557. (goto-char (org-element-property :end context))
  9558. (skip-chars-backward " \t")
  9559. (point)))
  9560. (user-error "No link found"))
  9561. ((eq type 'timestamp) (org-follow-timestamp-link))
  9562. ((eq type 'link)
  9563. (let ((type (org-element-property :type context))
  9564. (path (org-link-unescape (org-element-property :path context))))
  9565. ;; Switch back to REFERENCE-BUFFER needed when called in
  9566. ;; a temporary buffer through `org-open-link-from-string'.
  9567. (with-current-buffer (or reference-buffer (current-buffer))
  9568. (cond
  9569. ((equal type "file")
  9570. (if (string-match "[*?{]" (file-name-nondirectory path))
  9571. (dired path)
  9572. ;; Look into `org-link-parameters' in order to find
  9573. ;; a DEDICATED-FUNCTION to open file. The function
  9574. ;; will be applied on raw link instead of parsed
  9575. ;; link due to the limitation in `org-add-link-type'
  9576. ;; ("open" function called with a single argument).
  9577. ;; If no such function is found, fallback to
  9578. ;; `org-open-file'.
  9579. (let* ((option (org-element-property :search-option context))
  9580. (app (org-element-property :application context))
  9581. (dedicated-function
  9582. (org-link-get-parameter
  9583. (if app (concat type "+" app) type)
  9584. :follow)))
  9585. (if dedicated-function
  9586. (funcall dedicated-function
  9587. (concat path
  9588. (and option (concat "::" option))))
  9589. (apply #'org-open-file
  9590. path
  9591. (cond (arg)
  9592. ((equal app "emacs") 'emacs)
  9593. ((equal app "sys") 'system))
  9594. (cond ((not option) nil)
  9595. ((string-match-p "\\`[0-9]+\\'" option)
  9596. (list (string-to-number option)))
  9597. (t (list nil
  9598. (org-link-unescape option)))))))))
  9599. ((functionp (org-link-get-parameter type :follow))
  9600. (funcall (org-link-get-parameter type :follow) path))
  9601. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9602. (unless (run-hook-with-args-until-success
  9603. 'org-open-link-functions path)
  9604. (if (not arg) (org-mark-ring-push)
  9605. (switch-to-buffer-other-window
  9606. (org-get-buffer-for-internal-link (current-buffer))))
  9607. (let ((destination
  9608. (org-with-wide-buffer
  9609. (if (equal type "radio")
  9610. (org-search-radio-target
  9611. (org-element-property :path context))
  9612. (org-link-search
  9613. (if (member type '("custom-id" "coderef"))
  9614. (org-element-property :raw-link context)
  9615. path)
  9616. ;; Prevent fuzzy links from matching
  9617. ;; themselves.
  9618. (and (equal type "fuzzy")
  9619. (+ 2 (org-element-property :begin context)))))
  9620. (point))))
  9621. (unless (and (<= (point-min) destination)
  9622. (>= (point-max) destination))
  9623. (widen))
  9624. (goto-char destination))))
  9625. (t (browse-url-at-point))))))
  9626. (t (user-error "No link found")))))
  9627. (run-hook-with-args 'org-follow-link-hook)))
  9628. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9629. "Offer links in the current entry and return the selected link.
  9630. If there is only one link, return it.
  9631. If NTH is an integer, return the NTH link found.
  9632. If ZERO is a string, check also this string for a link, and if
  9633. there is one, return it."
  9634. (with-current-buffer buffer
  9635. (org-with-wide-buffer
  9636. (goto-char marker)
  9637. (let ((cnt ?0)
  9638. have-zero end links link c)
  9639. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9640. (push (match-string 0 zero) links)
  9641. (setq cnt (1- cnt) have-zero t))
  9642. (save-excursion
  9643. (org-back-to-heading t)
  9644. (setq end (save-excursion (outline-next-heading) (point)))
  9645. (while (re-search-forward org-any-link-re end t)
  9646. (push (match-string 0) links))
  9647. (setq links (org-uniquify (reverse links))))
  9648. (cond
  9649. ((null links)
  9650. (message "No links"))
  9651. ((equal (length links) 1)
  9652. (setq link (car links)))
  9653. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9654. (setq link (nth (if have-zero nth (1- nth)) links)))
  9655. (t ; we have to select a link
  9656. (save-excursion
  9657. (save-window-excursion
  9658. (delete-other-windows)
  9659. (with-output-to-temp-buffer "*Select Link*"
  9660. (dolist (l links)
  9661. (cond
  9662. ((not (string-match org-bracket-link-regexp l))
  9663. (princ (format "[%c] %s\n" (cl-incf cnt)
  9664. (org-unbracket-string "<" ">" l))))
  9665. ((match-end 3)
  9666. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9667. (match-string 3 l) (match-string 1 l))))
  9668. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9669. (match-string 1 l)))))))
  9670. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9671. (message "Select link to open, RET to open all:")
  9672. (setq c (read-char-exclusive))
  9673. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9674. (when (equal c ?q) (user-error "Abort"))
  9675. (if (equal c ?\C-m)
  9676. (setq link links)
  9677. (setq nth (- c ?0))
  9678. (when have-zero (setq nth (1+ nth)))
  9679. (unless (and (integerp nth) (>= (length links) nth))
  9680. (user-error "Invalid link selection"))
  9681. (setq link (nth (1- nth) links)))))
  9682. (cons link end)))))
  9683. ;; TODO: These functions are deprecated since `org-open-at-point'
  9684. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9685. (defun org-open-file-with-system (path)
  9686. "Open file at PATH using the system way of opening it."
  9687. (org-open-file path 'system))
  9688. (defun org-open-file-with-emacs (path)
  9689. "Open file at PATH in Emacs."
  9690. (org-open-file path 'emacs))
  9691. ;;; File search
  9692. (defvar org-create-file-search-functions nil
  9693. "List of functions to construct the right search string for a file link.
  9694. These functions are called in turn with point at the location to
  9695. which the link should point.
  9696. A function in the hook should first test if it would like to
  9697. handle this file type, for example by checking the `major-mode'
  9698. or the file extension. If it decides not to handle this file, it
  9699. should just return nil to give other functions a chance. If it
  9700. does handle the file, it must return the search string to be used
  9701. when following the link. The search string will be part of the
  9702. file link, given after a double colon, and `org-open-at-point'
  9703. will automatically search for it. If special measures must be
  9704. taken to make the search successful, another function should be
  9705. added to the companion hook `org-execute-file-search-functions',
  9706. which see.
  9707. A function in this hook may also use `setq' to set the variable
  9708. `description' to provide a suggestion for the descriptive text to
  9709. be used for this link when it gets inserted into an Org buffer
  9710. with \\[org-insert-link].")
  9711. (defvar org-execute-file-search-functions nil
  9712. "List of functions to execute a file search triggered by a link.
  9713. Functions added to this hook must accept a single argument, the
  9714. search string that was part of the file link, the part after the
  9715. double colon. The function must first check if it would like to
  9716. handle this search, for example by checking the `major-mode' or
  9717. the file extension. If it decides not to handle this search, it
  9718. should just return nil to give other functions a chance. If it
  9719. does handle the search, it must return a non-nil value to keep
  9720. other functions from trying.
  9721. Each function can access the current prefix argument through the
  9722. variable `current-prefix-arg'. Note that a single prefix is used
  9723. to force opening a link in Emacs, so it may be good to only use a
  9724. numeric or double prefix to guide the search function.
  9725. In case this is needed, a function in this hook can also restore
  9726. the window configuration before `org-open-at-point' was called using:
  9727. (set-window-configuration org-window-config-before-follow-link)")
  9728. (defun org-search-radio-target (target)
  9729. "Search a radio target matching TARGET in current buffer.
  9730. White spaces are not significant."
  9731. (let ((re (format "<<<%s>>>"
  9732. (mapconcat #'regexp-quote
  9733. (split-string target)
  9734. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9735. (origin (point)))
  9736. (goto-char (point-min))
  9737. (catch :radio-match
  9738. (while (re-search-forward re nil t)
  9739. (backward-char)
  9740. (let ((object (org-element-context)))
  9741. (when (eq (org-element-type object) 'radio-target)
  9742. (goto-char (org-element-property :begin object))
  9743. (org-show-context 'link-search)
  9744. (throw :radio-match nil))))
  9745. (goto-char origin)
  9746. (user-error "No match for radio target: %s" target))))
  9747. (defun org-link-search (s &optional avoid-pos stealth)
  9748. "Search for a search string S.
  9749. If S starts with \"#\", it triggers a custom ID search.
  9750. If S is enclosed within parenthesis, it initiates a coderef
  9751. search.
  9752. If S is surrounded by forward slashes, it is interpreted as
  9753. a regular expression. In Org mode files, this will create an
  9754. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9755. to list matches. If the current buffer is in `dired-mode', grep
  9756. will be used to search in all files.
  9757. When AVOID-POS is given, ignore matches near that position.
  9758. When optional argument STEALTH is non-nil, do not modify
  9759. visibility around point, thus ignoring `org-show-context-detail'
  9760. variable.
  9761. Search is case-insensitive and ignores white spaces. Return type
  9762. of matched result, which is either `dedicated' or `fuzzy'."
  9763. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9764. (let* ((case-fold-search t)
  9765. (origin (point))
  9766. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9767. (starred (eq (string-to-char normalized) ?*))
  9768. (words (split-string (if starred (substring s 1) s)))
  9769. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9770. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9771. type)
  9772. (cond
  9773. ;; Check if there are any special search functions.
  9774. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9775. ((eq (string-to-char s) ?#)
  9776. ;; Look for a custom ID S if S starts with "#".
  9777. (let* ((id (substring normalized 1))
  9778. (match (org-find-property "CUSTOM_ID" id)))
  9779. (if match (progn (goto-char match) (setf type 'dedicated))
  9780. (error "No match for custom ID: %s" id))))
  9781. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9782. ;; Look for coderef targets if S is enclosed within parenthesis.
  9783. (let ((coderef (match-string-no-properties 1 normalized))
  9784. (re (substring s-single-re 1 -1)))
  9785. (goto-char (point-min))
  9786. (catch :coderef-match
  9787. (while (re-search-forward re nil t)
  9788. (let ((element (org-element-at-point)))
  9789. (when (and (memq (org-element-type element)
  9790. '(example-block src-block))
  9791. ;; Build proper regexp according to current
  9792. ;; block's label format.
  9793. (let ((label-fmt
  9794. (regexp-quote
  9795. (or (org-element-property :label-fmt element)
  9796. org-coderef-label-format))))
  9797. (save-excursion
  9798. (beginning-of-line)
  9799. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9800. (format label-fmt coderef))))))
  9801. (setq type 'dedicated)
  9802. (goto-char (match-beginning 1))
  9803. (throw :coderef-match nil))))
  9804. (goto-char origin)
  9805. (error "No match for coderef: %s" coderef))))
  9806. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9807. ;; Look for a regular expression.
  9808. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9809. (match-string 1 s)))
  9810. ;; From here, we handle fuzzy links.
  9811. ;;
  9812. ;; Look for targets, only if not in a headline search.
  9813. ((and (not starred)
  9814. (let ((target (format "<<%s>>" s-multi-re)))
  9815. (catch :target-match
  9816. (goto-char (point-min))
  9817. (while (re-search-forward target nil t)
  9818. (backward-char)
  9819. (let ((context (org-element-context)))
  9820. (when (eq (org-element-type context) 'target)
  9821. (setq type 'dedicated)
  9822. (goto-char (org-element-property :begin context))
  9823. (throw :target-match t))))
  9824. nil))))
  9825. ;; Look for elements named after S, only if not in a headline
  9826. ;; search.
  9827. ((and (not starred)
  9828. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9829. (catch :name-match
  9830. (goto-char (point-min))
  9831. (while (re-search-forward name nil t)
  9832. (let ((element (org-element-at-point)))
  9833. (when (equal words
  9834. (split-string
  9835. (org-element-property :name element)))
  9836. (setq type 'dedicated)
  9837. (beginning-of-line)
  9838. (throw :name-match t))))
  9839. nil))))
  9840. ;; Regular text search. Prefer headlines in Org mode buffers.
  9841. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9842. ;; statistics cookies and tags.
  9843. ((and (derived-mode-p 'org-mode)
  9844. (let ((title-re
  9845. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9846. org-outline-regexp-bol
  9847. org-comment-string
  9848. (mapconcat #'regexp-quote words ".+")))
  9849. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9850. (comment-re (eval-when-compile
  9851. (format "\\`%s[ \t]+" org-comment-string))))
  9852. (goto-char (point-min))
  9853. (catch :found
  9854. (while (re-search-forward title-re nil t)
  9855. (when (equal words
  9856. (split-string
  9857. (replace-regexp-in-string
  9858. cookie-re ""
  9859. (replace-regexp-in-string
  9860. comment-re "" (org-get-heading t t t)))))
  9861. (throw :found t)))
  9862. nil)))
  9863. (beginning-of-line)
  9864. (setq type 'dedicated))
  9865. ;; Offer to create non-existent headline depending on
  9866. ;; `org-link-search-must-match-exact-headline'.
  9867. ((and (derived-mode-p 'org-mode)
  9868. (not org-link-search-inhibit-query)
  9869. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9870. (yes-or-no-p "No match - create this as a new heading? "))
  9871. (goto-char (point-max))
  9872. (unless (bolp) (newline))
  9873. (org-insert-heading nil t t)
  9874. (insert s "\n")
  9875. (beginning-of-line 0))
  9876. ;; Only headlines are looked after. No need to process
  9877. ;; further: throw an error.
  9878. ((and (derived-mode-p 'org-mode)
  9879. (or starred org-link-search-must-match-exact-headline))
  9880. (goto-char origin)
  9881. (error "No match for fuzzy expression: %s" normalized))
  9882. ;; Regular text search.
  9883. ((catch :fuzzy-match
  9884. (goto-char (point-min))
  9885. (while (re-search-forward s-multi-re nil t)
  9886. ;; Skip match if it contains AVOID-POS or it is included in
  9887. ;; a link with a description but outside the description.
  9888. (unless (or (and avoid-pos
  9889. (<= (match-beginning 0) avoid-pos)
  9890. (> (match-end 0) avoid-pos))
  9891. (and (save-match-data
  9892. (org-in-regexp org-bracket-link-regexp))
  9893. (match-beginning 3)
  9894. (or (> (match-beginning 3) (point))
  9895. (<= (match-end 3) (point)))
  9896. (org-element-lineage
  9897. (save-match-data (org-element-context))
  9898. '(link) t)))
  9899. (goto-char (match-beginning 0))
  9900. (setq type 'fuzzy)
  9901. (throw :fuzzy-match t)))
  9902. nil))
  9903. ;; All failed. Throw an error.
  9904. (t (goto-char origin)
  9905. (error "No match for fuzzy expression: %s" normalized)))
  9906. ;; Disclose surroundings of match, if appropriate.
  9907. (when (and (derived-mode-p 'org-mode) (not stealth))
  9908. (org-show-context 'link-search))
  9909. type))
  9910. (defun org-get-buffer-for-internal-link (buffer)
  9911. "Return a buffer to be used for displaying the link target of internal links."
  9912. (cond
  9913. ((not org-display-internal-link-with-indirect-buffer)
  9914. buffer)
  9915. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9916. (message "Buffer is already a clone, not making another one")
  9917. ;; we also do not modify visibility in this case
  9918. buffer)
  9919. (t ; make a new indirect buffer for displaying the link
  9920. (let* ((bn (buffer-name buffer))
  9921. (ibn (concat bn "(Clone)"))
  9922. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9923. (with-current-buffer ib (org-overview))
  9924. ib))))
  9925. (defun org-do-occur (regexp &optional cleanup)
  9926. "Call the Emacs command `occur'.
  9927. If CLEANUP is non-nil, remove the printout of the regular expression
  9928. in the *Occur* buffer. This is useful if the regex is long and not useful
  9929. to read."
  9930. (occur regexp)
  9931. (when cleanup
  9932. (let ((cwin (selected-window)) win beg end)
  9933. (when (setq win (get-buffer-window "*Occur*"))
  9934. (select-window win))
  9935. (goto-char (point-min))
  9936. (when (re-search-forward "match[a-z]+" nil t)
  9937. (setq beg (match-end 0))
  9938. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9939. (setq end (1- (match-beginning 0)))))
  9940. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9941. (goto-char (point-min))
  9942. (select-window cwin))))
  9943. ;;; The mark ring for links jumps
  9944. (defvar org-mark-ring nil
  9945. "Mark ring for positions before jumps in Org mode.")
  9946. (defvar org-mark-ring-last-goto nil
  9947. "Last position in the mark ring used to go back.")
  9948. ;; Fill and close the ring
  9949. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9950. (dotimes (_ org-mark-ring-length)
  9951. (push (make-marker) org-mark-ring))
  9952. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9953. org-mark-ring)
  9954. (defun org-mark-ring-push (&optional pos buffer)
  9955. "Put the current position or POS into the mark ring and rotate it."
  9956. (interactive)
  9957. (setq pos (or pos (point)))
  9958. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9959. (move-marker (car org-mark-ring)
  9960. (or pos (point))
  9961. (or buffer (current-buffer)))
  9962. (message "%s"
  9963. (substitute-command-keys
  9964. "Position saved to mark ring, go back with \
  9965. `\\[org-mark-ring-goto]'.")))
  9966. (defun org-mark-ring-goto (&optional n)
  9967. "Jump to the previous position in the mark ring.
  9968. With prefix arg N, jump back that many stored positions. When
  9969. called several times in succession, walk through the entire ring.
  9970. Org mode commands jumping to a different position in the current file,
  9971. or to another Org file, automatically push the old position onto the ring."
  9972. (interactive "p")
  9973. (let (p m)
  9974. (if (eq last-command this-command)
  9975. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9976. (setq p org-mark-ring))
  9977. (setq org-mark-ring-last-goto p)
  9978. (setq m (car p))
  9979. (pop-to-buffer-same-window (marker-buffer m))
  9980. (goto-char m)
  9981. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9982. (defun org-add-angle-brackets (s)
  9983. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9984. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9985. s)
  9986. ;;; Following specific links
  9987. (defvar org-agenda-buffer-tmp-name)
  9988. (defvar org-agenda-start-on-weekday)
  9989. (defun org-follow-timestamp-link ()
  9990. "Open an agenda view for the time-stamp date/range at point."
  9991. (cond
  9992. ((org-at-date-range-p t)
  9993. (let ((org-agenda-start-on-weekday)
  9994. (t1 (match-string 1))
  9995. (t2 (match-string 2)) tt1 tt2)
  9996. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9997. tt2 (time-to-days (org-time-string-to-time t2)))
  9998. (let ((org-agenda-buffer-tmp-name
  9999. (format "*Org Agenda(a:%s)"
  10000. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10001. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10002. ((org-at-timestamp-p 'lax)
  10003. (let ((org-agenda-buffer-tmp-name
  10004. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10005. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10006. (substring (match-string 1) 0 10)))
  10007. 1)))
  10008. (t (error "This should not happen"))))
  10009. ;;; Following file links
  10010. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10011. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10012. (declare-function mailcap-mime-info
  10013. "mailcap" (string &optional request no-decode))
  10014. (defvar org-wait nil)
  10015. (defun org-open-file (path &optional in-emacs line search)
  10016. "Open the file at PATH.
  10017. First, this expands any special file name abbreviations. Then the
  10018. configuration variable `org-file-apps' is checked if it contains an
  10019. entry for this file type, and if yes, the corresponding command is launched.
  10020. If no application is found, Emacs simply visits the file.
  10021. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10022. With a double \\[universal-argument] \\[universal-argument] \
  10023. prefix arg, Org tries to avoid opening in Emacs
  10024. and to use an external application to visit the file.
  10025. Optional LINE specifies a line to go to, optional SEARCH a string
  10026. to search for. If LINE or SEARCH is given, the file will be
  10027. opened in Emacs, unless an entry from org-file-apps that makes
  10028. use of groups in a regexp matches.
  10029. If you want to change the way frames are used when following a
  10030. link, please customize `org-link-frame-setup'.
  10031. If the file does not exist, an error is thrown."
  10032. (let* ((file (if (equal path "")
  10033. buffer-file-name
  10034. (substitute-in-file-name (expand-file-name path))))
  10035. (file-apps (append org-file-apps (org-default-apps)))
  10036. (apps (cl-remove-if
  10037. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10038. (apps-dlink (cl-remove-if-not
  10039. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10040. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10041. (dirp (unless remp (file-directory-p file)))
  10042. (file (if (and dirp org-open-directory-means-index-dot-org)
  10043. (concat (file-name-as-directory file) "index.org")
  10044. file))
  10045. (a-m-a-p (assq 'auto-mode apps))
  10046. (dfile (downcase file))
  10047. ;; Reconstruct the original link from the PATH, LINE and
  10048. ;; SEARCH args.
  10049. (link (cond (line (concat file "::" (number-to-string line)))
  10050. (search (concat file "::" search))
  10051. (t file)))
  10052. (dlink (downcase link))
  10053. (ext
  10054. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10055. (match-string 1 dfile)))
  10056. (save-position-maybe
  10057. (let ((old-buffer (current-buffer))
  10058. (old-pos (point))
  10059. (old-mode major-mode))
  10060. (lambda ()
  10061. (and (derived-mode-p 'org-mode)
  10062. (eq old-mode 'org-mode)
  10063. (or (not (eq old-buffer (current-buffer)))
  10064. (not (eq old-pos (point))))
  10065. (org-mark-ring-push old-pos old-buffer)))))
  10066. cmd link-match-data)
  10067. (cond
  10068. ((member in-emacs '((16) system))
  10069. (setq cmd (cdr (assq 'system apps))))
  10070. (in-emacs (setq cmd 'emacs))
  10071. (t
  10072. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10073. (and dirp (cdr (assq 'directory apps)))
  10074. ;; First, try matching against apps-dlink if we
  10075. ;; get a match here, store the match data for
  10076. ;; later.
  10077. (let ((match (assoc-default dlink apps-dlink
  10078. 'string-match)))
  10079. (if match
  10080. (progn (setq link-match-data (match-data))
  10081. match)
  10082. (progn (setq in-emacs (or in-emacs line search))
  10083. nil))) ; if we have no match in apps-dlink,
  10084. ; always open the file in emacs if line or search
  10085. ; is given (for backwards compatibility)
  10086. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10087. 'string-match)
  10088. (cdr (assoc ext apps))
  10089. (cdr (assq t apps))))))
  10090. (when (eq cmd 'system)
  10091. (setq cmd (cdr (assq 'system apps))))
  10092. (when (eq cmd 'default)
  10093. (setq cmd (cdr (assoc t apps))))
  10094. (when (eq cmd 'mailcap)
  10095. (require 'mailcap)
  10096. (mailcap-parse-mailcaps)
  10097. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10098. (command (mailcap-mime-info mime-type)))
  10099. (if (stringp command)
  10100. (setq cmd command)
  10101. (setq cmd 'emacs))))
  10102. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10103. (not (file-exists-p file))
  10104. (not org-open-non-existing-files))
  10105. (user-error "No such file: %s" file))
  10106. (cond
  10107. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10108. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10109. (while (string-match "['\"]%s['\"]" cmd)
  10110. (setq cmd (replace-match "%s" t t cmd)))
  10111. (setq cmd (replace-regexp-in-string
  10112. "%s"
  10113. (shell-quote-argument (convert-standard-filename file))
  10114. cmd
  10115. nil t))
  10116. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10117. (save-match-data
  10118. (let ((match-index 1)
  10119. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10120. (set-match-data link-match-data)
  10121. (while (<= match-index number-of-groups)
  10122. (let ((regex (concat "%" (number-to-string match-index)))
  10123. (replace-with (match-string match-index dlink)))
  10124. (while (string-match regex cmd)
  10125. (setq cmd (replace-match replace-with t t cmd))))
  10126. (setq match-index (+ match-index 1)))))
  10127. (save-window-excursion
  10128. (message "Running %s...done" cmd)
  10129. (start-process-shell-command cmd nil cmd)
  10130. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10131. ((or (stringp cmd)
  10132. (eq cmd 'emacs))
  10133. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10134. (widen)
  10135. (cond (line (org-goto-line line)
  10136. (when (derived-mode-p 'org-mode) (org-reveal)))
  10137. (search (condition-case err
  10138. (org-link-search search)
  10139. ;; Save position before error-ing out so user
  10140. ;; can easily move back to the original buffer.
  10141. (error (funcall save-position-maybe)
  10142. (error (nth 1 err)))))))
  10143. ((functionp cmd)
  10144. (save-match-data
  10145. (set-match-data link-match-data)
  10146. (condition-case nil
  10147. (funcall cmd file link)
  10148. ;; FIXME: Remove this check when most default installations
  10149. ;; of Emacs have at least Org 9.0.
  10150. ((debug wrong-number-of-arguments wrong-type-argument
  10151. invalid-function)
  10152. (user-error "Please see Org News for version 9.0 about \
  10153. `org-file-apps'--Lisp error: %S" cmd)))))
  10154. ((consp cmd)
  10155. ;; FIXME: Remove this check when most default installations of
  10156. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10157. ;; fall back to `org-link-frame-setup' for an old usage of
  10158. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10159. (user-error "Please see Org News for version 9.0 about \
  10160. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10161. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10162. (funcall save-position-maybe)))
  10163. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10164. "This function returns non-nil if `entry' uses a regular
  10165. expression which should be matched against the whole link by
  10166. org-open-file.
  10167. It assumes that is the case when the entry uses a regular
  10168. expression which has at least one grouping construct and the
  10169. action is either a lisp form or a command string containing
  10170. `%1', i.e. using at least one subexpression match as a
  10171. parameter."
  10172. (let ((selector (car entry))
  10173. (action (cdr entry)))
  10174. (if (stringp selector)
  10175. (and (> (regexp-opt-depth selector) 0)
  10176. (or (and (stringp action)
  10177. (string-match "%[0-9]" action))
  10178. (consp action)))
  10179. nil)))
  10180. (defun org-default-apps ()
  10181. "Return the default applications for this operating system."
  10182. (cond
  10183. ((eq system-type 'darwin)
  10184. org-file-apps-defaults-macosx)
  10185. ((eq system-type 'windows-nt)
  10186. org-file-apps-defaults-windowsnt)
  10187. (t org-file-apps-defaults-gnu)))
  10188. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10189. "Convert extensions to regular expressions in the cars of LIST.
  10190. Also, weed out any non-string entries, because the return value is used
  10191. only for regexp matching.
  10192. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10193. point to the symbol `emacs', indicating that the file should
  10194. be opened in Emacs."
  10195. (append
  10196. (delq nil
  10197. (mapcar (lambda (x)
  10198. (unless (not (stringp (car x)))
  10199. (if (string-match "\\W" (car x))
  10200. x
  10201. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10202. list))
  10203. (when add-auto-mode
  10204. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10205. (defvar ange-ftp-name-format)
  10206. (defun org-file-remote-p (file)
  10207. "Test whether FILE specifies a location on a remote system.
  10208. Return non-nil if the location is indeed remote.
  10209. For example, the filename \"/user@host:/foo\" specifies a location
  10210. on the system \"/user@host:\"."
  10211. (cond ((fboundp 'file-remote-p)
  10212. (file-remote-p file))
  10213. ((fboundp 'tramp-handle-file-remote-p)
  10214. (tramp-handle-file-remote-p file))
  10215. ((and (boundp 'ange-ftp-name-format)
  10216. (string-match (car ange-ftp-name-format) file))
  10217. t)))
  10218. ;;;; Refiling
  10219. (defun org-get-org-file ()
  10220. "Read a filename, with default directory `org-directory'."
  10221. (let ((default (or org-default-notes-file remember-data-file)))
  10222. (read-file-name (format "File name [%s]: " default)
  10223. (file-name-as-directory org-directory)
  10224. default)))
  10225. (defun org-notes-order-reversed-p ()
  10226. "Check if the current file should receive notes in reversed order."
  10227. (cond
  10228. ((not org-reverse-note-order) nil)
  10229. ((eq t org-reverse-note-order) t)
  10230. ((not (listp org-reverse-note-order)) nil)
  10231. (t (catch 'exit
  10232. (dolist (entry org-reverse-note-order)
  10233. (when (string-match (car entry) buffer-file-name)
  10234. (throw 'exit (cdr entry))))))))
  10235. (defvar org-refile-target-table nil
  10236. "The list of refile targets, created by `org-refile'.")
  10237. (defvar org-agenda-new-buffers nil
  10238. "Buffers created to visit agenda files.")
  10239. (defvar org-refile-cache nil
  10240. "Cache for refile targets.")
  10241. (defvar org-refile-markers nil
  10242. "All the markers used for caching refile locations.")
  10243. (defun org-refile-marker (pos)
  10244. "Get a new refile marker, but only if caching is in use."
  10245. (if (not org-refile-use-cache)
  10246. pos
  10247. (let ((m (make-marker)))
  10248. (move-marker m pos)
  10249. (push m org-refile-markers)
  10250. m)))
  10251. (defun org-refile-cache-clear ()
  10252. "Clear the refile cache and disable all the markers."
  10253. (dolist (m org-refile-markers) (move-marker m nil))
  10254. (setq org-refile-markers nil)
  10255. (setq org-refile-cache nil)
  10256. (message "Refile cache has been cleared"))
  10257. (defun org-refile-cache-check-set (set)
  10258. "Check if all the markers in the cache still have live buffers."
  10259. (let (marker)
  10260. (catch 'exit
  10261. (while (and set (setq marker (nth 3 (pop set))))
  10262. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10263. (when (and marker (null (marker-buffer marker)))
  10264. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10265. (sit-for 3)
  10266. (throw 'exit nil)))
  10267. t)))
  10268. (defun org-refile-cache-put (set &rest identifiers)
  10269. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10270. (let* ((key (sha1 (prin1-to-string identifiers)))
  10271. (entry (assoc key org-refile-cache)))
  10272. (if entry
  10273. (setcdr entry set)
  10274. (push (cons key set) org-refile-cache))))
  10275. (defun org-refile-cache-get (&rest identifiers)
  10276. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10277. (cond
  10278. ((not org-refile-cache) nil)
  10279. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10280. (t
  10281. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10282. org-refile-cache))))
  10283. (and set (org-refile-cache-check-set set) set)))))
  10284. (defvar org-outline-path-cache nil
  10285. "Alist between buffer positions and outline paths.
  10286. It value is an alist (POSITION . PATH) where POSITION is the
  10287. buffer position at the beginning of an entry and PATH is a list
  10288. of strings describing the outline path for that entry, in reverse
  10289. order.")
  10290. (defun org-refile-get-targets (&optional default-buffer)
  10291. "Produce a table with refile targets."
  10292. (let ((case-fold-search nil)
  10293. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10294. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10295. targets tgs files desc descre)
  10296. (message "Getting targets...")
  10297. (with-current-buffer (or default-buffer (current-buffer))
  10298. (dolist (entry entries)
  10299. (setq files (car entry) desc (cdr entry))
  10300. (cond
  10301. ((null files) (setq files (list (current-buffer))))
  10302. ((eq files 'org-agenda-files)
  10303. (setq files (org-agenda-files 'unrestricted)))
  10304. ((and (symbolp files) (fboundp files))
  10305. (setq files (funcall files)))
  10306. ((and (symbolp files) (boundp files))
  10307. (setq files (symbol-value files))))
  10308. (when (stringp files) (setq files (list files)))
  10309. (cond
  10310. ((eq (car desc) :tag)
  10311. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10312. ((eq (car desc) :todo)
  10313. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10314. ((eq (car desc) :regexp)
  10315. (setq descre (cdr desc)))
  10316. ((eq (car desc) :level)
  10317. (setq descre (concat "^\\*\\{" (number-to-string
  10318. (if org-odd-levels-only
  10319. (1- (* 2 (cdr desc)))
  10320. (cdr desc)))
  10321. "\\}[ \t]")))
  10322. ((eq (car desc) :maxlevel)
  10323. (setq descre (concat "^\\*\\{1," (number-to-string
  10324. (if org-odd-levels-only
  10325. (1- (* 2 (cdr desc)))
  10326. (cdr desc)))
  10327. "\\}[ \t]")))
  10328. (t (error "Bad refiling target description %s" desc)))
  10329. (dolist (f files)
  10330. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10331. (or
  10332. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10333. (progn
  10334. (when (bufferp f)
  10335. (setq f (buffer-file-name (buffer-base-buffer f))))
  10336. (setq f (and f (expand-file-name f)))
  10337. (when (eq org-refile-use-outline-path 'file)
  10338. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10339. (when (eq org-refile-use-outline-path 'buffer-name)
  10340. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10341. (when (eq org-refile-use-outline-path 'full-file-path)
  10342. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10343. (org-with-wide-buffer
  10344. (goto-char (point-min))
  10345. (setq org-outline-path-cache nil)
  10346. (while (re-search-forward descre nil t)
  10347. (beginning-of-line)
  10348. (let ((case-fold-search nil))
  10349. (looking-at org-complex-heading-regexp))
  10350. (let ((begin (point))
  10351. (heading (match-string-no-properties 4)))
  10352. (unless (or (and
  10353. org-refile-target-verify-function
  10354. (not
  10355. (funcall org-refile-target-verify-function)))
  10356. (not heading))
  10357. (let ((re (format org-complex-heading-regexp-format
  10358. (regexp-quote heading)))
  10359. (target
  10360. (if (not org-refile-use-outline-path) heading
  10361. (mapconcat
  10362. #'identity
  10363. (append
  10364. (pcase org-refile-use-outline-path
  10365. (`file (list (file-name-nondirectory
  10366. (buffer-file-name
  10367. (buffer-base-buffer)))))
  10368. (`full-file-path
  10369. (list (buffer-file-name
  10370. (buffer-base-buffer))))
  10371. (`buffer-name
  10372. (list (buffer-name
  10373. (buffer-base-buffer))))
  10374. (_ nil))
  10375. (mapcar (lambda (s) (replace-regexp-in-string
  10376. "/" "\\/" s nil t))
  10377. (org-get-outline-path t t)))
  10378. "/"))))
  10379. (push (list target f re (org-refile-marker (point)))
  10380. tgs)))
  10381. (when (= (point) begin)
  10382. ;; Verification function has not moved point.
  10383. (end-of-line)))))))
  10384. (when org-refile-use-cache
  10385. (org-refile-cache-put tgs (buffer-file-name) descre))
  10386. (setq targets (append tgs targets))))))
  10387. (message "Getting targets...done")
  10388. (delete-dups (nreverse targets))))
  10389. (defun org--get-outline-path-1 (&optional use-cache)
  10390. "Return outline path to current headline.
  10391. Outline path is a list of strings, in reverse order. When
  10392. optional argument USE-CACHE is non-nil, make use of a cache. See
  10393. `org-get-outline-path' for details.
  10394. Assume buffer is widened and point is on a headline."
  10395. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10396. (let ((p (point))
  10397. (heading (let ((case-fold-search nil))
  10398. (looking-at org-complex-heading-regexp)
  10399. (if (not (match-end 4)) ""
  10400. ;; Remove statistics cookies.
  10401. (org-trim
  10402. (org-link-display-format
  10403. (replace-regexp-in-string
  10404. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10405. (match-string-no-properties 4))))))))
  10406. (if (org-up-heading-safe)
  10407. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10408. (when use-cache
  10409. (push (cons p path) org-outline-path-cache))
  10410. path)
  10411. ;; This is a new root node. Since we assume we are moving
  10412. ;; forward, we can drop previous cache so as to limit number
  10413. ;; of associations there.
  10414. (let ((path (list heading)))
  10415. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10416. path)))))
  10417. (defun org-get-outline-path (&optional with-self use-cache)
  10418. "Return the outline path to the current entry.
  10419. An outline path is a list of ancestors for current headline, as
  10420. a list of strings. Statistics cookies are removed and links are
  10421. replaced with their description, if any, or their path otherwise.
  10422. When optional argument WITH-SELF is non-nil, the path also
  10423. includes the current headline.
  10424. When optional argument USE-CACHE is non-nil, cache outline paths
  10425. between calls to this function so as to avoid backtracking. This
  10426. argument is useful when planning to find more than one outline
  10427. path in the same document. In that case, there are two
  10428. conditions to satisfy:
  10429. - `org-outline-path-cache' is set to nil before starting the
  10430. process;
  10431. - outline paths are computed by increasing buffer positions."
  10432. (org-with-wide-buffer
  10433. (and (or (and with-self (org-back-to-heading t))
  10434. (org-up-heading-safe))
  10435. (reverse (org--get-outline-path-1 use-cache)))))
  10436. (defun org-format-outline-path (path &optional width prefix separator)
  10437. "Format the outline path PATH for display.
  10438. WIDTH is the maximum number of characters that is available.
  10439. PREFIX is a prefix to be included in the returned string,
  10440. such as the file name.
  10441. SEPARATOR is inserted between the different parts of the path,
  10442. the default is \"/\"."
  10443. (setq width (or width 79))
  10444. (setq path (delq nil path))
  10445. (unless (> width 0)
  10446. (user-error "Argument `width' must be positive"))
  10447. (setq separator (or separator "/"))
  10448. (let* ((org-odd-levels-only nil)
  10449. (fpath (concat
  10450. prefix (and prefix path separator)
  10451. (mapconcat
  10452. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10453. (cl-loop for head in path
  10454. for n from 0
  10455. collect (org-add-props
  10456. head nil 'face
  10457. (nth (% n org-n-level-faces) org-level-faces)))
  10458. separator))))
  10459. (when (> (length fpath) width)
  10460. (if (< width 7)
  10461. ;; It's unlikely that `width' will be this small, but don't
  10462. ;; waste characters by adding ".." if it is.
  10463. (setq fpath (substring fpath 0 width))
  10464. (setf (substring fpath (- width 2)) "..")))
  10465. fpath))
  10466. (defun org-display-outline-path (&optional file current separator just-return-string)
  10467. "Display the current outline path in the echo area.
  10468. If FILE is non-nil, prepend the output with the file name.
  10469. If CURRENT is non-nil, append the current heading to the output.
  10470. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10471. the different parts of the path and defaults to \"/\".
  10472. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10473. (interactive "P")
  10474. (let* (case-fold-search
  10475. (bfn (buffer-file-name (buffer-base-buffer)))
  10476. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10477. res)
  10478. (when current (setq path (append path
  10479. (save-excursion
  10480. (org-back-to-heading t)
  10481. (when (looking-at org-complex-heading-regexp)
  10482. (list (match-string 4)))))))
  10483. (setq res
  10484. (org-format-outline-path
  10485. path
  10486. (1- (frame-width))
  10487. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10488. separator))
  10489. (if just-return-string
  10490. (org-no-properties res)
  10491. (org-unlogged-message "%s" res))))
  10492. (defvar org-refile-history nil
  10493. "History for refiling operations.")
  10494. (defvar org-after-refile-insert-hook nil
  10495. "Hook run after `org-refile' has inserted its stuff at the new location.
  10496. Note that this is still *before* the stuff will be removed from
  10497. the *old* location.")
  10498. (defvar org-capture-last-stored-marker)
  10499. (defvar org-refile-keep nil
  10500. "Non-nil means `org-refile' will copy instead of refile.")
  10501. (defun org-copy ()
  10502. "Like `org-refile', but copy."
  10503. (interactive)
  10504. (let ((org-refile-keep t))
  10505. (funcall 'org-refile nil nil nil "Copy")))
  10506. (defun org-refile (&optional arg default-buffer rfloc msg)
  10507. "Move the entry or entries at point to another heading.
  10508. The list of target headings is compiled using the information in
  10509. `org-refile-targets', which see.
  10510. At the target location, the entry is filed as a subitem of the
  10511. target heading. Depending on `org-reverse-note-order', the new
  10512. subitem will either be the first or the last subitem.
  10513. If there is an active region, all entries in that region will be
  10514. refiled. However, the region must fulfill the requirement that
  10515. the first heading sets the top-level of the moved text.
  10516. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10517. location
  10518. and not actually move anything.
  10519. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10520. location where the last
  10521. refiling operation has put the subtree.
  10522. With a numeric prefix argument of `2', refile to the running clock.
  10523. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10524. being set to t and copy to the target location, don't move it.
  10525. Beware that keeping refiled entries may result in duplicated ID
  10526. properties.
  10527. RFLOC can be a refile location obtained in a different way.
  10528. MSG is a string to replace \"Refile\" in the default prompt with
  10529. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10530. See also `org-refile-use-outline-path'.
  10531. If you are using target caching (see `org-refile-use-cache'), you
  10532. have to clear the target cache in order to find new targets.
  10533. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10534. prefix argument (`C-u C-u C-u C-c C-w')."
  10535. (interactive "P")
  10536. (if (member arg '(0 (64)))
  10537. (org-refile-cache-clear)
  10538. (let* ((actionmsg (cond (msg msg)
  10539. ((equal arg 3) "Refile (and keep)")
  10540. (t "Refile")))
  10541. (regionp (org-region-active-p))
  10542. (region-start (and regionp (region-beginning)))
  10543. (region-end (and regionp (region-end)))
  10544. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10545. pos it nbuf file level reversed)
  10546. (setq last-command nil)
  10547. (when regionp
  10548. (goto-char region-start)
  10549. (or (bolp) (goto-char (point-at-bol)))
  10550. (setq region-start (point))
  10551. (unless (or (org-kill-is-subtree-p
  10552. (buffer-substring region-start region-end))
  10553. (prog1 org-refile-active-region-within-subtree
  10554. (let ((s (point-at-eol)))
  10555. (org-toggle-heading)
  10556. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10557. (user-error "The region is not a (sequence of) subtree(s)")))
  10558. (if (equal arg '(16))
  10559. (org-refile-goto-last-stored)
  10560. (when (or
  10561. (and (equal arg 2)
  10562. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10563. (prog1
  10564. (setq it (list (or org-clock-heading "running clock")
  10565. (buffer-file-name
  10566. (marker-buffer org-clock-hd-marker))
  10567. ""
  10568. (marker-position org-clock-hd-marker)))
  10569. (setq arg nil)))
  10570. (setq it
  10571. (or rfloc
  10572. (let (heading-text)
  10573. (save-excursion
  10574. (unless (and arg (listp arg))
  10575. (org-back-to-heading t)
  10576. (setq heading-text
  10577. (replace-regexp-in-string
  10578. org-bracket-link-regexp
  10579. "\\3"
  10580. (or (nth 4 (org-heading-components))
  10581. ""))))
  10582. (org-refile-get-location
  10583. (cond ((and arg (listp arg)) "Goto")
  10584. (regionp (concat actionmsg " region to"))
  10585. (t (concat actionmsg " subtree \""
  10586. heading-text "\" to")))
  10587. default-buffer
  10588. (and (not (equal '(4) arg))
  10589. org-refile-allow-creating-parent-nodes)))))))
  10590. (setq file (nth 1 it)
  10591. pos (nth 3 it))
  10592. (when (and (not arg)
  10593. pos
  10594. (equal (buffer-file-name) file)
  10595. (if regionp
  10596. (and (>= pos region-start)
  10597. (<= pos region-end))
  10598. (and (>= pos (point))
  10599. (< pos (save-excursion
  10600. (org-end-of-subtree t t))))))
  10601. (error "Cannot refile to position inside the tree or region"))
  10602. (setq nbuf (or (find-buffer-visiting file)
  10603. (find-file-noselect file)))
  10604. (if (and arg (not (equal arg 3)))
  10605. (progn
  10606. (pop-to-buffer-same-window nbuf)
  10607. (goto-char (cond (pos)
  10608. ((org-notes-order-reversed-p) (point-min))
  10609. (t (point-max))))
  10610. (org-show-context 'org-goto))
  10611. (if regionp
  10612. (progn
  10613. (org-kill-new (buffer-substring region-start region-end))
  10614. (org-save-markers-in-region region-start region-end))
  10615. (org-copy-subtree 1 nil t))
  10616. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10617. (find-file-noselect file)))
  10618. (setq reversed (org-notes-order-reversed-p))
  10619. (org-with-wide-buffer
  10620. (if pos
  10621. (progn
  10622. (goto-char pos)
  10623. (setq level (org-get-valid-level (funcall outline-level) 1))
  10624. (goto-char
  10625. (if reversed
  10626. (or (outline-next-heading) (point-max))
  10627. (or (save-excursion (org-get-next-sibling))
  10628. (org-end-of-subtree t t)
  10629. (point-max)))))
  10630. (setq level 1)
  10631. (if (not reversed)
  10632. (goto-char (point-max))
  10633. (goto-char (point-min))
  10634. (or (outline-next-heading) (goto-char (point-max)))))
  10635. (unless (bolp) (newline))
  10636. (org-paste-subtree level nil nil t)
  10637. (when org-log-refile
  10638. (org-add-log-setup 'refile nil nil org-log-refile)
  10639. (unless (eq org-log-refile 'note)
  10640. (save-excursion (org-add-log-note))))
  10641. (and org-auto-align-tags
  10642. (let ((org-loop-over-headlines-in-active-region nil))
  10643. (org-set-tags nil t)))
  10644. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10645. :last-refile)))
  10646. (when bookmark-name
  10647. (with-demoted-errors
  10648. (bookmark-set bookmark-name))))
  10649. ;; If we are refiling for capture, make sure that the
  10650. ;; last-capture pointers point here
  10651. (when (bound-and-true-p org-capture-is-refiling)
  10652. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10653. :last-capture-marker)))
  10654. (when bookmark-name
  10655. (with-demoted-errors
  10656. (bookmark-set bookmark-name))))
  10657. (move-marker org-capture-last-stored-marker (point)))
  10658. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10659. (run-hooks 'org-after-refile-insert-hook)))
  10660. (unless org-refile-keep
  10661. (if regionp
  10662. (delete-region (point) (+ (point) (- region-end region-start)))
  10663. (delete-region
  10664. (and (org-back-to-heading t) (point))
  10665. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10666. (when (featurep 'org-inlinetask)
  10667. (org-inlinetask-remove-END-maybe))
  10668. (setq org-markers-to-move nil)
  10669. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10670. (defun org-refile-goto-last-stored ()
  10671. "Go to the location where the last refile was stored."
  10672. (interactive)
  10673. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10674. (message "This is the location of the last refile"))
  10675. (defun org-refile--get-location (refloc tbl)
  10676. "When user refile to REFLOC, find the associated target in TBL.
  10677. Also check `org-refile-target-table'."
  10678. (car (delq
  10679. nil
  10680. (mapcar
  10681. (lambda (r) (or (assoc r tbl)
  10682. (assoc r org-refile-target-table)))
  10683. (list (replace-regexp-in-string "/$" "" refloc)
  10684. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10685. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10686. "Prompt the user for a refile location, using PROMPT.
  10687. PROMPT should not be suffixed with a colon and a space, because
  10688. this function appends the default value from
  10689. `org-refile-history' automatically, if that is not empty."
  10690. (let ((org-refile-targets org-refile-targets)
  10691. (org-refile-use-outline-path org-refile-use-outline-path))
  10692. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10693. (unless org-refile-target-table
  10694. (user-error "No refile targets"))
  10695. (let* ((cbuf (current-buffer))
  10696. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10697. (cfunc (if (and org-refile-use-outline-path
  10698. org-outline-path-complete-in-steps)
  10699. #'org-olpath-completing-read
  10700. #'completing-read))
  10701. (extra (if org-refile-use-outline-path "/" ""))
  10702. (cbnex (concat (buffer-name) extra))
  10703. (filename (and cfn (expand-file-name cfn)))
  10704. (tbl (mapcar
  10705. (lambda (x)
  10706. (if (and (not (member org-refile-use-outline-path
  10707. '(file full-file-path)))
  10708. (not (equal filename (nth 1 x))))
  10709. (cons (concat (car x) extra " ("
  10710. (file-name-nondirectory (nth 1 x)) ")")
  10711. (cdr x))
  10712. (cons (concat (car x) extra) (cdr x))))
  10713. org-refile-target-table))
  10714. (completion-ignore-case t)
  10715. cdef
  10716. (prompt (concat prompt
  10717. (or (and (car org-refile-history)
  10718. (concat " (default " (car org-refile-history) ")"))
  10719. (and (assoc cbnex tbl) (setq cdef cbnex)
  10720. (concat " (default " cbnex ")"))) ": "))
  10721. pa answ parent-target child parent old-hist)
  10722. (setq old-hist org-refile-history)
  10723. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10724. nil 'org-refile-history (or cdef (car org-refile-history))))
  10725. (if (setq pa (org-refile--get-location answ tbl))
  10726. (progn
  10727. (org-refile-check-position pa)
  10728. (when (or (not org-refile-history)
  10729. (not (eq old-hist org-refile-history))
  10730. (not (equal (car pa) (car org-refile-history))))
  10731. (setq org-refile-history
  10732. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10733. org-refile-history
  10734. (cdr org-refile-history))))
  10735. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10736. (pop org-refile-history)))
  10737. pa)
  10738. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10739. (progn
  10740. (setq parent (match-string 1 answ)
  10741. child (match-string 2 answ))
  10742. (setq parent-target (org-refile--get-location parent tbl))
  10743. (when (and parent-target
  10744. (or (eq new-nodes t)
  10745. (and (eq new-nodes 'confirm)
  10746. (y-or-n-p (format "Create new node \"%s\"? "
  10747. child)))))
  10748. (org-refile-new-child parent-target child)))
  10749. (user-error "Invalid target location")))))
  10750. (declare-function org-string-nw-p "org-macs" (s))
  10751. (defun org-refile-check-position (refile-pointer)
  10752. "Check if the refile pointer matches the headline to which it points."
  10753. (let* ((file (nth 1 refile-pointer))
  10754. (re (nth 2 refile-pointer))
  10755. (pos (nth 3 refile-pointer))
  10756. buffer)
  10757. (if (and (not (markerp pos)) (not file))
  10758. (user-error "Please indicate a target file in the refile path")
  10759. (when (org-string-nw-p re)
  10760. (setq buffer (if (markerp pos)
  10761. (marker-buffer pos)
  10762. (or (find-buffer-visiting file)
  10763. (find-file-noselect file))))
  10764. (with-current-buffer buffer
  10765. (org-with-wide-buffer
  10766. (goto-char pos)
  10767. (beginning-of-line 1)
  10768. (unless (looking-at-p re)
  10769. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10770. (defun org-refile-new-child (parent-target child)
  10771. "Use refile target PARENT-TARGET to add new CHILD below it."
  10772. (unless parent-target
  10773. (error "Cannot find parent for new node"))
  10774. (let ((file (nth 1 parent-target))
  10775. (pos (nth 3 parent-target))
  10776. level)
  10777. (with-current-buffer (or (find-buffer-visiting file)
  10778. (find-file-noselect file))
  10779. (org-with-wide-buffer
  10780. (if pos
  10781. (goto-char pos)
  10782. (goto-char (point-max))
  10783. (unless (bolp) (newline)))
  10784. (when (looking-at org-outline-regexp)
  10785. (setq level (funcall outline-level))
  10786. (org-end-of-subtree t t))
  10787. (org-back-over-empty-lines)
  10788. (insert "\n" (make-string
  10789. (if pos (org-get-valid-level level 1) 1) ?*)
  10790. " " child "\n")
  10791. (beginning-of-line 0)
  10792. (list (concat (car parent-target) "/" child) file "" (point))))))
  10793. (defun org-olpath-completing-read (prompt collection &rest args)
  10794. "Read an outline path like a file name."
  10795. (let ((thetable collection))
  10796. (apply #'completing-read
  10797. prompt
  10798. (lambda (string predicate &optional flag)
  10799. (cond
  10800. ((eq flag nil) (try-completion string thetable))
  10801. ((eq flag t)
  10802. (let ((l (length string)))
  10803. (mapcar (lambda (x)
  10804. (let ((r (substring x l))
  10805. (f (if (string-match " ([^)]*)$" x)
  10806. (match-string 0 x)
  10807. "")))
  10808. (if (string-match "/" r)
  10809. (concat string (substring r 0 (match-end 0)) f)
  10810. x)))
  10811. (all-completions string thetable predicate))))
  10812. ;; Exact match?
  10813. ((eq flag 'lambda) (assoc string thetable))))
  10814. args)))
  10815. ;;;; Dynamic blocks
  10816. (defun org-find-dblock (name)
  10817. "Find the first dynamic block with name NAME in the buffer.
  10818. If not found, stay at current position and return nil."
  10819. (let ((case-fold-search t) pos)
  10820. (save-excursion
  10821. (goto-char (point-min))
  10822. (setq pos (and (re-search-forward
  10823. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10824. (match-beginning 0))))
  10825. (when pos (goto-char pos))
  10826. pos))
  10827. (defun org-create-dblock (plist)
  10828. "Create a dynamic block section, with parameters taken from PLIST.
  10829. PLIST must contain a :name entry which is used as the name of the block."
  10830. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10831. (end-of-line 1)
  10832. (newline))
  10833. (let ((col (current-column))
  10834. (name (plist-get plist :name)))
  10835. (insert "#+BEGIN: " name)
  10836. (while plist
  10837. (if (eq (car plist) :name)
  10838. (setq plist (cddr plist))
  10839. (insert " " (prin1-to-string (pop plist)))))
  10840. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10841. (beginning-of-line -2)))
  10842. (defun org-prepare-dblock ()
  10843. "Prepare dynamic block for refresh.
  10844. This empties the block, puts the cursor at the insert position and returns
  10845. the property list including an extra property :name with the block name."
  10846. (unless (looking-at org-dblock-start-re)
  10847. (user-error "Not at a dynamic block"))
  10848. (let* ((begdel (1+ (match-end 0)))
  10849. (name (org-no-properties (match-string 1)))
  10850. (params (append (list :name name)
  10851. (read (concat "(" (match-string 3) ")")))))
  10852. (save-excursion
  10853. (beginning-of-line 1)
  10854. (skip-chars-forward " \t")
  10855. (setq params (plist-put params :indentation-column (current-column))))
  10856. (unless (re-search-forward org-dblock-end-re nil t)
  10857. (error "Dynamic block not terminated"))
  10858. (setq params
  10859. (append params
  10860. (list :content (buffer-substring
  10861. begdel (match-beginning 0)))))
  10862. (delete-region begdel (match-beginning 0))
  10863. (goto-char begdel)
  10864. (open-line 1)
  10865. params))
  10866. (defun org-map-dblocks (&optional command)
  10867. "Apply COMMAND to all dynamic blocks in the current buffer.
  10868. If COMMAND is not given, use `org-update-dblock'."
  10869. (let ((cmd (or command 'org-update-dblock)))
  10870. (save-excursion
  10871. (goto-char (point-min))
  10872. (while (re-search-forward org-dblock-start-re nil t)
  10873. (goto-char (match-beginning 0))
  10874. (save-excursion
  10875. (condition-case nil
  10876. (funcall cmd)
  10877. (error (message "Error during update of dynamic block"))))
  10878. (unless (re-search-forward org-dblock-end-re nil t)
  10879. (error "Dynamic block not terminated"))))))
  10880. (defun org-dblock-update (&optional arg)
  10881. "User command for updating dynamic blocks.
  10882. Update the dynamic block at point. With prefix ARG, update all dynamic
  10883. blocks in the buffer."
  10884. (interactive "P")
  10885. (if arg
  10886. (org-update-all-dblocks)
  10887. (or (looking-at org-dblock-start-re)
  10888. (org-beginning-of-dblock))
  10889. (org-update-dblock)))
  10890. (defun org-update-dblock ()
  10891. "Update the dynamic block at point.
  10892. This means to empty the block, parse for parameters and then call
  10893. the correct writing function."
  10894. (interactive)
  10895. (save-excursion
  10896. (let* ((win (selected-window))
  10897. (pos (point))
  10898. (line (org-current-line))
  10899. (params (org-prepare-dblock))
  10900. (name (plist-get params :name))
  10901. (indent (plist-get params :indentation-column))
  10902. (cmd (intern (concat "org-dblock-write:" name))))
  10903. (message "Updating dynamic block `%s' at line %d..." name line)
  10904. (funcall cmd params)
  10905. (message "Updating dynamic block `%s' at line %d...done" name line)
  10906. (goto-char pos)
  10907. (when (and indent (> indent 0))
  10908. (setq indent (make-string indent ?\ ))
  10909. (save-excursion
  10910. (select-window win)
  10911. (org-beginning-of-dblock)
  10912. (forward-line 1)
  10913. (while (not (looking-at org-dblock-end-re))
  10914. (insert indent)
  10915. (beginning-of-line 2))
  10916. (when (looking-at org-dblock-end-re)
  10917. (and (looking-at "[ \t]+")
  10918. (replace-match ""))
  10919. (insert indent)))))))
  10920. (defun org-beginning-of-dblock ()
  10921. "Find the beginning of the dynamic block at point.
  10922. Error if there is no such block at point."
  10923. (let ((pos (point))
  10924. beg)
  10925. (end-of-line 1)
  10926. (if (and (re-search-backward org-dblock-start-re nil t)
  10927. (setq beg (match-beginning 0))
  10928. (re-search-forward org-dblock-end-re nil t)
  10929. (> (match-end 0) pos))
  10930. (goto-char beg)
  10931. (goto-char pos)
  10932. (error "Not in a dynamic block"))))
  10933. (defun org-update-all-dblocks ()
  10934. "Update all dynamic blocks in the buffer.
  10935. This function can be used in a hook."
  10936. (interactive)
  10937. (when (derived-mode-p 'org-mode)
  10938. (org-map-dblocks 'org-update-dblock)))
  10939. ;;;; Completion
  10940. (declare-function org-export-backend-options "ox" (cl-x) t)
  10941. (defun org-get-export-keywords ()
  10942. "Return a list of all currently understood export keywords.
  10943. Export keywords include options, block names, attributes and
  10944. keywords relative to each registered export back-end."
  10945. (let (keywords)
  10946. (dolist (backend
  10947. (bound-and-true-p org-export-registered-backends)
  10948. (delq nil keywords))
  10949. ;; Back-end name (for keywords, like #+LATEX:)
  10950. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10951. (dolist (option-entry (org-export-backend-options backend))
  10952. ;; Back-end options.
  10953. (push (nth 1 option-entry) keywords)))))
  10954. (defconst org-options-keywords
  10955. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10956. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10957. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10958. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10959. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10960. (defcustom org-structure-template-alist
  10961. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10962. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10963. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10964. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10965. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10966. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10967. ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
  10968. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10969. ("L" "#+LaTeX: ")
  10970. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10971. ("H" "#+HTML: ")
  10972. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10973. ("A" "#+ASCII: ")
  10974. ("i" "#+INDEX: ?")
  10975. ("I" "#+INCLUDE: %file ?"))
  10976. "Structure completion elements.
  10977. This is a list of abbreviation keys and values. The value gets inserted
  10978. if you type `<' followed by the key and then press the completion key,
  10979. usually `TAB'. %file will be replaced by a file name after prompting
  10980. for the file using completion. The cursor will be placed at the position
  10981. of the `?' in the template.
  10982. There are two templates for each key, the first uses the original Org syntax,
  10983. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10984. the default when the /org-mtags.el/ module has been loaded. See also the
  10985. variable `org-mtags-prefer-muse-templates'."
  10986. :group 'org-edit-structure
  10987. :type '(repeat
  10988. (list
  10989. (string :tag "Key")
  10990. (string :tag "Template")))
  10991. :version "26.1"
  10992. :package-version '(Org . "8.3"))
  10993. (defun org-try-structure-completion ()
  10994. "Try to complete a structure template before point.
  10995. This looks for strings like \"<e\" on an otherwise empty line and
  10996. expands them."
  10997. (let ((l (buffer-substring (point-at-bol) (point)))
  10998. a)
  10999. (when (and (looking-at "[ \t]*$")
  11000. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11001. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11002. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11003. (match-beginning 1)) a)
  11004. t)))
  11005. (defun org-complete-expand-structure-template (start cell)
  11006. "Expand a structure template."
  11007. (let ((rpl (nth 1 cell))
  11008. (ind ""))
  11009. (delete-region start (point))
  11010. (when (string-match "\\`[ \t]*#\\+" rpl)
  11011. (cond
  11012. ((bolp))
  11013. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11014. (setq ind (buffer-substring (point-at-bol) (point))))
  11015. (t (newline))))
  11016. (setq start (point))
  11017. (when (string-match "%file" rpl)
  11018. (setq rpl (replace-match
  11019. (concat
  11020. "\""
  11021. (save-match-data
  11022. (abbreviate-file-name (read-file-name "Include file: ")))
  11023. "\"")
  11024. t t rpl)))
  11025. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11026. (concat "\n" ind)))
  11027. (insert rpl)
  11028. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11029. ;;;; TODO, DEADLINE, Comments
  11030. (defun org-toggle-comment ()
  11031. "Change the COMMENT state of an entry."
  11032. (interactive)
  11033. (save-excursion
  11034. (org-back-to-heading)
  11035. (let ((case-fold-search nil))
  11036. (looking-at org-complex-heading-regexp))
  11037. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11038. (skip-chars-forward " \t")
  11039. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11040. (if (org-in-commented-heading-p t)
  11041. (delete-region (point)
  11042. (progn (search-forward " " (line-end-position) 'move)
  11043. (skip-chars-forward " \t")
  11044. (point)))
  11045. (insert org-comment-string)
  11046. (unless (eolp) (insert " ")))))
  11047. (defvar org-last-todo-state-is-todo nil
  11048. "This is non-nil when the last TODO state change led to a TODO state.
  11049. If the last change removed the TODO tag or switched to DONE, then
  11050. this is nil.")
  11051. (defvar org-setting-tags nil) ; dynamically skipped
  11052. (defvar org-todo-setup-filter-hook nil
  11053. "Hook for functions that pre-filter todo specs.
  11054. Each function takes a todo spec and returns either nil or the spec
  11055. transformed into canonical form." )
  11056. (defvar org-todo-get-default-hook nil
  11057. "Hook for functions that get a default item for todo.
  11058. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11059. nil or a string to be used for the todo mark." )
  11060. (defvar org-agenda-headline-snapshot-before-repeat)
  11061. (defun org-current-effective-time ()
  11062. "Return current time adjusted for `org-extend-today-until' variable."
  11063. (let* ((ct (org-current-time))
  11064. (dct (decode-time ct))
  11065. (ct1
  11066. (cond
  11067. (org-use-last-clock-out-time-as-effective-time
  11068. (or (org-clock-get-last-clock-out-time) ct))
  11069. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11070. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11071. (t ct))))
  11072. ct1))
  11073. (defun org-todo-yesterday (&optional arg)
  11074. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11075. (interactive "P")
  11076. (if (eq major-mode 'org-agenda-mode)
  11077. (apply 'org-agenda-todo-yesterday arg)
  11078. (let* ((org-use-effective-time t)
  11079. (hour (nth 2 (decode-time (org-current-time))))
  11080. (org-extend-today-until (1+ hour)))
  11081. (org-todo arg))))
  11082. (defvar org-block-entry-blocking ""
  11083. "First entry preventing the TODO state change.")
  11084. (defun org-cancel-repeater ()
  11085. "Cancel a repeater by setting its numeric value to zero."
  11086. (interactive)
  11087. (save-excursion
  11088. (org-back-to-heading t)
  11089. (let ((bound1 (point))
  11090. (bound0 (save-excursion (outline-next-heading) (point))))
  11091. (when (and (re-search-forward
  11092. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11093. org-deadline-time-regexp "\\)\\|\\("
  11094. org-ts-regexp "\\)")
  11095. bound0 t)
  11096. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11097. bound1 t))
  11098. (replace-match "0" t nil nil 1)))))
  11099. (defvar org-state)
  11100. (defvar org-blocked-by-checkboxes)
  11101. (defun org-todo (&optional arg)
  11102. "Change the TODO state of an item.
  11103. The state of an item is given by a keyword at the start of the heading,
  11104. like
  11105. *** TODO Write paper
  11106. *** DONE Call mom
  11107. The different keywords are specified in the variable `org-todo-keywords'.
  11108. By default the available states are \"TODO\" and \"DONE\". So, for this
  11109. example: when the item starts with TODO, it is changed to DONE.
  11110. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11111. DONE are present, add TODO at the beginning of the heading.
  11112. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11113. state.
  11114. With numeric prefix ARG, switch to that state.
  11115. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11116. next set of TODO \
  11117. keywords (nextset).
  11118. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11119. prefix, circumvent any state blocking.
  11120. With a numeric prefix arg of 0, inhibit note taking for the change.
  11121. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11122. When called through ELisp, arg is also interpreted in the following way:
  11123. `none' -> empty state
  11124. \"\" -> switch to empty state
  11125. `done' -> switch to DONE
  11126. `nextset' -> switch to the next set of keywords
  11127. `previousset' -> switch to the previous set of keywords
  11128. \"WAITING\" -> switch to the specified keyword, but only if it
  11129. really is a member of `org-todo-keywords'."
  11130. (interactive "P")
  11131. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11132. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11133. 'region-start-level 'region))
  11134. org-loop-over-headlines-in-active-region)
  11135. (org-map-entries
  11136. `(org-todo ,arg)
  11137. org-loop-over-headlines-in-active-region
  11138. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11139. (when (equal arg '(16)) (setq arg 'nextset))
  11140. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11141. (let ((org-blocker-hook org-blocker-hook)
  11142. commentp
  11143. case-fold-search)
  11144. (when (equal arg '(64))
  11145. (setq arg nil org-blocker-hook nil))
  11146. (when (and org-blocker-hook
  11147. (or org-inhibit-blocking
  11148. (org-entry-get nil "NOBLOCKING")))
  11149. (setq org-blocker-hook nil))
  11150. (save-excursion
  11151. (catch 'exit
  11152. (org-back-to-heading t)
  11153. (when (org-in-commented-heading-p t)
  11154. (org-toggle-comment)
  11155. (setq commentp t))
  11156. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11157. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11158. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11159. (let* ((match-data (match-data))
  11160. (startpos (copy-marker (line-beginning-position)))
  11161. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11162. (org-log-done org-log-done)
  11163. (org-log-repeat org-log-repeat)
  11164. (org-todo-log-states org-todo-log-states)
  11165. (org-inhibit-logging
  11166. (if (equal arg 0)
  11167. (progn (setq arg nil) 'note) org-inhibit-logging))
  11168. (this (match-string 1))
  11169. (hl-pos (match-beginning 0))
  11170. (head (org-get-todo-sequence-head this))
  11171. (ass (assoc head org-todo-kwd-alist))
  11172. (interpret (nth 1 ass))
  11173. (done-word (nth 3 ass))
  11174. (final-done-word (nth 4 ass))
  11175. (org-last-state (or this ""))
  11176. (completion-ignore-case t)
  11177. (member (member this org-todo-keywords-1))
  11178. (tail (cdr member))
  11179. (org-state (cond
  11180. ((and org-todo-key-trigger
  11181. (or (and (equal arg '(4))
  11182. (eq org-use-fast-todo-selection 'prefix))
  11183. (and (not arg) org-use-fast-todo-selection
  11184. (not (eq org-use-fast-todo-selection
  11185. 'prefix)))))
  11186. ;; Use fast selection.
  11187. (org-fast-todo-selection))
  11188. ((and (equal arg '(4))
  11189. (or (not org-use-fast-todo-selection)
  11190. (not org-todo-key-trigger)))
  11191. ;; Read a state with completion.
  11192. (completing-read
  11193. "State: " (mapcar #'list org-todo-keywords-1)
  11194. nil t))
  11195. ((eq arg 'right)
  11196. (if this
  11197. (if tail (car tail) nil)
  11198. (car org-todo-keywords-1)))
  11199. ((eq arg 'left)
  11200. (unless (equal member org-todo-keywords-1)
  11201. (if this
  11202. (nth (- (length org-todo-keywords-1)
  11203. (length tail) 2)
  11204. org-todo-keywords-1)
  11205. (org-last org-todo-keywords-1))))
  11206. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11207. (setq arg nil))) ;hack to fall back to cycling
  11208. (arg
  11209. ;; User or caller requests a specific state.
  11210. (cond
  11211. ((equal arg "") nil)
  11212. ((eq arg 'none) nil)
  11213. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11214. ((eq arg 'nextset)
  11215. (or (car (cdr (member head org-todo-heads)))
  11216. (car org-todo-heads)))
  11217. ((eq arg 'previousset)
  11218. (let ((org-todo-heads (reverse org-todo-heads)))
  11219. (or (car (cdr (member head org-todo-heads)))
  11220. (car org-todo-heads))))
  11221. ((car (member arg org-todo-keywords-1)))
  11222. ((stringp arg)
  11223. (user-error "State `%s' not valid in this file" arg))
  11224. ((nth (1- (prefix-numeric-value arg))
  11225. org-todo-keywords-1))))
  11226. ((null member) (or head (car org-todo-keywords-1)))
  11227. ((equal this final-done-word) nil) ;-> make empty
  11228. ((null tail) nil) ;-> first entry
  11229. ((memq interpret '(type priority))
  11230. (if (eq this-command last-command)
  11231. (car tail)
  11232. (if (> (length tail) 0)
  11233. (or done-word (car org-done-keywords))
  11234. nil)))
  11235. (t
  11236. (car tail))))
  11237. (org-state (or
  11238. (run-hook-with-args-until-success
  11239. 'org-todo-get-default-hook org-state org-last-state)
  11240. org-state))
  11241. (next (if org-state (concat " " org-state " ") " "))
  11242. (change-plist (list :type 'todo-state-change :from this :to org-state
  11243. :position startpos))
  11244. dolog now-done-p)
  11245. (when org-blocker-hook
  11246. (let (org-blocked-by-checkboxes block-reason)
  11247. (setq org-last-todo-state-is-todo
  11248. (not (member this org-done-keywords)))
  11249. (unless (save-excursion
  11250. (save-match-data
  11251. (org-with-wide-buffer
  11252. (run-hook-with-args-until-failure
  11253. 'org-blocker-hook change-plist))))
  11254. (setq block-reason (if org-blocked-by-checkboxes
  11255. "contained checkboxes"
  11256. (format "\"%s\"" org-block-entry-blocking)))
  11257. (if (called-interactively-p 'interactive)
  11258. (user-error "TODO state change from %s to %s blocked (by %s)"
  11259. this org-state block-reason)
  11260. ;; Fail silently.
  11261. (message "TODO state change from %s to %s blocked (by %s)"
  11262. this org-state block-reason)
  11263. (throw 'exit nil)))))
  11264. (store-match-data match-data)
  11265. (replace-match next t t)
  11266. (cond ((equal this org-state)
  11267. (message "TODO state was already %s" (org-trim next)))
  11268. ((not (pos-visible-in-window-p hl-pos))
  11269. (message "TODO state changed to %s" (org-trim next))))
  11270. (unless head
  11271. (setq head (org-get-todo-sequence-head org-state)
  11272. ass (assoc head org-todo-kwd-alist)
  11273. interpret (nth 1 ass)
  11274. done-word (nth 3 ass)
  11275. final-done-word (nth 4 ass)))
  11276. (when (memq arg '(nextset previousset))
  11277. (message "Keyword-Set %d/%d: %s"
  11278. (- (length org-todo-sets) -1
  11279. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11280. (length org-todo-sets)
  11281. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11282. (setq org-last-todo-state-is-todo
  11283. (not (member org-state org-done-keywords)))
  11284. (setq now-done-p (and (member org-state org-done-keywords)
  11285. (not (member this org-done-keywords))))
  11286. (and logging (org-local-logging logging))
  11287. (when (and (or org-todo-log-states org-log-done)
  11288. (not (eq org-inhibit-logging t))
  11289. (not (memq arg '(nextset previousset))))
  11290. ;; We need to look at recording a time and note.
  11291. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11292. (nth 2 (assoc this org-todo-log-states))))
  11293. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11294. (setq dolog 'time))
  11295. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11296. (and org-state
  11297. (member org-state org-not-done-keywords)
  11298. (not (member this org-not-done-keywords))))
  11299. ;; This is now a todo state and was not one before
  11300. ;; If there was a CLOSED time stamp, get rid of it.
  11301. (org-add-planning-info nil nil 'closed))
  11302. (when (and now-done-p org-log-done)
  11303. ;; It is now done, and it was not done before.
  11304. (org-add-planning-info 'closed (org-current-effective-time))
  11305. (when (and (not dolog) (eq 'note org-log-done))
  11306. (org-add-log-setup 'done org-state this 'note)))
  11307. (when (and org-state dolog)
  11308. ;; This is a non-nil state, and we need to log it.
  11309. (org-add-log-setup 'state org-state this dolog)))
  11310. ;; Fixup tag positioning.
  11311. (org-todo-trigger-tag-changes org-state)
  11312. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11313. (when org-provide-todo-statistics
  11314. (org-update-parent-todo-statistics))
  11315. (run-hooks 'org-after-todo-state-change-hook)
  11316. (when (and arg (not (member org-state org-done-keywords)))
  11317. (setq head (org-get-todo-sequence-head org-state)))
  11318. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11319. ;; Do we need to trigger a repeat?
  11320. (when now-done-p
  11321. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11322. ;; This is for the agenda, take a snapshot of the headline.
  11323. (save-match-data
  11324. (setq org-agenda-headline-snapshot-before-repeat
  11325. (org-get-heading))))
  11326. (org-auto-repeat-maybe org-state))
  11327. ;; Fixup cursor location if close to the keyword.
  11328. (when (and (outline-on-heading-p)
  11329. (not (bolp))
  11330. (save-excursion (beginning-of-line 1)
  11331. (looking-at org-todo-line-regexp))
  11332. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11333. (goto-char (or (match-end 2) (match-end 1)))
  11334. (and (looking-at " ") (just-one-space)))
  11335. (when org-trigger-hook
  11336. (save-excursion
  11337. (run-hook-with-args 'org-trigger-hook change-plist)))
  11338. (when commentp (org-toggle-comment))))))))
  11339. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11340. "Block turning an entry into a TODO, using the hierarchy.
  11341. This checks whether the current task should be blocked from state
  11342. changes. Such blocking occurs when:
  11343. 1. The task has children which are not all in a completed state.
  11344. 2. A task has a parent with the property :ORDERED:, and there
  11345. are siblings prior to the current task with incomplete
  11346. status.
  11347. 3. The parent of the task is blocked because it has siblings that should
  11348. be done first, or is child of a block grandparent TODO entry."
  11349. (if (not org-enforce-todo-dependencies)
  11350. t ; if locally turned off don't block
  11351. (catch 'dont-block
  11352. ;; If this is not a todo state change, or if this entry is already DONE,
  11353. ;; do not block
  11354. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11355. (member (plist-get change-plist :from)
  11356. (cons 'done org-done-keywords))
  11357. (member (plist-get change-plist :to)
  11358. (cons 'todo org-not-done-keywords))
  11359. (not (plist-get change-plist :to)))
  11360. (throw 'dont-block t))
  11361. ;; If this task has children, and any are undone, it's blocked
  11362. (save-excursion
  11363. (org-back-to-heading t)
  11364. (let ((this-level (funcall outline-level)))
  11365. (outline-next-heading)
  11366. (let ((child-level (funcall outline-level)))
  11367. (while (and (not (eobp))
  11368. (> child-level this-level))
  11369. ;; this todo has children, check whether they are all
  11370. ;; completed
  11371. (when (and (not (org-entry-is-done-p))
  11372. (org-entry-is-todo-p))
  11373. (setq org-block-entry-blocking (org-get-heading))
  11374. (throw 'dont-block nil))
  11375. (outline-next-heading)
  11376. (setq child-level (funcall outline-level))))))
  11377. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11378. ;; any previous siblings are undone, it's blocked
  11379. (save-excursion
  11380. (org-back-to-heading t)
  11381. (let* ((pos (point))
  11382. (parent-pos (and (org-up-heading-safe) (point)))
  11383. (case-fold-search nil))
  11384. (unless parent-pos (throw 'dont-block t)) ; no parent
  11385. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11386. (forward-line 1)
  11387. (re-search-forward org-not-done-heading-regexp pos t))
  11388. (setq org-block-entry-blocking (match-string 0))
  11389. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11390. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11391. (while t
  11392. (goto-char parent-pos)
  11393. (unless (looking-at org-not-done-heading-regexp)
  11394. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11395. (setq pos (point))
  11396. (setq parent-pos (and (org-up-heading-safe) (point)))
  11397. (unless parent-pos (throw 'dont-block t)) ; no parent
  11398. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11399. (forward-line 1)
  11400. (re-search-forward org-not-done-heading-regexp pos t)
  11401. (setq org-block-entry-blocking (org-get-heading)))
  11402. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11403. (defcustom org-track-ordered-property-with-tag nil
  11404. "Should the ORDERED property also be shown as a tag?
  11405. The ORDERED property decides if an entry should require subtasks to be
  11406. completed in sequence. Since a property is not very visible, setting
  11407. this option means that toggling the ORDERED property with the command
  11408. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11409. not relevant for the behavior, but it makes things more visible.
  11410. Note that toggling the tag with tags commands will not change the property
  11411. and therefore not influence behavior!
  11412. This can be t, meaning the tag ORDERED should be used, It can also be a
  11413. string to select a different tag for this task."
  11414. :group 'org-todo
  11415. :type '(choice
  11416. (const :tag "No tracking" nil)
  11417. (const :tag "Track with ORDERED tag" t)
  11418. (string :tag "Use other tag")))
  11419. (defun org-toggle-ordered-property ()
  11420. "Toggle the ORDERED property of the current entry.
  11421. For better visibility, you can track the value of this property with a tag.
  11422. See variable `org-track-ordered-property-with-tag'."
  11423. (interactive)
  11424. (let* ((t1 org-track-ordered-property-with-tag)
  11425. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11426. (save-excursion
  11427. (org-back-to-heading)
  11428. (if (org-entry-get nil "ORDERED")
  11429. (progn
  11430. (org-delete-property "ORDERED")
  11431. (and tag (org-toggle-tag tag 'off))
  11432. (message "Subtasks can be completed in arbitrary order"))
  11433. (org-entry-put nil "ORDERED" "t")
  11434. (and tag (org-toggle-tag tag 'on))
  11435. (message "Subtasks must be completed in sequence")))))
  11436. (defun org-block-todo-from-checkboxes (change-plist)
  11437. "Block turning an entry into a TODO, using checkboxes.
  11438. This checks whether the current task should be blocked from state
  11439. changes because there are unchecked boxes in this entry."
  11440. (if (not org-enforce-todo-checkbox-dependencies)
  11441. t ; if locally turned off don't block
  11442. (catch 'dont-block
  11443. ;; If this is not a todo state change, or if this entry is already DONE,
  11444. ;; do not block
  11445. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11446. (member (plist-get change-plist :from)
  11447. (cons 'done org-done-keywords))
  11448. (member (plist-get change-plist :to)
  11449. (cons 'todo org-not-done-keywords))
  11450. (not (plist-get change-plist :to)))
  11451. (throw 'dont-block t))
  11452. ;; If this task has checkboxes that are not checked, it's blocked
  11453. (save-excursion
  11454. (org-back-to-heading t)
  11455. (let ((beg (point)) end)
  11456. (outline-next-heading)
  11457. (setq end (point))
  11458. (goto-char beg)
  11459. (when (org-list-search-forward
  11460. (concat (org-item-beginning-re)
  11461. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11462. "\\[[- ]\\]")
  11463. end t)
  11464. (when (boundp 'org-blocked-by-checkboxes)
  11465. (setq org-blocked-by-checkboxes t))
  11466. (throw 'dont-block nil))))
  11467. t))) ; do not block
  11468. (defun org-entry-blocked-p ()
  11469. "Non-nil if entry at point is blocked."
  11470. (and (not (org-entry-get nil "NOBLOCKING"))
  11471. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11472. (not (run-hook-with-args-until-failure
  11473. 'org-blocker-hook
  11474. (list :type 'todo-state-change
  11475. :position (point)
  11476. :from 'todo
  11477. :to 'done)))))
  11478. (defun org-update-statistics-cookies (all)
  11479. "Update the statistics cookie, either from TODO or from checkboxes.
  11480. This should be called with the cursor in a line with a statistics
  11481. cookie. When called with a \\[universal-argument] prefix, update
  11482. all statistics cookies in the buffer."
  11483. (interactive "P")
  11484. (if all
  11485. (progn
  11486. (org-update-checkbox-count 'all)
  11487. (org-map-entries 'org-update-parent-todo-statistics))
  11488. (if (not (org-at-heading-p))
  11489. (org-update-checkbox-count)
  11490. (let ((pos (point-marker))
  11491. end l1 l2)
  11492. (ignore-errors (org-back-to-heading t))
  11493. (if (not (org-at-heading-p))
  11494. (org-update-checkbox-count)
  11495. (setq l1 (org-outline-level))
  11496. (setq end (save-excursion
  11497. (outline-next-heading)
  11498. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11499. (point)))
  11500. (if (and (save-excursion
  11501. (re-search-forward
  11502. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11503. (not (save-excursion (re-search-forward
  11504. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11505. (org-update-checkbox-count)
  11506. (if (and l2 (> l2 l1))
  11507. (progn
  11508. (goto-char end)
  11509. (org-update-parent-todo-statistics))
  11510. (goto-char pos)
  11511. (beginning-of-line 1)
  11512. (while (re-search-forward
  11513. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11514. (point-at-eol) t)
  11515. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11516. (goto-char pos)
  11517. (move-marker pos nil)))))
  11518. (defvar org-entry-property-inherited-from) ;; defined below
  11519. (defun org-update-parent-todo-statistics ()
  11520. "Update any statistics cookie in the parent of the current headline.
  11521. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11522. the entire subtree and this will travel up the hierarchy and update
  11523. statistics everywhere."
  11524. (let* ((prop (save-excursion (org-up-heading-safe)
  11525. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11526. (recursive (or (not org-hierarchical-todo-statistics)
  11527. (and prop (string-match "\\<recursive\\>" prop))))
  11528. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11529. 0))
  11530. (first t)
  11531. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11532. level ltoggle l1 new ndel
  11533. (cnt-all 0) (cnt-done 0) is-percent kwd
  11534. checkbox-beg cookie-present)
  11535. (catch 'exit
  11536. (save-excursion
  11537. (beginning-of-line 1)
  11538. (setq ltoggle (funcall outline-level))
  11539. ;; Three situations are to consider:
  11540. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11541. ;; to the top-level ancestor on the headline;
  11542. ;; 2. If parent has "recursive" property, repeat up to the
  11543. ;; headline setting that property, taking inheritance into
  11544. ;; account;
  11545. ;; 3. Else, move up to direct parent and proceed only once.
  11546. (while (and (setq level (org-up-heading-safe))
  11547. (or recursive first)
  11548. (>= (point) lim))
  11549. (setq first nil cookie-present nil)
  11550. (unless (and level
  11551. (not (string-match
  11552. "\\<checkbox\\>"
  11553. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11554. "")))))
  11555. (throw 'exit nil))
  11556. (while (re-search-forward box-re (point-at-eol) t)
  11557. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11558. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11559. (save-match-data
  11560. (unless (outline-next-heading) (throw 'exit nil))
  11561. (while (and (looking-at org-complex-heading-regexp)
  11562. (> (setq l1 (length (match-string 1))) level))
  11563. (setq kwd (and (or recursive (= l1 ltoggle))
  11564. (match-string 2)))
  11565. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11566. (and (eq org-provide-todo-statistics t)
  11567. (or (member kwd org-done-keywords)))
  11568. (and (listp org-provide-todo-statistics)
  11569. (stringp (car org-provide-todo-statistics))
  11570. (or (member kwd org-provide-todo-statistics)
  11571. (member kwd org-done-keywords)))
  11572. (and (listp org-provide-todo-statistics)
  11573. (listp (car org-provide-todo-statistics))
  11574. (or (member kwd (car org-provide-todo-statistics))
  11575. (and (member kwd org-done-keywords)
  11576. (member kwd (cadr org-provide-todo-statistics))))))
  11577. (setq cnt-all (1+ cnt-all))
  11578. (and (eq org-provide-todo-statistics t)
  11579. kwd
  11580. (setq cnt-all (1+ cnt-all))))
  11581. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11582. (member kwd org-done-keywords))
  11583. (and (listp org-provide-todo-statistics)
  11584. (listp (car org-provide-todo-statistics))
  11585. (member kwd org-done-keywords)
  11586. (member kwd (cadr org-provide-todo-statistics)))
  11587. (and (listp org-provide-todo-statistics)
  11588. (stringp (car org-provide-todo-statistics))
  11589. (member kwd org-done-keywords)))
  11590. (setq cnt-done (1+ cnt-done)))
  11591. (outline-next-heading)))
  11592. (setq new
  11593. (if is-percent
  11594. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11595. (max 1 cnt-all)))
  11596. (format "[%d/%d]" cnt-done cnt-all))
  11597. ndel (- (match-end 0) checkbox-beg))
  11598. (goto-char checkbox-beg)
  11599. (insert new)
  11600. (delete-region (point) (+ (point) ndel))
  11601. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11602. (when cookie-present
  11603. (run-hook-with-args 'org-after-todo-statistics-hook
  11604. cnt-done (- cnt-all cnt-done))))))
  11605. (run-hooks 'org-todo-statistics-hook)))
  11606. (defvar org-after-todo-statistics-hook nil
  11607. "Hook that is called after a TODO statistics cookie has been updated.
  11608. Each function is called with two arguments: the number of not-done entries
  11609. and the number of done entries.
  11610. For example, the following function, when added to this hook, will switch
  11611. an entry to DONE when all children are done, and back to TODO when new
  11612. entries are set to a TODO status. Note that this hook is only called
  11613. when there is a statistics cookie in the headline!
  11614. (defun org-summary-todo (n-done n-not-done)
  11615. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11616. (let (org-log-done org-log-states) ; turn off logging
  11617. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11618. ")
  11619. (defvar org-todo-statistics-hook nil
  11620. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11621. This hook runs even if there is no statistics cookie present, in which case
  11622. `org-after-todo-statistics-hook' would not run.")
  11623. (defun org-todo-trigger-tag-changes (state)
  11624. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11625. (let ((l org-todo-state-tags-triggers)
  11626. changes)
  11627. (when (or (not state) (equal state ""))
  11628. (setq changes (append changes (cdr (assoc "" l)))))
  11629. (when (and (stringp state) (> (length state) 0))
  11630. (setq changes (append changes (cdr (assoc state l)))))
  11631. (when (member state org-not-done-keywords)
  11632. (setq changes (append changes (cdr (assq 'todo l)))))
  11633. (when (member state org-done-keywords)
  11634. (setq changes (append changes (cdr (assq 'done l)))))
  11635. (dolist (c changes)
  11636. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11637. (defun org-local-logging (value)
  11638. "Get logging settings from a property VALUE."
  11639. ;; Directly set the variables, they are already local.
  11640. (setq org-log-done nil
  11641. org-log-repeat nil
  11642. org-todo-log-states nil)
  11643. (dolist (w (split-string value))
  11644. (let (a)
  11645. (cond
  11646. ((setq a (assoc w org-startup-options))
  11647. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11648. (set (nth 1 a) (nth 2 a))))
  11649. ((setq a (org-extract-log-state-settings w))
  11650. (and (member (car a) org-todo-keywords-1)
  11651. (push a org-todo-log-states)))))))
  11652. (defun org-get-todo-sequence-head (kwd)
  11653. "Return the head of the TODO sequence to which KWD belongs.
  11654. If KWD is not set, check if there is a text property remembering the
  11655. right sequence."
  11656. (let (p)
  11657. (cond
  11658. ((not kwd)
  11659. (or (get-text-property (point-at-bol) 'org-todo-head)
  11660. (progn
  11661. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11662. nil (point-at-eol)))
  11663. (get-text-property p 'org-todo-head))))
  11664. ((not (member kwd org-todo-keywords-1))
  11665. (car org-todo-keywords-1))
  11666. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11667. (defun org-fast-todo-selection ()
  11668. "Fast TODO keyword selection with single keys.
  11669. Returns the new TODO keyword, or nil if no state change should occur."
  11670. (let* ((fulltable org-todo-key-alist)
  11671. (done-keywords org-done-keywords) ;; needed for the faces.
  11672. (maxlen (apply 'max (mapcar
  11673. (lambda (x)
  11674. (if (stringp (car x)) (string-width (car x)) 0))
  11675. fulltable)))
  11676. (expert nil)
  11677. (fwidth (+ maxlen 3 1 3))
  11678. (ncol (/ (- (window-width) 4) fwidth))
  11679. tg cnt e c tbl
  11680. groups ingroup)
  11681. (save-excursion
  11682. (save-window-excursion
  11683. (if expert
  11684. (set-buffer (get-buffer-create " *Org todo*"))
  11685. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11686. (erase-buffer)
  11687. (setq-local org-done-keywords done-keywords)
  11688. (setq tbl fulltable cnt 0)
  11689. (while (setq e (pop tbl))
  11690. (cond
  11691. ((equal e '(:startgroup))
  11692. (push '() groups) (setq ingroup t)
  11693. (unless (= cnt 0)
  11694. (setq cnt 0)
  11695. (insert "\n"))
  11696. (insert "{ "))
  11697. ((equal e '(:endgroup))
  11698. (setq ingroup nil cnt 0)
  11699. (insert "}\n"))
  11700. ((equal e '(:newline))
  11701. (unless (= cnt 0)
  11702. (setq cnt 0)
  11703. (insert "\n")
  11704. (setq e (car tbl))
  11705. (while (equal (car tbl) '(:newline))
  11706. (insert "\n")
  11707. (setq tbl (cdr tbl)))))
  11708. (t
  11709. (setq tg (car e) c (cdr e))
  11710. (when ingroup (push tg (car groups)))
  11711. (setq tg (org-add-props tg nil 'face
  11712. (org-get-todo-face tg)))
  11713. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11714. (insert "[" c "] " tg (make-string
  11715. (- fwidth 4 (length tg)) ?\ ))
  11716. (when (= (setq cnt (1+ cnt)) ncol)
  11717. (insert "\n")
  11718. (when ingroup (insert " "))
  11719. (setq cnt 0)))))
  11720. (insert "\n")
  11721. (goto-char (point-min))
  11722. (unless expert (org-fit-window-to-buffer))
  11723. (message "[a-z..]:Set [SPC]:clear")
  11724. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11725. (cond
  11726. ((or (= c ?\C-g)
  11727. (and (= c ?q) (not (rassoc c fulltable))))
  11728. (setq quit-flag t))
  11729. ((= c ?\ ) nil)
  11730. ((setq e (rassoc c fulltable) tg (car e))
  11731. tg)
  11732. (t (setq quit-flag t)))))))
  11733. (defun org-entry-is-todo-p ()
  11734. (member (org-get-todo-state) org-not-done-keywords))
  11735. (defun org-entry-is-done-p ()
  11736. (member (org-get-todo-state) org-done-keywords))
  11737. (defun org-get-todo-state ()
  11738. "Return the TODO keyword of the current subtree."
  11739. (save-excursion
  11740. (org-back-to-heading t)
  11741. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11742. (match-end 2)
  11743. (match-string 2))))
  11744. (defun org-at-date-range-p (&optional inactive-ok)
  11745. "Non-nil if point is inside a date range.
  11746. When optional argument INACTIVE-OK is non-nil, also consider
  11747. inactive time ranges.
  11748. When this function returns a non-nil value, match data is set
  11749. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11750. on INACTIVE-OK."
  11751. (interactive)
  11752. (save-excursion
  11753. (catch 'exit
  11754. (let ((pos (point)))
  11755. (skip-chars-backward "^[<\r\n")
  11756. (skip-chars-backward "<[")
  11757. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11758. (>= (match-end 0) pos)
  11759. (throw 'exit t))
  11760. (skip-chars-backward "^<[\r\n")
  11761. (skip-chars-backward "<[")
  11762. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11763. (>= (match-end 0) pos)
  11764. (throw 'exit t)))
  11765. nil)))
  11766. (defun org-get-repeat (&optional timestamp)
  11767. "Check if there is a time-stamp with repeater in this entry.
  11768. Return the repeater, as a string, or nil. Also return nil when
  11769. this function is called before first heading.
  11770. When optional argument TIMESTAMP is a string, extract the
  11771. repeater from there instead."
  11772. (save-match-data
  11773. (cond (timestamp
  11774. (and (string-match org-repeat-re timestamp)
  11775. (match-string-no-properties 1 timestamp)))
  11776. ((org-before-first-heading-p) nil)
  11777. (t
  11778. (save-excursion
  11779. (org-back-to-heading t)
  11780. (let ((end (org-entry-end-position)))
  11781. (catch :repeat
  11782. (while (re-search-forward org-repeat-re end t)
  11783. (when (save-match-data (org-at-timestamp-p 'agenda))
  11784. (throw :repeat (match-string-no-properties 1)))))))))))
  11785. (defvar org-last-changed-timestamp)
  11786. (defvar org-last-inserted-timestamp)
  11787. (defvar org-log-post-message)
  11788. (defvar org-log-note-purpose)
  11789. (defvar org-log-note-how nil)
  11790. (defvar org-log-note-extra)
  11791. (defun org-auto-repeat-maybe (done-word)
  11792. "Check if the current headline contains a repeated time-stamp.
  11793. If yes, set TODO state back to what it was and change the base date
  11794. of repeating deadline/scheduled time stamps to new date.
  11795. This function is run automatically after each state change to a DONE state."
  11796. (let* ((repeat (org-get-repeat))
  11797. (aa (assoc org-last-state org-todo-kwd-alist))
  11798. (interpret (nth 1 aa))
  11799. (head (nth 2 aa))
  11800. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11801. (msg "Entry repeats: ")
  11802. (org-log-done nil)
  11803. (org-todo-log-states nil)
  11804. (end (copy-marker (org-entry-end-position))))
  11805. (unwind-protect
  11806. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11807. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11808. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11809. org-todo-repeat-to-state)))
  11810. (org-todo (cond
  11811. ((and to-state (member to-state org-todo-keywords-1))
  11812. to-state)
  11813. ((eq interpret 'type) org-last-state)
  11814. (head)
  11815. (t 'none))))
  11816. (org-back-to-heading t)
  11817. (org-add-planning-info nil nil 'closed)
  11818. ;; When `org-log-repeat' is non-nil or entry contains
  11819. ;; a clock, set LAST_REPEAT property.
  11820. (when (or org-log-repeat
  11821. (catch :clock
  11822. (save-excursion
  11823. (while (re-search-forward org-clock-line-re end t)
  11824. (when (org-at-clock-log-p) (throw :clock t))))))
  11825. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11826. (org-time-stamp-format t t)
  11827. (current-time))))
  11828. (when org-log-repeat
  11829. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11830. (memq 'org-add-log-note post-command-hook))
  11831. ;; We are already setup for some record.
  11832. (when (eq org-log-repeat 'note)
  11833. ;; Make sure we take a note, not only a time stamp.
  11834. (setq org-log-note-how 'note))
  11835. ;; Set up for taking a record.
  11836. (org-add-log-setup 'state
  11837. (or done-word (car org-done-keywords))
  11838. org-last-state
  11839. org-log-repeat)))
  11840. (let ((planning-re (regexp-opt
  11841. (list org-scheduled-string org-deadline-string))))
  11842. (while (re-search-forward org-ts-regexp end t)
  11843. (let* ((ts (match-string 0))
  11844. (planning? (org-at-planning-p))
  11845. (type (if (not planning?) "Plain:"
  11846. (save-excursion
  11847. (re-search-backward
  11848. planning-re (line-beginning-position) t)
  11849. (match-string 0)))))
  11850. (cond
  11851. ;; Ignore fake time-stamps (e.g., within comments).
  11852. ((not (org-at-timestamp-p 'agenda)))
  11853. ;; Time-stamps without a repeater are usually
  11854. ;; skipped. However, a SCHEDULED time-stamp without
  11855. ;; one is removed, as they are no longer relevant.
  11856. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11857. ts))
  11858. (when (equal type org-scheduled-string)
  11859. (org-remove-timestamp-with-keyword type)))
  11860. (t
  11861. (let ((n (string-to-number (match-string 2 ts)))
  11862. (what (match-string 3 ts)))
  11863. (when (equal what "w") (setq n (* n 7) what "d"))
  11864. (when (and (equal what "h")
  11865. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11866. ts)))
  11867. (user-error
  11868. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11869. has been set"
  11870. n))
  11871. ;; Preparation, see if we need to modify the start
  11872. ;; date for the change.
  11873. (when (match-end 1)
  11874. (let ((time (save-match-data
  11875. (org-time-string-to-time ts))))
  11876. (cond
  11877. ((equal (match-string 1 ts) ".")
  11878. ;; Shift starting date to today
  11879. (org-timestamp-change
  11880. (- (org-today) (time-to-days time))
  11881. 'day))
  11882. ((equal (match-string 1 ts) "+")
  11883. (let ((nshiftmax 10)
  11884. (nshift 0))
  11885. (while (or (= nshift 0)
  11886. (not (time-less-p (current-time) time)))
  11887. (when (= (cl-incf nshift) nshiftmax)
  11888. (or (y-or-n-p
  11889. (format "%d repeater intervals were not \
  11890. enough to shift date past today. Continue? "
  11891. nshift))
  11892. (user-error "Abort")))
  11893. (org-timestamp-change n (cdr (assoc what whata)))
  11894. (org-in-regexp org-ts-regexp3)
  11895. (setq ts (match-string 1))
  11896. (setq time
  11897. (save-match-data
  11898. (org-time-string-to-time ts)))))
  11899. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11900. ;; Rematch, so that we have everything in place
  11901. ;; for the real shift.
  11902. (org-in-regexp org-ts-regexp3)
  11903. (setq ts (match-string 1))
  11904. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11905. ts)))))
  11906. (save-excursion
  11907. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11908. (setq msg
  11909. (concat
  11910. msg type " " org-last-changed-timestamp " "))))))))
  11911. (setq org-log-post-message msg)
  11912. (message "%s" msg))
  11913. (set-marker end nil))))
  11914. (defun org-show-todo-tree (arg)
  11915. "Make a compact tree which shows all headlines marked with TODO.
  11916. The tree will show the lines where the regexp matches, and all higher
  11917. headlines above the match.
  11918. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11919. With a numeric prefix N, construct a sparse tree for the Nth element
  11920. of `org-todo-keywords-1'."
  11921. (interactive "P")
  11922. (let ((case-fold-search nil)
  11923. (kwd-re
  11924. (cond ((null arg) org-not-done-regexp)
  11925. ((equal arg '(4))
  11926. (let ((kwd
  11927. (completing-read "Keyword (or KWD1|KWD2|...): "
  11928. (mapcar #'list org-todo-keywords-1))))
  11929. (concat "\\("
  11930. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11931. "\\)\\>")))
  11932. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11933. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11934. org-todo-keywords-1)))
  11935. (t (user-error "Invalid prefix argument: %s" arg)))))
  11936. (message "%d TODO entries found"
  11937. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11938. (defun org--deadline-or-schedule (arg type time)
  11939. "Insert DEADLINE or SCHEDULE information in current entry.
  11940. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11941. `org-schedule' for information about ARG and TIME arguments."
  11942. (let* ((deadline? (eq type 'deadline))
  11943. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11944. (log (if deadline? org-log-redeadline org-log-reschedule))
  11945. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11946. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11947. ;; Save repeater cookie from either TIME or current scheduled
  11948. ;; time stamp. We are going to insert it back at the end of
  11949. ;; the process.
  11950. (repeater (or (and (org-string-nw-p time)
  11951. ;; We use `org-repeat-re' because we need
  11952. ;; to tell the difference between a real
  11953. ;; repeater and a time delta, e.g. "+2d".
  11954. (string-match org-repeat-re time)
  11955. (match-string 1 time))
  11956. (and (org-string-nw-p old-date)
  11957. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11958. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11959. old-date)
  11960. (match-string 1 old-date)))))
  11961. (pcase arg
  11962. (`(4)
  11963. (when (and old-date log)
  11964. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11965. nil old-date log))
  11966. (org-remove-timestamp-with-keyword keyword)
  11967. (message (if deadline? "Item no longer has a deadline."
  11968. "Item is no longer scheduled.")))
  11969. (`(16)
  11970. (save-excursion
  11971. (org-back-to-heading t)
  11972. (let ((regexp (if deadline? org-deadline-time-regexp
  11973. org-scheduled-time-regexp)))
  11974. (if (not (re-search-forward regexp (line-end-position 2) t))
  11975. (user-error (if deadline? "No deadline information to update"
  11976. "No scheduled information to update"))
  11977. (let* ((rpl0 (match-string 1))
  11978. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11979. (msg (if deadline? "Warn starting from" "Delay until")))
  11980. (replace-match
  11981. (concat keyword
  11982. " <" rpl
  11983. (format " -%dd"
  11984. (abs (- (time-to-days
  11985. (save-match-data
  11986. (org-read-date
  11987. nil t nil msg old-date-time)))
  11988. (time-to-days old-date-time))))
  11989. ">") t t))))))
  11990. (_
  11991. (org-add-planning-info type time 'closed)
  11992. (when (and old-date
  11993. log
  11994. (not (equal old-date org-last-inserted-timestamp)))
  11995. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11996. org-last-inserted-timestamp
  11997. old-date
  11998. log))
  11999. (when repeater
  12000. (save-excursion
  12001. (org-back-to-heading t)
  12002. (when (re-search-forward
  12003. (concat keyword " " org-last-inserted-timestamp)
  12004. (line-end-position 2)
  12005. t)
  12006. (goto-char (1- (match-end 0)))
  12007. (insert " " repeater)
  12008. (setq org-last-inserted-timestamp
  12009. (concat (substring org-last-inserted-timestamp 0 -1)
  12010. " " repeater
  12011. (substring org-last-inserted-timestamp -1))))))
  12012. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12013. org-last-inserted-timestamp)))))
  12014. (defun org-deadline (arg &optional time)
  12015. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12016. With one universal prefix argument, remove any deadline from the item.
  12017. With two universal prefix arguments, prompt for a warning delay.
  12018. With argument TIME, set the deadline at the corresponding date. TIME
  12019. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12020. (interactive "P")
  12021. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12022. (org-map-entries
  12023. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12024. nil
  12025. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12026. 'region-start-level
  12027. 'region)
  12028. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12029. (org--deadline-or-schedule arg 'deadline time)))
  12030. (defun org-schedule (arg &optional time)
  12031. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12032. With one universal prefix argument, remove any scheduling date from the item.
  12033. With two universal prefix arguments, prompt for a delay cookie.
  12034. With argument TIME, scheduled at the corresponding date. TIME can
  12035. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12036. (interactive "P")
  12037. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12038. (org-map-entries
  12039. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12040. nil
  12041. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12042. 'region-start-level
  12043. 'region)
  12044. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12045. (org--deadline-or-schedule arg 'scheduled time)))
  12046. (defun org-get-scheduled-time (pom &optional inherit)
  12047. "Get the scheduled time as a time tuple, of a format suitable
  12048. for calling org-schedule with, or if there is no scheduling,
  12049. returns nil."
  12050. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12051. (when time
  12052. (apply 'encode-time (org-parse-time-string time)))))
  12053. (defun org-get-deadline-time (pom &optional inherit)
  12054. "Get the deadline as a time tuple, of a format suitable for
  12055. calling org-deadline with, or if there is no scheduling, returns
  12056. nil."
  12057. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12058. (when time
  12059. (apply 'encode-time (org-parse-time-string time)))))
  12060. (defun org-remove-timestamp-with-keyword (keyword)
  12061. "Remove all time stamps with KEYWORD in the current entry."
  12062. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12063. beg)
  12064. (save-excursion
  12065. (org-back-to-heading t)
  12066. (setq beg (point))
  12067. (outline-next-heading)
  12068. (while (re-search-backward re beg t)
  12069. (replace-match "")
  12070. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12071. (equal (char-before) ?\ ))
  12072. (backward-delete-char 1)
  12073. (when (string-match "^[ \t]*$" (buffer-substring
  12074. (point-at-bol) (point-at-eol)))
  12075. (delete-region (point-at-bol)
  12076. (min (point-max) (1+ (point-at-eol))))))))))
  12077. (defvar org-time-was-given) ; dynamically scoped parameter
  12078. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12079. (defun org-at-planning-p ()
  12080. "Non-nil when point is on a planning info line."
  12081. ;; This is as accurate and faster than `org-element-at-point' since
  12082. ;; planning info location is fixed in the section.
  12083. (org-with-wide-buffer
  12084. (beginning-of-line)
  12085. (and (looking-at-p org-planning-line-re)
  12086. (eq (point)
  12087. (ignore-errors
  12088. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12089. (org-back-to-heading t)
  12090. (org-with-limited-levels (org-back-to-heading t)))
  12091. (line-beginning-position 2))))))
  12092. (defun org-add-planning-info (what &optional time &rest remove)
  12093. "Insert new timestamp with keyword in the planning line.
  12094. WHAT indicates what kind of time stamp to add. It is a symbol
  12095. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12096. the time to use. If none is given, the user is prompted for
  12097. a date. REMOVE indicates what kind of entries to remove. An old
  12098. WHAT entry will also be removed."
  12099. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12100. (catch 'exit
  12101. (when (and (memq what '(scheduled deadline))
  12102. (or (not time)
  12103. (and (stringp time)
  12104. (string-match "^[-+]+[0-9]" time))))
  12105. ;; Try to get a default date/time from existing timestamp
  12106. (save-excursion
  12107. (org-back-to-heading t)
  12108. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12109. (when (re-search-forward (if (eq what 'scheduled)
  12110. org-scheduled-time-regexp
  12111. org-deadline-time-regexp)
  12112. end t)
  12113. (setq ts (match-string 1)
  12114. default-time (apply 'encode-time (org-parse-time-string ts))
  12115. default-input (and ts (org-get-compact-tod ts)))))))
  12116. (when what
  12117. (setq time
  12118. (if (stringp time)
  12119. ;; This is a string (relative or absolute), set
  12120. ;; proper date.
  12121. (apply #'encode-time
  12122. (org-read-date-analyze
  12123. time default-time (decode-time default-time)))
  12124. ;; If necessary, get the time from the user
  12125. (or time (org-read-date nil 'to-time nil nil
  12126. default-time default-input)))))
  12127. (org-with-wide-buffer
  12128. (org-back-to-heading t)
  12129. (forward-line)
  12130. (unless (bolp) (insert "\n"))
  12131. (cond ((looking-at-p org-planning-line-re)
  12132. ;; Move to current indentation.
  12133. (skip-chars-forward " \t")
  12134. ;; Check if we have to remove something.
  12135. (dolist (type (if what (cons what remove) remove))
  12136. (save-excursion
  12137. (when (re-search-forward
  12138. (cl-case type
  12139. (closed org-closed-time-regexp)
  12140. (deadline org-deadline-time-regexp)
  12141. (scheduled org-scheduled-time-regexp)
  12142. (otherwise
  12143. (error "Invalid planning type: %s" type)))
  12144. (line-end-position) t)
  12145. ;; Delete until next keyword or end of line.
  12146. (delete-region
  12147. (match-beginning 0)
  12148. (if (re-search-forward org-keyword-time-not-clock-regexp
  12149. (line-end-position)
  12150. t)
  12151. (match-beginning 0)
  12152. (line-end-position))))))
  12153. ;; If there is nothing more to add and no more keyword
  12154. ;; is left, remove the line completely.
  12155. (if (and (looking-at-p "[ \t]*$") (not what))
  12156. (delete-region (line-beginning-position)
  12157. (line-beginning-position 2))
  12158. ;; If we removed last keyword, do not leave trailing
  12159. ;; white space at the end of line.
  12160. (let ((p (point)))
  12161. (save-excursion
  12162. (end-of-line)
  12163. (unless (= (skip-chars-backward " \t" p) 0)
  12164. (delete-region (point) (line-end-position)))))))
  12165. ((not what) (throw 'exit nil)) ; Nothing to do.
  12166. (t (insert-before-markers "\n")
  12167. (backward-char 1)
  12168. (when org-adapt-indentation
  12169. (indent-to-column (1+ (org-outline-level))))))
  12170. (when what
  12171. ;; Insert planning keyword.
  12172. (insert (cl-case what
  12173. (closed org-closed-string)
  12174. (deadline org-deadline-string)
  12175. (scheduled org-scheduled-string)
  12176. (otherwise (error "Invalid planning type: %s" what)))
  12177. " ")
  12178. ;; Insert associated timestamp.
  12179. (let ((ts (org-insert-time-stamp
  12180. time
  12181. (or org-time-was-given
  12182. (and (eq what 'closed) org-log-done-with-time))
  12183. (eq what 'closed)
  12184. nil nil (list org-end-time-was-given))))
  12185. (unless (eolp) (insert " "))
  12186. ts))))))
  12187. (defvar org-log-note-marker (make-marker)
  12188. "Marker pointing at the entry where the note is to be inserted.")
  12189. (defvar org-log-note-purpose nil)
  12190. (defvar org-log-note-state nil)
  12191. (defvar org-log-note-previous-state nil)
  12192. (defvar org-log-note-extra nil)
  12193. (defvar org-log-note-window-configuration nil)
  12194. (defvar org-log-note-return-to (make-marker))
  12195. (defvar org-log-note-effective-time nil
  12196. "Remembered current time so that dynamically scoped
  12197. `org-extend-today-until' affects timestamps in state change log")
  12198. (defvar org-log-post-message nil
  12199. "Message to be displayed after a log note has been stored.
  12200. The auto-repeater uses this.")
  12201. (defun org-add-note ()
  12202. "Add a note to the current entry.
  12203. This is done in the same way as adding a state change note."
  12204. (interactive)
  12205. (org-add-log-setup 'note))
  12206. (defun org-log-beginning (&optional create)
  12207. "Return expected start of log notes in current entry.
  12208. When optional argument CREATE is non-nil, the function creates
  12209. a drawer to store notes, if necessary. Returned position ignores
  12210. narrowing."
  12211. (org-with-wide-buffer
  12212. (let ((drawer (org-log-into-drawer)))
  12213. (cond
  12214. (drawer
  12215. (org-end-of-meta-data)
  12216. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12217. (end (if (org-at-heading-p) (point)
  12218. (save-excursion (outline-next-heading) (point))))
  12219. (case-fold-search t))
  12220. (catch 'exit
  12221. ;; Try to find existing drawer.
  12222. (while (re-search-forward regexp end t)
  12223. (let ((element (org-element-at-point)))
  12224. (when (eq (org-element-type element) 'drawer)
  12225. (let ((cend (org-element-property :contents-end element)))
  12226. (when (and (not org-log-states-order-reversed) cend)
  12227. (goto-char cend)))
  12228. (throw 'exit nil))))
  12229. ;; No drawer found. Create one, if permitted.
  12230. (when create
  12231. (unless (bolp) (insert "\n"))
  12232. (let ((beg (point)))
  12233. (insert ":" drawer ":\n:END:\n")
  12234. (org-indent-region beg (point)))
  12235. (end-of-line -1)))))
  12236. (t
  12237. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12238. (skip-chars-forward " \t\n")
  12239. (beginning-of-line)
  12240. (unless org-log-states-order-reversed
  12241. (org-skip-over-state-notes)
  12242. (skip-chars-backward " \t\n")
  12243. (forward-line)))))
  12244. (if (bolp) (point) (line-beginning-position 2))))
  12245. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12246. "Set up the post command hook to take a note.
  12247. If this is about to TODO state change, the new state is expected in STATE.
  12248. HOW is an indicator what kind of note should be created.
  12249. EXTRA is additional text that will be inserted into the notes buffer."
  12250. (move-marker org-log-note-marker (point))
  12251. (setq org-log-note-purpose purpose
  12252. org-log-note-state state
  12253. org-log-note-previous-state prev-state
  12254. org-log-note-how how
  12255. org-log-note-extra extra
  12256. org-log-note-effective-time (org-current-effective-time))
  12257. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12258. (defun org-skip-over-state-notes ()
  12259. "Skip past the list of State notes in an entry."
  12260. (when (ignore-errors (goto-char (org-in-item-p)))
  12261. (let* ((struct (org-list-struct))
  12262. (prevs (org-list-prevs-alist struct))
  12263. (regexp
  12264. (concat "[ \t]*- +"
  12265. (replace-regexp-in-string
  12266. " +" " +"
  12267. (org-replace-escapes
  12268. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12269. `(("%d" . ,org-ts-regexp-inactive)
  12270. ("%D" . ,org-ts-regexp)
  12271. ("%s" . "\"\\S-+\"")
  12272. ("%S" . "\"\\S-+\"")
  12273. ("%t" . ,org-ts-regexp-inactive)
  12274. ("%T" . ,org-ts-regexp)
  12275. ("%u" . ".*?")
  12276. ("%U" . ".*?")))))))
  12277. (while (looking-at-p regexp)
  12278. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12279. (org-list-get-item-end (point) struct)))))))
  12280. (defun org-add-log-note (&optional _purpose)
  12281. "Pop up a window for taking a note, and add this note later."
  12282. (remove-hook 'post-command-hook 'org-add-log-note)
  12283. (setq org-log-note-window-configuration (current-window-configuration))
  12284. (delete-other-windows)
  12285. (move-marker org-log-note-return-to (point))
  12286. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12287. (goto-char org-log-note-marker)
  12288. (org-switch-to-buffer-other-window "*Org Note*")
  12289. (erase-buffer)
  12290. (if (memq org-log-note-how '(time state))
  12291. (org-store-log-note)
  12292. (let ((org-inhibit-startup t)) (org-mode))
  12293. (insert (format "# Insert note for %s.
  12294. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12295. (cond
  12296. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12297. ((eq org-log-note-purpose 'done) "closed todo item")
  12298. ((eq org-log-note-purpose 'state)
  12299. (format "state change from \"%s\" to \"%s\""
  12300. (or org-log-note-previous-state "")
  12301. (or org-log-note-state "")))
  12302. ((eq org-log-note-purpose 'reschedule)
  12303. "rescheduling")
  12304. ((eq org-log-note-purpose 'delschedule)
  12305. "no longer scheduled")
  12306. ((eq org-log-note-purpose 'redeadline)
  12307. "changing deadline")
  12308. ((eq org-log-note-purpose 'deldeadline)
  12309. "removing deadline")
  12310. ((eq org-log-note-purpose 'refile)
  12311. "refiling")
  12312. ((eq org-log-note-purpose 'note)
  12313. "this entry")
  12314. (t (error "This should not happen")))))
  12315. (when org-log-note-extra (insert org-log-note-extra))
  12316. (setq-local org-finish-function 'org-store-log-note)
  12317. (run-hooks 'org-log-buffer-setup-hook)))
  12318. (defvar org-note-abort nil) ; dynamically scoped
  12319. (defun org-store-log-note ()
  12320. "Finish taking a log note, and insert it to where it belongs."
  12321. (let ((txt (prog1 (buffer-string)
  12322. (kill-buffer)))
  12323. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12324. lines)
  12325. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12326. (setq txt (replace-match "" t t txt)))
  12327. (when (string-match "\\s-+\\'" txt)
  12328. (setq txt (replace-match "" t t txt)))
  12329. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12330. (when (org-string-nw-p note)
  12331. (setq note
  12332. (org-replace-escapes
  12333. note
  12334. (list (cons "%u" (user-login-name))
  12335. (cons "%U" user-full-name)
  12336. (cons "%t" (format-time-string
  12337. (org-time-stamp-format 'long 'inactive)
  12338. org-log-note-effective-time))
  12339. (cons "%T" (format-time-string
  12340. (org-time-stamp-format 'long nil)
  12341. org-log-note-effective-time))
  12342. (cons "%d" (format-time-string
  12343. (org-time-stamp-format nil 'inactive)
  12344. org-log-note-effective-time))
  12345. (cons "%D" (format-time-string
  12346. (org-time-stamp-format nil nil)
  12347. org-log-note-effective-time))
  12348. (cons "%s" (cond
  12349. ((not org-log-note-state) "")
  12350. ((string-match-p org-ts-regexp
  12351. org-log-note-state)
  12352. (format "\"[%s]\""
  12353. (substring org-log-note-state 1 -1)))
  12354. (t (format "\"%s\"" org-log-note-state))))
  12355. (cons "%S"
  12356. (cond
  12357. ((not org-log-note-previous-state) "")
  12358. ((string-match-p org-ts-regexp
  12359. org-log-note-previous-state)
  12360. (format "\"[%s]\""
  12361. (substring
  12362. org-log-note-previous-state 1 -1)))
  12363. (t (format "\"%s\""
  12364. org-log-note-previous-state)))))))
  12365. (when lines (setq note (concat note " \\\\")))
  12366. (push note lines))
  12367. (when (and lines (not org-note-abort))
  12368. (with-current-buffer (marker-buffer org-log-note-marker)
  12369. (org-with-wide-buffer
  12370. ;; Find location for the new note.
  12371. (goto-char org-log-note-marker)
  12372. (set-marker org-log-note-marker nil)
  12373. ;; Note associated to a clock is to be located right after
  12374. ;; the clock. Do not move point.
  12375. (unless (eq org-log-note-purpose 'clock-out)
  12376. (goto-char (org-log-beginning t)))
  12377. ;; Make sure point is at the beginning of an empty line.
  12378. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12379. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12380. ;; In an existing list, add a new item at the top level.
  12381. ;; Otherwise, indent line like a regular one.
  12382. (let ((itemp (org-in-item-p)))
  12383. (if itemp
  12384. (indent-line-to
  12385. (let ((struct (save-excursion
  12386. (goto-char itemp) (org-list-struct))))
  12387. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12388. (org-indent-line)))
  12389. (insert (org-list-bullet-string "-") (pop lines))
  12390. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12391. (dolist (line lines)
  12392. (insert "\n")
  12393. (indent-line-to ind)
  12394. (insert line)))
  12395. (message "Note stored")
  12396. (org-back-to-heading t)
  12397. (org-cycle-hide-drawers 'children))
  12398. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12399. ;; from within `org-add-log-note' because `buffer-undo-list'
  12400. ;; is then modified outside of `org-with-remote-undo'.
  12401. (when (eq this-command 'org-agenda-todo)
  12402. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12403. ;; Don't add undo information when called from `org-agenda-todo'.
  12404. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12405. (set-window-configuration org-log-note-window-configuration)
  12406. (with-current-buffer (marker-buffer org-log-note-return-to)
  12407. (goto-char org-log-note-return-to))
  12408. (move-marker org-log-note-return-to nil)
  12409. (when org-log-post-message (message "%s" org-log-post-message))))
  12410. (defun org-remove-empty-drawer-at (pos)
  12411. "Remove an empty drawer at position POS.
  12412. POS may also be a marker."
  12413. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12414. (org-with-wide-buffer
  12415. (goto-char pos)
  12416. (let ((drawer (org-element-at-point)))
  12417. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12418. (not (org-element-property :contents-begin drawer)))
  12419. (delete-region (org-element-property :begin drawer)
  12420. (progn (goto-char (org-element-property :end drawer))
  12421. (skip-chars-backward " \r\t\n")
  12422. (forward-line)
  12423. (point))))))))
  12424. (defvar org-ts-type nil)
  12425. (defun org-sparse-tree (&optional arg type)
  12426. "Create a sparse tree, prompt for the details.
  12427. This command can create sparse trees. You first need to select the type
  12428. of match used to create the tree:
  12429. t Show all TODO entries.
  12430. T Show entries with a specific TODO keyword.
  12431. m Show entries selected by a tags/property match.
  12432. p Enter a property name and its value (both with completion on existing
  12433. names/values) and show entries with that property.
  12434. r Show entries matching a regular expression (`/' can be used as well).
  12435. b Show deadlines and scheduled items before a date.
  12436. a Show deadlines and scheduled items after a date.
  12437. d Show deadlines due within `org-deadline-warning-days'.
  12438. D Show deadlines and scheduled items between a date range."
  12439. (interactive "P")
  12440. (setq type (or type org-sparse-tree-default-date-type))
  12441. (setq org-ts-type type)
  12442. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12443. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12444. \[c]ycle through date types: %s"
  12445. (cl-case type
  12446. (all "all timestamps")
  12447. (scheduled "only scheduled")
  12448. (deadline "only deadline")
  12449. (active "only active timestamps")
  12450. (inactive "only inactive timestamps")
  12451. (closed "with a closed time-stamp")
  12452. (otherwise "scheduled/deadline")))
  12453. (let ((answer (read-char-exclusive)))
  12454. (cl-case answer
  12455. (?c
  12456. (org-sparse-tree
  12457. arg
  12458. (cadr
  12459. (memq type '(nil all scheduled deadline active inactive closed)))))
  12460. (?d (call-interactively 'org-check-deadlines))
  12461. (?b (call-interactively 'org-check-before-date))
  12462. (?a (call-interactively 'org-check-after-date))
  12463. (?D (call-interactively 'org-check-dates-range))
  12464. (?t (call-interactively 'org-show-todo-tree))
  12465. (?T (org-show-todo-tree '(4)))
  12466. (?m (call-interactively 'org-match-sparse-tree))
  12467. ((?p ?P)
  12468. (let* ((kwd (completing-read
  12469. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12470. (value (completing-read
  12471. "Value: " (mapcar #'list (org-property-values kwd)))))
  12472. (unless (string-match "\\`{.*}\\'" value)
  12473. (setq value (concat "\"" value "\"")))
  12474. (org-match-sparse-tree arg (concat kwd "=" value))))
  12475. ((?r ?R ?/) (call-interactively 'org-occur))
  12476. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12477. (defvar-local org-occur-highlights nil
  12478. "List of overlays used for occur matches.")
  12479. (defvar-local org-occur-parameters nil
  12480. "Parameters of the active org-occur calls.
  12481. This is a list, each call to org-occur pushes as cons cell,
  12482. containing the regular expression and the callback, onto the list.
  12483. The list can contain several entries if `org-occur' has been called
  12484. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12485. will only contain one set of parameters. When the highlights are
  12486. removed (for example with `C-c C-c', or with the next edit (depending
  12487. on `org-remove-highlights-with-change'), this variable is emptied
  12488. as well.")
  12489. (defun org-occur (regexp &optional keep-previous callback)
  12490. "Make a compact tree which shows all matches of REGEXP.
  12491. The tree will show the lines where the regexp matches, and any other context
  12492. defined in `org-show-context-detail', which see.
  12493. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12494. done by a previous call to `org-occur' will be kept, to allow stacking of
  12495. calls to this command.
  12496. Optional argument CALLBACK can be a function of no argument. In this case,
  12497. it is called with point at the end of the match, match data being set
  12498. accordingly. Current match is shown only if the return value is non-nil.
  12499. The function must neither move point nor alter narrowing."
  12500. (interactive "sRegexp: \nP")
  12501. (when (equal regexp "")
  12502. (user-error "Regexp cannot be empty"))
  12503. (unless keep-previous
  12504. (org-remove-occur-highlights nil nil t))
  12505. (push (cons regexp callback) org-occur-parameters)
  12506. (let ((cnt 0))
  12507. (save-excursion
  12508. (goto-char (point-min))
  12509. (when (or (not keep-previous) ; do not want to keep
  12510. (not org-occur-highlights)) ; no previous matches
  12511. ;; hide everything
  12512. (org-overview))
  12513. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12514. (isearch-no-upper-case-p regexp t)
  12515. org-occur-case-fold-search)))
  12516. (while (re-search-forward regexp nil t)
  12517. (when (or (not callback)
  12518. (save-match-data (funcall callback)))
  12519. (setq cnt (1+ cnt))
  12520. (when org-highlight-sparse-tree-matches
  12521. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12522. (org-show-context 'occur-tree)))))
  12523. (when org-remove-highlights-with-change
  12524. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12525. nil 'local))
  12526. (unless org-sparse-tree-open-archived-trees
  12527. (org-hide-archived-subtrees (point-min) (point-max)))
  12528. (run-hooks 'org-occur-hook)
  12529. (when (called-interactively-p 'interactive)
  12530. (message "%d match(es) for regexp %s" cnt regexp))
  12531. cnt))
  12532. (defun org-occur-next-match (&optional n _reset)
  12533. "Function for `next-error-function' to find sparse tree matches.
  12534. N is the number of matches to move, when negative move backwards.
  12535. This function always goes back to the starting point when no
  12536. match is found."
  12537. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12538. (search-func (if (< n 0)
  12539. 'previous-single-char-property-change
  12540. 'next-single-char-property-change))
  12541. (n (abs n))
  12542. (pos (point))
  12543. p1)
  12544. (catch 'exit
  12545. (while (setq p1 (funcall search-func (point) 'org-type))
  12546. (when (equal p1 limit)
  12547. (goto-char pos)
  12548. (user-error "No more matches"))
  12549. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12550. (setq n (1- n))
  12551. (when (= n 0)
  12552. (goto-char p1)
  12553. (throw 'exit (point))))
  12554. (goto-char p1))
  12555. (goto-char p1)
  12556. (user-error "No more matches"))))
  12557. (defun org-show-context (&optional key)
  12558. "Make sure point and context are visible.
  12559. Optional argument KEY, when non-nil, is a symbol. See
  12560. `org-show-context-detail' for allowed values and how much is to
  12561. be shown."
  12562. (org-show-set-visibility
  12563. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12564. ((cdr (assq key org-show-context-detail)))
  12565. (t (cdr (assq 'default org-show-context-detail))))))
  12566. (defun org-show-set-visibility (detail)
  12567. "Set visibility around point according to DETAIL.
  12568. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12569. `tree', `canonical' or t. See `org-show-context-detail' for more
  12570. information."
  12571. ;; Show current heading and possibly its entry, following headline
  12572. ;; or all children.
  12573. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12574. (org-flag-heading nil)
  12575. (org-show-entry)
  12576. ;; If point is hidden within a drawer or a block, make sure to
  12577. ;; expose it.
  12578. (dolist (o (overlays-at (point)))
  12579. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12580. (delete-overlay o)))
  12581. (unless (org-before-first-heading-p)
  12582. (org-with-limited-levels
  12583. (cl-case detail
  12584. ((tree canonical t) (org-show-children))
  12585. ((nil minimal ancestors))
  12586. (t (save-excursion
  12587. (outline-next-heading)
  12588. (org-flag-heading nil)))))))
  12589. ;; Show all siblings.
  12590. (when (eq detail 'lineage) (org-show-siblings))
  12591. ;; Show ancestors, possibly with their children.
  12592. (when (memq detail '(ancestors lineage tree canonical t))
  12593. (save-excursion
  12594. (while (org-up-heading-safe)
  12595. (org-flag-heading nil)
  12596. (when (memq detail '(canonical t)) (org-show-entry))
  12597. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12598. (defvar org-reveal-start-hook nil
  12599. "Hook run before revealing a location.")
  12600. (defun org-reveal (&optional siblings)
  12601. "Show current entry, hierarchy above it, and the following headline.
  12602. This can be used to show a consistent set of context around
  12603. locations exposed with `org-show-context'.
  12604. With optional argument SIBLINGS, on each level of the hierarchy all
  12605. siblings are shown. This repairs the tree structure to what it would
  12606. look like when opened with hierarchical calls to `org-cycle'.
  12607. With a \\[universal-argument] \\[universal-argument] prefix, \
  12608. go to the parent and show the entire tree."
  12609. (interactive "P")
  12610. (run-hooks 'org-reveal-start-hook)
  12611. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12612. ((equal siblings '(16))
  12613. (save-excursion
  12614. (when (org-up-heading-safe)
  12615. (org-show-subtree)
  12616. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12617. (t (org-show-set-visibility 'lineage))))
  12618. (defun org-highlight-new-match (beg end)
  12619. "Highlight from BEG to END and mark the highlight is an occur headline."
  12620. (let ((ov (make-overlay beg end)))
  12621. (overlay-put ov 'face 'secondary-selection)
  12622. (overlay-put ov 'org-type 'org-occur)
  12623. (push ov org-occur-highlights)))
  12624. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12625. "Remove the occur highlights from the buffer.
  12626. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12627. from the `before-change-functions' in the current buffer."
  12628. (interactive)
  12629. (unless org-inhibit-highlight-removal
  12630. (mapc #'delete-overlay org-occur-highlights)
  12631. (setq org-occur-highlights nil)
  12632. (setq org-occur-parameters nil)
  12633. (unless noremove
  12634. (remove-hook 'before-change-functions
  12635. 'org-remove-occur-highlights 'local))))
  12636. ;;;; Priorities
  12637. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12638. "Regular expression matching the priority indicator.")
  12639. (defvar org-remove-priority-next-time nil)
  12640. (defun org-priority-up ()
  12641. "Increase the priority of the current item."
  12642. (interactive)
  12643. (org-priority 'up))
  12644. (defun org-priority-down ()
  12645. "Decrease the priority of the current item."
  12646. (interactive)
  12647. (org-priority 'down))
  12648. (defun org-priority (&optional action _show)
  12649. "Change the priority of an item.
  12650. ACTION can be `set', `up', `down', or a character."
  12651. (interactive "P")
  12652. (if (equal action '(4))
  12653. (org-show-priority)
  12654. (unless org-enable-priority-commands
  12655. (user-error "Priority commands are disabled"))
  12656. (setq action (or action 'set))
  12657. (let (current new news have remove)
  12658. (save-excursion
  12659. (org-back-to-heading t)
  12660. (when (looking-at org-priority-regexp)
  12661. (setq current (string-to-char (match-string 2))
  12662. have t))
  12663. (cond
  12664. ((eq action 'remove)
  12665. (setq remove t new ?\ ))
  12666. ((or (eq action 'set)
  12667. (integerp action))
  12668. (if (not (eq action 'set))
  12669. (setq new action)
  12670. (message "Priority %c-%c, SPC to remove: "
  12671. org-highest-priority org-lowest-priority)
  12672. (save-match-data
  12673. (setq new (read-char-exclusive))))
  12674. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12675. (= (upcase org-lowest-priority) org-lowest-priority))
  12676. (setq new (upcase new)))
  12677. (cond ((equal new ?\ ) (setq remove t))
  12678. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12679. (user-error "Priority must be between `%c' and `%c'"
  12680. org-highest-priority org-lowest-priority))))
  12681. ((eq action 'up)
  12682. (setq new (if have
  12683. (1- current) ; normal cycling
  12684. ;; last priority was empty
  12685. (if (eq last-command this-command)
  12686. org-lowest-priority ; wrap around empty to lowest
  12687. ;; default
  12688. (if org-priority-start-cycle-with-default
  12689. org-default-priority
  12690. (1- org-default-priority))))))
  12691. ((eq action 'down)
  12692. (setq new (if have
  12693. (1+ current) ; normal cycling
  12694. ;; last priority was empty
  12695. (if (eq last-command this-command)
  12696. org-highest-priority ; wrap around empty to highest
  12697. ;; default
  12698. (if org-priority-start-cycle-with-default
  12699. org-default-priority
  12700. (1+ org-default-priority))))))
  12701. (t (user-error "Invalid action")))
  12702. (when (or (< (upcase new) org-highest-priority)
  12703. (> (upcase new) org-lowest-priority))
  12704. (if (and (memq action '(up down))
  12705. (not have) (not (eq last-command this-command)))
  12706. ;; `new' is from default priority
  12707. (error
  12708. "The default can not be set, see `org-default-priority' why")
  12709. ;; normal cycling: `new' is beyond highest/lowest priority
  12710. ;; and is wrapped around to the empty priority
  12711. (setq remove t)))
  12712. (setq news (format "%c" new))
  12713. (if have
  12714. (if remove
  12715. (replace-match "" t t nil 1)
  12716. (replace-match news t t nil 2))
  12717. (if remove
  12718. (user-error "No priority cookie found in line")
  12719. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12720. (if (match-end 2)
  12721. (progn
  12722. (goto-char (match-end 2))
  12723. (insert " [#" news "]"))
  12724. (goto-char (match-beginning 3))
  12725. (insert "[#" news "] "))))
  12726. (org-set-tags nil 'align))
  12727. (if remove
  12728. (message "Priority removed")
  12729. (message "Priority of current item set to %s" news)))))
  12730. (defun org-show-priority ()
  12731. "Show the priority of the current item.
  12732. This priority is composed of the main priority given with the [#A] cookies,
  12733. and by additional input from the age of a schedules or deadline entry."
  12734. (interactive)
  12735. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12736. (org-get-at-bol 'priority)
  12737. (save-excursion
  12738. (save-match-data
  12739. (beginning-of-line)
  12740. (and (looking-at org-heading-regexp)
  12741. (org-get-priority (match-string 0))))))))
  12742. (message "Priority is %d" (if pri pri -1000))))
  12743. (defun org-get-priority (s)
  12744. "Find priority cookie and return priority."
  12745. (save-match-data
  12746. (if (functionp org-get-priority-function)
  12747. (funcall org-get-priority-function)
  12748. (if (not (string-match org-priority-regexp s))
  12749. (* 1000 (- org-lowest-priority org-default-priority))
  12750. (* 1000 (- org-lowest-priority
  12751. (string-to-char (match-string 2 s))))))))
  12752. ;;;; Tags
  12753. (defvar org-agenda-archives-mode)
  12754. (defvar org-map-continue-from nil
  12755. "Position from where mapping should continue.
  12756. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12757. (defvar org-scanner-tags nil
  12758. "The current tag list while the tags scanner is running.")
  12759. (defvar org-trust-scanner-tags nil
  12760. "Should `org-get-tags-at' use the tags for the scanner.
  12761. This is for internal dynamical scoping only.
  12762. When this is non-nil, the function `org-get-tags-at' will return the value
  12763. of `org-scanner-tags' instead of building the list by itself. This
  12764. can lead to large speed-ups when the tags scanner is used in a file with
  12765. many entries, and when the list of tags is retrieved, for example to
  12766. obtain a list of properties. Building the tags list for each entry in such
  12767. a file becomes an N^2 operation - but with this variable set, it scales
  12768. as N.")
  12769. (defvar org--matcher-tags-todo-only nil)
  12770. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12771. "Scan headline tags with inheritance and produce output ACTION.
  12772. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12773. or `agenda' to produce an entry list for an agenda view. It can also be
  12774. a Lisp form or a function that should be called at each matched headline, in
  12775. this case the return value is a list of all return values from these calls.
  12776. MATCHER is a function accepting three arguments, returning
  12777. a non-nil value whenever a given set of tags qualifies a headline
  12778. for inclusion. See `org-make-tags-matcher' for more information.
  12779. As a special case, it can also be set to t (respectively nil) in
  12780. order to match all (respectively none) headline.
  12781. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12782. included in the output.
  12783. START-LEVEL can be a string with asterisks, reducing the scope to
  12784. headlines matching this string."
  12785. (require 'org-agenda)
  12786. (let* ((re (concat "^"
  12787. (if start-level
  12788. ;; Get the correct level to match
  12789. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12790. org-outline-regexp)
  12791. " *\\(\\<\\("
  12792. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12793. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12794. (props (list 'face 'default
  12795. 'done-face 'org-agenda-done
  12796. 'undone-face 'default
  12797. 'mouse-face 'highlight
  12798. 'org-not-done-regexp org-not-done-regexp
  12799. 'org-todo-regexp org-todo-regexp
  12800. 'org-complex-heading-regexp org-complex-heading-regexp
  12801. 'help-echo
  12802. (format "mouse-2 or RET jump to org file %s"
  12803. (abbreviate-file-name
  12804. (or (buffer-file-name (buffer-base-buffer))
  12805. (buffer-name (buffer-base-buffer)))))))
  12806. (org-map-continue-from nil)
  12807. lspos tags tags-list
  12808. (tags-alist (list (cons 0 org-file-tags)))
  12809. (llast 0) rtn rtn1 level category i txt
  12810. todo marker entry priority
  12811. ts-date ts-date-type ts-date-pair)
  12812. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12813. (setq action (list 'lambda nil action)))
  12814. (save-excursion
  12815. (goto-char (point-min))
  12816. (when (eq action 'sparse-tree)
  12817. (org-overview)
  12818. (org-remove-occur-highlights))
  12819. (while (let (case-fold-search)
  12820. (re-search-forward re nil t))
  12821. (setq org-map-continue-from nil)
  12822. (catch :skip
  12823. (setq todo
  12824. ;; TODO: is the 1-2 difference a bug?
  12825. (when (match-end 1) (match-string-no-properties 2))
  12826. tags (when (match-end 4) (match-string-no-properties 4)))
  12827. (goto-char (setq lspos (match-beginning 0)))
  12828. (setq level (org-reduced-level (org-outline-level))
  12829. category (org-get-category))
  12830. (when (eq action 'agenda)
  12831. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12832. ts-date (car ts-date-pair)
  12833. ts-date-type (cdr ts-date-pair)))
  12834. (setq i llast llast level)
  12835. ;; remove tag lists from same and sublevels
  12836. (while (>= i level)
  12837. (when (setq entry (assoc i tags-alist))
  12838. (setq tags-alist (delete entry tags-alist)))
  12839. (setq i (1- i)))
  12840. ;; add the next tags
  12841. (when tags
  12842. (setq tags (org-split-string tags ":")
  12843. tags-alist
  12844. (cons (cons level tags) tags-alist)))
  12845. ;; compile tags for current headline
  12846. (setq tags-list
  12847. (if org-use-tag-inheritance
  12848. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12849. tags)
  12850. org-scanner-tags tags-list)
  12851. (when org-use-tag-inheritance
  12852. (setcdr (car tags-alist)
  12853. (mapcar (lambda (x)
  12854. (setq x (copy-sequence x))
  12855. (org-add-prop-inherited x))
  12856. (cdar tags-alist))))
  12857. (when (and tags org-use-tag-inheritance
  12858. (or (not (eq t org-use-tag-inheritance))
  12859. org-tags-exclude-from-inheritance))
  12860. ;; Selective inheritance, remove uninherited ones.
  12861. (setcdr (car tags-alist)
  12862. (org-remove-uninherited-tags (cdar tags-alist))))
  12863. (when (and
  12864. ;; eval matcher only when the todo condition is OK
  12865. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12866. (if (functionp matcher)
  12867. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12868. (funcall matcher todo tags-list level))
  12869. matcher))
  12870. ;; Call the skipper, but return t if it does not
  12871. ;; skip, so that the `and' form continues evaluating.
  12872. (progn
  12873. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12874. t)
  12875. ;; Check if timestamps are deselecting this entry
  12876. (or (not todo-only)
  12877. (and (member todo org-todo-keywords-1)
  12878. (or (not org-agenda-tags-todo-honor-ignore-options)
  12879. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12880. ;; select this headline
  12881. (cond
  12882. ((eq action 'sparse-tree)
  12883. (and org-highlight-sparse-tree-matches
  12884. (org-get-heading) (match-end 0)
  12885. (org-highlight-new-match
  12886. (match-beginning 1) (match-end 1)))
  12887. (org-show-context 'tags-tree))
  12888. ((eq action 'agenda)
  12889. (setq txt (org-agenda-format-item
  12890. ""
  12891. (concat
  12892. (if (eq org-tags-match-list-sublevels 'indented)
  12893. (make-string (1- level) ?.) "")
  12894. (org-get-heading))
  12895. (make-string level ?\s)
  12896. category
  12897. tags-list)
  12898. priority (org-get-priority txt))
  12899. (goto-char lspos)
  12900. (setq marker (org-agenda-new-marker))
  12901. (org-add-props txt props
  12902. 'org-marker marker 'org-hd-marker marker 'org-category category
  12903. 'todo-state todo
  12904. 'ts-date ts-date
  12905. 'priority priority
  12906. 'type (concat "tagsmatch" ts-date-type))
  12907. (push txt rtn))
  12908. ((functionp action)
  12909. (setq org-map-continue-from nil)
  12910. (save-excursion
  12911. (setq rtn1 (funcall action))
  12912. (push rtn1 rtn)))
  12913. (t (user-error "Invalid action")))
  12914. ;; if we are to skip sublevels, jump to end of subtree
  12915. (unless org-tags-match-list-sublevels
  12916. (org-end-of-subtree t)
  12917. (backward-char 1))))
  12918. ;; Get the correct position from where to continue
  12919. (if org-map-continue-from
  12920. (goto-char org-map-continue-from)
  12921. (and (= (point) lspos) (end-of-line 1)))))
  12922. (when (and (eq action 'sparse-tree)
  12923. (not org-sparse-tree-open-archived-trees))
  12924. (org-hide-archived-subtrees (point-min) (point-max)))
  12925. (nreverse rtn)))
  12926. (defun org-remove-uninherited-tags (tags)
  12927. "Remove all tags that are not inherited from the list TAGS."
  12928. (cond
  12929. ((eq org-use-tag-inheritance t)
  12930. (if org-tags-exclude-from-inheritance
  12931. (org-delete-all org-tags-exclude-from-inheritance tags)
  12932. tags))
  12933. ((not org-use-tag-inheritance) nil)
  12934. ((stringp org-use-tag-inheritance)
  12935. (delq nil (mapcar
  12936. (lambda (x)
  12937. (if (and (string-match org-use-tag-inheritance x)
  12938. (not (member x org-tags-exclude-from-inheritance)))
  12939. x nil))
  12940. tags)))
  12941. ((listp org-use-tag-inheritance)
  12942. (delq nil (mapcar
  12943. (lambda (x)
  12944. (if (member x org-use-tag-inheritance) x nil))
  12945. tags)))))
  12946. (defun org-match-sparse-tree (&optional todo-only match)
  12947. "Create a sparse tree according to tags string MATCH.
  12948. MATCH is a string with match syntax. It can contain a selection
  12949. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12950. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12951. those. See the manual for details.
  12952. If optional argument TODO-ONLY is non-nil, only select lines that
  12953. are also TODO tasks."
  12954. (interactive "P")
  12955. (org-agenda-prepare-buffers (list (current-buffer)))
  12956. (let ((org--matcher-tags-todo-only todo-only))
  12957. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12958. org--matcher-tags-todo-only)))
  12959. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12960. (defvar org-cached-props nil)
  12961. (defun org-cached-entry-get (pom property)
  12962. (if (or (eq t org-use-property-inheritance)
  12963. (and (stringp org-use-property-inheritance)
  12964. (let ((case-fold-search t))
  12965. (string-match-p org-use-property-inheritance property)))
  12966. (and (listp org-use-property-inheritance)
  12967. (member-ignore-case property org-use-property-inheritance)))
  12968. ;; Caching is not possible, check it directly.
  12969. (org-entry-get pom property 'inherit)
  12970. ;; Get all properties, so we can do complicated checks easily.
  12971. (cdr (assoc-string property
  12972. (or org-cached-props
  12973. (setq org-cached-props (org-entry-properties pom)))
  12974. t))))
  12975. (defun org-global-tags-completion-table (&optional files)
  12976. "Return the list of all tags in all agenda buffer/files.
  12977. Optional FILES argument is a list of files which can be used
  12978. instead of the agenda files."
  12979. (save-excursion
  12980. (org-uniquify
  12981. (delq nil
  12982. (apply #'append
  12983. (mapcar
  12984. (lambda (file)
  12985. (set-buffer (find-file-noselect file))
  12986. (mapcar (lambda (x)
  12987. (and (stringp (car-safe x))
  12988. (list (car-safe x))))
  12989. (or org-current-tag-alist (org-get-buffer-tags))))
  12990. (if (car-safe files) files
  12991. (org-agenda-files))))))))
  12992. (defun org-make-tags-matcher (match)
  12993. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12994. Returns a cons of the selection string MATCH and a function
  12995. implementing the matcher.
  12996. The matcher is to be called at an Org entry, with point on the
  12997. headline, and returns non-nil if the entry matches the selection
  12998. string MATCH. It must be called with three arguments: the TODO
  12999. keyword at the entry (or nil if none), the list of all tags at
  13000. the entry including inherited ones and the reduced level of the
  13001. headline. Additionally, the category of the entry, if any, must
  13002. be specified as the text property `org-category' on the headline.
  13003. This function sets the variable `org--matcher-tags-todo-only' to
  13004. a non-nil value if the matcher restricts matching to TODO
  13005. entries, otherwise it is not touched.
  13006. See also `org-scan-tags'."
  13007. (unless match
  13008. ;; Get a new match request, with completion against the global
  13009. ;; tags table and the local tags in current buffer.
  13010. (let ((org-last-tags-completion-table
  13011. (org-uniquify
  13012. (delq nil (append (org-get-buffer-tags)
  13013. (org-global-tags-completion-table))))))
  13014. (setq match
  13015. (completing-read
  13016. "Match: "
  13017. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13018. (let ((match0 match)
  13019. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13020. (start 0)
  13021. tagsmatch todomatch tagsmatcher todomatcher)
  13022. ;; Expand group tags.
  13023. (setq match (org-tags-expand match))
  13024. ;; Check if there is a TODO part of this match, which would be the
  13025. ;; part after a "/". To make sure that this slash is not part of
  13026. ;; a property value to be matched against, we also check that
  13027. ;; there is no / after that slash. First, find the last slash.
  13028. (let ((s 0))
  13029. (while (string-match "/+" match s)
  13030. (setq start (match-beginning 0))
  13031. (setq s (match-end 0))))
  13032. (if (and (string-match "/+" match start)
  13033. (not (string-match-p "\"" match start)))
  13034. ;; Match contains also a TODO-matching request.
  13035. (progn
  13036. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13037. (setq todomatch (substring match (match-end 0)))
  13038. (when (string-prefix-p "!" todomatch)
  13039. (setq org--matcher-tags-todo-only t)
  13040. (setq todomatch (substring todomatch 1)))
  13041. (when (string-match "\\`\\s-*\\'" todomatch)
  13042. (setq todomatch nil)))
  13043. ;; Only matching tags.
  13044. (setq tagsmatch match)
  13045. (setq todomatch nil))
  13046. ;; Make the tags matcher.
  13047. (when (org-string-nw-p tagsmatch)
  13048. (let ((orlist nil)
  13049. (orterms (org-split-string tagsmatch "|"))
  13050. term)
  13051. (while (setq term (pop orterms))
  13052. (while (and (equal (substring term -1) "\\") orterms)
  13053. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13054. (while (string-match re term)
  13055. (let* ((rest (substring term (match-end 0)))
  13056. (minus (and (match-end 1)
  13057. (equal (match-string 1 term) "-")))
  13058. (tag (save-match-data
  13059. (replace-regexp-in-string
  13060. "\\\\-" "-" (match-string 2 term))))
  13061. (regexp (eq (string-to-char tag) ?{))
  13062. (levelp (match-end 4))
  13063. (propp (match-end 5))
  13064. (mm
  13065. (cond
  13066. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13067. (levelp
  13068. `(,(org-op-to-function (match-string 3 term))
  13069. level
  13070. ,(string-to-number (match-string 4 term))))
  13071. (propp
  13072. (let* ((gv (pcase (upcase (match-string 5 term))
  13073. ("CATEGORY"
  13074. '(get-text-property (point) 'org-category))
  13075. ("TODO" 'todo)
  13076. (p `(org-cached-entry-get nil ,p))))
  13077. (pv (match-string 7 term))
  13078. (regexp (eq (string-to-char pv) ?{))
  13079. (strp (eq (string-to-char pv) ?\"))
  13080. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13081. (po (org-op-to-function (match-string 6 term)
  13082. (if timep 'time strp))))
  13083. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13084. (when timep (setq pv (org-matcher-time pv)))
  13085. (cond ((and regexp (eq po 'org<>))
  13086. `(not (string-match ,pv (or ,gv ""))))
  13087. (regexp `(string-match ,pv (or ,gv "")))
  13088. (strp `(,po (or ,gv "") ,pv))
  13089. (t
  13090. `(,po
  13091. (string-to-number (or ,gv ""))
  13092. ,(string-to-number pv))))))
  13093. (t `(member ,tag tags-list)))))
  13094. (push (if minus `(not ,mm) mm) tagsmatcher)
  13095. (setq term rest)))
  13096. (push `(and ,@tagsmatcher) orlist)
  13097. (setq tagsmatcher nil))
  13098. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13099. ;; Make the TODO matcher.
  13100. (when (org-string-nw-p todomatch)
  13101. (let ((orlist nil))
  13102. (dolist (term (org-split-string todomatch "|"))
  13103. (while (string-match re term)
  13104. (let* ((minus (and (match-end 1)
  13105. (equal (match-string 1 term) "-")))
  13106. (kwd (match-string 2 term))
  13107. (regexp (eq (string-to-char kwd) ?{))
  13108. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13109. `(equal todo ,kwd))))
  13110. (push (if minus `(not ,mm) mm) todomatcher))
  13111. (setq term (substring term (match-end 0))))
  13112. (push (if (> (length todomatcher) 1)
  13113. (cons 'and todomatcher)
  13114. (car todomatcher))
  13115. orlist)
  13116. (setq todomatcher nil))
  13117. (setq todomatcher (cons 'or orlist))))
  13118. ;; Return the string and function of the matcher. If no
  13119. ;; tags-specific or todo-specific matcher exists, match
  13120. ;; everything.
  13121. (let ((matcher (if (and tagsmatcher todomatcher)
  13122. `(and ,tagsmatcher ,todomatcher)
  13123. (or tagsmatcher todomatcher t))))
  13124. (when org--matcher-tags-todo-only
  13125. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13126. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13127. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13128. "Expand group tags in MATCH.
  13129. This replaces every group tag in MATCH with a regexp tag search.
  13130. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13131. will be replaced like this:
  13132. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13133. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13134. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13135. Replacing by a regexp preserves the structure of the match.
  13136. E.g., this expansion
  13137. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13138. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13139. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13140. A group tag in MATCH can contain regular expressions of its own.
  13141. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13142. will be replaced like this:
  13143. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13144. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13145. assumed to be a single group tag, and the function will return
  13146. the list of tags in this group.
  13147. When DOWNCASE is non-nil, expand downcased TAGS."
  13148. (if org-group-tags
  13149. (let* ((case-fold-search t)
  13150. (stable org-mode-syntax-table)
  13151. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13152. (taggroups (if downcased
  13153. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13154. taggroups)
  13155. taggroups))
  13156. (taggroups-keys (mapcar #'car taggroups))
  13157. (return-match (if downcased (downcase match) match))
  13158. (count 0)
  13159. (work-already-expanded tags-already-expanded)
  13160. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13161. ;; @ and _ are allowed as word-components in tags.
  13162. (modify-syntax-entry ?@ "w" stable)
  13163. (modify-syntax-entry ?_ "w" stable)
  13164. ;; Temporarily replace regexp-expressions in the match-expression.
  13165. (while (string-match "{.+?}" return-match)
  13166. (cl-incf count)
  13167. (push (match-string 0 return-match) regexps-in-match)
  13168. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13169. (while (and taggroups-keys
  13170. (with-syntax-table stable
  13171. (string-match
  13172. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13173. (regexp-opt taggroups-keys) "\\>\\)")
  13174. return-match)))
  13175. (let* ((dir (match-string 1 return-match))
  13176. (tag (match-string 2 return-match))
  13177. (tag (if downcased (downcase tag) tag)))
  13178. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13179. (member tag work-already-expanded))
  13180. (setq tags-in-group (assoc tag taggroups))
  13181. (push tag work-already-expanded)
  13182. ;; Recursively expand each tag in the group, if the tag hasn't
  13183. ;; already been expanded. Restore the match-data after all recursive calls.
  13184. (save-match-data
  13185. (let (tags-expanded)
  13186. (dolist (x (cdr tags-in-group))
  13187. (if (and (member x taggroups-keys)
  13188. (not (member x work-already-expanded)))
  13189. (setq tags-expanded
  13190. (delete-dups
  13191. (append
  13192. (org-tags-expand x t downcased
  13193. work-already-expanded)
  13194. tags-expanded)))
  13195. (setq tags-expanded
  13196. (append (list x) tags-expanded)))
  13197. (setq work-already-expanded
  13198. (delete-dups
  13199. (append tags-expanded
  13200. work-already-expanded))))
  13201. (setq tags-in-group
  13202. (delete-dups (cons (car tags-in-group)
  13203. tags-expanded)))))
  13204. ;; Filter tag-regexps from tags.
  13205. (setq regexp-in-group-escaped
  13206. (delq nil (mapcar (lambda (x)
  13207. (if (stringp x)
  13208. (and (equal "{" (substring x 0 1))
  13209. (equal "}" (substring x -1))
  13210. x)
  13211. x))
  13212. tags-in-group))
  13213. regexp-in-group
  13214. (mapcar (lambda (x)
  13215. (substring x 1 -1))
  13216. regexp-in-group-escaped)
  13217. tags-in-group
  13218. (delq nil (mapcar (lambda (x)
  13219. (if (stringp x)
  13220. (and (not (equal "{" (substring x 0 1)))
  13221. (not (equal "}" (substring x -1)))
  13222. x)
  13223. x))
  13224. tags-in-group)))
  13225. ;; If single-as-list, do no more in the while-loop.
  13226. (if (not single-as-list)
  13227. (progn
  13228. (when regexp-in-group
  13229. (setq regexp-in-group
  13230. (concat "\\|"
  13231. (mapconcat 'identity regexp-in-group
  13232. "\\|"))))
  13233. (setq tags-in-group
  13234. (concat dir
  13235. "{\\<"
  13236. (regexp-opt tags-in-group)
  13237. "\\>"
  13238. regexp-in-group
  13239. "}"))
  13240. (when (stringp tags-in-group)
  13241. (org-add-props tags-in-group '(grouptag t)))
  13242. (setq return-match
  13243. (replace-match tags-in-group t t return-match)))
  13244. (setq tags-in-group
  13245. (append regexp-in-group-escaped tags-in-group))))
  13246. (setq taggroups-keys (delete tag taggroups-keys))))
  13247. ;; Add the regular expressions back into the match-expression again.
  13248. (while regexps-in-match
  13249. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13250. (pop regexps-in-match)
  13251. return-match t t))
  13252. (cl-decf count))
  13253. (if single-as-list
  13254. (if tags-in-group tags-in-group (list return-match))
  13255. return-match))
  13256. (if single-as-list
  13257. (list (if downcased (downcase match) match))
  13258. match)))
  13259. (defun org-op-to-function (op &optional stringp)
  13260. "Turn an operator into the appropriate function."
  13261. (setq op
  13262. (cond
  13263. ((equal op "<" ) '(< string< org-time<))
  13264. ((equal op ">" ) '(> org-string> org-time>))
  13265. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13266. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13267. ((member op '("=" "==")) '(= string= org-time=))
  13268. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13269. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13270. (defun org<> (a b) (not (= a b)))
  13271. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13272. (defun org-string>= (a b) (not (string< a b)))
  13273. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13274. (defun org-string<> (a b) (not (string= a b)))
  13275. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13276. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13277. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13278. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13279. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13280. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13281. (defun org-2ft (s)
  13282. "Convert S to a floating point time.
  13283. If S is already a number, just return it. If it is a string, parse
  13284. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13285. (cond
  13286. ((numberp s) s)
  13287. ((stringp s)
  13288. (condition-case nil
  13289. (float-time (apply #'encode-time (org-parse-time-string s)))
  13290. (error 0.)))
  13291. (t 0.)))
  13292. (defun org-time-today ()
  13293. "Time in seconds today at 0:00.
  13294. Returns the float number of seconds since the beginning of the
  13295. epoch to the beginning of today (00:00)."
  13296. (float-time (apply 'encode-time
  13297. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13298. (defun org-matcher-time (s)
  13299. "Interpret a time comparison value."
  13300. (save-match-data
  13301. (cond
  13302. ((string= s "<now>") (float-time))
  13303. ((string= s "<today>") (org-time-today))
  13304. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13305. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13306. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13307. (+ (org-time-today)
  13308. (* (string-to-number (match-string 1 s))
  13309. (cdr (assoc (match-string 2 s)
  13310. '(("d" . 86400.0) ("w" . 604800.0)
  13311. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13312. (t (org-2ft s)))))
  13313. (defun org-match-any-p (re list)
  13314. "Does re match any element of list?"
  13315. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13316. (delq nil list))
  13317. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13318. (defvar org-tags-overlay (make-overlay 1 1))
  13319. (delete-overlay org-tags-overlay)
  13320. (defun org-get-local-tags-at (&optional pos)
  13321. "Get a list of tags defined in the current headline."
  13322. (org-get-tags-at pos 'local))
  13323. (defun org-get-local-tags ()
  13324. "Get a list of tags defined in the current headline."
  13325. (org-get-tags-at nil 'local))
  13326. (defun org-get-tags-at (&optional pos local)
  13327. "Get a list of all headline tags applicable at POS.
  13328. POS defaults to point. If tags are inherited, the list contains
  13329. the targets in the same sequence as the headlines appear, i.e.
  13330. the tags of the current headline come last.
  13331. When LOCAL is non-nil, only return tags from the current headline,
  13332. ignore inherited ones."
  13333. (interactive)
  13334. (if (and org-trust-scanner-tags
  13335. (or (not pos) (equal pos (point)))
  13336. (not local))
  13337. org-scanner-tags
  13338. (let (tags ltags lastpos parent)
  13339. (save-excursion
  13340. (save-restriction
  13341. (widen)
  13342. (goto-char (or pos (point)))
  13343. (save-match-data
  13344. (catch 'done
  13345. (condition-case nil
  13346. (progn
  13347. (org-back-to-heading t)
  13348. (while (not (equal lastpos (point)))
  13349. (setq lastpos (point))
  13350. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13351. (setq ltags (org-split-string
  13352. (match-string-no-properties 1) ":"))
  13353. (when parent
  13354. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13355. (setq tags (append
  13356. (if parent
  13357. (org-remove-uninherited-tags ltags)
  13358. ltags)
  13359. tags)))
  13360. (or org-use-tag-inheritance (throw 'done t))
  13361. (when local (throw 'done t))
  13362. (or (org-up-heading-safe) (error nil))
  13363. (setq parent t)))
  13364. (error nil)))))
  13365. (if local
  13366. tags
  13367. (reverse (delete-dups
  13368. (reverse (append
  13369. (org-remove-uninherited-tags
  13370. org-file-tags)
  13371. tags)))))))))
  13372. (defun org-add-prop-inherited (s)
  13373. (add-text-properties 0 (length s) '(inherited t) s)
  13374. s)
  13375. (defun org-toggle-tag (tag &optional onoff)
  13376. "Toggle the tag TAG for the current line.
  13377. If ONOFF is `on' or `off', don't toggle but set to this state."
  13378. (save-excursion
  13379. (org-back-to-heading t)
  13380. (let ((current
  13381. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13382. (line-end-position) t)
  13383. (let ((tags (match-string 1)))
  13384. ;; Clear current tags.
  13385. (replace-match "")
  13386. ;; Reverse the tags list so any new tag is appended to
  13387. ;; the current list of tags.
  13388. (nreverse (org-split-string tags ":")))))
  13389. res)
  13390. (pcase onoff
  13391. (`off (setq current (delete tag current)))
  13392. ((or `on (guard (not (member tag current))))
  13393. (setq res t)
  13394. (cl-pushnew tag current :test #'equal))
  13395. (_ (setq current (delete tag current))))
  13396. (end-of-line)
  13397. (if current
  13398. (progn
  13399. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13400. (org-set-tags nil t))
  13401. (delete-horizontal-space))
  13402. (run-hooks 'org-after-tags-change-hook)
  13403. res)))
  13404. (defun org--align-tags-here (to-col)
  13405. "Align tags on the current headline to TO-COL.
  13406. Assume point is on a headline."
  13407. (let ((pos (point)))
  13408. (beginning-of-line)
  13409. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13410. (>= pos (match-beginning 2)))
  13411. ;; No tags or point within tags: do not align.
  13412. (goto-char pos)
  13413. (goto-char (match-beginning 1))
  13414. (let ((shift (max (- (if (>= to-col 0) to-col
  13415. (- (abs to-col) (string-width (match-string 2))))
  13416. (current-column))
  13417. 1)))
  13418. (replace-match (make-string shift ?\s) nil nil nil 1)
  13419. ;; Preserve initial position, if possible. In any case, stop
  13420. ;; before tags.
  13421. (when (< pos (point)) (goto-char pos))))))
  13422. (defun org-set-tags-command (&optional arg just-align)
  13423. "Call the set-tags command for the current entry."
  13424. (interactive "P")
  13425. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13426. (org-set-tags arg just-align)
  13427. (save-excursion
  13428. (unless (and (org-region-active-p)
  13429. org-loop-over-headlines-in-active-region)
  13430. (org-back-to-heading t))
  13431. (org-set-tags arg just-align))))
  13432. (defun org-set-tags-to (data)
  13433. "Set the tags of the current entry to DATA, replacing the current tags.
  13434. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13435. If DATA is nil or the empty string, any tags will be removed."
  13436. (interactive "sTags: ")
  13437. (setq data
  13438. (cond
  13439. ((eq data nil) "")
  13440. ((equal data "") "")
  13441. ((stringp data)
  13442. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13443. ":"))
  13444. ((listp data)
  13445. (concat ":" (mapconcat 'identity data ":") ":"))))
  13446. (when data
  13447. (save-excursion
  13448. (org-back-to-heading t)
  13449. (when (let ((case-fold-search nil))
  13450. (looking-at org-complex-heading-regexp))
  13451. (if (match-end 5)
  13452. (progn
  13453. (goto-char (match-beginning 5))
  13454. (insert data)
  13455. (delete-region (point) (point-at-eol))
  13456. (org-set-tags nil 'align))
  13457. (goto-char (point-at-eol))
  13458. (insert " " data)
  13459. (org-set-tags nil 'align)))
  13460. (beginning-of-line 1)
  13461. (when (looking-at ".*?\\([ \t]+\\)$")
  13462. (delete-region (match-beginning 1) (match-end 1))))))
  13463. (defun org-align-all-tags ()
  13464. "Align the tags in all headings."
  13465. (interactive)
  13466. (save-excursion
  13467. (or (ignore-errors (org-back-to-heading t))
  13468. (outline-next-heading))
  13469. (if (org-at-heading-p)
  13470. (org-set-tags t)
  13471. (message "No headings"))))
  13472. (defvar org-indent-indentation-per-level)
  13473. (defun org-set-tags (&optional arg just-align)
  13474. "Set the tags for the current headline.
  13475. With prefix ARG, realign all tags in headings in the current buffer.
  13476. When JUST-ALIGN is non-nil, only align tags."
  13477. (interactive "P")
  13478. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13479. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13480. 'region-start-level
  13481. 'region))
  13482. org-loop-over-headlines-in-active-region)
  13483. (org-map-entries
  13484. ;; We don't use ARG and JUST-ALIGN here because these args
  13485. ;; are not useful when looping over headlines.
  13486. #'org-set-tags
  13487. org-loop-over-headlines-in-active-region
  13488. cl
  13489. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13490. (let ((org-setting-tags t))
  13491. (if arg
  13492. (save-excursion
  13493. (goto-char (point-min))
  13494. (while (re-search-forward org-outline-regexp-bol nil t)
  13495. (org-set-tags nil t)
  13496. (end-of-line))
  13497. (message "All tags realigned to column %d" org-tags-column))
  13498. (let* ((current (org-get-tags-string))
  13499. (tags
  13500. (if just-align current
  13501. ;; Get a new set of tags from the user.
  13502. (save-excursion
  13503. (let* ((seen)
  13504. (table
  13505. (setq
  13506. org-last-tags-completion-table
  13507. ;; Uniquify tags in alists, yet preserve
  13508. ;; structure (i.e., keywords).
  13509. (delq nil
  13510. (mapcar
  13511. (lambda (pair)
  13512. (let ((head (car pair)))
  13513. (cond ((symbolp head) pair)
  13514. ((member head seen) nil)
  13515. (t (push head seen)
  13516. pair))))
  13517. (append
  13518. (or org-current-tag-alist
  13519. (org-get-buffer-tags))
  13520. (and
  13521. org-complete-tags-always-offer-all-agenda-tags
  13522. (org-global-tags-completion-table
  13523. (org-agenda-files))))))))
  13524. (current-tags (org-split-string current ":"))
  13525. (inherited-tags
  13526. (nreverse (nthcdr (length current-tags)
  13527. (nreverse (org-get-tags-at))))))
  13528. (replace-regexp-in-string
  13529. "\\([-+&]+\\|,\\)"
  13530. ":"
  13531. (if (or (eq t org-use-fast-tag-selection)
  13532. (and org-use-fast-tag-selection
  13533. (delq nil (mapcar #'cdr table))))
  13534. (org-fast-tag-selection
  13535. current-tags inherited-tags table
  13536. (and org-fast-tag-selection-include-todo
  13537. org-todo-key-alist))
  13538. (let ((org-add-colon-after-tag-completion
  13539. (< 1 (length table))))
  13540. (org-trim
  13541. (completing-read
  13542. "Tags: "
  13543. #'org-tags-completion-function
  13544. nil nil current 'org-tags-history))))))))))
  13545. (when org-tags-sort-function
  13546. (setq tags
  13547. (mapconcat
  13548. #'identity
  13549. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13550. org-tags-sort-function)
  13551. ":")))
  13552. (if (or (string= ":" tags)
  13553. (string= "::" tags))
  13554. (setq tags ""))
  13555. (if (not (org-string-nw-p tags)) (setq tags "")
  13556. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13557. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13558. ;; Insert new tags at the correct column.
  13559. (unless (equal current tags)
  13560. (save-excursion
  13561. (beginning-of-line)
  13562. (let ((case-fold-search nil))
  13563. (looking-at org-complex-heading-regexp))
  13564. ;; Remove current tags, if any.
  13565. (when (match-end 5) (replace-match "" nil nil nil 5))
  13566. ;; Insert new tags, if any. Otherwise, remove trailing
  13567. ;; white spaces.
  13568. (end-of-line)
  13569. (if (not (equal tags ""))
  13570. ;; When text is being inserted on an invisible
  13571. ;; region boundary, it can be inadvertently sucked
  13572. ;; into invisibility.
  13573. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13574. (skip-chars-backward " \t")
  13575. (delete-region (point) (line-end-position)))))
  13576. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13577. ;; is on.
  13578. (unless (equal tags "")
  13579. (let* ((level (save-excursion
  13580. (beginning-of-line)
  13581. (skip-chars-forward "\\*")))
  13582. (offset (if (bound-and-true-p org-indent-mode)
  13583. (* (1- org-indent-indentation-per-level)
  13584. (1- level))
  13585. 0))
  13586. (tags-column
  13587. (+ org-tags-column
  13588. (if (> org-tags-column 0) (- offset) offset))))
  13589. (org--align-tags-here tags-column))))
  13590. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13591. (defun org-change-tag-in-region (beg end tag off)
  13592. "Add or remove TAG for each entry in the region.
  13593. This works in the agenda, and also in an Org buffer."
  13594. (interactive
  13595. (list (region-beginning) (region-end)
  13596. (let ((org-last-tags-completion-table
  13597. (if (derived-mode-p 'org-mode)
  13598. (org-uniquify
  13599. (delq nil (append (org-get-buffer-tags)
  13600. (org-global-tags-completion-table))))
  13601. (org-global-tags-completion-table))))
  13602. (completing-read
  13603. "Tag: " 'org-tags-completion-function nil nil nil
  13604. 'org-tags-history))
  13605. (progn
  13606. (message "[s]et or [r]emove? ")
  13607. (equal (read-char-exclusive) ?r))))
  13608. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13609. (let ((agendap (equal major-mode 'org-agenda-mode))
  13610. l1 l2 m buf pos newhead (cnt 0))
  13611. (goto-char end)
  13612. (setq l2 (1- (org-current-line)))
  13613. (goto-char beg)
  13614. (setq l1 (org-current-line))
  13615. (cl-loop for l from l1 to l2 do
  13616. (org-goto-line l)
  13617. (setq m (get-text-property (point) 'org-hd-marker))
  13618. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13619. (and agendap m))
  13620. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13621. pos (if agendap m (point)))
  13622. (with-current-buffer buf
  13623. (save-excursion
  13624. (save-restriction
  13625. (goto-char pos)
  13626. (setq cnt (1+ cnt))
  13627. (org-toggle-tag tag (if off 'off 'on))
  13628. (setq newhead (org-get-heading)))))
  13629. (and agendap (org-agenda-change-all-lines newhead m))))
  13630. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13631. (defun org-tags-completion-function (string _predicate &optional flag)
  13632. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13633. (confirm (lambda (x) (stringp (car x)))))
  13634. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13635. (setq s1 (match-string 1 string)
  13636. s2 (match-string 2 string))
  13637. (setq s1 "" s2 string))
  13638. (cond
  13639. ((eq flag nil)
  13640. ;; try completion
  13641. (setq rtn (try-completion s2 ctable confirm))
  13642. (when (stringp rtn)
  13643. (setq rtn
  13644. (concat s1 s2 (substring rtn (length s2))
  13645. (if (and org-add-colon-after-tag-completion
  13646. (assoc rtn ctable))
  13647. ":" ""))))
  13648. rtn)
  13649. ((eq flag t)
  13650. ;; all-completions
  13651. (all-completions s2 ctable confirm))
  13652. ((eq flag 'lambda)
  13653. ;; exact match?
  13654. (assoc s2 ctable)))))
  13655. (defun org-fast-tag-insert (kwd tags face &optional end)
  13656. "Insert KDW, and the TAGS, the latter with face FACE.
  13657. Also insert END."
  13658. (insert (format "%-12s" (concat kwd ":"))
  13659. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13660. (or end "")))
  13661. (defun org-fast-tag-show-exit (flag)
  13662. (save-excursion
  13663. (org-goto-line 3)
  13664. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13665. (replace-match ""))
  13666. (when flag
  13667. (end-of-line 1)
  13668. (org-move-to-column (- (window-width) 19) t)
  13669. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13670. (defun org-set-current-tags-overlay (current prefix)
  13671. "Add an overlay to CURRENT tag with PREFIX."
  13672. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13673. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13674. (org-overlay-display org-tags-overlay (concat prefix s))))
  13675. (defvar org-last-tag-selection-key nil)
  13676. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13677. "Fast tag selection with single keys.
  13678. CURRENT is the current list of tags in the headline, INHERITED is the
  13679. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13680. possibly with grouping information. TODO-TABLE is a similar table with
  13681. TODO keywords, should these have keys assigned to them.
  13682. If the keys are nil, a-z are automatically assigned.
  13683. Returns the new tags string, or nil to not change the current settings."
  13684. (let* ((fulltable (append table todo-table))
  13685. (maxlen (apply 'max (mapcar
  13686. (lambda (x)
  13687. (if (stringp (car x)) (string-width (car x)) 0))
  13688. fulltable)))
  13689. (buf (current-buffer))
  13690. (expert (eq org-fast-tag-selection-single-key 'expert))
  13691. (buffer-tags nil)
  13692. (fwidth (+ maxlen 3 1 3))
  13693. (ncol (/ (- (window-width) 4) fwidth))
  13694. (i-face 'org-done)
  13695. (c-face 'org-todo)
  13696. tg cnt e c char c1 c2 ntable tbl rtn
  13697. ov-start ov-end ov-prefix
  13698. (exit-after-next org-fast-tag-selection-single-key)
  13699. (done-keywords org-done-keywords)
  13700. groups ingroup intaggroup)
  13701. (save-excursion
  13702. (beginning-of-line 1)
  13703. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13704. (setq ov-start (match-beginning 1)
  13705. ov-end (match-end 1)
  13706. ov-prefix "")
  13707. (setq ov-start (1- (point-at-eol))
  13708. ov-end (1+ ov-start))
  13709. (skip-chars-forward "^\n\r")
  13710. (setq ov-prefix
  13711. (concat
  13712. (buffer-substring (1- (point)) (point))
  13713. (if (> (current-column) org-tags-column)
  13714. " "
  13715. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13716. (move-overlay org-tags-overlay ov-start ov-end)
  13717. (save-window-excursion
  13718. (if expert
  13719. (set-buffer (get-buffer-create " *Org tags*"))
  13720. (delete-other-windows)
  13721. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13722. (org-switch-to-buffer-other-window " *Org tags*"))
  13723. (erase-buffer)
  13724. (setq-local org-done-keywords done-keywords)
  13725. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13726. (org-fast-tag-insert "Current" current c-face "\n\n")
  13727. (org-fast-tag-show-exit exit-after-next)
  13728. (org-set-current-tags-overlay current ov-prefix)
  13729. (setq tbl fulltable char ?a cnt 0)
  13730. (while (setq e (pop tbl))
  13731. (cond
  13732. ((eq (car e) :startgroup)
  13733. (push '() groups) (setq ingroup t)
  13734. (unless (zerop cnt)
  13735. (setq cnt 0)
  13736. (insert "\n"))
  13737. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13738. ((eq (car e) :endgroup)
  13739. (setq ingroup nil cnt 0)
  13740. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13741. ((eq (car e) :startgrouptag)
  13742. (setq intaggroup t)
  13743. (unless (zerop cnt)
  13744. (setq cnt 0)
  13745. (insert "\n"))
  13746. (insert "[ "))
  13747. ((eq (car e) :endgrouptag)
  13748. (setq intaggroup nil cnt 0)
  13749. (insert "]\n"))
  13750. ((equal e '(:newline))
  13751. (unless (zerop cnt)
  13752. (setq cnt 0)
  13753. (insert "\n")
  13754. (setq e (car tbl))
  13755. (while (equal (car tbl) '(:newline))
  13756. (insert "\n")
  13757. (setq tbl (cdr tbl)))))
  13758. ((equal e '(:grouptags)) (insert " : "))
  13759. (t
  13760. (setq tg (copy-sequence (car e)) c2 nil)
  13761. (if (cdr e)
  13762. (setq c (cdr e))
  13763. ;; automatically assign a character.
  13764. (setq c1 (string-to-char
  13765. (downcase (substring
  13766. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13767. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13768. (while (or (rassoc char ntable) (rassoc char table))
  13769. (setq char (1+ char)))
  13770. (setq c2 c1))
  13771. (setq c (or c2 char)))
  13772. (when ingroup (push tg (car groups)))
  13773. (setq tg (org-add-props tg nil 'face
  13774. (cond
  13775. ((not (assoc tg table))
  13776. (org-get-todo-face tg))
  13777. ((member tg current) c-face)
  13778. ((member tg inherited) i-face))))
  13779. (when (equal (caar tbl) :grouptags)
  13780. (org-add-props tg nil 'face 'org-tag-group))
  13781. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13782. (insert "[" c "] " tg (make-string
  13783. (- fwidth 4 (length tg)) ?\ ))
  13784. (push (cons tg c) ntable)
  13785. (when (= (cl-incf cnt) ncol)
  13786. (insert "\n")
  13787. (when (or ingroup intaggroup) (insert " "))
  13788. (setq cnt 0)))))
  13789. (setq ntable (nreverse ntable))
  13790. (insert "\n")
  13791. (goto-char (point-min))
  13792. (unless expert (org-fit-window-to-buffer))
  13793. (setq rtn
  13794. (catch 'exit
  13795. (while t
  13796. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13797. (if (not groups) "no " "")
  13798. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13799. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13800. (setq org-last-tag-selection-key c)
  13801. (cond
  13802. ((= c ?\r) (throw 'exit t))
  13803. ((= c ?!)
  13804. (setq groups (not groups))
  13805. (goto-char (point-min))
  13806. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13807. ((= c ?\C-c)
  13808. (if (not expert)
  13809. (org-fast-tag-show-exit
  13810. (setq exit-after-next (not exit-after-next)))
  13811. (setq expert nil)
  13812. (delete-other-windows)
  13813. (set-window-buffer (split-window-vertically) " *Org tags*")
  13814. (org-switch-to-buffer-other-window " *Org tags*")
  13815. (org-fit-window-to-buffer)))
  13816. ((or (= c ?\C-g)
  13817. (and (= c ?q) (not (rassoc c ntable))))
  13818. (delete-overlay org-tags-overlay)
  13819. (setq quit-flag t))
  13820. ((= c ?\ )
  13821. (setq current nil)
  13822. (when exit-after-next (setq exit-after-next 'now)))
  13823. ((= c ?\t)
  13824. (condition-case nil
  13825. (setq tg (completing-read
  13826. "Tag: "
  13827. (or buffer-tags
  13828. (with-current-buffer buf
  13829. (setq buffer-tags
  13830. (org-get-buffer-tags))))))
  13831. (quit (setq tg "")))
  13832. (when (string-match "\\S-" tg)
  13833. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13834. (if (member tg current)
  13835. (setq current (delete tg current))
  13836. (push tg current)))
  13837. (when exit-after-next (setq exit-after-next 'now)))
  13838. ((setq e (rassoc c todo-table) tg (car e))
  13839. (with-current-buffer buf
  13840. (save-excursion (org-todo tg)))
  13841. (when exit-after-next (setq exit-after-next 'now)))
  13842. ((setq e (rassoc c ntable) tg (car e))
  13843. (if (member tg current)
  13844. (setq current (delete tg current))
  13845. (cl-loop for g in groups do
  13846. (when (member tg g)
  13847. (dolist (x g) (setq current (delete x current)))))
  13848. (push tg current))
  13849. (when exit-after-next (setq exit-after-next 'now))))
  13850. ;; Create a sorted list
  13851. (setq current
  13852. (sort current
  13853. (lambda (a b)
  13854. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13855. (when (eq exit-after-next 'now) (throw 'exit t))
  13856. (goto-char (point-min))
  13857. (beginning-of-line 2)
  13858. (delete-region (point) (point-at-eol))
  13859. (org-fast-tag-insert "Current" current c-face)
  13860. (org-set-current-tags-overlay current ov-prefix)
  13861. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13862. (setq tg (match-string 1))
  13863. (add-text-properties
  13864. (match-beginning 1) (match-end 1)
  13865. (list 'face
  13866. (cond
  13867. ((member tg current) c-face)
  13868. ((member tg inherited) i-face)
  13869. (t (get-text-property (match-beginning 1) 'face))))))
  13870. (goto-char (point-min)))))
  13871. (delete-overlay org-tags-overlay)
  13872. (if rtn
  13873. (mapconcat 'identity current ":")
  13874. nil))))
  13875. (defun org-get-tags-string ()
  13876. "Get the TAGS string in the current headline."
  13877. (unless (org-at-heading-p t)
  13878. (user-error "Not on a heading"))
  13879. (save-excursion
  13880. (beginning-of-line 1)
  13881. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13882. (match-string-no-properties 1)
  13883. "")))
  13884. (defun org-get-tags ()
  13885. "Get the list of tags specified in the current headline."
  13886. (org-split-string (org-get-tags-string) ":"))
  13887. (defun org-get-buffer-tags ()
  13888. "Get a table of all tags used in the buffer, for completion."
  13889. (org-with-wide-buffer
  13890. (goto-char (point-min))
  13891. (let ((tag-re (concat org-outline-regexp-bol
  13892. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13893. tags)
  13894. (while (re-search-forward tag-re nil t)
  13895. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13896. (push tag tags)))
  13897. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13898. ;;;; The mapping API
  13899. (defvar org-agenda-skip-comment-trees)
  13900. (defvar org-agenda-skip-function)
  13901. (defun org-map-entries (func &optional match scope &rest skip)
  13902. "Call FUNC at each headline selected by MATCH in SCOPE.
  13903. FUNC is a function or a lisp form. The function will be called without
  13904. arguments, with the cursor positioned at the beginning of the headline.
  13905. The return values of all calls to the function will be collected and
  13906. returned as a list.
  13907. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13908. does not need to preserve point. After evaluation, the cursor will be
  13909. moved to the end of the line (presumably of the headline of the
  13910. processed entry) and search continues from there. Under some
  13911. circumstances, this may not produce the wanted results. For example,
  13912. if you have removed (e.g. archived) the current (sub)tree it could
  13913. mean that the next entry will be skipped entirely. In such cases, you
  13914. can specify the position from where search should continue by making
  13915. FUNC set the variable `org-map-continue-from' to the desired buffer
  13916. position.
  13917. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13918. Only headlines that are matched by this query will be considered during
  13919. the iteration. When MATCH is nil or t, all headlines will be
  13920. visited by the iteration.
  13921. SCOPE determines the scope of this command. It can be any of:
  13922. nil The current buffer, respecting the restriction if any
  13923. tree The subtree started with the entry at point
  13924. region The entries within the active region, if any
  13925. region-start-level
  13926. The entries within the active region, but only those at
  13927. the same level than the first one.
  13928. file The current buffer, without restriction
  13929. file-with-archives
  13930. The current buffer, and any archives associated with it
  13931. agenda All agenda files
  13932. agenda-with-archives
  13933. All agenda files with any archive files associated with them
  13934. \(file1 file2 ...)
  13935. If this is a list, all files in the list will be scanned
  13936. The remaining args are treated as settings for the skipping facilities of
  13937. the scanner. The following items can be given here:
  13938. archive skip trees with the archive tag
  13939. comment skip trees with the COMMENT keyword
  13940. function or Emacs Lisp form:
  13941. will be used as value for `org-agenda-skip-function', so
  13942. whenever the function returns a position, FUNC will not be
  13943. called for that entry and search will continue from the
  13944. position returned
  13945. If your function needs to retrieve the tags including inherited tags
  13946. at the *current* entry, you can use the value of the variable
  13947. `org-scanner-tags' which will be much faster than getting the value
  13948. with `org-get-tags-at'. If your function gets properties with
  13949. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13950. to t around the call to `org-entry-properties' to get the same speedup.
  13951. Note that if your function moves around to retrieve tags and properties at
  13952. a *different* entry, you cannot use these techniques."
  13953. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13954. (not (org-region-active-p)))
  13955. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13956. (org-agenda-skip-archived-trees (memq 'archive skip))
  13957. (org-agenda-skip-comment-trees (memq 'comment skip))
  13958. (org-agenda-skip-function
  13959. (car (org-delete-all '(comment archive) skip)))
  13960. (org-tags-match-list-sublevels t)
  13961. (start-level (eq scope 'region-start-level))
  13962. matcher res
  13963. org-todo-keywords-for-agenda
  13964. org-done-keywords-for-agenda
  13965. org-todo-keyword-alist-for-agenda
  13966. org-tag-alist-for-agenda
  13967. org--matcher-tags-todo-only)
  13968. (cond
  13969. ((eq match t) (setq matcher t))
  13970. ((eq match nil) (setq matcher t))
  13971. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13972. (save-excursion
  13973. (save-restriction
  13974. (cond ((eq scope 'tree)
  13975. (org-back-to-heading t)
  13976. (org-narrow-to-subtree)
  13977. (setq scope nil))
  13978. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13979. (org-region-active-p))
  13980. ;; If needed, set start-level to a string like "2"
  13981. (when start-level
  13982. (save-excursion
  13983. (goto-char (region-beginning))
  13984. (unless (org-at-heading-p) (outline-next-heading))
  13985. (setq start-level (org-current-level))))
  13986. (narrow-to-region (region-beginning)
  13987. (save-excursion
  13988. (goto-char (region-end))
  13989. (unless (and (bolp) (org-at-heading-p))
  13990. (outline-next-heading))
  13991. (point)))
  13992. (setq scope nil)))
  13993. (if (not scope)
  13994. (progn
  13995. (org-agenda-prepare-buffers
  13996. (and buffer-file-name (list buffer-file-name)))
  13997. (setq res
  13998. (org-scan-tags
  13999. func matcher org--matcher-tags-todo-only start-level)))
  14000. ;; Get the right scope
  14001. (cond
  14002. ((and scope (listp scope) (symbolp (car scope)))
  14003. (setq scope (eval scope)))
  14004. ((eq scope 'agenda)
  14005. (setq scope (org-agenda-files t)))
  14006. ((eq scope 'agenda-with-archives)
  14007. (setq scope (org-agenda-files t))
  14008. (setq scope (org-add-archive-files scope)))
  14009. ((eq scope 'file)
  14010. (setq scope (and buffer-file-name (list buffer-file-name))))
  14011. ((eq scope 'file-with-archives)
  14012. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14013. (org-agenda-prepare-buffers scope)
  14014. (dolist (file scope)
  14015. (with-current-buffer (org-find-base-buffer-visiting file)
  14016. (org-with-wide-buffer
  14017. (goto-char (point-min))
  14018. (setq res
  14019. (append
  14020. res
  14021. (org-scan-tags
  14022. func matcher org--matcher-tags-todo-only)))))))))
  14023. res)))
  14024. ;;; Properties API
  14025. (defconst org-special-properties
  14026. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14027. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14028. "The special properties valid in Org mode.
  14029. These are properties that are not defined in the property drawer,
  14030. but in some other way.")
  14031. (defconst org-default-properties
  14032. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14033. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14034. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14035. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14036. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14037. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14038. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14039. "Some properties that are used by Org mode for various purposes.
  14040. Being in this list makes sure that they are offered for completion.")
  14041. (defun org--valid-property-p (property)
  14042. "Non nil when string PROPERTY is a valid property name."
  14043. (not
  14044. (or (equal property "")
  14045. (string-match-p "\\s-" property))))
  14046. (defun org--update-property-plist (key val props)
  14047. "Associate KEY to VAL in alist PROPS.
  14048. Modifications are made by side-effect. Return new alist."
  14049. (let* ((appending (string= (substring key -1) "+"))
  14050. (key (if appending (substring key 0 -1) key))
  14051. (old (assoc-string key props t)))
  14052. (if (not old) (cons (cons key val) props)
  14053. (setcdr old (if appending (concat (cdr old) " " val) val))
  14054. props)))
  14055. (defun org-get-property-block (&optional beg force)
  14056. "Return the (beg . end) range of the body of the property drawer.
  14057. BEG is the beginning of the current subtree, or of the part
  14058. before the first headline. If it is not given, it will be found.
  14059. If the drawer does not exist, create it if FORCE is non-nil, or
  14060. return nil."
  14061. (org-with-wide-buffer
  14062. (when beg (goto-char beg))
  14063. (unless (org-before-first-heading-p)
  14064. (let ((beg (cond (beg)
  14065. ((or (not (featurep 'org-inlinetask))
  14066. (org-inlinetask-in-task-p))
  14067. (org-back-to-heading t))
  14068. (t (org-with-limited-levels (org-back-to-heading t))))))
  14069. (forward-line)
  14070. (when (looking-at-p org-planning-line-re) (forward-line))
  14071. (cond ((looking-at org-property-drawer-re)
  14072. (forward-line)
  14073. (cons (point) (progn (goto-char (match-end 0))
  14074. (line-beginning-position))))
  14075. (force
  14076. (goto-char beg)
  14077. (org-insert-property-drawer)
  14078. (let ((pos (save-excursion (search-forward ":END:")
  14079. (line-beginning-position))))
  14080. (cons pos pos))))))))
  14081. (defun org-at-property-p ()
  14082. "Non-nil when point is inside a property drawer.
  14083. See `org-property-re' for match data, if applicable."
  14084. (save-excursion
  14085. (beginning-of-line)
  14086. (and (looking-at org-property-re)
  14087. (let ((property-drawer (save-match-data (org-get-property-block))))
  14088. (and property-drawer
  14089. (>= (point) (car property-drawer))
  14090. (< (point) (cdr property-drawer)))))))
  14091. (defun org-property-action ()
  14092. "Do an action on properties."
  14093. (interactive)
  14094. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14095. (let ((c (read-char-exclusive)))
  14096. (cl-case c
  14097. (?s (call-interactively #'org-set-property))
  14098. (?d (call-interactively #'org-delete-property))
  14099. (?D (call-interactively #'org-delete-property-globally))
  14100. (?c (call-interactively #'org-compute-property-at-point))
  14101. (otherwise (user-error "No such property action %c" c)))))
  14102. (defun org-inc-effort ()
  14103. "Increment the value of the effort property in the current entry."
  14104. (interactive)
  14105. (org-set-effort nil t))
  14106. (defvar org-clock-effort) ; Defined in org-clock.el.
  14107. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14108. (defun org-set-effort (&optional value increment)
  14109. "Set the effort property of the current entry.
  14110. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14111. 10th allowed value.
  14112. When INCREMENT is non-nil, set the property to the next allowed value."
  14113. (interactive "P")
  14114. (when (equal value 0) (setq value 10))
  14115. (let* ((completion-ignore-case t)
  14116. (prop org-effort-property)
  14117. (cur (org-entry-get nil prop))
  14118. (allowed (org-property-get-allowed-values nil prop 'table))
  14119. (existing (mapcar 'list (org-property-values prop)))
  14120. (heading (nth 4 (org-heading-components)))
  14121. rpl
  14122. (val (cond
  14123. ((stringp value) value)
  14124. ((and allowed (integerp value))
  14125. (or (car (nth (1- value) allowed))
  14126. (car (org-last allowed))))
  14127. ((and allowed increment)
  14128. (or (cl-caadr (member (list cur) allowed))
  14129. (user-error "Allowed effort values are not set")))
  14130. (allowed
  14131. (message "Select 1-9,0, [RET%s]: %s"
  14132. (if cur (concat "=" cur) "")
  14133. (mapconcat 'car allowed " "))
  14134. (setq rpl (read-char-exclusive))
  14135. (if (equal rpl ?\r)
  14136. cur
  14137. (setq rpl (- rpl ?0))
  14138. (when (equal rpl 0) (setq rpl 10))
  14139. (if (and (> rpl 0) (<= rpl (length allowed)))
  14140. (car (nth (1- rpl) allowed))
  14141. (org-completing-read "Effort: " allowed nil))))
  14142. (t
  14143. (org-completing-read
  14144. (concat "Effort" (and cur (string-match "\\S-" cur)
  14145. (concat " [" cur "]"))
  14146. ": ")
  14147. existing nil nil "" nil cur)))))
  14148. (unless (equal (org-entry-get nil prop) val)
  14149. (org-entry-put nil prop val))
  14150. (org-refresh-property
  14151. '((effort . identity)
  14152. (effort-minutes . org-duration-to-minutes))
  14153. val)
  14154. (when (equal heading (bound-and-true-p org-clock-current-task))
  14155. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14156. (org-clock-update-mode-line))
  14157. (message "%s is now %s" prop val)))
  14158. (defun org-entry-properties (&optional pom which)
  14159. "Get all properties of the current entry.
  14160. When POM is a buffer position, get all properties from the entry
  14161. there instead.
  14162. This includes the TODO keyword, the tags, time strings for
  14163. deadline, scheduled, and clocking, and any additional properties
  14164. defined in the entry.
  14165. If WHICH is nil or `all', get all properties. If WHICH is
  14166. `special' or `standard', only get that subclass. If WHICH is
  14167. a string, only get that property.
  14168. Return value is an alist. Keys are properties, as upcased
  14169. strings."
  14170. (org-with-point-at pom
  14171. (when (and (derived-mode-p 'org-mode)
  14172. (ignore-errors (org-back-to-heading t)))
  14173. (catch 'exit
  14174. (let* ((beg (point))
  14175. (specific (and (stringp which) (upcase which)))
  14176. (which (cond ((not specific) which)
  14177. ((member specific org-special-properties) 'special)
  14178. (t 'standard)))
  14179. props)
  14180. ;; Get the special properties, like TODO and TAGS.
  14181. (when (memq which '(nil all special))
  14182. (when (or (not specific) (string= specific "CLOCKSUM"))
  14183. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14184. (when clocksum
  14185. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14186. props)))
  14187. (when specific (throw 'exit props)))
  14188. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14189. (let ((clocksumt (get-text-property (point)
  14190. :org-clock-minutes-today)))
  14191. (when clocksumt
  14192. (push (cons "CLOCKSUM_T"
  14193. (org-duration-from-minutes clocksumt))
  14194. props)))
  14195. (when specific (throw 'exit props)))
  14196. (when (or (not specific) (string= specific "ITEM"))
  14197. (let ((case-fold-search nil))
  14198. (when (looking-at org-complex-heading-regexp)
  14199. (push (cons "ITEM"
  14200. (let ((title (match-string-no-properties 4)))
  14201. (if (org-string-nw-p title)
  14202. (org-remove-tabs title)
  14203. "")))
  14204. props)))
  14205. (when specific (throw 'exit props)))
  14206. (when (or (not specific) (string= specific "TODO"))
  14207. (let ((case-fold-search nil))
  14208. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14209. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14210. (when specific (throw 'exit props)))
  14211. (when (or (not specific) (string= specific "PRIORITY"))
  14212. (push (cons "PRIORITY"
  14213. (if (looking-at org-priority-regexp)
  14214. (match-string-no-properties 2)
  14215. (char-to-string org-default-priority)))
  14216. props)
  14217. (when specific (throw 'exit props)))
  14218. (when (or (not specific) (string= specific "FILE"))
  14219. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14220. props)
  14221. (when specific (throw 'exit props)))
  14222. (when (or (not specific) (string= specific "TAGS"))
  14223. (let ((value (org-string-nw-p (org-get-tags-string))))
  14224. (when value (push (cons "TAGS" value) props)))
  14225. (when specific (throw 'exit props)))
  14226. (when (or (not specific) (string= specific "ALLTAGS"))
  14227. (let ((value (org-get-tags-at)))
  14228. (when value
  14229. (push (cons "ALLTAGS"
  14230. (format ":%s:" (mapconcat #'identity value ":")))
  14231. props)))
  14232. (when specific (throw 'exit props)))
  14233. (when (or (not specific) (string= specific "BLOCKED"))
  14234. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14235. (when specific (throw 'exit props)))
  14236. (when (or (not specific)
  14237. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14238. (forward-line)
  14239. (when (looking-at-p org-planning-line-re)
  14240. (end-of-line)
  14241. (let ((bol (line-beginning-position))
  14242. ;; Backward compatibility: time keywords used to
  14243. ;; be configurable (before 8.3). Make sure we
  14244. ;; get the correct keyword.
  14245. (key-assoc `(("CLOSED" . ,org-closed-string)
  14246. ("DEADLINE" . ,org-deadline-string)
  14247. ("SCHEDULED" . ,org-scheduled-string))))
  14248. (dolist (pair (if specific (list (assoc specific key-assoc))
  14249. key-assoc))
  14250. (save-excursion
  14251. (when (search-backward (cdr pair) bol t)
  14252. (goto-char (match-end 0))
  14253. (skip-chars-forward " \t")
  14254. (and (looking-at org-ts-regexp-both)
  14255. (push (cons (car pair)
  14256. (match-string-no-properties 0))
  14257. props)))))))
  14258. (when specific (throw 'exit props)))
  14259. (when (or (not specific)
  14260. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14261. (let ((find-ts
  14262. (lambda (end ts)
  14263. ;; Fix next time-stamp before END. TS is the
  14264. ;; list of time-stamps found so far.
  14265. (let ((ts ts)
  14266. (regexp (cond
  14267. ((string= specific "TIMESTAMP")
  14268. org-ts-regexp)
  14269. ((string= specific "TIMESTAMP_IA")
  14270. org-ts-regexp-inactive)
  14271. ((assoc "TIMESTAMP_IA" ts)
  14272. org-ts-regexp)
  14273. ((assoc "TIMESTAMP" ts)
  14274. org-ts-regexp-inactive)
  14275. (t org-ts-regexp-both))))
  14276. (catch 'next
  14277. (while (re-search-forward regexp end t)
  14278. (backward-char)
  14279. (let ((object (org-element-context)))
  14280. ;; Accept to match timestamps in node
  14281. ;; properties, too.
  14282. (when (memq (org-element-type object)
  14283. '(node-property timestamp))
  14284. (let ((type
  14285. (org-element-property :type object)))
  14286. (cond
  14287. ((and (memq type '(active active-range))
  14288. (not (equal specific "TIMESTAMP_IA")))
  14289. (unless (assoc "TIMESTAMP" ts)
  14290. (push (cons "TIMESTAMP"
  14291. (org-element-property
  14292. :raw-value object))
  14293. ts)
  14294. (when specific (throw 'exit ts))))
  14295. ((and (memq type '(inactive inactive-range))
  14296. (not (string= specific "TIMESTAMP")))
  14297. (unless (assoc "TIMESTAMP_IA" ts)
  14298. (push (cons "TIMESTAMP_IA"
  14299. (org-element-property
  14300. :raw-value object))
  14301. ts)
  14302. (when specific (throw 'exit ts))))))
  14303. ;; Both timestamp types are found,
  14304. ;; move to next part.
  14305. (when (= (length ts) 2) (throw 'next ts)))))
  14306. ts)))))
  14307. (goto-char beg)
  14308. ;; First look for timestamps within headline.
  14309. (let ((ts (funcall find-ts (line-end-position) nil)))
  14310. (if (= (length ts) 2) (setq props (nconc ts props))
  14311. ;; Then find timestamps in the section, skipping
  14312. ;; planning line.
  14313. (let ((end (save-excursion (outline-next-heading))))
  14314. (forward-line)
  14315. (when (looking-at-p org-planning-line-re) (forward-line))
  14316. (setq props (nconc (funcall find-ts end ts) props))))))))
  14317. ;; Get the standard properties, like :PROP:.
  14318. (when (memq which '(nil all standard))
  14319. ;; If we are looking after a specific property, delegate
  14320. ;; to `org-entry-get', which is faster. However, make an
  14321. ;; exception for "CATEGORY", since it can be also set
  14322. ;; through keywords (i.e. #+CATEGORY).
  14323. (if (and specific (not (equal specific "CATEGORY")))
  14324. (let ((value (org-entry-get beg specific nil t)))
  14325. (throw 'exit (and value (list (cons specific value)))))
  14326. (let ((range (org-get-property-block beg)))
  14327. (when range
  14328. (let ((end (cdr range)) seen-base)
  14329. (goto-char (car range))
  14330. ;; Unlike to `org--update-property-plist', we
  14331. ;; handle the case where base values is found
  14332. ;; after its extension. We also forbid standard
  14333. ;; properties to be named as special properties.
  14334. (while (re-search-forward org-property-re end t)
  14335. (let* ((key (upcase (match-string-no-properties 2)))
  14336. (extendp (string-match-p "\\+\\'" key))
  14337. (key-base (if extendp (substring key 0 -1) key))
  14338. (value (match-string-no-properties 3)))
  14339. (cond
  14340. ((member-ignore-case key-base org-special-properties))
  14341. (extendp
  14342. (setq props
  14343. (org--update-property-plist key value props)))
  14344. ((member key seen-base))
  14345. (t (push key seen-base)
  14346. (let ((p (assoc-string key props t)))
  14347. (if p (setcdr p (concat value " " (cdr p)))
  14348. (push (cons key value) props))))))))))))
  14349. (unless (assoc "CATEGORY" props)
  14350. (push (cons "CATEGORY" (org-get-category beg)) props)
  14351. (when (string= specific "CATEGORY") (throw 'exit props)))
  14352. ;; Return value.
  14353. props)))))
  14354. (defun org--property-local-values (property literal-nil)
  14355. "Return value for PROPERTY in current entry.
  14356. Value is a list whose car is the base value for PROPERTY and cdr
  14357. a list of accumulated values. Return nil if neither is found in
  14358. the entry. Also return nil when PROPERTY is set to \"nil\",
  14359. unless LITERAL-NIL is non-nil."
  14360. (let ((range (org-get-property-block)))
  14361. (when range
  14362. (goto-char (car range))
  14363. (let* ((case-fold-search t)
  14364. (end (cdr range))
  14365. (value
  14366. ;; Base value.
  14367. (save-excursion
  14368. (let ((v (and (re-search-forward
  14369. (org-re-property property nil t) end t)
  14370. (match-string-no-properties 3))))
  14371. (list (if literal-nil v (org-not-nil v)))))))
  14372. ;; Find additional values.
  14373. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14374. (while (re-search-forward property+ end t)
  14375. (push (match-string-no-properties 3) value)))
  14376. ;; Return final values.
  14377. (and (not (equal value '(nil))) (nreverse value))))))
  14378. (defun org--property-global-value (property literal-nil)
  14379. "Return value for PROPERTY in current buffer.
  14380. Return value is a string. Return nil if property is not set
  14381. globally. Also return nil when PROPERTY is set to \"nil\",
  14382. unless LITERAL-NIL is non-nil."
  14383. (let ((global
  14384. (cdr (or (assoc-string property org-file-properties t)
  14385. (assoc-string property org-global-properties t)
  14386. (assoc-string property org-global-properties-fixed t)))))
  14387. (if literal-nil global (org-not-nil global))))
  14388. (defun org-entry-get (pom property &optional inherit literal-nil)
  14389. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14390. If INHERIT is non-nil and the entry does not have the property,
  14391. then also check higher levels of the hierarchy. If INHERIT is
  14392. the symbol `selective', use inheritance only if the setting in
  14393. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14394. If the property is present but empty, the return value is the
  14395. empty string. If the property is not present at all, nil is
  14396. returned. In any other case, return the value as a string.
  14397. Search is case-insensitive.
  14398. If LITERAL-NIL is set, return the string value \"nil\" as
  14399. a string, do not interpret it as the list atom nil. This is used
  14400. for inheritance when a \"nil\" value can supersede a non-nil
  14401. value higher up the hierarchy."
  14402. (org-with-point-at pom
  14403. (cond
  14404. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14405. ;; We need a special property. Use `org-entry-properties' to
  14406. ;; retrieve it, but specify the wanted property.
  14407. (cdr (assoc-string property (org-entry-properties nil property))))
  14408. ((and inherit
  14409. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14410. (org-entry-get-with-inheritance property literal-nil))
  14411. (t
  14412. (let* ((local (org--property-local-values property literal-nil))
  14413. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14414. (if literal-nil value (org-not-nil value)))))))
  14415. (defun org-property-or-variable-value (var &optional inherit)
  14416. "Check if there is a property fixing the value of VAR.
  14417. If yes, return this value. If not, return the current value of the variable."
  14418. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14419. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14420. (read prop)
  14421. (symbol-value var))))
  14422. (defun org-entry-delete (pom property)
  14423. "Delete PROPERTY from entry at point-or-marker POM.
  14424. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14425. non-nil when a property was removed."
  14426. (org-with-point-at pom
  14427. (pcase (org-get-property-block)
  14428. (`(,begin . ,origin)
  14429. (let* ((end (copy-marker origin))
  14430. (re (org-re-property
  14431. (concat (regexp-quote property) "\\+?") t t)))
  14432. (goto-char begin)
  14433. (while (re-search-forward re end t)
  14434. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14435. ;; If drawer is empty, remove it altogether.
  14436. (when (= begin end)
  14437. (delete-region (line-beginning-position 0)
  14438. (line-beginning-position 2)))
  14439. ;; Return non-nil if some property was removed.
  14440. (prog1 (/= end origin) (set-marker end nil))))
  14441. (_ nil))))
  14442. ;; Multi-values properties are properties that contain multiple values
  14443. ;; These values are assumed to be single words, separated by whitespace.
  14444. (defun org-entry-add-to-multivalued-property (pom property value)
  14445. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14446. (let* ((old (org-entry-get pom property))
  14447. (values (and old (split-string old))))
  14448. (setq value (org-entry-protect-space value))
  14449. (unless (member value values)
  14450. (setq values (append values (list value)))
  14451. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14452. (defun org-entry-remove-from-multivalued-property (pom property value)
  14453. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14454. (let* ((old (org-entry-get pom property))
  14455. (values (and old (split-string old))))
  14456. (setq value (org-entry-protect-space value))
  14457. (when (member value values)
  14458. (setq values (delete value values))
  14459. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14460. (defun org-entry-member-in-multivalued-property (pom property value)
  14461. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14462. (let* ((old (org-entry-get pom property))
  14463. (values (and old (split-string old))))
  14464. (setq value (org-entry-protect-space value))
  14465. (member value values)))
  14466. (defun org-entry-get-multivalued-property (pom property)
  14467. "Return a list of values in a multivalued property."
  14468. (let* ((value (org-entry-get pom property))
  14469. (values (and value (split-string value))))
  14470. (mapcar #'org-entry-restore-space values)))
  14471. (defun org-entry-put-multivalued-property (pom property &rest values)
  14472. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14473. VALUES should be a list of strings. Spaces will be protected."
  14474. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14475. (let* ((value (org-entry-get pom property))
  14476. (values (and value (split-string value))))
  14477. (mapcar #'org-entry-restore-space values)))
  14478. (defun org-entry-protect-space (s)
  14479. "Protect spaces and newline in string S."
  14480. (while (string-match " " s)
  14481. (setq s (replace-match "%20" t t s)))
  14482. (while (string-match "\n" s)
  14483. (setq s (replace-match "%0A" t t s)))
  14484. s)
  14485. (defun org-entry-restore-space (s)
  14486. "Restore spaces and newline in string S."
  14487. (while (string-match "%20" s)
  14488. (setq s (replace-match " " t t s)))
  14489. (while (string-match "%0A" s)
  14490. (setq s (replace-match "\n" t t s)))
  14491. s)
  14492. (defvar org-entry-property-inherited-from (make-marker)
  14493. "Marker pointing to the entry from where a property was inherited.
  14494. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14495. location of the entry where the inheritance search matched. If there was
  14496. no match, the marker will point nowhere.
  14497. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14498. is set.")
  14499. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14500. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14501. The search will stop at the first ancestor which has the property defined.
  14502. If the value found is \"nil\", return nil to show that the property
  14503. should be considered as undefined (this is the meaning of nil here).
  14504. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14505. (move-marker org-entry-property-inherited-from nil)
  14506. (org-with-wide-buffer
  14507. (let (value)
  14508. (catch 'exit
  14509. (while t
  14510. (let ((v (org--property-local-values property literal-nil)))
  14511. (when v
  14512. (setq value
  14513. (concat (mapconcat #'identity (delq nil v) " ")
  14514. (and value " ")
  14515. value)))
  14516. (cond
  14517. ((car v)
  14518. (org-back-to-heading t)
  14519. (move-marker org-entry-property-inherited-from (point))
  14520. (throw 'exit nil))
  14521. ((org-up-heading-safe))
  14522. (t
  14523. (let ((global (org--property-global-value property literal-nil)))
  14524. (cond ((not global))
  14525. (value (setq value (concat global " " value)))
  14526. (t (setq value global))))
  14527. (throw 'exit nil))))))
  14528. (if literal-nil value (org-not-nil value)))))
  14529. (defvar org-property-changed-functions nil
  14530. "Hook called when the value of a property has changed.
  14531. Each hook function should accept two arguments, the name of the property
  14532. and the new value.")
  14533. (defun org-entry-put (pom property value)
  14534. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14535. If the value is nil, it is converted to the empty string. If it
  14536. is not a string, an error is raised. Also raise an error on
  14537. invalid property names.
  14538. PROPERTY can be any regular property (see
  14539. `org-special-properties'). It can also be \"TODO\",
  14540. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14541. For the last two properties, VALUE may have any of the special
  14542. values \"earlier\" and \"later\". The function then increases or
  14543. decreases scheduled or deadline date by one day."
  14544. (cond ((null value) (setq value ""))
  14545. ((not (stringp value)) (error "Properties values should be strings"))
  14546. ((not (org--valid-property-p property))
  14547. (user-error "Invalid property name: \"%s\"" property)))
  14548. (org-with-point-at pom
  14549. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14550. (org-back-to-heading t)
  14551. (org-with-limited-levels (org-back-to-heading t)))
  14552. (let ((beg (point)))
  14553. (cond
  14554. ((equal property "TODO")
  14555. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14556. ((not (member value org-todo-keywords-1))
  14557. (user-error "\"%s\" is not a valid TODO state" value)))
  14558. (org-todo value)
  14559. (org-set-tags nil 'align))
  14560. ((equal property "PRIORITY")
  14561. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14562. (org-set-tags nil 'align))
  14563. ((equal property "SCHEDULED")
  14564. (forward-line)
  14565. (if (and (looking-at-p org-planning-line-re)
  14566. (re-search-forward
  14567. org-scheduled-time-regexp (line-end-position) t))
  14568. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14569. ((string= value "later") (org-timestamp-change 1 'day))
  14570. ((string= value "") (org-schedule '(4)))
  14571. (t (org-schedule nil value)))
  14572. (if (member value '("earlier" "later" ""))
  14573. (call-interactively #'org-schedule)
  14574. (org-schedule nil value))))
  14575. ((equal property "DEADLINE")
  14576. (forward-line)
  14577. (if (and (looking-at-p org-planning-line-re)
  14578. (re-search-forward
  14579. org-deadline-time-regexp (line-end-position) t))
  14580. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14581. ((string= value "later") (org-timestamp-change 1 'day))
  14582. ((string= value "") (org-deadline '(4)))
  14583. (t (org-deadline nil value)))
  14584. (if (member value '("earlier" "later" ""))
  14585. (call-interactively #'org-deadline)
  14586. (org-deadline nil value))))
  14587. ((member property org-special-properties)
  14588. (error "The %s property cannot be set with `org-entry-put'" property))
  14589. (t
  14590. (let* ((range (org-get-property-block beg 'force))
  14591. (end (cdr range))
  14592. (case-fold-search t))
  14593. (goto-char (car range))
  14594. (if (re-search-forward (org-re-property property nil t) end t)
  14595. (progn (delete-region (match-beginning 0) (match-end 0))
  14596. (goto-char (match-beginning 0)))
  14597. (goto-char end)
  14598. (insert "\n")
  14599. (backward-char))
  14600. (insert ":" property ":")
  14601. (when value (insert " " value))
  14602. (org-indent-line)))))
  14603. (run-hook-with-args 'org-property-changed-functions property value)))
  14604. (defun org-buffer-property-keys
  14605. (&optional specials defaults columns ignore-malformed)
  14606. "Get all property keys in the current buffer.
  14607. When SPECIALS is non-nil, also list the special properties that
  14608. reflect things like tags and TODO state.
  14609. When DEFAULTS is non-nil, also include properties that has
  14610. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14611. DESCRIPTION, LOCATION, and LOGGING and others.
  14612. When COLUMNS in non-nil, also include property names given in
  14613. COLUMN formats in the current buffer.
  14614. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14615. automatically performed, such drawers will be silently ignored."
  14616. (let ((case-fold-search t)
  14617. (props (append
  14618. (and specials org-special-properties)
  14619. (and defaults (cons org-effort-property org-default-properties))
  14620. nil)))
  14621. (org-with-wide-buffer
  14622. (goto-char (point-min))
  14623. (while (re-search-forward org-property-start-re nil t)
  14624. (let ((range (org-get-property-block)))
  14625. (catch 'skip
  14626. (unless range
  14627. (when (and (not ignore-malformed)
  14628. (not (org-before-first-heading-p))
  14629. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14630. (line-beginning-position))))
  14631. (org-get-property-block nil t))
  14632. (throw 'skip nil))
  14633. (goto-char (car range))
  14634. (let ((begin (car range))
  14635. (end (cdr range)))
  14636. ;; Make sure that found property block is not located
  14637. ;; before current point, as it would generate an infloop.
  14638. ;; It can happen, for example, in the following
  14639. ;; situation:
  14640. ;;
  14641. ;; * Headline
  14642. ;; :PROPERTIES:
  14643. ;; ...
  14644. ;; :END:
  14645. ;; *************** Inlinetask
  14646. ;; #+BEGIN_EXAMPLE
  14647. ;; :PROPERTIES:
  14648. ;; #+END_EXAMPLE
  14649. ;;
  14650. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14651. (while (< (point) end)
  14652. (let ((p (progn (looking-at org-property-re)
  14653. (match-string-no-properties 2))))
  14654. ;; Only add true property name, not extension symbol.
  14655. (push (if (not (string-match-p "\\+\\'" p)) p
  14656. (substring p 0 -1))
  14657. props))
  14658. (forward-line))))
  14659. (outline-next-heading)))
  14660. (when columns
  14661. (goto-char (point-min))
  14662. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14663. (let ((element (org-element-at-point)))
  14664. (when (memq (org-element-type element) '(keyword node-property))
  14665. (let ((value (org-element-property :value element))
  14666. (start 0))
  14667. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14668. \\(?:{[^}]+}\\)?"
  14669. value start)
  14670. (setq start (match-end 0))
  14671. (let ((p (match-string-no-properties 1 value)))
  14672. (unless (member-ignore-case p org-special-properties)
  14673. (push p props))))))))))
  14674. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14675. (defun org-property-values (key)
  14676. "List all non-nil values of property KEY in current buffer."
  14677. (org-with-wide-buffer
  14678. (goto-char (point-min))
  14679. (let ((case-fold-search t)
  14680. (re (org-re-property key))
  14681. values)
  14682. (while (re-search-forward re nil t)
  14683. (push (org-entry-get (point) key) values))
  14684. (delete-dups values))))
  14685. (defun org-insert-property-drawer ()
  14686. "Insert a property drawer into the current entry."
  14687. (org-with-wide-buffer
  14688. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14689. (org-back-to-heading t)
  14690. (org-with-limited-levels (org-back-to-heading t)))
  14691. (forward-line)
  14692. (when (looking-at-p org-planning-line-re) (forward-line))
  14693. (unless (looking-at-p org-property-drawer-re)
  14694. ;; Make sure we start editing a line from current entry, not from
  14695. ;; next one. It prevents extending text properties or overlays
  14696. ;; belonging to the latter.
  14697. (when (bolp) (backward-char))
  14698. (let ((begin (1+ (point)))
  14699. (inhibit-read-only t))
  14700. (insert "\n:PROPERTIES:\n:END:")
  14701. (when (eobp) (insert "\n"))
  14702. (org-indent-region begin (point))))))
  14703. (defun org-insert-drawer (&optional arg drawer)
  14704. "Insert a drawer at point.
  14705. When optional argument ARG is non-nil, insert a property drawer.
  14706. Optional argument DRAWER, when non-nil, is a string representing
  14707. drawer's name. Otherwise, the user is prompted for a name.
  14708. If a region is active, insert the drawer around that region
  14709. instead.
  14710. Point is left between drawer's boundaries."
  14711. (interactive "P")
  14712. (let* ((drawer (if arg "PROPERTIES"
  14713. (or drawer (read-from-minibuffer "Drawer: ")))))
  14714. (cond
  14715. ;; With C-u, fall back on `org-insert-property-drawer'
  14716. (arg (org-insert-property-drawer))
  14717. ;; Check validity of suggested drawer's name.
  14718. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14719. (user-error "Invalid drawer name"))
  14720. ;; With an active region, insert a drawer at point.
  14721. ((not (org-region-active-p))
  14722. (progn
  14723. (unless (bolp) (insert "\n"))
  14724. (insert (format ":%s:\n\n:END:\n" drawer))
  14725. (forward-line -2)))
  14726. ;; Otherwise, insert the drawer at point
  14727. (t
  14728. (let ((rbeg (region-beginning))
  14729. (rend (copy-marker (region-end))))
  14730. (unwind-protect
  14731. (progn
  14732. (goto-char rbeg)
  14733. (beginning-of-line)
  14734. (when (save-excursion
  14735. (re-search-forward org-outline-regexp-bol rend t))
  14736. (user-error "Drawers cannot contain headlines"))
  14737. ;; Position point at the beginning of the first
  14738. ;; non-blank line in region. Insert drawer's opening
  14739. ;; there, then indent it.
  14740. (org-skip-whitespace)
  14741. (beginning-of-line)
  14742. (insert ":" drawer ":\n")
  14743. (forward-line -1)
  14744. (indent-for-tab-command)
  14745. ;; Move point to the beginning of the first blank line
  14746. ;; after the last non-blank line in region. Insert
  14747. ;; drawer's closing, then indent it.
  14748. (goto-char rend)
  14749. (skip-chars-backward " \r\t\n")
  14750. (insert "\n:END:")
  14751. (deactivate-mark t)
  14752. (indent-for-tab-command)
  14753. (unless (eolp) (insert "\n")))
  14754. ;; Clear marker, whatever the outcome of insertion is.
  14755. (set-marker rend nil)))))))
  14756. (defvar org-property-set-functions-alist nil
  14757. "Property set function alist.
  14758. Each entry should have the following format:
  14759. (PROPERTY . READ-FUNCTION)
  14760. The read function will be called with the same argument as
  14761. `org-completing-read'.")
  14762. (defun org-set-property-function (property)
  14763. "Get the function that should be used to set PROPERTY.
  14764. This is computed according to `org-property-set-functions-alist'."
  14765. (or (cdr (assoc property org-property-set-functions-alist))
  14766. 'org-completing-read))
  14767. (defun org-read-property-value (property)
  14768. "Read PROPERTY value from user."
  14769. (let* ((completion-ignore-case t)
  14770. (allowed (org-property-get-allowed-values nil property 'table))
  14771. (cur (org-entry-get nil property))
  14772. (prompt (concat property " value"
  14773. (if (and cur (string-match "\\S-" cur))
  14774. (concat " [" cur "]") "") ": "))
  14775. (set-function (org-set-property-function property))
  14776. (val (if allowed
  14777. (funcall set-function prompt allowed nil
  14778. (not (get-text-property 0 'org-unrestricted
  14779. (caar allowed))))
  14780. (funcall set-function prompt
  14781. (mapcar 'list (org-property-values property))
  14782. nil nil "" nil cur))))
  14783. (org-trim val)))
  14784. (defvar org-last-set-property nil)
  14785. (defvar org-last-set-property-value nil)
  14786. (defun org-read-property-name ()
  14787. "Read a property name."
  14788. (let ((completion-ignore-case t)
  14789. (default-prop (or (and (org-at-property-p)
  14790. (match-string-no-properties 2))
  14791. org-last-set-property)))
  14792. (org-completing-read
  14793. (concat "Property"
  14794. (if default-prop (concat " [" default-prop "]") "")
  14795. ": ")
  14796. (mapcar #'list (org-buffer-property-keys nil t t))
  14797. nil nil nil nil default-prop)))
  14798. (defun org-set-property-and-value (use-last)
  14799. "Allow to set [PROPERTY]: [value] direction from prompt.
  14800. When use-default, don't even ask, just use the last
  14801. \"[PROPERTY]: [value]\" string from the history."
  14802. (interactive "P")
  14803. (let* ((completion-ignore-case t)
  14804. (pv (or (and use-last org-last-set-property-value)
  14805. (org-completing-read
  14806. "Enter a \"[Property]: [value]\" pair: "
  14807. nil nil nil nil nil
  14808. org-last-set-property-value)))
  14809. prop val)
  14810. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14811. (setq prop (match-string 1 pv)
  14812. val (match-string 2 pv))
  14813. (org-set-property prop val))))
  14814. (defun org-set-property (property value)
  14815. "In the current entry, set PROPERTY to VALUE.
  14816. When called interactively, this will prompt for a property name, offering
  14817. completion on existing and default properties. And then it will prompt
  14818. for a value, offering completion either on allowed values (via an inherited
  14819. xxx_ALL property) or on existing values in other instances of this property
  14820. in the current file.
  14821. Throw an error when trying to set a property with an invalid name."
  14822. (interactive (list nil nil))
  14823. (let ((property (or property (org-read-property-name))))
  14824. ;; `org-entry-put' also makes the following check, but this one
  14825. ;; avoids polluting `org-last-set-property' and
  14826. ;; `org-last-set-property-value' needlessly.
  14827. (unless (org--valid-property-p property)
  14828. (user-error "Invalid property name: \"%s\"" property))
  14829. (let ((value (or value (org-read-property-value property)))
  14830. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14831. (setq org-last-set-property property)
  14832. (setq org-last-set-property-value (concat property ": " value))
  14833. ;; Possibly postprocess the inserted value:
  14834. (when fn (setq value (funcall fn value)))
  14835. (unless (equal (org-entry-get nil property) value)
  14836. (org-entry-put nil property value)))))
  14837. (defun org-find-property (property &optional value)
  14838. "Find first entry in buffer that sets PROPERTY.
  14839. When optional argument VALUE is non-nil, only consider an entry
  14840. if it contains PROPERTY set to this value. If PROPERTY should be
  14841. explicitly set to nil, use string \"nil\" for VALUE.
  14842. Return position where the entry begins, or nil if there is no
  14843. such entry. If narrowing is in effect, only search the visible
  14844. part of the buffer."
  14845. (save-excursion
  14846. (goto-char (point-min))
  14847. (let ((case-fold-search t)
  14848. (re (org-re-property property nil (not value) value)))
  14849. (catch 'exit
  14850. (while (re-search-forward re nil t)
  14851. (when (if value (org-at-property-p)
  14852. (org-entry-get (point) property nil t))
  14853. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14854. (defun org-delete-property (property)
  14855. "In the current entry, delete PROPERTY."
  14856. (interactive
  14857. (let* ((completion-ignore-case t)
  14858. (cat (org-entry-get (point) "CATEGORY"))
  14859. (props0 (org-entry-properties nil 'standard))
  14860. (props (if cat props0
  14861. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14862. (prop (if (< 1 (length props))
  14863. (completing-read "Property: " props nil t)
  14864. (caar props))))
  14865. (list prop)))
  14866. (if (not property)
  14867. (message "No property to delete in this entry")
  14868. (org-entry-delete nil property)
  14869. (message "Property \"%s\" deleted" property)))
  14870. (defun org-delete-property-globally (property)
  14871. "Remove PROPERTY globally, from all entries.
  14872. This function ignores narrowing, if any."
  14873. (interactive
  14874. (let* ((completion-ignore-case t)
  14875. (prop (completing-read
  14876. "Globally remove property: "
  14877. (mapcar #'list (org-buffer-property-keys)))))
  14878. (list prop)))
  14879. (org-with-wide-buffer
  14880. (goto-char (point-min))
  14881. (let ((count 0)
  14882. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14883. (while (re-search-forward re nil t)
  14884. (when (org-entry-delete (point) property) (cl-incf count)))
  14885. (message "Property \"%s\" removed from %d entries" property count))))
  14886. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14887. (defun org-compute-property-at-point ()
  14888. "Compute the property at point.
  14889. This looks for an enclosing column format, extracts the operator and
  14890. then applies it to the property in the column format's scope."
  14891. (interactive)
  14892. (unless (org-at-property-p)
  14893. (user-error "Not at a property"))
  14894. (let ((prop (match-string-no-properties 2)))
  14895. (org-columns-get-format-and-top-level)
  14896. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14897. (user-error "No operator defined for property %s" prop))
  14898. (org-columns-compute prop)))
  14899. (defvar org-property-allowed-value-functions nil
  14900. "Hook for functions supplying allowed values for a specific property.
  14901. The functions must take a single argument, the name of the property, and
  14902. return a flat list of allowed values. If \":ETC\" is one of
  14903. the values, this means that these values are intended as defaults for
  14904. completion, but that other values should be allowed too.
  14905. The functions must return nil if they are not responsible for this
  14906. property.")
  14907. (defun org-property-get-allowed-values (pom property &optional table)
  14908. "Get allowed values for the property PROPERTY.
  14909. When TABLE is non-nil, return an alist that can directly be used for
  14910. completion."
  14911. (let (vals)
  14912. (cond
  14913. ((equal property "TODO")
  14914. (setq vals (org-with-point-at pom
  14915. (append org-todo-keywords-1 '("")))))
  14916. ((equal property "PRIORITY")
  14917. (let ((n org-lowest-priority))
  14918. (while (>= n org-highest-priority)
  14919. (push (char-to-string n) vals)
  14920. (setq n (1- n)))))
  14921. ((equal property "CATEGORY"))
  14922. ((member property org-special-properties))
  14923. ((setq vals (run-hook-with-args-until-success
  14924. 'org-property-allowed-value-functions property)))
  14925. (t
  14926. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14927. (when (and vals (string-match "\\S-" vals))
  14928. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14929. (setq vals (mapcar (lambda (x)
  14930. (cond ((stringp x) x)
  14931. ((numberp x) (number-to-string x))
  14932. ((symbolp x) (symbol-name x))
  14933. (t "???")))
  14934. vals)))))
  14935. (when (member ":ETC" vals)
  14936. (setq vals (remove ":ETC" vals))
  14937. (org-add-props (car vals) '(org-unrestricted t)))
  14938. (if table (mapcar 'list vals) vals)))
  14939. (defun org-property-previous-allowed-value (&optional _previous)
  14940. "Switch to the next allowed value for this property."
  14941. (interactive)
  14942. (org-property-next-allowed-value t))
  14943. (defun org-property-next-allowed-value (&optional previous)
  14944. "Switch to the next allowed value for this property."
  14945. (interactive)
  14946. (unless (org-at-property-p)
  14947. (user-error "Not at a property"))
  14948. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14949. (key (match-string 2))
  14950. (value (match-string 3))
  14951. (allowed (or (org-property-get-allowed-values (point) key)
  14952. (and (member value '("[ ]" "[-]" "[X]"))
  14953. '("[ ]" "[X]"))))
  14954. (heading (save-match-data (nth 4 (org-heading-components))))
  14955. nval)
  14956. (unless allowed
  14957. (user-error "Allowed values for this property have not been defined"))
  14958. (when previous (setq allowed (reverse allowed)))
  14959. (when (member value allowed)
  14960. (setq nval (car (cdr (member value allowed)))))
  14961. (setq nval (or nval (car allowed)))
  14962. (when (equal nval value)
  14963. (user-error "Only one allowed value for this property"))
  14964. (org-at-property-p)
  14965. (replace-match (concat " :" key ": " nval) t t)
  14966. (org-indent-line)
  14967. (beginning-of-line 1)
  14968. (skip-chars-forward " \t")
  14969. (when (equal prop org-effort-property)
  14970. (org-refresh-property
  14971. '((effort . identity)
  14972. (effort-minutes . org-duration-to-minutes))
  14973. nval)
  14974. (when (string= org-clock-current-task heading)
  14975. (setq org-clock-effort nval)
  14976. (org-clock-update-mode-line)))
  14977. (run-hook-with-args 'org-property-changed-functions key nval)))
  14978. (defun org-find-olp (path &optional this-buffer)
  14979. "Return a marker pointing to the entry at outline path OLP.
  14980. If anything goes wrong, throw an error.
  14981. You can wrap this call to catch the error like this:
  14982. (condition-case msg
  14983. (org-mobile-locate-entry (match-string 4))
  14984. (error (nth 1 msg)))
  14985. The return value will then be either a string with the error message,
  14986. or a marker if everything is OK.
  14987. If THIS-BUFFER is set, the outline path does not contain a file,
  14988. only headings."
  14989. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14990. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14991. (level 1)
  14992. (lmin 1)
  14993. (lmax 1)
  14994. end found flevel)
  14995. (unless buffer (error "File not found :%s" file))
  14996. (with-current-buffer buffer
  14997. (unless (derived-mode-p 'org-mode)
  14998. (error "Buffer %s needs to be in Org mode" buffer))
  14999. (org-with-wide-buffer
  15000. (goto-char (point-min))
  15001. (dolist (heading path)
  15002. (let ((re (format org-complex-heading-regexp-format
  15003. (regexp-quote heading)))
  15004. (cnt 0))
  15005. (while (re-search-forward re end t)
  15006. (setq level (- (match-end 1) (match-beginning 1)))
  15007. (when (and (>= level lmin) (<= level lmax))
  15008. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15009. (when (= cnt 0)
  15010. (error "Heading not found on level %d: %s" lmax heading))
  15011. (when (> cnt 1)
  15012. (error "Heading not unique on level %d: %s" lmax heading))
  15013. (goto-char found)
  15014. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15015. (setq end (save-excursion (org-end-of-subtree t t)))))
  15016. (when (org-at-heading-p)
  15017. (point-marker))))))
  15018. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15019. "Find node HEADING in BUFFER.
  15020. Return a marker to the heading if it was found, or nil if not.
  15021. If POS-ONLY is set, return just the position instead of a marker.
  15022. The heading text must match exact, but it may have a TODO keyword,
  15023. a priority cookie and tags in the standard locations."
  15024. (with-current-buffer (or buffer (current-buffer))
  15025. (org-with-wide-buffer
  15026. (goto-char (point-min))
  15027. (let (case-fold-search)
  15028. (when (re-search-forward
  15029. (format org-complex-heading-regexp-format
  15030. (regexp-quote heading)) nil t)
  15031. (if pos-only
  15032. (match-beginning 0)
  15033. (move-marker (make-marker) (match-beginning 0))))))))
  15034. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15035. "Find Org node headline HEADING in all .org files in directory DIR.
  15036. When the target headline is found, return a marker to this location."
  15037. (let ((files (directory-files (or dir default-directory)
  15038. t "\\`[^.#].*\\.org\\'"))
  15039. visiting m buffer)
  15040. (catch 'found
  15041. (dolist (file files)
  15042. (message "trying %s" file)
  15043. (setq visiting (org-find-base-buffer-visiting file))
  15044. (setq buffer (or visiting (find-file-noselect file)))
  15045. (setq m (org-find-exact-headline-in-buffer
  15046. heading buffer))
  15047. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15048. (and m (throw 'found m))))))
  15049. (defun org-find-entry-with-id (ident)
  15050. "Locate the entry that contains the ID property with exact value IDENT.
  15051. IDENT can be a string, a symbol or a number, this function will search for
  15052. the string representation of it.
  15053. Return the position where this entry starts, or nil if there is no such entry."
  15054. (interactive "sID: ")
  15055. (let ((id (cond
  15056. ((stringp ident) ident)
  15057. ((symbolp ident) (symbol-name ident))
  15058. ((numberp ident) (number-to-string ident))
  15059. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15060. (org-with-wide-buffer (org-find-property "ID" id))))
  15061. ;;;; Timestamps
  15062. (defvar org-last-changed-timestamp nil)
  15063. (defvar org-last-inserted-timestamp nil
  15064. "The last time stamp inserted with `org-insert-time-stamp'.")
  15065. (defun org-time-stamp (arg &optional inactive)
  15066. "Prompt for a date/time and insert a time stamp.
  15067. If the user specifies a time like HH:MM or if this command is
  15068. called with at least one prefix argument, the time stamp contains
  15069. the date and the time. Otherwise, only the date is included.
  15070. All parts of a date not specified by the user are filled in from
  15071. the timestamp at point, if any, or the current date/time
  15072. otherwise.
  15073. If there is already a timestamp at the cursor, it is replaced.
  15074. With two universal prefix arguments, insert an active timestamp
  15075. with the current time without prompting the user.
  15076. When called from lisp, the timestamp is inactive if INACTIVE is
  15077. non-nil."
  15078. (interactive "P")
  15079. (let* ((ts (cond
  15080. ((org-at-date-range-p t)
  15081. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15082. ((org-at-timestamp-p 'lax) (match-string 0))))
  15083. ;; Default time is either the timestamp at point or today.
  15084. ;; When entering a range, only the range start is considered.
  15085. (default-time (if (not ts) (current-time)
  15086. (apply #'encode-time (org-parse-time-string ts))))
  15087. (default-input (and ts (org-get-compact-tod ts)))
  15088. (repeater (and ts
  15089. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15090. (match-string 0 ts)))
  15091. org-time-was-given
  15092. org-end-time-was-given
  15093. (time
  15094. (and (if (equal arg '(16)) (current-time)
  15095. ;; Preserve `this-command' and `last-command'.
  15096. (let ((this-command this-command)
  15097. (last-command last-command))
  15098. (org-read-date
  15099. arg 'totime nil nil default-time default-input
  15100. inactive))))))
  15101. (cond
  15102. ((and ts
  15103. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15104. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15105. (insert "--")
  15106. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15107. (ts
  15108. ;; Make sure we're on a timestamp. When in the middle of a date
  15109. ;; range, move arbitrarily to range end.
  15110. (unless (org-at-timestamp-p 'lax)
  15111. (skip-chars-forward "-")
  15112. (org-at-timestamp-p 'lax))
  15113. (replace-match "")
  15114. (setq org-last-changed-timestamp
  15115. (org-insert-time-stamp
  15116. time (or org-time-was-given arg)
  15117. inactive nil nil (list org-end-time-was-given)))
  15118. (when repeater
  15119. (backward-char)
  15120. (insert " " repeater)
  15121. (setq org-last-changed-timestamp
  15122. (concat (substring org-last-inserted-timestamp 0 -1)
  15123. " " repeater ">")))
  15124. (message "Timestamp updated"))
  15125. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15126. (t (org-insert-time-stamp
  15127. time (or org-time-was-given arg) inactive nil nil
  15128. (list org-end-time-was-given))))))
  15129. ;; FIXME: can we use this for something else, like computing time differences?
  15130. (defun org-get-compact-tod (s)
  15131. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15132. (let* ((t1 (match-string 1 s))
  15133. (h1 (string-to-number (match-string 2 s)))
  15134. (m1 (string-to-number (match-string 3 s)))
  15135. (t2 (and (match-end 4) (match-string 5 s)))
  15136. (h2 (and t2 (string-to-number (match-string 6 s))))
  15137. (m2 (and t2 (string-to-number (match-string 7 s))))
  15138. dh dm)
  15139. (if (not t2)
  15140. t1
  15141. (setq dh (- h2 h1) dm (- m2 m1))
  15142. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15143. (concat t1 "+" (number-to-string dh)
  15144. (and (/= 0 dm) (format ":%02d" dm)))))))
  15145. (defun org-time-stamp-inactive (&optional arg)
  15146. "Insert an inactive time stamp.
  15147. An inactive time stamp is enclosed in square brackets instead of angle
  15148. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15149. does not link to the calendar and cannot be changed with the S-cursor keys.
  15150. So these are more for recording a certain time/date."
  15151. (interactive "P")
  15152. (org-time-stamp arg 'inactive))
  15153. (defvar org-date-ovl (make-overlay 1 1))
  15154. (overlay-put org-date-ovl 'face 'org-date-selected)
  15155. (delete-overlay org-date-ovl)
  15156. (defvar org-ans1) ; dynamically scoped parameter
  15157. (defvar org-ans2) ; dynamically scoped parameter
  15158. (defvar org-plain-time-of-day-regexp) ; defined below
  15159. (defvar org-overriding-default-time nil) ; dynamically scoped
  15160. (defvar org-read-date-overlay nil)
  15161. (defvar org-dcst nil) ; dynamically scoped
  15162. (defvar org-read-date-history nil)
  15163. (defvar org-read-date-final-answer nil)
  15164. (defvar org-read-date-analyze-futurep nil)
  15165. (defvar org-read-date-analyze-forced-year nil)
  15166. (defvar org-read-date-inactive)
  15167. (defvar org-read-date-minibuffer-local-map
  15168. (let* ((map (make-sparse-keymap)))
  15169. (set-keymap-parent map minibuffer-local-map)
  15170. (org-defkey map (kbd ".")
  15171. (lambda () (interactive)
  15172. ;; Are we at the beginning of the prompt?
  15173. (if (looking-back "^[^:]+: "
  15174. (let ((inhibit-field-text-motion t))
  15175. (line-beginning-position)))
  15176. (org-eval-in-calendar '(calendar-goto-today))
  15177. (insert "."))))
  15178. (org-defkey map (kbd "C-.")
  15179. (lambda () (interactive)
  15180. (org-eval-in-calendar '(calendar-goto-today))))
  15181. (org-defkey map [(meta shift left)]
  15182. (lambda () (interactive)
  15183. (org-eval-in-calendar '(calendar-backward-month 1))))
  15184. (org-defkey map [(meta shift right)]
  15185. (lambda () (interactive)
  15186. (org-eval-in-calendar '(calendar-forward-month 1))))
  15187. (org-defkey map [(meta shift up)]
  15188. (lambda () (interactive)
  15189. (org-eval-in-calendar '(calendar-backward-year 1))))
  15190. (org-defkey map [(meta shift down)]
  15191. (lambda () (interactive)
  15192. (org-eval-in-calendar '(calendar-forward-year 1))))
  15193. (org-defkey map [?\e (shift left)]
  15194. (lambda () (interactive)
  15195. (org-eval-in-calendar '(calendar-backward-month 1))))
  15196. (org-defkey map [?\e (shift right)]
  15197. (lambda () (interactive)
  15198. (org-eval-in-calendar '(calendar-forward-month 1))))
  15199. (org-defkey map [?\e (shift up)]
  15200. (lambda () (interactive)
  15201. (org-eval-in-calendar '(calendar-backward-year 1))))
  15202. (org-defkey map [?\e (shift down)]
  15203. (lambda () (interactive)
  15204. (org-eval-in-calendar '(calendar-forward-year 1))))
  15205. (org-defkey map [(shift up)]
  15206. (lambda () (interactive)
  15207. (org-eval-in-calendar '(calendar-backward-week 1))))
  15208. (org-defkey map [(shift down)]
  15209. (lambda () (interactive)
  15210. (org-eval-in-calendar '(calendar-forward-week 1))))
  15211. (org-defkey map [(shift left)]
  15212. (lambda () (interactive)
  15213. (org-eval-in-calendar '(calendar-backward-day 1))))
  15214. (org-defkey map [(shift right)]
  15215. (lambda () (interactive)
  15216. (org-eval-in-calendar '(calendar-forward-day 1))))
  15217. (org-defkey map "!"
  15218. (lambda () (interactive)
  15219. (org-eval-in-calendar '(diary-view-entries))
  15220. (message "")))
  15221. (org-defkey map ">"
  15222. (lambda () (interactive)
  15223. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15224. (org-defkey map "<"
  15225. (lambda () (interactive)
  15226. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15227. (org-defkey map "\C-v"
  15228. (lambda () (interactive)
  15229. (org-eval-in-calendar
  15230. '(calendar-scroll-left-three-months 1))))
  15231. (org-defkey map "\M-v"
  15232. (lambda () (interactive)
  15233. (org-eval-in-calendar
  15234. '(calendar-scroll-right-three-months 1))))
  15235. map)
  15236. "Keymap for minibuffer commands when using `org-read-date'.")
  15237. (defvar org-def)
  15238. (defvar org-defdecode)
  15239. (defvar org-with-time)
  15240. (defvar calendar-setup) ; Dynamically scoped.
  15241. (defun org-read-date (&optional with-time to-time from-string prompt
  15242. default-time default-input inactive)
  15243. "Read a date, possibly a time, and make things smooth for the user.
  15244. The prompt will suggest to enter an ISO date, but you can also enter anything
  15245. which will at least partially be understood by `parse-time-string'.
  15246. Unrecognized parts of the date will default to the current day, month, year,
  15247. hour and minute. If this command is called to replace a timestamp at point,
  15248. or to enter the second timestamp of a range, the default time is taken
  15249. from the existing stamp. Furthermore, the command prefers the future,
  15250. so if you are giving a date where the year is not given, and the day-month
  15251. combination is already past in the current year, it will assume you
  15252. mean next year. For details, see the manual. A few examples:
  15253. 3-2-5 --> 2003-02-05
  15254. feb 15 --> currentyear-02-15
  15255. 2/15 --> currentyear-02-15
  15256. sep 12 9 --> 2009-09-12
  15257. 12:45 --> today 12:45
  15258. 22 sept 0:34 --> currentyear-09-22 0:34
  15259. 12 --> currentyear-currentmonth-12
  15260. Fri --> nearest Friday after today
  15261. -Tue --> last Tuesday
  15262. etc.
  15263. Furthermore you can specify a relative date by giving, as the *first* thing
  15264. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15265. change in days weeks, months, years.
  15266. With a single plus or minus, the date is relative to today. With a double
  15267. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15268. +4d --> four days from today
  15269. +4 --> same as above
  15270. +2w --> two weeks from today
  15271. ++5 --> five days from default date
  15272. The function understands only English month and weekday abbreviations.
  15273. While prompting, a calendar is popped up - you can also select the
  15274. date with the mouse (button 1). The calendar shows a period of three
  15275. months. To scroll it to other months, use the keys `>' and `<'.
  15276. If you don't like the calendar, turn it off with
  15277. (setq org-read-date-popup-calendar nil)
  15278. With optional argument TO-TIME, the date will immediately be converted
  15279. to an internal time.
  15280. With an optional argument WITH-TIME, the prompt will suggest to
  15281. also insert a time. Note that when WITH-TIME is not set, you can
  15282. still enter a time, and this function will inform the calling routine
  15283. about this change. The calling routine may then choose to change the
  15284. format used to insert the time stamp into the buffer to include the time.
  15285. With optional argument FROM-STRING, read from this string instead from
  15286. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15287. the time/date that is used for everything that is not specified by the
  15288. user."
  15289. (require 'parse-time)
  15290. (let* ((org-with-time with-time)
  15291. (org-time-stamp-rounding-minutes
  15292. (if (equal org-with-time '(16))
  15293. '(0 0)
  15294. org-time-stamp-rounding-minutes))
  15295. (org-dcst org-display-custom-times)
  15296. (ct (org-current-time))
  15297. (org-def (or org-overriding-default-time default-time ct))
  15298. (org-defdecode (decode-time org-def))
  15299. (cur-frame (selected-frame))
  15300. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15301. (calendar-setup
  15302. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15303. (calendar-move-hook nil)
  15304. (calendar-view-diary-initially-flag nil)
  15305. (calendar-view-holidays-initially-flag nil)
  15306. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15307. ;; Rationalize `org-def' and `org-defdecode', if required.
  15308. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15309. (setf (nth 2 org-defdecode) -1)
  15310. (setf (nth 1 org-defdecode) 59)
  15311. (setq org-def (apply #'encode-time org-defdecode))
  15312. (setq org-defdecode (decode-time org-def)))
  15313. (let* ((timestr (format-time-string
  15314. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15315. org-def))
  15316. (prompt (concat (if prompt (concat prompt " ") "")
  15317. (format "Date+time [%s]: " timestr))))
  15318. (cond
  15319. (from-string (setq ans from-string))
  15320. (org-read-date-popup-calendar
  15321. (save-excursion
  15322. (save-window-excursion
  15323. (calendar)
  15324. (when (eq calendar-setup 'calendar-only)
  15325. (setq cal-frame
  15326. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15327. (select-frame cal-frame))
  15328. (org-eval-in-calendar '(setq cursor-type nil) t)
  15329. (unwind-protect
  15330. (progn
  15331. (calendar-forward-day (- (time-to-days org-def)
  15332. (calendar-absolute-from-gregorian
  15333. (calendar-current-date))))
  15334. (org-eval-in-calendar nil t)
  15335. (let* ((old-map (current-local-map))
  15336. (map (copy-keymap calendar-mode-map))
  15337. (minibuffer-local-map
  15338. (copy-keymap org-read-date-minibuffer-local-map)))
  15339. (org-defkey map (kbd "RET") 'org-calendar-select)
  15340. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15341. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15342. (unwind-protect
  15343. (progn
  15344. (use-local-map map)
  15345. (setq org-read-date-inactive inactive)
  15346. (add-hook 'post-command-hook 'org-read-date-display)
  15347. (setq org-ans0
  15348. (read-string prompt
  15349. default-input
  15350. 'org-read-date-history
  15351. nil))
  15352. ;; org-ans0: from prompt
  15353. ;; org-ans1: from mouse click
  15354. ;; org-ans2: from calendar motion
  15355. (setq ans
  15356. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15357. (remove-hook 'post-command-hook 'org-read-date-display)
  15358. (use-local-map old-map)
  15359. (when org-read-date-overlay
  15360. (delete-overlay org-read-date-overlay)
  15361. (setq org-read-date-overlay nil)))))
  15362. (bury-buffer "*Calendar*")
  15363. (when cal-frame
  15364. (delete-frame cal-frame)
  15365. (select-frame-set-input-focus cur-frame))))))
  15366. (t ; Naked prompt only
  15367. (unwind-protect
  15368. (setq ans (read-string prompt default-input
  15369. 'org-read-date-history timestr))
  15370. (when org-read-date-overlay
  15371. (delete-overlay org-read-date-overlay)
  15372. (setq org-read-date-overlay nil))))))
  15373. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15374. (when org-read-date-analyze-forced-year
  15375. (message "Year was forced into %s"
  15376. (if org-read-date-force-compatible-dates
  15377. "compatible range (1970-2037)"
  15378. "range representable on this machine"))
  15379. (ding))
  15380. ;; One round trip to get rid of 34th of August and stuff like that....
  15381. (setq final (decode-time (apply 'encode-time final)))
  15382. (setq org-read-date-final-answer ans)
  15383. (if to-time
  15384. (apply 'encode-time final)
  15385. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15386. (format "%04d-%02d-%02d %02d:%02d"
  15387. (nth 5 final) (nth 4 final) (nth 3 final)
  15388. (nth 2 final) (nth 1 final))
  15389. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15390. (defun org-read-date-display ()
  15391. "Display the current date prompt interpretation in the minibuffer."
  15392. (when org-read-date-display-live
  15393. (when org-read-date-overlay
  15394. (delete-overlay org-read-date-overlay))
  15395. (when (minibufferp (current-buffer))
  15396. (save-excursion
  15397. (end-of-line 1)
  15398. (while (not (equal (buffer-substring
  15399. (max (point-min) (- (point) 4)) (point))
  15400. " "))
  15401. (insert " ")))
  15402. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15403. " " (or org-ans1 org-ans2)))
  15404. (org-end-time-was-given nil)
  15405. (f (org-read-date-analyze ans org-def org-defdecode))
  15406. (fmts (if org-dcst
  15407. org-time-stamp-custom-formats
  15408. org-time-stamp-formats))
  15409. (fmt (if (or org-with-time
  15410. (and (boundp 'org-time-was-given) org-time-was-given))
  15411. (cdr fmts)
  15412. (car fmts)))
  15413. (txt (format-time-string fmt (apply 'encode-time f)))
  15414. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15415. (txt (concat "=> " txt)))
  15416. (when (and org-end-time-was-given
  15417. (string-match org-plain-time-of-day-regexp txt))
  15418. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15419. org-end-time-was-given
  15420. (substring txt (match-end 0)))))
  15421. (when org-read-date-analyze-futurep
  15422. (setq txt (concat txt " (=>F)")))
  15423. (setq org-read-date-overlay
  15424. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15425. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15426. (defun org-read-date-analyze (ans def defdecode)
  15427. "Analyze the combined answer of the date prompt."
  15428. ;; FIXME: cleanup and comment
  15429. ;; Pass `current-time' result to `decode-time' (instead of calling
  15430. ;; without arguments) so that only `current-time' has to be
  15431. ;; overridden in tests.
  15432. (let ((org-def def)
  15433. (org-defdecode defdecode)
  15434. (nowdecode (decode-time (current-time)))
  15435. delta deltan deltaw deltadef year month day
  15436. hour minute second wday pm h2 m2 tl wday1
  15437. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15438. (setq org-read-date-analyze-futurep nil
  15439. org-read-date-analyze-forced-year nil)
  15440. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15441. (setq ans "+0"))
  15442. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15443. (setq ans (replace-match "" t t ans)
  15444. deltan (car delta)
  15445. deltaw (nth 1 delta)
  15446. deltadef (nth 2 delta)))
  15447. ;; Check if there is an iso week date in there. If yes, store the
  15448. ;; info and postpone interpreting it until the rest of the parsing
  15449. ;; is done.
  15450. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15451. (setq iso-year (when (match-end 1)
  15452. (org-small-year-to-year
  15453. (string-to-number (match-string 1 ans))))
  15454. iso-weekday (when (match-end 3)
  15455. (string-to-number (match-string 3 ans)))
  15456. iso-week (string-to-number (match-string 2 ans)))
  15457. (setq ans (replace-match "" t t ans)))
  15458. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15459. (when (string-match
  15460. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15461. (setq year (if (match-end 2)
  15462. (string-to-number (match-string 2 ans))
  15463. (progn (setq kill-year t)
  15464. (string-to-number (format-time-string "%Y"))))
  15465. month (string-to-number (match-string 3 ans))
  15466. day (string-to-number (match-string 4 ans)))
  15467. (setq year (org-small-year-to-year year))
  15468. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15469. t nil ans)))
  15470. ;; Help matching dotted european dates
  15471. (when (string-match
  15472. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15473. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15474. (setq kill-year t)
  15475. (string-to-number (format-time-string "%Y")))
  15476. day (string-to-number (match-string 1 ans))
  15477. month (string-to-number (match-string 2 ans))
  15478. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15479. t nil ans)))
  15480. ;; Help matching american dates, like 5/30 or 5/30/7
  15481. (when (string-match
  15482. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15483. (setq year (if (match-end 4)
  15484. (string-to-number (match-string 4 ans))
  15485. (progn (setq kill-year t)
  15486. (string-to-number (format-time-string "%Y"))))
  15487. month (string-to-number (match-string 1 ans))
  15488. day (string-to-number (match-string 2 ans)))
  15489. (setq year (org-small-year-to-year year))
  15490. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15491. t nil ans)))
  15492. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15493. ;; If there is a time with am/pm, and *no* time without it, we convert
  15494. ;; so that matching will be successful.
  15495. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15496. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15497. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15498. (setq hour (string-to-number (match-string 1 ans))
  15499. minute (if (match-end 3)
  15500. (string-to-number (match-string 3 ans))
  15501. 0)
  15502. pm (equal ?p
  15503. (string-to-char (downcase (match-string 4 ans)))))
  15504. (if (and (= hour 12) (not pm))
  15505. (setq hour 0)
  15506. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15507. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15508. t t ans))))
  15509. ;; Check if a time range is given as a duration
  15510. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15511. (setq hour (string-to-number (match-string 1 ans))
  15512. h2 (+ hour (string-to-number (match-string 3 ans)))
  15513. minute (string-to-number (match-string 2 ans))
  15514. m2 (+ minute (if (match-end 5) (string-to-number
  15515. (match-string 5 ans))0)))
  15516. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15517. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15518. t t ans)))
  15519. ;; Check if there is a time range
  15520. (when (boundp 'org-end-time-was-given)
  15521. (setq org-time-was-given nil)
  15522. (when (and (string-match org-plain-time-of-day-regexp ans)
  15523. (match-end 8))
  15524. (setq org-end-time-was-given (match-string 8 ans))
  15525. (setq ans (concat (substring ans 0 (match-beginning 7))
  15526. (substring ans (match-end 7))))))
  15527. (setq tl (parse-time-string ans)
  15528. day (or (nth 3 tl) (nth 3 org-defdecode))
  15529. month
  15530. (cond ((nth 4 tl))
  15531. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15532. ;; Day was specified. Make sure DAY+MONTH
  15533. ;; combination happens in the future.
  15534. ((nth 3 tl)
  15535. (setq futurep t)
  15536. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15537. (nth 4 nowdecode)))
  15538. (t (nth 4 org-defdecode)))
  15539. year
  15540. (cond ((and (not kill-year) (nth 5 tl)))
  15541. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15542. ;; Month was guessed in the future and is at least
  15543. ;; equal to NOWDECODE's. Fix year accordingly.
  15544. (futurep
  15545. (if (or (> month (nth 4 nowdecode))
  15546. (>= day (nth 3 nowdecode)))
  15547. (nth 5 nowdecode)
  15548. (1+ (nth 5 nowdecode))))
  15549. ;; Month was specified. Make sure MONTH+YEAR
  15550. ;; combination happens in the future.
  15551. ((nth 4 tl)
  15552. (setq futurep t)
  15553. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15554. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15555. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15556. (t (nth 5 nowdecode))))
  15557. (t (nth 5 org-defdecode)))
  15558. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15559. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15560. second (or (nth 0 tl) 0)
  15561. wday (nth 6 tl))
  15562. (when (and (eq org-read-date-prefer-future 'time)
  15563. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15564. (equal day (nth 3 nowdecode))
  15565. (equal month (nth 4 nowdecode))
  15566. (equal year (nth 5 nowdecode))
  15567. (nth 2 tl)
  15568. (or (< (nth 2 tl) (nth 2 nowdecode))
  15569. (and (= (nth 2 tl) (nth 2 nowdecode))
  15570. (nth 1 tl)
  15571. (< (nth 1 tl) (nth 1 nowdecode)))))
  15572. (setq day (1+ day)
  15573. futurep t))
  15574. ;; Special date definitions below
  15575. (cond
  15576. (iso-week
  15577. ;; There was an iso week
  15578. (require 'cal-iso)
  15579. (setq futurep nil)
  15580. (setq year (or iso-year year)
  15581. day (or iso-weekday wday 1)
  15582. wday nil ; to make sure that the trigger below does not match
  15583. iso-date (calendar-gregorian-from-absolute
  15584. (calendar-iso-to-absolute
  15585. (list iso-week day year))))
  15586. ; FIXME: Should we also push ISO weeks into the future?
  15587. ; (when (and org-read-date-prefer-future
  15588. ; (not iso-year)
  15589. ; (< (calendar-absolute-from-gregorian iso-date)
  15590. ; (time-to-days (current-time))))
  15591. ; (setq year (1+ year)
  15592. ; iso-date (calendar-gregorian-from-absolute
  15593. ; (calendar-iso-to-absolute
  15594. ; (list iso-week day year)))))
  15595. (setq month (car iso-date)
  15596. year (nth 2 iso-date)
  15597. day (nth 1 iso-date)))
  15598. (deltan
  15599. (setq futurep nil)
  15600. (unless deltadef
  15601. ;; Pass `current-time' result to `decode-time' (instead of
  15602. ;; calling without arguments) so that only `current-time' has
  15603. ;; to be overridden in tests.
  15604. (let ((now (decode-time (current-time))))
  15605. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15606. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15607. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15608. ((equal deltaw "m") (setq month (+ month deltan)))
  15609. ((equal deltaw "y") (setq year (+ year deltan)))))
  15610. ((and wday (not (nth 3 tl)))
  15611. ;; Weekday was given, but no day, so pick that day in the week
  15612. ;; on or after the derived date.
  15613. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15614. (unless (equal wday wday1)
  15615. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15616. (when (and (boundp 'org-time-was-given)
  15617. (nth 2 tl))
  15618. (setq org-time-was-given t))
  15619. (when (< year 100) (setq year (+ 2000 year)))
  15620. ;; Check of the date is representable
  15621. (if org-read-date-force-compatible-dates
  15622. (progn
  15623. (when (< year 1970)
  15624. (setq year 1970 org-read-date-analyze-forced-year t))
  15625. (when (> year 2037)
  15626. (setq year 2037 org-read-date-analyze-forced-year t)))
  15627. (condition-case nil
  15628. (ignore (encode-time second minute hour day month year))
  15629. (error
  15630. (setq year (nth 5 org-defdecode))
  15631. (setq org-read-date-analyze-forced-year t))))
  15632. (setq org-read-date-analyze-futurep futurep)
  15633. (list second minute hour day month year)))
  15634. (defvar parse-time-weekdays)
  15635. (defun org-read-date-get-relative (s today default)
  15636. "Check string S for special relative date string.
  15637. TODAY and DEFAULT are internal times, for today and for a default.
  15638. Return shift list (N what def-flag)
  15639. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15640. N is the number of WHATs to shift.
  15641. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15642. the DEFAULT date rather than TODAY."
  15643. (require 'parse-time)
  15644. (when (and
  15645. (string-match
  15646. (concat
  15647. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15648. "\\([0-9]+\\)?"
  15649. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15650. "\\([ \t]\\|$\\)") s)
  15651. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15652. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15653. (string-to-char (substring (match-string 1 s) -1))
  15654. ?+))
  15655. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15656. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15657. (what (if (match-end 3) (match-string 3 s) "d"))
  15658. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15659. (date (if rel default today))
  15660. (wday (nth 6 (decode-time date)))
  15661. delta)
  15662. (if wday1
  15663. (progn
  15664. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15665. (when (= delta 0) (setq delta 7))
  15666. (when (= dir ?-)
  15667. (setq delta (- delta 7))
  15668. (when (= delta 0) (setq delta -7)))
  15669. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15670. (list delta "d" rel))
  15671. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15672. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15673. "Turn a user-specified date into the internal representation.
  15674. The internal representation needed by the calendar is (month day year).
  15675. This is a wrapper to handle the brain-dead convention in calendar that
  15676. user function argument order change dependent on argument order."
  15677. (pcase calendar-date-style
  15678. (`american (list arg1 arg2 arg3))
  15679. (`european (list arg2 arg1 arg3))
  15680. (`iso (list arg2 arg3 arg1))))
  15681. (defun org-eval-in-calendar (form &optional keepdate)
  15682. "Eval FORM in the calendar window and return to current window.
  15683. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15684. (let ((sf (selected-frame))
  15685. (sw (selected-window)))
  15686. (select-window (get-buffer-window "*Calendar*" t))
  15687. (eval form)
  15688. (when (and (not keepdate) (calendar-cursor-to-date))
  15689. (let* ((date (calendar-cursor-to-date))
  15690. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15691. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15692. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15693. (select-window sw)
  15694. (select-frame-set-input-focus sf)))
  15695. (defun org-calendar-select ()
  15696. "Return to `org-read-date' with the date currently selected.
  15697. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15698. (interactive)
  15699. (when (calendar-cursor-to-date)
  15700. (let* ((date (calendar-cursor-to-date))
  15701. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15702. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15703. (when (active-minibuffer-window) (exit-minibuffer))))
  15704. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15705. "Insert a date stamp for the date given by the internal TIME.
  15706. See `format-time-string' for the format of TIME.
  15707. WITH-HM means use the stamp format that includes the time of the day.
  15708. INACTIVE means use square brackets instead of angular ones, so that the
  15709. stamp will not contribute to the agenda.
  15710. PRE and POST are optional strings to be inserted before and after the
  15711. stamp.
  15712. The command returns the inserted time stamp."
  15713. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15714. stamp)
  15715. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15716. (insert-before-markers (or pre ""))
  15717. (when (listp extra)
  15718. (setq extra (car extra))
  15719. (if (and (stringp extra)
  15720. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15721. (setq extra (format "-%02d:%02d"
  15722. (string-to-number (match-string 1 extra))
  15723. (string-to-number (match-string 2 extra))))
  15724. (setq extra nil)))
  15725. (when extra
  15726. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15727. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15728. (insert-before-markers (or post ""))
  15729. (setq org-last-inserted-timestamp stamp)))
  15730. (defun org-toggle-time-stamp-overlays ()
  15731. "Toggle the use of custom time stamp formats."
  15732. (interactive)
  15733. (setq org-display-custom-times (not org-display-custom-times))
  15734. (unless org-display-custom-times
  15735. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15736. (while (setq p (next-single-property-change p 'display))
  15737. (when (and (get-text-property p 'display)
  15738. (eq (get-text-property p 'face) 'org-date))
  15739. (remove-text-properties
  15740. p (setq p (next-single-property-change p 'display))
  15741. '(display t))))
  15742. (set-buffer-modified-p bmp)))
  15743. (org-restart-font-lock)
  15744. (setq org-table-may-need-update t)
  15745. (if org-display-custom-times
  15746. (message "Time stamps are overlaid with custom format")
  15747. (message "Time stamp overlays removed")))
  15748. (defun org-display-custom-time (beg end)
  15749. "Overlay modified time stamp format over timestamp between BEG and END."
  15750. (let* ((ts (buffer-substring beg end))
  15751. t1 with-hm tf time str (off 0))
  15752. (save-match-data
  15753. (setq t1 (org-parse-time-string ts t))
  15754. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15755. (setq off (- (match-end 0) (match-beginning 0)))))
  15756. (setq end (- end off))
  15757. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15758. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15759. time (org-fix-decoded-time t1)
  15760. str (org-add-props
  15761. (format-time-string
  15762. (substring tf 1 -1) (apply 'encode-time time))
  15763. nil 'mouse-face 'highlight))
  15764. (put-text-property beg end 'display str)))
  15765. (defun org-fix-decoded-time (time)
  15766. "Set 0 instead of nil for the first 6 elements of time.
  15767. Don't touch the rest."
  15768. (let ((n 0))
  15769. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15770. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15771. "Difference between TIMESTAMP-STRING and now in days.
  15772. If SECONDS is non-nil, return the difference in seconds."
  15773. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15774. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15775. (funcall fdiff (current-time)))))
  15776. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15777. "Is the time in TIMESTAMP-STRING close to the current date?"
  15778. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15779. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15780. (not (org-entry-is-done-p))))
  15781. (defun org-get-wdays (ts &optional delay zero-delay)
  15782. "Get the deadline lead time appropriate for timestring TS.
  15783. When DELAY is non-nil, get the delay time for scheduled items
  15784. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15785. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15786. don't try to find the delay cookie in the scheduled timestamp."
  15787. (let ((tv (if delay org-scheduled-delay-days
  15788. org-deadline-warning-days)))
  15789. (cond
  15790. ((or (and delay (< tv 0))
  15791. (and delay zero-delay (<= tv 0))
  15792. (and (not delay) (<= tv 0)))
  15793. ;; Enforce this value no matter what
  15794. (- tv))
  15795. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15796. ;; lead time is specified.
  15797. (floor (* (string-to-number (match-string 1 ts))
  15798. (cdr (assoc (match-string 2 ts)
  15799. '(("d" . 1) ("w" . 7)
  15800. ("m" . 30.4) ("y" . 365.25)
  15801. ("h" . 0.041667)))))))
  15802. ;; go for the default.
  15803. (t tv))))
  15804. (defun org-calendar-select-mouse (ev)
  15805. "Return to `org-read-date' with the date currently selected.
  15806. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15807. (interactive "e")
  15808. (mouse-set-point ev)
  15809. (when (calendar-cursor-to-date)
  15810. (let* ((date (calendar-cursor-to-date))
  15811. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15812. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15813. (when (active-minibuffer-window) (exit-minibuffer))))
  15814. (defun org-check-deadlines (ndays)
  15815. "Check if there are any deadlines due or past due.
  15816. A deadline is considered due if it happens within `org-deadline-warning-days'
  15817. days from today's date. If the deadline appears in an entry marked DONE,
  15818. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15819. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15820. are shown."
  15821. (interactive "P")
  15822. (let* ((org-warn-days
  15823. (cond
  15824. ((equal ndays '(4)) 100000)
  15825. (ndays (prefix-numeric-value ndays))
  15826. (t (abs org-deadline-warning-days))))
  15827. (case-fold-search nil)
  15828. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15829. (callback
  15830. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15831. (message "%d deadlines past-due or due within %d days"
  15832. (org-occur regexp nil callback)
  15833. org-warn-days)))
  15834. (defsubst org-re-timestamp (type)
  15835. "Return a regexp for timestamp TYPE.
  15836. Allowed values for TYPE are:
  15837. all: all timestamps
  15838. active: only active timestamps (<...>)
  15839. inactive: only inactive timestamps ([...])
  15840. scheduled: only scheduled timestamps
  15841. deadline: only deadline timestamps
  15842. closed: only closed time-stamps
  15843. When TYPE is nil, fall back on returning a regexp that matches
  15844. both scheduled and deadline timestamps."
  15845. (cl-case type
  15846. (all org-ts-regexp-both)
  15847. (active org-ts-regexp)
  15848. (inactive org-ts-regexp-inactive)
  15849. (scheduled org-scheduled-time-regexp)
  15850. (deadline org-deadline-time-regexp)
  15851. (closed org-closed-time-regexp)
  15852. (otherwise
  15853. (concat "\\<"
  15854. (regexp-opt (list org-deadline-string org-scheduled-string))
  15855. " *<\\([^>]+\\)>"))))
  15856. (defun org-check-before-date (d)
  15857. "Check if there are deadlines or scheduled entries before date D."
  15858. (interactive (list (org-read-date)))
  15859. (let* ((case-fold-search nil)
  15860. (regexp (org-re-timestamp org-ts-type))
  15861. (ts-type org-ts-type)
  15862. (callback
  15863. (lambda ()
  15864. (let ((match (match-string 1)))
  15865. (and (if (memq ts-type '(active inactive all))
  15866. (eq (org-element-type (save-excursion
  15867. (backward-char)
  15868. (org-element-context)))
  15869. 'timestamp)
  15870. (org-at-planning-p))
  15871. (time-less-p
  15872. (org-time-string-to-time match)
  15873. (org-time-string-to-time d)))))))
  15874. (message "%d entries before %s"
  15875. (org-occur regexp nil callback)
  15876. d)))
  15877. (defun org-check-after-date (d)
  15878. "Check if there are deadlines or scheduled entries after date D."
  15879. (interactive (list (org-read-date)))
  15880. (let* ((case-fold-search nil)
  15881. (regexp (org-re-timestamp org-ts-type))
  15882. (ts-type org-ts-type)
  15883. (callback
  15884. (lambda ()
  15885. (let ((match (match-string 1)))
  15886. (and (if (memq ts-type '(active inactive all))
  15887. (eq (org-element-type (save-excursion
  15888. (backward-char)
  15889. (org-element-context)))
  15890. 'timestamp)
  15891. (org-at-planning-p))
  15892. (not (time-less-p
  15893. (org-time-string-to-time match)
  15894. (org-time-string-to-time d))))))))
  15895. (message "%d entries after %s"
  15896. (org-occur regexp nil callback)
  15897. d)))
  15898. (defun org-check-dates-range (start-date end-date)
  15899. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15900. (interactive (list (org-read-date nil nil nil "Range starts")
  15901. (org-read-date nil nil nil "Range end")))
  15902. (let ((case-fold-search nil)
  15903. (regexp (org-re-timestamp org-ts-type))
  15904. (callback
  15905. (let ((type org-ts-type))
  15906. (lambda ()
  15907. (let ((match (match-string 1)))
  15908. (and
  15909. (if (memq type '(active inactive all))
  15910. (eq (org-element-type (save-excursion
  15911. (backward-char)
  15912. (org-element-context)))
  15913. 'timestamp)
  15914. (org-at-planning-p))
  15915. (not (time-less-p
  15916. (org-time-string-to-time match)
  15917. (org-time-string-to-time start-date)))
  15918. (time-less-p
  15919. (org-time-string-to-time match)
  15920. (org-time-string-to-time end-date))))))))
  15921. (message "%d entries between %s and %s"
  15922. (org-occur regexp nil callback) start-date end-date)))
  15923. (defun org-evaluate-time-range (&optional to-buffer)
  15924. "Evaluate a time range by computing the difference between start and end.
  15925. Normally the result is just printed in the echo area, but with prefix arg
  15926. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15927. If the time range is actually in a table, the result is inserted into the
  15928. next column.
  15929. For time difference computation, a year is assumed to be exactly 365
  15930. days in order to avoid rounding problems."
  15931. (interactive "P")
  15932. (or
  15933. (org-clock-update-time-maybe)
  15934. (save-excursion
  15935. (unless (org-at-date-range-p t)
  15936. (goto-char (point-at-bol))
  15937. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15938. (unless (org-at-date-range-p t)
  15939. (user-error "Not at a time-stamp range, and none found in current line")))
  15940. (let* ((ts1 (match-string 1))
  15941. (ts2 (match-string 2))
  15942. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15943. (match-end (match-end 0))
  15944. (time1 (org-time-string-to-time ts1))
  15945. (time2 (org-time-string-to-time ts2))
  15946. (t1 (float-time time1))
  15947. (t2 (float-time time2))
  15948. (diff (abs (- t2 t1)))
  15949. (negative (< (- t2 t1) 0))
  15950. ;; (ys (floor (* 365 24 60 60)))
  15951. (ds (* 24 60 60))
  15952. (hs (* 60 60))
  15953. (fy "%dy %dd %02d:%02d")
  15954. (fy1 "%dy %dd")
  15955. (fd "%dd %02d:%02d")
  15956. (fd1 "%dd")
  15957. (fh "%02d:%02d")
  15958. y d h m align)
  15959. (if havetime
  15960. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15961. y 0
  15962. d (floor (/ diff ds)) diff (mod diff ds)
  15963. h (floor (/ diff hs)) diff (mod diff hs)
  15964. m (floor (/ diff 60)))
  15965. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15966. y 0
  15967. d (floor (+ (/ diff ds) 0.5))
  15968. h 0 m 0))
  15969. (if (not to-buffer)
  15970. (message "%s" (org-make-tdiff-string y d h m))
  15971. (if (org-at-table-p)
  15972. (progn
  15973. (goto-char match-end)
  15974. (setq align t)
  15975. (and (looking-at " *|") (goto-char (match-end 0))))
  15976. (goto-char match-end))
  15977. (when (looking-at
  15978. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15979. (replace-match ""))
  15980. (when negative (insert " -"))
  15981. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15982. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15983. (insert " " (format fh h m))))
  15984. (when align (org-table-align))
  15985. (message "Time difference inserted")))))
  15986. (defun org-make-tdiff-string (y d h m)
  15987. (let ((fmt "")
  15988. (l nil))
  15989. (when (> y 0)
  15990. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15991. (push y l))
  15992. (when (> d 0)
  15993. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15994. (push d l))
  15995. (when (> h 0)
  15996. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15997. (push h l))
  15998. (when (> m 0)
  15999. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16000. (push m l))
  16001. (apply 'format fmt (nreverse l))))
  16002. (defun org-time-string-to-time (s)
  16003. "Convert timestamp string S into internal time."
  16004. (apply #'encode-time (org-parse-time-string s)))
  16005. (defun org-time-string-to-seconds (s)
  16006. "Convert a timestamp string S into a number of seconds."
  16007. (float-time (org-time-string-to-time s)))
  16008. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16009. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16010. "Convert time stamp S to an absolute day number.
  16011. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16012. stamp, get the closest date to DAYNR. If PREFER is
  16013. `past' (respectively `future') return a date past (respectively
  16014. after) or equal to DAYNR.
  16015. POS is the location of time stamp S, as a buffer position in
  16016. BUFFER.
  16017. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16018. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16019. signaled."
  16020. (cond
  16021. ((string-match "\\`%%\\((.*)\\)" s)
  16022. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16023. ;; only able to match individual dates. If it fails, raise an
  16024. ;; error.
  16025. (if (and daynr
  16026. (org-diary-sexp-entry
  16027. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16028. daynr
  16029. (signal 'org-diary-sexp-no-match (list s))))
  16030. (daynr (org-closest-date s daynr prefer))
  16031. (t (time-to-days
  16032. (condition-case errdata
  16033. (apply #'encode-time (org-parse-time-string s))
  16034. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16035. s
  16036. (if (not (and buffer pos)) ""
  16037. (format-message " at %d in buffer `%s'" pos buffer))
  16038. (cdr errdata))))))))
  16039. (defun org-days-to-iso-week (days)
  16040. "Return the iso week number."
  16041. (require 'cal-iso)
  16042. (car (calendar-iso-from-absolute days)))
  16043. (defun org-small-year-to-year (year)
  16044. "Convert 2-digit years into 4-digit years.
  16045. YEAR is expanded into one of the 30 next years, if possible, or
  16046. into a past one. Any year larger than 99 is returned unchanged."
  16047. (if (>= year 100) year
  16048. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16049. (century (/ current 100))
  16050. (offset (- year (% current 100))))
  16051. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16052. ((> offset -70) (+ (* century 100) year))
  16053. (t (+ (* (1+ century) 100) year))))))
  16054. (defun org-time-from-absolute (d)
  16055. "Return the time corresponding to date D.
  16056. D may be an absolute day number, or a calendar-type list (month day year)."
  16057. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16058. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16059. (defvar org-agenda-current-date)
  16060. (defun org-calendar-holiday ()
  16061. "List of holidays, for Diary display in Org mode."
  16062. (require 'holidays)
  16063. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16064. (and hl (mapconcat #'identity hl "; "))))
  16065. (defun org-diary-sexp-entry (sexp entry d)
  16066. "Process a SEXP diary ENTRY for date D."
  16067. (require 'diary-lib)
  16068. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16069. ;; dynamically.
  16070. (let* ((sexp `(let ((entry ,entry)
  16071. (date ',d))
  16072. ,(car (read-from-string sexp))))
  16073. (result (if calendar-debug-sexp (eval sexp)
  16074. (condition-case nil
  16075. (eval sexp)
  16076. (error
  16077. (beep)
  16078. (message "Bad sexp at line %d in %s: %s"
  16079. (org-current-line)
  16080. (buffer-file-name) sexp)
  16081. (sleep-for 2))))))
  16082. (cond ((stringp result) (split-string result "; "))
  16083. ((and (consp result)
  16084. (not (consp (cdr result)))
  16085. (stringp (cdr result))) (cdr result))
  16086. ((and (consp result)
  16087. (stringp (car result))) result)
  16088. (result entry))))
  16089. (defun org-diary-to-ical-string (frombuf)
  16090. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16091. This uses the icalendar.el library."
  16092. (let* ((tmpdir temporary-file-directory)
  16093. (tmpfile (make-temp-name
  16094. (expand-file-name "orgics" tmpdir)))
  16095. buf rtn b e)
  16096. (with-current-buffer frombuf
  16097. (icalendar-export-region (point-min) (point-max) tmpfile)
  16098. (setq buf (find-buffer-visiting tmpfile))
  16099. (set-buffer buf)
  16100. (goto-char (point-min))
  16101. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16102. (setq b (match-beginning 0)))
  16103. (goto-char (point-max))
  16104. (when (re-search-backward "^END:VEVENT" nil t)
  16105. (setq e (match-end 0)))
  16106. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16107. (kill-buffer buf)
  16108. (delete-file tmpfile)
  16109. rtn))
  16110. (defun org-closest-date (start current prefer)
  16111. "Return closest date to CURRENT starting from START.
  16112. CURRENT and START are both time stamps.
  16113. When PREFER is `past', return a date that is either CURRENT or
  16114. past. When PREFER is `future', return a date that is either
  16115. CURRENT or future.
  16116. Only time stamps with a repeater are modified. Any other time
  16117. stamp stay unchanged. In any case, return value is an absolute
  16118. day number."
  16119. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16120. ;; No repeater. Do not shift time stamp.
  16121. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16122. (let ((value (string-to-number (match-string 1 start)))
  16123. (type (match-string 2 start)))
  16124. (if (= 0 value)
  16125. ;; Repeater with a 0-value is considered as void.
  16126. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16127. (let* ((base (org-date-to-gregorian start))
  16128. (target (org-date-to-gregorian current))
  16129. (sday (calendar-absolute-from-gregorian base))
  16130. (cday (calendar-absolute-from-gregorian target))
  16131. n1 n2)
  16132. ;; If START is already past CURRENT, just return START.
  16133. (if (<= cday sday) sday
  16134. ;; Compute closest date before (N1) and closest date past
  16135. ;; (N2) CURRENT.
  16136. (pcase type
  16137. ("h"
  16138. (let ((missing-hours
  16139. (mod (+ (- (* 24 (- cday sday))
  16140. (nth 2 (org-parse-time-string start)))
  16141. org-extend-today-until)
  16142. value)))
  16143. (setf n1 (if (= missing-hours 0) cday
  16144. (- cday (1+ (/ missing-hours 24)))))
  16145. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16146. ((or "d" "w")
  16147. (let ((value (if (equal type "w") (* 7 value) value)))
  16148. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16149. (setf n2 (+ n1 value))))
  16150. ("m"
  16151. (let* ((add-months
  16152. (lambda (d n)
  16153. ;; Add N months to gregorian date D, i.e.,
  16154. ;; a list (MONTH DAY YEAR). Return a valid
  16155. ;; gregorian date.
  16156. (let ((m (+ (nth 0 d) n)))
  16157. (list (mod m 12)
  16158. (nth 1 d)
  16159. (+ (/ m 12) (nth 2 d))))))
  16160. (months ; Complete months to TARGET.
  16161. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16162. (- (nth 0 target) (nth 0 base))
  16163. ;; If START's day is greater than
  16164. ;; TARGET's, remove incomplete month.
  16165. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16166. value)
  16167. value))
  16168. (before (funcall add-months base months)))
  16169. (setf n1 (calendar-absolute-from-gregorian before))
  16170. (setf n2
  16171. (calendar-absolute-from-gregorian
  16172. (funcall add-months before value)))))
  16173. (_
  16174. (let* ((d (nth 1 base))
  16175. (m (nth 0 base))
  16176. (y (nth 2 base))
  16177. (years ; Complete years to TARGET.
  16178. (* (/ (- (nth 2 target)
  16179. y
  16180. ;; If START's month and day are
  16181. ;; greater than TARGET's, remove
  16182. ;; incomplete year.
  16183. (if (or (> (nth 0 target) m)
  16184. (and (= (nth 0 target) m)
  16185. (> (nth 1 target) d)))
  16186. 0
  16187. 1))
  16188. value)
  16189. value))
  16190. (before (list m d (+ y years))))
  16191. (setf n1 (calendar-absolute-from-gregorian before))
  16192. (setf n2 (calendar-absolute-from-gregorian
  16193. (list m d (+ (nth 2 before) value)))))))
  16194. ;; Handle PREFER parameter, if any.
  16195. (cond
  16196. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16197. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16198. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16199. (defun org-date-to-gregorian (d)
  16200. "Turn any specification of date D into a Gregorian date for the calendar."
  16201. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16202. ((and (listp d) (= (length d) 3)) d)
  16203. ((stringp d)
  16204. (let ((d (org-parse-time-string d)))
  16205. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16206. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16207. (defun org-parse-time-string (s &optional nodefault)
  16208. "Parse the standard Org time string.
  16209. This should be a lot faster than the normal `parse-time-string'.
  16210. If time is not given, defaults to 0:00. However, with optional
  16211. NODEFAULT, hour and minute fields will be nil if not given."
  16212. (cond ((string-match org-ts-regexp0 s)
  16213. (list 0
  16214. (when (or (match-beginning 8) (not nodefault))
  16215. (string-to-number (or (match-string 8 s) "0")))
  16216. (when (or (match-beginning 7) (not nodefault))
  16217. (string-to-number (or (match-string 7 s) "0")))
  16218. (string-to-number (match-string 4 s))
  16219. (string-to-number (match-string 3 s))
  16220. (string-to-number (match-string 2 s))
  16221. nil nil nil))
  16222. ((string-match "^<[^>]+>$" s)
  16223. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16224. ;; second argument. However, this requires at least Emacs
  16225. ;; 25.1. We can do it when we switch to this version as our
  16226. ;; minimal requirement.
  16227. (decode-time (seconds-to-time (org-matcher-time s))))
  16228. (t (error "Not a standard Org time string: %s" s))))
  16229. (defun org-timestamp-up (&optional arg)
  16230. "Increase the date item at the cursor by one.
  16231. If the cursor is on the year, change the year. If it is on the month,
  16232. the day or the time, change that.
  16233. With prefix ARG, change by that many units."
  16234. (interactive "p")
  16235. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16236. (defun org-timestamp-down (&optional arg)
  16237. "Decrease the date item at the cursor by one.
  16238. If the cursor is on the year, change the year. If it is on the month,
  16239. the day or the time, change that.
  16240. With prefix ARG, change by that many units."
  16241. (interactive "p")
  16242. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16243. (defun org-timestamp-up-day (&optional arg)
  16244. "Increase the date in the time stamp by one day.
  16245. With prefix ARG, change that many days."
  16246. (interactive "p")
  16247. (if (and (not (org-at-timestamp-p 'lax))
  16248. (org-at-heading-p))
  16249. (org-todo 'up)
  16250. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16251. (defun org-timestamp-down-day (&optional arg)
  16252. "Decrease the date in the time stamp by one day.
  16253. With prefix ARG, change that many days."
  16254. (interactive "p")
  16255. (if (and (not (org-at-timestamp-p 'lax))
  16256. (org-at-heading-p))
  16257. (org-todo 'down)
  16258. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16259. (defun org-at-timestamp-p (&optional extended)
  16260. "Non-nil if point is inside a timestamp.
  16261. By default, the function only consider syntactically valid active
  16262. timestamps. However, the caller may have a broader definition
  16263. for timestamps. As a consequence, optional argument EXTENDED can
  16264. be set to the following values
  16265. `inactive'
  16266. Include also syntactically valid inactive timestamps.
  16267. `agenda'
  16268. Include timestamps allowed in Agenda, i.e., those in
  16269. properties drawers, planning lines and clock lines.
  16270. `lax'
  16271. Ignore context. The function matches any part of the
  16272. document looking like a timestamp. This includes comments,
  16273. example blocks...
  16274. For backward-compatibility with Org 9.0, every other non-nil
  16275. value is equivalent to `inactive'.
  16276. When at a timestamp, return the position of the point as a symbol
  16277. among `bracket', `after', `year', `month', `hour', `minute',
  16278. `day' or a number of character from the last know part of the
  16279. time stamp.
  16280. When matching, the match groups are the following:
  16281. group 1: year
  16282. group 2: month
  16283. group 3: day number
  16284. group 4: day name
  16285. group 5: hours, if any
  16286. group 6: minutes, if any"
  16287. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16288. (pos (point))
  16289. (match?
  16290. (let ((boundaries (org-in-regexp regexp)))
  16291. (save-match-data
  16292. (cond ((null boundaries) nil)
  16293. ((eq extended 'lax) t)
  16294. (t
  16295. (or (and (eq extended 'agenda)
  16296. (or (org-at-planning-p)
  16297. (org-at-property-p)
  16298. (and (bound-and-true-p
  16299. org-agenda-include-inactive-timestamps)
  16300. (org-at-clock-log-p))))
  16301. (eq 'timestamp
  16302. (save-excursion
  16303. (when (= pos (cdr boundaries)) (forward-char -1))
  16304. (org-element-type (org-element-context)))))))))))
  16305. (cond
  16306. ((not match?) nil)
  16307. ((= pos (match-beginning 0)) 'bracket)
  16308. ;; Distinguish location right before the closing bracket from
  16309. ;; right after it.
  16310. ((= pos (1- (match-end 0))) 'bracket)
  16311. ((= pos (match-end 0)) 'after)
  16312. ((org-pos-in-match-range pos 2) 'year)
  16313. ((org-pos-in-match-range pos 3) 'month)
  16314. ((org-pos-in-match-range pos 7) 'hour)
  16315. ((org-pos-in-match-range pos 8) 'minute)
  16316. ((or (org-pos-in-match-range pos 4)
  16317. (org-pos-in-match-range pos 5)) 'day)
  16318. ((and (> pos (or (match-end 8) (match-end 5)))
  16319. (< pos (match-end 0)))
  16320. (- pos (or (match-end 8) (match-end 5))))
  16321. (t 'day))))
  16322. (defun org-toggle-timestamp-type ()
  16323. "Toggle the type (<active> or [inactive]) of a time stamp."
  16324. (interactive)
  16325. (when (org-at-timestamp-p 'lax)
  16326. (let ((beg (match-beginning 0)) (end (match-end 0))
  16327. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16328. (save-excursion
  16329. (goto-char beg)
  16330. (while (re-search-forward "[][<>]" end t)
  16331. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16332. t t)))
  16333. (message "Timestamp is now %sactive"
  16334. (if (equal (char-after beg) ?<) "" "in")))))
  16335. (defun org-at-clock-log-p ()
  16336. "Non-nil if point is on a clock log line."
  16337. (and (org-match-line org-clock-line-re)
  16338. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16339. (defvar org-clock-history) ; defined in org-clock.el
  16340. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16341. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16342. "Change the date in the time stamp at point.
  16343. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16344. `year', `minute', `second'. If WHAT is not given, the cursor position
  16345. in the timestamp determines what will be changed.
  16346. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16347. (let ((origin (point))
  16348. (timestamp? (org-at-timestamp-p 'lax))
  16349. origin-cat
  16350. with-hm inactive
  16351. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16352. extra rem
  16353. ts time time0 fixnext clrgx)
  16354. (unless timestamp? (user-error "Not at a timestamp"))
  16355. (if (and (not what) (eq timestamp? 'bracket))
  16356. (org-toggle-timestamp-type)
  16357. ;; Point isn't on brackets. Remember the part of the time-stamp
  16358. ;; the point was in. Indeed, size of time-stamps may change,
  16359. ;; but point must be kept in the same category nonetheless.
  16360. (setq origin-cat timestamp?)
  16361. (when (and (not what) (not (eq timestamp? 'day))
  16362. org-display-custom-times
  16363. (get-text-property (point) 'display)
  16364. (not (get-text-property (1- (point)) 'display)))
  16365. (setq timestamp? 'day))
  16366. (setq timestamp? (or what timestamp?)
  16367. inactive (= (char-after (match-beginning 0)) ?\[)
  16368. ts (match-string 0))
  16369. (replace-match "")
  16370. (when (string-match
  16371. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16372. ts)
  16373. (setq extra (match-string 1 ts))
  16374. (when suppress-tmp-delay
  16375. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16376. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16377. (setq with-hm t))
  16378. (setq time0 (org-parse-time-string ts))
  16379. (when (and updown
  16380. (eq timestamp? 'minute)
  16381. (not current-prefix-arg))
  16382. ;; This looks like s-up and s-down. Change by one rounding step.
  16383. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16384. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16385. (setcar (cdr time0) (+ (nth 1 time0)
  16386. (if (> n 0) (- rem) (- dm rem))))))
  16387. (setq time
  16388. (apply #'encode-time
  16389. (or (car time0) 0)
  16390. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16391. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16392. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16393. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16394. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16395. (nthcdr 6 time0)))
  16396. (when (and (memq timestamp? '(hour minute))
  16397. extra
  16398. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16399. (setq extra (org-modify-ts-extra
  16400. extra
  16401. (if (eq timestamp? 'hour) 2 5)
  16402. n dm)))
  16403. (when (integerp timestamp?)
  16404. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16405. (when (eq what 'calendar)
  16406. (let ((cal-date (org-get-date-from-calendar)))
  16407. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16408. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16409. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16410. (setcar time0 (or (car time0) 0))
  16411. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16412. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16413. (setq time (apply 'encode-time time0))))
  16414. ;; Insert the new time-stamp, and ensure point stays in the same
  16415. ;; category as before (i.e. not after the last position in that
  16416. ;; category).
  16417. (let ((pos (point)))
  16418. ;; Stay before inserted string. `save-excursion' is of no use.
  16419. (setq org-last-changed-timestamp
  16420. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16421. (goto-char pos))
  16422. (save-match-data
  16423. (looking-at org-ts-regexp3)
  16424. (goto-char
  16425. (pcase origin-cat
  16426. ;; `day' category ends before `hour' if any, or at the end
  16427. ;; of the day name.
  16428. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16429. (`hour (min (match-end 7) origin))
  16430. (`minute (min (1- (match-end 8)) origin))
  16431. ((pred integerp) (min (1- (match-end 0)) origin))
  16432. ;; Point was right after the time-stamp. However, the
  16433. ;; time-stamp length might have changed, so refer to
  16434. ;; (match-end 0) instead.
  16435. (`after (match-end 0))
  16436. ;; `year' and `month' have both fixed size: point couldn't
  16437. ;; have moved into another part.
  16438. (_ origin))))
  16439. ;; Update clock if on a CLOCK line.
  16440. (org-clock-update-time-maybe)
  16441. ;; Maybe adjust the closest clock in `org-clock-history'
  16442. (when org-clock-adjust-closest
  16443. (if (not (and (org-at-clock-log-p)
  16444. (< 1 (length (delq nil (mapcar 'marker-position
  16445. org-clock-history))))))
  16446. (message "No clock to adjust")
  16447. (cond ((save-excursion ; fix previous clock?
  16448. (re-search-backward org-ts-regexp0 nil t)
  16449. (looking-back (concat org-clock-string " \\[")
  16450. (line-beginning-position)))
  16451. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16452. ((save-excursion ; fix next clock?
  16453. (re-search-backward org-ts-regexp0 nil t)
  16454. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16455. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16456. (save-window-excursion
  16457. ;; Find closest clock to point, adjust the previous/next one in history
  16458. (let* ((p (save-excursion (org-back-to-heading t)))
  16459. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16460. (clfixnth
  16461. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16462. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16463. (if (not clfixpos)
  16464. (message "No clock to adjust")
  16465. (save-excursion
  16466. (org-goto-marker-or-bmk clfixpos)
  16467. (org-show-subtree)
  16468. (when (re-search-forward clrgx nil t)
  16469. (goto-char (match-beginning 1))
  16470. (let (org-clock-adjust-closest)
  16471. (org-timestamp-change n timestamp? updown))
  16472. (message "Clock adjusted in %s for heading: %s"
  16473. (file-name-nondirectory (buffer-file-name))
  16474. (org-get-heading t t)))))))))
  16475. ;; Try to recenter the calendar window, if any.
  16476. (when (and org-calendar-follow-timestamp-change
  16477. (get-buffer-window "*Calendar*" t)
  16478. (memq timestamp? '(day month year)))
  16479. (org-recenter-calendar (time-to-days time))))))
  16480. (defun org-modify-ts-extra (s pos n dm)
  16481. "Change the different parts of the lead-time and repeat fields in timestamp."
  16482. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16483. ng h m new rem)
  16484. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16485. (cond
  16486. ((or (org-pos-in-match-range pos 2)
  16487. (org-pos-in-match-range pos 3))
  16488. (setq m (string-to-number (match-string 3 s))
  16489. h (string-to-number (match-string 2 s)))
  16490. (if (org-pos-in-match-range pos 2)
  16491. (setq h (+ h n))
  16492. (setq n (* dm (with-no-warnings (signum n))))
  16493. (unless (= 0 (setq rem (% m dm)))
  16494. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16495. (setq m (+ m n)))
  16496. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16497. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16498. (setq h (mod h 24))
  16499. (setq ng 1 new (format "-%02d:%02d" h m)))
  16500. ((org-pos-in-match-range pos 6)
  16501. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16502. ((org-pos-in-match-range pos 5)
  16503. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16504. ((org-pos-in-match-range pos 9)
  16505. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16506. ((org-pos-in-match-range pos 8)
  16507. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16508. (when ng
  16509. (setq s (concat
  16510. (substring s 0 (match-beginning ng))
  16511. new
  16512. (substring s (match-end ng))))))
  16513. s))
  16514. (defun org-recenter-calendar (d)
  16515. "If the calendar is visible, recenter it to date D."
  16516. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16517. (when cwin
  16518. (let ((calendar-move-hook nil))
  16519. (with-selected-window cwin
  16520. (calendar-goto-date
  16521. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16522. (defun org-goto-calendar (&optional arg)
  16523. "Go to the Emacs calendar at the current date.
  16524. If there is a time stamp in the current line, go to that date.
  16525. A prefix ARG can be used to force the current date."
  16526. (interactive "P")
  16527. (let ((calendar-move-hook nil)
  16528. (calendar-view-holidays-initially-flag nil)
  16529. (calendar-view-diary-initially-flag nil)
  16530. diff)
  16531. (when (or (org-at-timestamp-p 'lax)
  16532. (org-match-line (concat ".*" org-ts-regexp)))
  16533. (let ((d1 (time-to-days (current-time)))
  16534. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16535. (setq diff (- d2 d1))))
  16536. (calendar)
  16537. (calendar-goto-today)
  16538. (when (and diff (not arg)) (calendar-forward-day diff))))
  16539. (defun org-get-date-from-calendar ()
  16540. "Return a list (month day year) of date at point in calendar."
  16541. (with-current-buffer "*Calendar*"
  16542. (save-match-data
  16543. (calendar-cursor-to-date))))
  16544. (defun org-date-from-calendar ()
  16545. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16546. If there is already a time stamp at the cursor position, update it."
  16547. (interactive)
  16548. (if (org-at-timestamp-p 'lax)
  16549. (org-timestamp-change 0 'calendar)
  16550. (let ((cal-date (org-get-date-from-calendar)))
  16551. (org-insert-time-stamp
  16552. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16553. (defcustom org-effort-durations
  16554. `(("min" . 1)
  16555. ("h" . 60)
  16556. ("d" . ,(* 60 8))
  16557. ("w" . ,(* 60 8 5))
  16558. ("m" . ,(* 60 8 5 4))
  16559. ("y" . ,(* 60 8 5 40)))
  16560. "Conversion factor to minutes for an effort modifier.
  16561. Each entry has the form (MODIFIER . MINUTES).
  16562. In an effort string, a number followed by MODIFIER is multiplied
  16563. by the specified number of MINUTES to obtain an effort in
  16564. minutes.
  16565. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16566. effort string \"2hours\" is equivalent to 120 minutes."
  16567. :group 'org-agenda
  16568. :version "26.1"
  16569. :package-version '(Org . "8.3")
  16570. :type '(alist :key-type (string :tag "Modifier")
  16571. :value-type (number :tag "Minutes")))
  16572. (defcustom org-image-actual-width t
  16573. "Should we use the actual width of images when inlining them?
  16574. When set to t, always use the image width.
  16575. When set to a number, use imagemagick (when available) to set
  16576. the image's width to this value.
  16577. When set to a number in a list, try to get the width from any
  16578. #+ATTR.* keyword if it matches a width specification like
  16579. #+ATTR_HTML: :width 300px
  16580. and fall back on that number if none is found.
  16581. When set to nil, try to get the width from an #+ATTR.* keyword
  16582. and fall back on the original width if none is found.
  16583. This requires Emacs >= 24.1, build with imagemagick support."
  16584. :group 'org-appearance
  16585. :version "24.4"
  16586. :package-version '(Org . "8.0")
  16587. :type '(choice
  16588. (const :tag "Use the image width" t)
  16589. (integer :tag "Use a number of pixels")
  16590. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16591. (const :tag "Use #+ATTR* or don't resize" nil)))
  16592. (defcustom org-agenda-inhibit-startup nil
  16593. "Inhibit startup when preparing agenda buffers.
  16594. When this variable is t, the initialization of the Org agenda
  16595. buffers is inhibited: e.g. the visibility state is not set, the
  16596. tables are not re-aligned, etc."
  16597. :type 'boolean
  16598. :version "24.3"
  16599. :group 'org-agenda)
  16600. (defcustom org-agenda-ignore-properties nil
  16601. "Avoid updating text properties when building the agenda.
  16602. Properties are used to prepare buffers for effort estimates,
  16603. appointments, statistics and subtree-local categories.
  16604. If you don't use these in the agenda, you can add them to this
  16605. list and agenda building will be a bit faster.
  16606. The value is a list, with zero or more of the symbols `effort', `appt',
  16607. `stats' or `category'."
  16608. :type '(set :greedy t
  16609. (const effort)
  16610. (const appt)
  16611. (const stats)
  16612. (const category))
  16613. :version "26.1"
  16614. :package-version '(Org . "8.3")
  16615. :group 'org-agenda)
  16616. ;;;; Files
  16617. (defun org-save-all-org-buffers ()
  16618. "Save all Org buffers without user confirmation."
  16619. (interactive)
  16620. (message "Saving all Org buffers...")
  16621. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16622. (when (featurep 'org-id) (org-id-locations-save))
  16623. (message "Saving all Org buffers... done"))
  16624. (defun org-revert-all-org-buffers ()
  16625. "Revert all Org buffers.
  16626. Prompt for confirmation when there are unsaved changes.
  16627. Be sure you know what you are doing before letting this function
  16628. overwrite your changes.
  16629. This function is useful in a setup where one tracks org files
  16630. with a version control system, to revert on one machine after pulling
  16631. changes from another. I believe the procedure must be like this:
  16632. 1. M-x org-save-all-org-buffers
  16633. 2. Pull changes from the other machine, resolve conflicts
  16634. 3. M-x org-revert-all-org-buffers"
  16635. (interactive)
  16636. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16637. (user-error "Abort"))
  16638. (save-excursion
  16639. (save-window-excursion
  16640. (dolist (b (buffer-list))
  16641. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16642. (with-current-buffer b buffer-file-name))
  16643. (pop-to-buffer-same-window b)
  16644. (revert-buffer t 'no-confirm)))
  16645. (when (and (featurep 'org-id) org-id-track-globally)
  16646. (org-id-locations-load)))))
  16647. ;;;; Agenda files
  16648. ;;;###autoload
  16649. (defun org-switchb (&optional arg)
  16650. "Switch between Org buffers.
  16651. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16652. With `\\[universal-argument] \\[universal-argument]' \
  16653. prefix, restrict available buffers to agenda files."
  16654. (interactive "P")
  16655. (let ((blist (org-buffer-list
  16656. (cond ((equal arg '(4)) 'files)
  16657. ((equal arg '(16)) 'agenda)))))
  16658. (pop-to-buffer-same-window
  16659. (completing-read "Org buffer: "
  16660. (mapcar #'list (mapcar #'buffer-name blist))
  16661. nil t))))
  16662. (defun org-buffer-list (&optional predicate exclude-tmp)
  16663. "Return a list of Org buffers.
  16664. PREDICATE can be `export', `files' or `agenda'.
  16665. export restrict the list to Export buffers.
  16666. files restrict the list to buffers visiting Org files.
  16667. agenda restrict the list to buffers visiting agenda files.
  16668. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16669. (let* ((bfn nil)
  16670. (agenda-files (and (eq predicate 'agenda)
  16671. (mapcar 'file-truename (org-agenda-files t))))
  16672. (filter
  16673. (cond
  16674. ((eq predicate 'files)
  16675. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16676. ((eq predicate 'export)
  16677. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16678. ((eq predicate 'agenda)
  16679. (lambda (b)
  16680. (with-current-buffer b
  16681. (and (derived-mode-p 'org-mode)
  16682. (setq bfn (buffer-file-name b))
  16683. (member (file-truename bfn) agenda-files)))))
  16684. (t (lambda (b) (with-current-buffer b
  16685. (or (derived-mode-p 'org-mode)
  16686. (string-match "\\*Org .*Export"
  16687. (buffer-name b)))))))))
  16688. (delq nil
  16689. (mapcar
  16690. (lambda(b)
  16691. (if (and (funcall filter b)
  16692. (or (not exclude-tmp)
  16693. (not (string-match "tmp" (buffer-name b)))))
  16694. b
  16695. nil))
  16696. (buffer-list)))))
  16697. (defun org-agenda-files (&optional unrestricted archives)
  16698. "Get the list of agenda files.
  16699. Optional UNRESTRICTED means return the full list even if a restriction
  16700. is currently in place.
  16701. When ARCHIVES is t, include all archive files that are really being
  16702. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16703. `org-agenda-archives-mode' is t."
  16704. (let ((files
  16705. (cond
  16706. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16707. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16708. ((listp org-agenda-files) org-agenda-files)
  16709. (t (error "Invalid value of `org-agenda-files'")))))
  16710. (setq files (apply 'append
  16711. (mapcar (lambda (f)
  16712. (if (file-directory-p f)
  16713. (directory-files
  16714. f t org-agenda-file-regexp)
  16715. (list f)))
  16716. files)))
  16717. (when org-agenda-skip-unavailable-files
  16718. (setq files (delq nil
  16719. (mapcar (function
  16720. (lambda (file)
  16721. (and (file-readable-p file) file)))
  16722. files))))
  16723. (when (or (eq archives t)
  16724. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16725. (setq files (org-add-archive-files files)))
  16726. files))
  16727. (defun org-agenda-file-p (&optional file)
  16728. "Return non-nil, if FILE is an agenda file.
  16729. If FILE is omitted, use the file associated with the current
  16730. buffer."
  16731. (let ((fname (or file (buffer-file-name))))
  16732. (and fname
  16733. (member (file-truename fname)
  16734. (mapcar #'file-truename (org-agenda-files t))))))
  16735. (defun org-edit-agenda-file-list ()
  16736. "Edit the list of agenda files.
  16737. Depending on setup, this either uses customize to edit the variable
  16738. `org-agenda-files', or it visits the file that is holding the list. In the
  16739. latter case, the buffer is set up in a way that saving it automatically kills
  16740. the buffer and restores the previous window configuration."
  16741. (interactive)
  16742. (if (stringp org-agenda-files)
  16743. (let ((cw (current-window-configuration)))
  16744. (find-file org-agenda-files)
  16745. (setq-local org-window-configuration cw)
  16746. (add-hook 'after-save-hook
  16747. (lambda ()
  16748. (set-window-configuration
  16749. (prog1 org-window-configuration
  16750. (kill-buffer (current-buffer))))
  16751. (org-install-agenda-files-menu)
  16752. (message "New agenda file list installed"))
  16753. nil 'local)
  16754. (message "%s" (substitute-command-keys
  16755. "Edit list and finish with \\[save-buffer]")))
  16756. (customize-variable 'org-agenda-files)))
  16757. (defun org-store-new-agenda-file-list (list)
  16758. "Set new value for the agenda file list and save it correctly."
  16759. (if (stringp org-agenda-files)
  16760. (let ((fe (org-read-agenda-file-list t)) b u)
  16761. (while (setq b (find-buffer-visiting org-agenda-files))
  16762. (kill-buffer b))
  16763. (with-temp-file org-agenda-files
  16764. (insert
  16765. (mapconcat
  16766. (lambda (f) ;; Keep un-expanded entries.
  16767. (if (setq u (assoc f fe))
  16768. (cdr u)
  16769. f))
  16770. list "\n")
  16771. "\n")))
  16772. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16773. (org-insert-mode-line-in-empty-file nil))
  16774. (setq org-agenda-files list)
  16775. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16776. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16777. "Read the list of agenda files from a file.
  16778. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16779. filenames, used by `org-store-new-agenda-file-list' to write back
  16780. un-expanded file names."
  16781. (when (file-directory-p org-agenda-files)
  16782. (error "`org-agenda-files' cannot be a single directory"))
  16783. (when (stringp org-agenda-files)
  16784. (with-temp-buffer
  16785. (insert-file-contents org-agenda-files)
  16786. (mapcar
  16787. (lambda (f)
  16788. (let ((e (expand-file-name (substitute-in-file-name f)
  16789. org-directory)))
  16790. (if pair-with-expansion
  16791. (cons e f)
  16792. e)))
  16793. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16794. ;;;###autoload
  16795. (defun org-cycle-agenda-files ()
  16796. "Cycle through the files in `org-agenda-files'.
  16797. If the current buffer visits an agenda file, find the next one in the list.
  16798. If the current buffer does not, find the first agenda file."
  16799. (interactive)
  16800. (let* ((fs (or (org-agenda-files t)
  16801. (user-error "No agenda files")))
  16802. (files (copy-sequence fs))
  16803. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16804. file)
  16805. (when tcf
  16806. (while (and (setq file (pop files))
  16807. (not (equal (file-truename file) tcf)))))
  16808. (find-file (car (or files fs)))
  16809. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16810. (defun org-agenda-file-to-front (&optional to-end)
  16811. "Move/add the current file to the top of the agenda file list.
  16812. If the file is not present in the list, it is added to the front. If it is
  16813. present, it is moved there. With optional argument TO-END, add/move to the
  16814. end of the list."
  16815. (interactive "P")
  16816. (let ((org-agenda-skip-unavailable-files nil)
  16817. (file-alist (mapcar (lambda (x)
  16818. (cons (file-truename x) x))
  16819. (org-agenda-files t)))
  16820. (ctf (file-truename
  16821. (or buffer-file-name
  16822. (user-error "Please save the current buffer to a file"))))
  16823. x had)
  16824. (setq x (assoc ctf file-alist) had x)
  16825. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16826. (if to-end
  16827. (setq file-alist (append (delq x file-alist) (list x)))
  16828. (setq file-alist (cons x (delq x file-alist))))
  16829. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16830. (org-install-agenda-files-menu)
  16831. (message "File %s to %s of agenda file list"
  16832. (if had "moved" "added") (if to-end "end" "front"))))
  16833. (defun org-remove-file (&optional file)
  16834. "Remove current file from the list of files in variable `org-agenda-files'.
  16835. These are the files which are being checked for agenda entries.
  16836. Optional argument FILE means use this file instead of the current."
  16837. (interactive)
  16838. (let* ((org-agenda-skip-unavailable-files nil)
  16839. (file (or file buffer-file-name
  16840. (user-error "Current buffer does not visit a file")))
  16841. (true-file (file-truename file))
  16842. (afile (abbreviate-file-name file))
  16843. (files (delq nil (mapcar
  16844. (lambda (x)
  16845. (unless (equal true-file
  16846. (file-truename x))
  16847. x))
  16848. (org-agenda-files t)))))
  16849. (if (not (= (length files) (length (org-agenda-files t))))
  16850. (progn
  16851. (org-store-new-agenda-file-list files)
  16852. (org-install-agenda-files-menu)
  16853. (message "Removed from Org Agenda list: %s" afile))
  16854. (message "File was not in list: %s (not removed)" afile))))
  16855. (defun org-file-menu-entry (file)
  16856. (vector file (list 'find-file file) t))
  16857. (defun org-check-agenda-file (file)
  16858. "Make sure FILE exists. If not, ask user what to do."
  16859. (unless (file-exists-p file)
  16860. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16861. (abbreviate-file-name file))
  16862. (let ((r (downcase (read-char-exclusive))))
  16863. (cond
  16864. ((equal r ?r)
  16865. (org-remove-file file)
  16866. (throw 'nextfile t))
  16867. (t (user-error "Abort"))))))
  16868. (defun org-get-agenda-file-buffer (file)
  16869. "Get an agenda buffer visiting FILE.
  16870. If the buffer needs to be created, add it to the list of buffers
  16871. which might be released later."
  16872. (let ((buf (org-find-base-buffer-visiting file)))
  16873. (if buf
  16874. buf ; just return it
  16875. ;; Make a new buffer and remember it
  16876. (setq buf (find-file-noselect file))
  16877. (when buf (push buf org-agenda-new-buffers))
  16878. buf)))
  16879. (defun org-release-buffers (blist)
  16880. "Release all buffers in list, asking the user for confirmation when needed.
  16881. When a buffer is unmodified, it is just killed. When modified, it is saved
  16882. \(if the user agrees) and then killed."
  16883. (let (file)
  16884. (dolist (buf blist)
  16885. (setq file (buffer-file-name buf))
  16886. (when (and (buffer-modified-p buf)
  16887. file
  16888. (y-or-n-p (format "Save file %s? " file)))
  16889. (with-current-buffer buf (save-buffer)))
  16890. (kill-buffer buf))))
  16891. (defun org-agenda-prepare-buffers (files)
  16892. "Create buffers for all agenda files, protect archived trees and comments."
  16893. (interactive)
  16894. (let ((pa '(:org-archived t))
  16895. (pc '(:org-comment t))
  16896. (pall '(:org-archived t :org-comment t))
  16897. (inhibit-read-only t)
  16898. (org-inhibit-startup org-agenda-inhibit-startup)
  16899. (rea (concat ":" org-archive-tag ":"))
  16900. re pos)
  16901. (setq org-tag-alist-for-agenda nil
  16902. org-tag-groups-alist-for-agenda nil)
  16903. (save-excursion
  16904. (save-restriction
  16905. (dolist (file files)
  16906. (catch 'nextfile
  16907. (if (bufferp file)
  16908. (set-buffer file)
  16909. (org-check-agenda-file file)
  16910. (set-buffer (org-get-agenda-file-buffer file)))
  16911. (widen)
  16912. (org-set-regexps-and-options 'tags-only)
  16913. (setq pos (point))
  16914. (or (memq 'category org-agenda-ignore-properties)
  16915. (org-refresh-category-properties))
  16916. (or (memq 'stats org-agenda-ignore-properties)
  16917. (org-refresh-stats-properties))
  16918. (or (memq 'effort org-agenda-ignore-properties)
  16919. (org-refresh-effort-properties))
  16920. (or (memq 'appt org-agenda-ignore-properties)
  16921. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16922. (setq org-todo-keywords-for-agenda
  16923. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16924. (setq org-done-keywords-for-agenda
  16925. (append org-done-keywords-for-agenda org-done-keywords))
  16926. (setq org-todo-keyword-alist-for-agenda
  16927. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16928. (setq org-tag-alist-for-agenda
  16929. (org-uniquify
  16930. (append org-tag-alist-for-agenda
  16931. org-current-tag-alist)))
  16932. ;; Merge current file's tag groups into global
  16933. ;; `org-tag-groups-alist-for-agenda'.
  16934. (when org-group-tags
  16935. (dolist (alist org-tag-groups-alist)
  16936. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16937. (if old
  16938. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16939. (push alist org-tag-groups-alist-for-agenda)))))
  16940. (org-with-silent-modifications
  16941. (save-excursion
  16942. (remove-text-properties (point-min) (point-max) pall)
  16943. (when org-agenda-skip-archived-trees
  16944. (goto-char (point-min))
  16945. (while (re-search-forward rea nil t)
  16946. (when (org-at-heading-p t)
  16947. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16948. (goto-char (point-min))
  16949. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16950. (while (re-search-forward re nil t)
  16951. (when (save-match-data (org-in-commented-heading-p t))
  16952. (add-text-properties
  16953. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16954. (goto-char pos)))))
  16955. (setq org-todo-keywords-for-agenda
  16956. (org-uniquify org-todo-keywords-for-agenda))
  16957. (setq org-todo-keyword-alist-for-agenda
  16958. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16959. ;;;; CDLaTeX minor mode
  16960. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16961. "Keymap for the minor `org-cdlatex-mode'.")
  16962. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16963. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16964. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16965. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16966. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16967. (defvar org-cdlatex-texmathp-advice-is-done nil
  16968. "Flag remembering if we have applied the advice to texmathp already.")
  16969. (define-minor-mode org-cdlatex-mode
  16970. "Toggle the minor `org-cdlatex-mode'.
  16971. This mode supports entering LaTeX environment and math in LaTeX fragments
  16972. in Org mode.
  16973. \\{org-cdlatex-mode-map}"
  16974. nil " OCDL" nil
  16975. (when org-cdlatex-mode
  16976. (require 'cdlatex)
  16977. (run-hooks 'cdlatex-mode-hook)
  16978. (cdlatex-compute-tables))
  16979. (unless org-cdlatex-texmathp-advice-is-done
  16980. (setq org-cdlatex-texmathp-advice-is-done t)
  16981. (defadvice texmathp (around org-math-always-on activate)
  16982. "Always return t in Org buffers.
  16983. This is because we want to insert math symbols without dollars even outside
  16984. the LaTeX math segments. If Org mode thinks that point is actually inside
  16985. an embedded LaTeX fragment, let `texmathp' do its job.
  16986. `\\[org-cdlatex-mode-map]'"
  16987. (interactive)
  16988. (let (p)
  16989. (cond
  16990. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16991. ((eq this-command 'cdlatex-math-symbol)
  16992. (setq ad-return-value t
  16993. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16994. (t
  16995. (let ((p (org-inside-LaTeX-fragment-p)))
  16996. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16997. (setq ad-return-value t
  16998. texmathp-why '("Org mode embedded math" . 0))
  16999. (when p ad-do-it)))))))))
  17000. (defun turn-on-org-cdlatex ()
  17001. "Unconditionally turn on `org-cdlatex-mode'."
  17002. (org-cdlatex-mode 1))
  17003. (defun org-try-cdlatex-tab ()
  17004. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17005. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17006. - inside a LaTeX fragment, or
  17007. - after the first word in a line, where an abbreviation expansion could
  17008. insert a LaTeX environment."
  17009. (when org-cdlatex-mode
  17010. (cond
  17011. ;; Before any word on the line: No expansion possible.
  17012. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17013. ;; Just after first word on the line: Expand it. Make sure it
  17014. ;; cannot happen on headlines, though.
  17015. ((save-excursion
  17016. (skip-chars-backward "a-zA-Z0-9*")
  17017. (skip-chars-backward " \t")
  17018. (and (bolp) (not (org-at-heading-p))))
  17019. (cdlatex-tab) t)
  17020. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17021. (defun org-cdlatex-underscore-caret (&optional _arg)
  17022. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17023. Revert to the normal definition outside of these fragments."
  17024. (interactive "P")
  17025. (if (org-inside-LaTeX-fragment-p)
  17026. (call-interactively 'cdlatex-sub-superscript)
  17027. (let (org-cdlatex-mode)
  17028. (call-interactively (key-binding (vector last-input-event))))))
  17029. (defun org-cdlatex-math-modify (&optional _arg)
  17030. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17031. Revert to the normal definition outside of these fragments."
  17032. (interactive "P")
  17033. (if (org-inside-LaTeX-fragment-p)
  17034. (call-interactively 'cdlatex-math-modify)
  17035. (let (org-cdlatex-mode)
  17036. (call-interactively (key-binding (vector last-input-event))))))
  17037. (defun org-cdlatex-environment-indent (&optional environment item)
  17038. "Execute `cdlatex-environment' and indent the inserted environment.
  17039. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17040. The inserted environment is indented to current indentation
  17041. unless point is at the beginning of the line, in which the
  17042. environment remains unintended."
  17043. (interactive)
  17044. ;; cdlatex-environment always return nil. Therefore, capture output
  17045. ;; first and determine if an environment was selected.
  17046. (let* ((beg (point-marker))
  17047. (end (copy-marker (point) t))
  17048. (inserted (progn
  17049. (ignore-errors (cdlatex-environment environment item))
  17050. (< beg end)))
  17051. ;; Figure out how many lines to move forward after the
  17052. ;; environment has been inserted.
  17053. (lines (when inserted
  17054. (save-excursion
  17055. (- (cl-loop while (< beg (point))
  17056. with x = 0
  17057. do (forward-line -1)
  17058. (cl-incf x)
  17059. finally return x)
  17060. (if (progn (goto-char beg)
  17061. (and (progn (skip-chars-forward " \t") (eolp))
  17062. (progn (skip-chars-backward " \t") (bolp))))
  17063. 1 0)))))
  17064. (env (org-trim (delete-and-extract-region beg end))))
  17065. (when inserted
  17066. ;; Get indentation of next line unless at column 0.
  17067. (let ((ind (if (bolp) 0
  17068. (save-excursion
  17069. (org-return-indent)
  17070. (prog1 (org-get-indentation)
  17071. (when (progn (skip-chars-forward " \t") (eolp))
  17072. (delete-region beg (point)))))))
  17073. (bol (progn (skip-chars-backward " \t") (bolp))))
  17074. ;; Insert a newline before environment unless at column zero
  17075. ;; to "escape" the current line. Insert a newline if
  17076. ;; something is one the same line as \end{ENVIRONMENT}.
  17077. (insert
  17078. (concat (unless bol "\n") env
  17079. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17080. (unless (zerop ind)
  17081. (save-excursion
  17082. (goto-char beg)
  17083. (while (< (point) end)
  17084. (unless (eolp) (indent-line-to ind))
  17085. (forward-line))))
  17086. (goto-char beg)
  17087. (forward-line lines)
  17088. (indent-line-to ind)))
  17089. (set-marker beg nil)
  17090. (set-marker end nil)))
  17091. ;;;; LaTeX fragments
  17092. (defun org-inside-LaTeX-fragment-p ()
  17093. "Test if point is inside a LaTeX fragment.
  17094. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17095. sequence appearing also before point.
  17096. Even though the matchers for math are configurable, this function assumes
  17097. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17098. delimiters are skipped when they have been removed by customization.
  17099. The return value is nil, or a cons cell with the delimiter and the
  17100. position of this delimiter.
  17101. This function does a reasonably good job, but can locally be fooled by
  17102. for example currency specifications. For example it will assume being in
  17103. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17104. fragments that are properly closed, but during editing, we have to live
  17105. with the uncertainty caused by missing closing delimiters. This function
  17106. looks only before point, not after."
  17107. (catch 'exit
  17108. (let ((pos (point))
  17109. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17110. (lim (save-excursion (org-backward-paragraph) (point)))
  17111. dd-on str (start 0) m re)
  17112. (goto-char pos)
  17113. (when dodollar
  17114. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17115. re (nth 1 (assoc "$" org-latex-regexps)))
  17116. (while (string-match re str start)
  17117. (cond
  17118. ((= (match-end 0) (length str))
  17119. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17120. ((= (match-end 0) (- (length str) 5))
  17121. (throw 'exit nil))
  17122. (t (setq start (match-end 0))))))
  17123. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17124. (goto-char pos)
  17125. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17126. (and (match-beginning 2) (throw 'exit nil))
  17127. ;; count $$
  17128. (while (re-search-backward "\\$\\$" lim t)
  17129. (setq dd-on (not dd-on)))
  17130. (goto-char pos)
  17131. (when dd-on (cons "$$" m))))))
  17132. (defun org-inside-latex-macro-p ()
  17133. "Is point inside a LaTeX macro or its arguments?"
  17134. (save-match-data
  17135. (org-in-regexp
  17136. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17137. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17138. "Build an overlay between BEG and END using IMAGE file.
  17139. Argument IMAGETYPE is the extension of the displayed image,
  17140. as a string. It defaults to \"png\"."
  17141. (let ((ov (make-overlay beg end))
  17142. (imagetype (or (intern imagetype) 'png)))
  17143. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17144. (overlay-put ov 'evaporate t)
  17145. (overlay-put ov
  17146. 'modification-hooks
  17147. (list (lambda (o _flag _beg _end &optional _l)
  17148. (delete-overlay o))))
  17149. (overlay-put ov
  17150. 'display
  17151. (list 'image :type imagetype :file image :ascent 'center))))
  17152. (defun org--list-latex-overlays (&optional beg end)
  17153. "List all Org LaTeX overlays in current buffer.
  17154. Limit to overlays between BEG and END when those are provided."
  17155. (cl-remove-if-not
  17156. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17157. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17158. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17159. "Remove all overlays with LaTeX fragment images in current buffer.
  17160. When optional arguments BEG and END are non-nil, remove all
  17161. overlays between them instead. Return a non-nil value when some
  17162. overlays were removed, nil otherwise."
  17163. (let ((overlays (org--list-latex-overlays beg end)))
  17164. (mapc #'delete-overlay overlays)
  17165. overlays))
  17166. (defun org-toggle-latex-fragment (&optional arg)
  17167. "Preview the LaTeX fragment at point, or all locally or globally.
  17168. If the cursor is on a LaTeX fragment, create the image and overlay
  17169. it over the source code, if there is none. Remove it otherwise.
  17170. If there is no fragment at point, display all fragments in the
  17171. current section.
  17172. With prefix ARG, preview or clear image for all fragments in the
  17173. current subtree or in the whole buffer when used before the first
  17174. headline. With a prefix ARG `\\[universal-argument] \
  17175. \\[universal-argument]' preview or clear images
  17176. for all fragments in the buffer."
  17177. (interactive "P")
  17178. (when (display-graphic-p)
  17179. (catch 'exit
  17180. (save-excursion
  17181. (let (beg end msg)
  17182. (cond
  17183. ((or (equal arg '(16))
  17184. (and (equal arg '(4))
  17185. (org-with-limited-levels (org-before-first-heading-p))))
  17186. (if (org-remove-latex-fragment-image-overlays)
  17187. (progn (message "LaTeX fragments images removed from buffer")
  17188. (throw 'exit nil))
  17189. (setq msg "Creating images for buffer...")))
  17190. ((equal arg '(4))
  17191. (org-with-limited-levels (org-back-to-heading t))
  17192. (setq beg (point))
  17193. (setq end (progn (org-end-of-subtree t) (point)))
  17194. (if (org-remove-latex-fragment-image-overlays beg end)
  17195. (progn
  17196. (message "LaTeX fragment images removed from subtree")
  17197. (throw 'exit nil))
  17198. (setq msg "Creating images for subtree...")))
  17199. ((let ((datum (org-element-context)))
  17200. (when (memq (org-element-type datum)
  17201. '(latex-environment latex-fragment))
  17202. (setq beg (org-element-property :begin datum))
  17203. (setq end (org-element-property :end datum))
  17204. (if (org-remove-latex-fragment-image-overlays beg end)
  17205. (progn (message "LaTeX fragment image removed")
  17206. (throw 'exit nil))
  17207. (setq msg "Creating image...")))))
  17208. (t
  17209. (org-with-limited-levels
  17210. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17211. (outline-previous-heading)
  17212. (point)))
  17213. (setq end (progn (outline-next-heading) (point)))
  17214. (if (org-remove-latex-fragment-image-overlays beg end)
  17215. (progn
  17216. (message "LaTeX fragment images removed from section")
  17217. (throw 'exit nil))
  17218. (setq msg "Creating images for section...")))))
  17219. (let ((file (buffer-file-name (buffer-base-buffer))))
  17220. (org-format-latex
  17221. (concat org-preview-latex-image-directory "org-ltximg")
  17222. beg end
  17223. ;; Emacs cannot overlay images from remote hosts. Create
  17224. ;; it in `temporary-file-directory' instead.
  17225. (if (or (not file) (file-remote-p file))
  17226. temporary-file-directory
  17227. default-directory)
  17228. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17229. (message (concat msg "done")))))))
  17230. (defun org-format-latex
  17231. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17232. "Replace LaTeX fragments with links to an image.
  17233. The function takes care of creating the replacement image.
  17234. Only consider fragments between BEG and END when those are
  17235. provided.
  17236. When optional argument OVERLAYS is non-nil, display the image on
  17237. top of the fragment instead of replacing it.
  17238. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17239. Some of the options can be changed using the variable
  17240. `org-format-latex-options', which see."
  17241. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17242. (unless (eq processing-type 'verbatim)
  17243. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17244. (cnt 0)
  17245. checkdir-flag)
  17246. (goto-char (or beg (point-min)))
  17247. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17248. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17249. (overlay-recenter (or end (point-max))))
  17250. (while (re-search-forward math-regexp end t)
  17251. (unless (and overlays
  17252. (eq (get-char-property (point) 'org-overlay-type)
  17253. 'org-latex-overlay))
  17254. (let* ((context (org-element-context))
  17255. (type (org-element-type context)))
  17256. (when (memq type '(latex-environment latex-fragment))
  17257. (let ((block-type (eq type 'latex-environment))
  17258. (value (org-element-property :value context))
  17259. (beg (org-element-property :begin context))
  17260. (end (save-excursion
  17261. (goto-char (org-element-property :end context))
  17262. (skip-chars-backward " \r\t\n")
  17263. (point))))
  17264. (cond
  17265. ((eq processing-type 'mathjax)
  17266. ;; Prepare for MathJax processing.
  17267. (if (not (string-match "\\`\\$\\$?" value))
  17268. (goto-char end)
  17269. (delete-region beg end)
  17270. (if (string= (match-string 0 value) "$$")
  17271. (insert "\\[" (substring value 2 -2) "\\]")
  17272. (insert "\\(" (substring value 1 -1) "\\)"))))
  17273. ((assq processing-type org-preview-latex-process-alist)
  17274. ;; Process to an image.
  17275. (cl-incf cnt)
  17276. (goto-char beg)
  17277. (let* ((processing-info
  17278. (cdr (assq processing-type org-preview-latex-process-alist)))
  17279. (face (face-at-point))
  17280. ;; Get the colors from the face at point.
  17281. (fg
  17282. (let ((color (plist-get org-format-latex-options
  17283. :foreground)))
  17284. (if (and forbuffer (eq color 'auto))
  17285. (face-attribute face :foreground nil 'default)
  17286. color)))
  17287. (bg
  17288. (let ((color (plist-get org-format-latex-options
  17289. :background)))
  17290. (if (and forbuffer (eq color 'auto))
  17291. (face-attribute face :background nil 'default)
  17292. color)))
  17293. (hash (sha1 (prin1-to-string
  17294. (list org-format-latex-header
  17295. org-latex-default-packages-alist
  17296. org-latex-packages-alist
  17297. org-format-latex-options
  17298. forbuffer value fg bg))))
  17299. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17300. (absprefix (expand-file-name prefix dir))
  17301. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17302. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17303. (sep (and block-type "\n\n"))
  17304. (link (concat sep "[[file:" linkfile "]]" sep))
  17305. (options
  17306. (org-combine-plists
  17307. org-format-latex-options
  17308. `(:foreground ,fg :background ,bg))))
  17309. (when msg (message msg cnt))
  17310. (unless checkdir-flag ; Ensure the directory exists.
  17311. (setq checkdir-flag t)
  17312. (let ((todir (file-name-directory absprefix)))
  17313. (unless (file-directory-p todir)
  17314. (make-directory todir t))))
  17315. (unless (file-exists-p movefile)
  17316. (org-create-formula-image
  17317. value movefile options forbuffer processing-type))
  17318. (if overlays
  17319. (progn
  17320. (dolist (o (overlays-in beg end))
  17321. (when (eq (overlay-get o 'org-overlay-type)
  17322. 'org-latex-overlay)
  17323. (delete-overlay o)))
  17324. (org--format-latex-make-overlay beg end movefile imagetype)
  17325. (goto-char end))
  17326. (delete-region beg end)
  17327. (insert
  17328. (org-add-props link
  17329. (list 'org-latex-src
  17330. (replace-regexp-in-string "\"" "" value)
  17331. 'org-latex-src-embed-type
  17332. (if block-type 'paragraph 'character)))))))
  17333. ((eq processing-type 'mathml)
  17334. ;; Process to MathML.
  17335. (unless (org-format-latex-mathml-available-p)
  17336. (user-error "LaTeX to MathML converter not configured"))
  17337. (cl-incf cnt)
  17338. (when msg (message msg cnt))
  17339. (goto-char beg)
  17340. (delete-region beg end)
  17341. (insert (org-format-latex-as-mathml
  17342. value block-type prefix dir)))
  17343. (t
  17344. (error "Unknown conversion process %s for LaTeX fragments"
  17345. processing-type)))))))))))
  17346. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17347. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17348. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17349. sucessful, return the portion between \"<math...> </math>\"
  17350. elements otherwise return nil. When MATHML-FILE is specified,
  17351. write the results in to that file. When invoked as an
  17352. interactive command, prompt for LATEX-FRAG, with initial value
  17353. set to the current active region and echo the results for user
  17354. inspection."
  17355. (interactive (list (let ((frag (when (org-region-active-p)
  17356. (buffer-substring-no-properties
  17357. (region-beginning) (region-end)))))
  17358. (read-string "LaTeX Fragment: " frag nil frag))))
  17359. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17360. (let* ((tmp-in-file
  17361. (let ((file (file-relative-name
  17362. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17363. (write-region latex-frag nil file)
  17364. file))
  17365. (tmp-out-file (file-relative-name
  17366. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17367. (cmd (format-spec
  17368. org-latex-to-mathml-convert-command
  17369. `((?j . ,(and org-latex-to-mathml-jar-file
  17370. (shell-quote-argument
  17371. (expand-file-name
  17372. org-latex-to-mathml-jar-file))))
  17373. (?I . ,(shell-quote-argument tmp-in-file))
  17374. (?i . ,latex-frag)
  17375. (?o . ,(shell-quote-argument tmp-out-file)))))
  17376. mathml shell-command-output)
  17377. (when (called-interactively-p 'any)
  17378. (unless (org-format-latex-mathml-available-p)
  17379. (user-error "LaTeX to MathML converter not configured")))
  17380. (message "Running %s" cmd)
  17381. (setq shell-command-output (shell-command-to-string cmd))
  17382. (setq mathml
  17383. (when (file-readable-p tmp-out-file)
  17384. (with-current-buffer (find-file-noselect tmp-out-file t)
  17385. (goto-char (point-min))
  17386. (when (re-search-forward
  17387. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17388. (regexp-quote
  17389. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17390. nil t)
  17391. (prog1 (match-string 0) (kill-buffer))))))
  17392. (cond
  17393. (mathml
  17394. (setq mathml
  17395. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17396. (when mathml-file
  17397. (write-region mathml nil mathml-file))
  17398. (when (called-interactively-p 'any)
  17399. (message mathml)))
  17400. ((message "LaTeX to MathML conversion failed")
  17401. (message shell-command-output)))
  17402. (delete-file tmp-in-file)
  17403. (when (file-exists-p tmp-out-file)
  17404. (delete-file tmp-out-file))
  17405. mathml))
  17406. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17407. prefix &optional dir)
  17408. "Use `org-create-math-formula' but check local cache first."
  17409. (let* ((absprefix (expand-file-name prefix dir))
  17410. (print-length nil) (print-level nil)
  17411. (formula-id (concat
  17412. "formula-"
  17413. (sha1
  17414. (prin1-to-string
  17415. (list latex-frag
  17416. org-latex-to-mathml-convert-command)))))
  17417. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17418. (formula-cache-dir (file-name-directory formula-cache)))
  17419. (unless (file-directory-p formula-cache-dir)
  17420. (make-directory formula-cache-dir t))
  17421. (unless (file-exists-p formula-cache)
  17422. (org-create-math-formula latex-frag formula-cache))
  17423. (if (file-exists-p formula-cache)
  17424. ;; Successful conversion. Return the link to MathML file.
  17425. (org-add-props
  17426. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17427. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17428. 'org-latex-src-embed-type (if latex-frag-type
  17429. 'paragraph 'character)))
  17430. ;; Failed conversion. Return the LaTeX fragment verbatim
  17431. latex-frag)))
  17432. (defun org--get-display-dpi ()
  17433. "Get the DPI of the display.
  17434. The function assumes that the display has the same pixel width in
  17435. the horizontal and vertical directions."
  17436. (if (display-graphic-p)
  17437. (round (/ (display-pixel-height)
  17438. (/ (display-mm-height) 25.4)))
  17439. (error "Attempt to calculate the dpi of a non-graphic display")))
  17440. (defun org-create-formula-image
  17441. (string tofile options buffer &optional processing-type)
  17442. "Create an image from LaTeX source using external processes.
  17443. The LaTeX STRING is saved to a temporary LaTeX file, then
  17444. converted to an image file by process PROCESSING-TYPE defined in
  17445. `org-preview-latex-process-alist'. A nil value defaults to
  17446. `org-preview-latex-default-process'.
  17447. The generated image file is eventually moved to TOFILE.
  17448. The OPTIONS argument controls the size, foreground color and
  17449. background color of the generated image.
  17450. When BUFFER non-nil, this function is used for LaTeX previewing.
  17451. Otherwise, it is used to deal with LaTeX snippets showed in
  17452. a HTML file."
  17453. (let* ((processing-type (or processing-type
  17454. org-preview-latex-default-process))
  17455. (processing-info
  17456. (cdr (assq processing-type org-preview-latex-process-alist)))
  17457. (programs (plist-get processing-info :programs))
  17458. (error-message (or (plist-get processing-info :message) ""))
  17459. (use-xcolor (plist-get processing-info :use-xcolor))
  17460. (image-input-type (plist-get processing-info :image-input-type))
  17461. (image-output-type (plist-get processing-info :image-output-type))
  17462. (post-clean (or (plist-get processing-info :post-clean)
  17463. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17464. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17465. (latex-header
  17466. (or (plist-get processing-info :latex-header)
  17467. (org-latex-make-preamble
  17468. (org-export-get-environment (org-export-get-backend 'latex))
  17469. org-format-latex-header
  17470. 'snippet)))
  17471. (latex-compiler (plist-get processing-info :latex-compiler))
  17472. (image-converter (plist-get processing-info :image-converter))
  17473. (tmpdir temporary-file-directory)
  17474. (texfilebase (make-temp-name
  17475. (expand-file-name "orgtex" tmpdir)))
  17476. (texfile (concat texfilebase ".tex"))
  17477. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17478. '(1.0 . 1.0)))
  17479. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17480. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17481. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17482. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17483. "Black"))
  17484. (bg (or (plist-get options (if buffer :background :html-background))
  17485. "Transparent"))
  17486. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17487. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17488. (dolist (program programs)
  17489. (org-check-external-command program error-message))
  17490. (if use-xcolor
  17491. (progn (if (eq fg 'default)
  17492. (setq fg (org-latex-color :foreground))
  17493. (setq fg (org-latex-color-format fg)))
  17494. (if (eq bg 'default)
  17495. (setq bg (org-latex-color :background))
  17496. (setq bg (org-latex-color-format
  17497. (if (string= bg "Transparent") "white" bg))))
  17498. (with-temp-file texfile
  17499. (insert latex-header)
  17500. (insert "\n\\begin{document}\n"
  17501. "\\definecolor{fg}{rgb}{" fg "}\n"
  17502. "\\definecolor{bg}{rgb}{" bg "}\n"
  17503. "\n\\pagecolor{bg}\n"
  17504. "\n{\\color{fg}\n"
  17505. string
  17506. "\n}\n"
  17507. "\n\\end{document}\n")))
  17508. (if (eq fg 'default)
  17509. (setq fg (org-dvipng-color :foreground))
  17510. (unless (string= fg "Transparent")
  17511. (setq fg (org-dvipng-color-format fg))))
  17512. (if (eq bg 'default)
  17513. (setq bg (org-dvipng-color :background))
  17514. (unless (string= bg "Transparent")
  17515. (setq bg (org-dvipng-color-format bg))))
  17516. (with-temp-file texfile
  17517. (insert latex-header)
  17518. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17519. (let* ((err-msg (format "Please adjust `%s' part of \
  17520. `org-preview-latex-process-alist'."
  17521. processing-type))
  17522. (image-input-file
  17523. (org-compile-file
  17524. texfile latex-compiler image-input-type err-msg log-buf))
  17525. (image-output-file
  17526. (org-compile-file
  17527. image-input-file image-converter image-output-type err-msg log-buf
  17528. `((?F . ,(shell-quote-argument fg))
  17529. (?B . ,(shell-quote-argument bg))
  17530. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17531. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17532. (copy-file image-output-file tofile 'replace)
  17533. (dolist (e post-clean)
  17534. (when (file-exists-p (concat texfilebase e))
  17535. (delete-file (concat texfilebase e))))
  17536. image-output-file)))
  17537. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17538. "Fill a LaTeX header template TPL.
  17539. In the template, the following place holders will be recognized:
  17540. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17541. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17542. [PACKAGES] \\usepackage statements for PKG
  17543. [NO-PACKAGES] do not include PKG
  17544. [EXTRA] the string EXTRA
  17545. [NO-EXTRA] do not include EXTRA
  17546. For backward compatibility, if both the positive and the negative place
  17547. holder is missing, the positive one (without the \"NO-\") will be
  17548. assumed to be present at the end of the template.
  17549. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17550. EXTRA is a string.
  17551. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17552. (let (rpl (end ""))
  17553. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17554. (setq rpl (if (or (match-end 1) (not def-pkg))
  17555. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17556. tpl (replace-match rpl t t tpl))
  17557. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17558. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17559. (setq rpl (if (or (match-end 1) (not pkg))
  17560. "" (org-latex-packages-to-string pkg snippets-p t))
  17561. tpl (replace-match rpl t t tpl))
  17562. (when pkg (setq end
  17563. (concat end "\n"
  17564. (org-latex-packages-to-string pkg snippets-p)))))
  17565. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17566. (setq rpl (if (or (match-end 1) (not extra))
  17567. "" (concat extra "\n"))
  17568. tpl (replace-match rpl t t tpl))
  17569. (when (and extra (string-match "\\S-" extra))
  17570. (setq end (concat end "\n" extra))))
  17571. (if (string-match "\\S-" end)
  17572. (concat tpl "\n" end)
  17573. tpl)))
  17574. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17575. "Turn an alist of packages into a string with the \\usepackage macros."
  17576. (setq pkg (mapconcat (lambda(p)
  17577. (cond
  17578. ((stringp p) p)
  17579. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17580. (format "%% Package %s omitted" (cadr p)))
  17581. ((equal "" (car p))
  17582. (format "\\usepackage{%s}" (cadr p)))
  17583. (t
  17584. (format "\\usepackage[%s]{%s}"
  17585. (car p) (cadr p)))))
  17586. pkg
  17587. "\n"))
  17588. (if newline (concat pkg "\n") pkg))
  17589. (defun org-dvipng-color (attr)
  17590. "Return a RGB color specification for dvipng."
  17591. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17592. (defun org-dvipng-color-format (color-name)
  17593. "Convert COLOR-NAME to a RGB color value for dvipng."
  17594. (apply #'format "rgb %s %s %s"
  17595. (mapcar 'org-normalize-color
  17596. (color-values color-name))))
  17597. (defun org-latex-color (attr)
  17598. "Return a RGB color for the LaTeX color package."
  17599. (org-latex-color-format (face-attribute 'default attr nil)))
  17600. (defun org-latex-color-format (color-name)
  17601. "Convert COLOR-NAME to a RGB color value."
  17602. (apply #'format "%s,%s,%s"
  17603. (mapcar 'org-normalize-color
  17604. (color-values color-name))))
  17605. (defun org-normalize-color (value)
  17606. "Return string to be used as color value for an RGB component."
  17607. (format "%g" (/ value 65535.0)))
  17608. ;; Image display
  17609. (defvar-local org-inline-image-overlays nil)
  17610. (defun org-toggle-inline-images (&optional include-linked)
  17611. "Toggle the display of inline images.
  17612. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17613. (interactive "P")
  17614. (if org-inline-image-overlays
  17615. (progn
  17616. (org-remove-inline-images)
  17617. (when (called-interactively-p 'interactive)
  17618. (message "Inline image display turned off")))
  17619. (org-display-inline-images include-linked)
  17620. (when (called-interactively-p 'interactive)
  17621. (message (if org-inline-image-overlays
  17622. (format "%d images displayed inline"
  17623. (length org-inline-image-overlays))
  17624. "No images to display inline")))))
  17625. (defun org-redisplay-inline-images ()
  17626. "Refresh the display of inline images."
  17627. (interactive)
  17628. (if (not org-inline-image-overlays)
  17629. (org-toggle-inline-images)
  17630. (org-toggle-inline-images)
  17631. (org-toggle-inline-images)))
  17632. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17633. "Display inline images.
  17634. An inline image is a link which follows either of these
  17635. conventions:
  17636. 1. Its path is a file with an extension matching return value
  17637. from `image-file-name-regexp' and it has no contents.
  17638. 2. Its description consists in a single link of the previous
  17639. type.
  17640. When optional argument INCLUDE-LINKED is non-nil, also links with
  17641. a text description part will be inlined. This can be nice for
  17642. a quick look at those images, but it does not reflect what
  17643. exported files will look like.
  17644. When optional argument REFRESH is non-nil, refresh existing
  17645. images between BEG and END. This will create new image displays
  17646. only if necessary. BEG and END default to the buffer
  17647. boundaries."
  17648. (interactive "P")
  17649. (when (display-graphic-p)
  17650. (unless refresh
  17651. (org-remove-inline-images)
  17652. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17653. (org-with-wide-buffer
  17654. (goto-char (or beg (point-min)))
  17655. (let* ((case-fold-search t)
  17656. (file-extension-re (image-file-name-regexp))
  17657. (link-abbrevs (mapcar #'car
  17658. (append org-link-abbrev-alist-local
  17659. org-link-abbrev-alist)))
  17660. ;; Check absolute, relative file names and explicit
  17661. ;; "file:" links. Also check link abbreviations since
  17662. ;; some might expand to "file" links.
  17663. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17664. (if (not link-abbrevs) ""
  17665. (format "\\|\\(?:%s:\\)"
  17666. (regexp-opt link-abbrevs))))))
  17667. (while (re-search-forward file-types-re end t)
  17668. (let ((link (save-match-data (org-element-context))))
  17669. ;; Check if we're at an inline image, i.e., an image file
  17670. ;; link without a description (unless INCLUDE-LINKED is
  17671. ;; non-nil).
  17672. (when (and (equal "file" (org-element-property :type link))
  17673. (or include-linked
  17674. (null (org-element-contents link)))
  17675. (string-match-p file-extension-re
  17676. (org-element-property :path link)))
  17677. (let ((file (expand-file-name
  17678. (org-link-unescape
  17679. (org-element-property :path link)))))
  17680. (when (file-exists-p file)
  17681. (let ((width
  17682. ;; Apply `org-image-actual-width' specifications.
  17683. (cond
  17684. ((not (image-type-available-p 'imagemagick)) nil)
  17685. ((eq org-image-actual-width t) nil)
  17686. ((listp org-image-actual-width)
  17687. (or
  17688. ;; First try to find a width among
  17689. ;; attributes associated to the paragraph
  17690. ;; containing link.
  17691. (let ((paragraph
  17692. (let ((e link))
  17693. (while (and (setq e (org-element-property
  17694. :parent e))
  17695. (not (eq (org-element-type e)
  17696. 'paragraph))))
  17697. e)))
  17698. (when paragraph
  17699. (save-excursion
  17700. (goto-char (org-element-property :begin paragraph))
  17701. (when
  17702. (re-search-forward
  17703. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17704. (org-element-property
  17705. :post-affiliated paragraph)
  17706. t)
  17707. (string-to-number (match-string 1))))))
  17708. ;; Otherwise, fall-back to provided number.
  17709. (car org-image-actual-width)))
  17710. ((numberp org-image-actual-width)
  17711. org-image-actual-width)))
  17712. (old (get-char-property-and-overlay
  17713. (org-element-property :begin link)
  17714. 'org-image-overlay)))
  17715. (if (and (car-safe old) refresh)
  17716. (image-refresh (overlay-get (cdr old) 'display))
  17717. (let ((image (create-image file
  17718. (and width 'imagemagick)
  17719. nil
  17720. :width width)))
  17721. (when image
  17722. (let ((ov (make-overlay
  17723. (org-element-property :begin link)
  17724. (progn
  17725. (goto-char
  17726. (org-element-property :end link))
  17727. (skip-chars-backward " \t")
  17728. (point)))))
  17729. (overlay-put ov 'display image)
  17730. (overlay-put ov 'face 'default)
  17731. (overlay-put ov 'org-image-overlay t)
  17732. (overlay-put
  17733. ov 'modification-hooks
  17734. (list 'org-display-inline-remove-overlay))
  17735. (push ov org-inline-image-overlays)))))))))))))))
  17736. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17737. "Remove inline-display overlay if a corresponding region is modified."
  17738. (let ((inhibit-modification-hooks t))
  17739. (when (and ov after)
  17740. (delete ov org-inline-image-overlays)
  17741. (delete-overlay ov))))
  17742. (defun org-remove-inline-images ()
  17743. "Remove inline display of images."
  17744. (interactive)
  17745. (mapc #'delete-overlay org-inline-image-overlays)
  17746. (setq org-inline-image-overlays nil))
  17747. ;;;; Key bindings
  17748. (defun org-remap (map &rest commands)
  17749. "In MAP, remap the functions given in COMMANDS.
  17750. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17751. (let (new old)
  17752. (while commands
  17753. (setq old (pop commands) new (pop commands))
  17754. (org-defkey map (vector 'remap old) new))))
  17755. ;; Outline functions from `outline-mode-prefix-map'
  17756. ;; that can be remapped in Org:
  17757. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17758. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17759. (define-key org-mode-map [remap outline-forward-same-level]
  17760. 'org-forward-heading-same-level)
  17761. (define-key org-mode-map [remap outline-backward-same-level]
  17762. 'org-backward-heading-same-level)
  17763. (define-key org-mode-map [remap outline-show-branches]
  17764. 'org-kill-note-or-show-branches)
  17765. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17766. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17767. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17768. (define-key org-mode-map [remap outline-next-visible-heading]
  17769. 'org-next-visible-heading)
  17770. (define-key org-mode-map [remap outline-previous-visible-heading]
  17771. 'org-previous-visible-heading)
  17772. (define-key org-mode-map [remap show-children] 'org-show-children)
  17773. ;; Outline functions from `outline-mode-prefix-map' that can not
  17774. ;; be remapped in Org:
  17775. ;; - the column "key binding" shows whether the Outline function is still
  17776. ;; available in Org mode on the same key that it has been bound to in
  17777. ;; Outline mode:
  17778. ;; - "overridden": key used for a different functionality in Org mode
  17779. ;; - else: key still bound to the same Outline function in Org mode
  17780. ;; | Outline function | key binding | Org replacement |
  17781. ;; |------------------------------------+-------------+--------------------------|
  17782. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17783. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17784. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17785. ;; | `show-entry' | overridden | no replacement |
  17786. ;; | `show-branches' | `C-c C-k' | still same function |
  17787. ;; | `show-subtree' | overridden | visibility cycling |
  17788. ;; | `show-all' | overridden | no replacement |
  17789. ;; | `hide-subtree' | overridden | visibility cycling |
  17790. ;; | `hide-body' | overridden | no replacement |
  17791. ;; | `hide-entry' | overridden | visibility cycling |
  17792. ;; | `hide-leaves' | overridden | no replacement |
  17793. ;; | `hide-sublevels' | overridden | no replacement |
  17794. ;; | `hide-other' | overridden | no replacement |
  17795. ;; Make `C-c C-x' a prefix key
  17796. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17797. ;; TAB key with modifiers
  17798. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17799. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17800. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17801. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17802. ;; The following line is necessary under Suse GNU/Linux
  17803. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17804. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17805. (define-key org-mode-map [backtab] 'org-shifttab)
  17806. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17807. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17808. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17809. ;; Cursor keys with modifiers
  17810. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17811. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17812. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17813. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17814. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17815. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17816. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17817. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17818. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17819. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17820. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17821. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17822. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17823. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17824. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17825. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17826. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17827. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17828. ;; Babel keys
  17829. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17830. (dolist (pair org-babel-key-bindings)
  17831. (define-key org-babel-map (car pair) (cdr pair)))
  17832. ;;; Extra keys for tty access.
  17833. ;; We only set them when really needed because otherwise the
  17834. ;; menus don't show the simple keys
  17835. (when (or org-use-extra-keys (not window-system))
  17836. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17837. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17838. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17839. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17840. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17841. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17842. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17843. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17844. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17845. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17846. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17847. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17848. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17849. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17850. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17851. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17852. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17853. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17854. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17855. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17856. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17857. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17858. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17859. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17860. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17861. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17862. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17863. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17864. ;; All the other keys
  17865. (org-remap org-mode-map
  17866. 'self-insert-command 'org-self-insert-command
  17867. 'delete-char 'org-delete-char
  17868. 'delete-backward-char 'org-delete-backward-char)
  17869. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17870. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17871. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17872. (if (boundp 'narrow-map)
  17873. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17874. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17875. (if (boundp 'narrow-map)
  17876. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17877. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17878. (if (boundp 'narrow-map)
  17879. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17880. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17881. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17882. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17883. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17884. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17885. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17886. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17887. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17888. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17889. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17890. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17891. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17892. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17893. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17894. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17895. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17896. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17897. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17898. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17899. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17900. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17901. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17902. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17903. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17904. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17905. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17906. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17907. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17908. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17909. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17910. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17911. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17912. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17913. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17914. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17915. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17916. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17917. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17918. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17919. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17920. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17921. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17922. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17923. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17924. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17925. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17926. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17927. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17928. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17929. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17930. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17931. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17932. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17933. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17934. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17935. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17936. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17937. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17938. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17939. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17940. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17941. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17942. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17943. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17944. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17945. (org-defkey org-mode-map "\C-m" 'org-return)
  17946. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17947. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17948. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17949. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17950. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17951. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17952. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17953. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17954. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17955. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17956. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17957. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17958. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17959. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17960. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17961. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17962. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17963. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17964. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17965. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17966. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17967. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17968. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17969. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17970. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17971. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17972. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17973. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17974. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17975. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17976. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17977. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17978. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17979. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17980. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17981. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17982. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17983. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17984. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17985. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17986. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17987. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17988. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17989. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17990. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17991. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17992. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17993. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17994. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17995. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17996. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17997. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17998. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17999. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18000. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18001. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18002. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18003. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18004. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18005. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18006. (defconst org-speed-commands-default
  18007. '(
  18008. ("Outline Navigation")
  18009. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18010. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18011. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18012. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18013. ("F" . org-next-block)
  18014. ("B" . org-previous-block)
  18015. ("u" . (org-speed-move-safe 'outline-up-heading))
  18016. ("j" . org-goto)
  18017. ("g" . (org-refile t))
  18018. ("Outline Visibility")
  18019. ("c" . org-cycle)
  18020. ("C" . org-shifttab)
  18021. (" " . org-display-outline-path)
  18022. ("s" . org-narrow-to-subtree)
  18023. ("=" . org-columns)
  18024. ("Outline Structure Editing")
  18025. ("U" . org-metaup)
  18026. ("D" . org-metadown)
  18027. ("r" . org-metaright)
  18028. ("l" . org-metaleft)
  18029. ("R" . org-shiftmetaright)
  18030. ("L" . org-shiftmetaleft)
  18031. ("i" . (progn (forward-char 1) (call-interactively
  18032. 'org-insert-heading-respect-content)))
  18033. ("^" . org-sort)
  18034. ("w" . org-refile)
  18035. ("a" . org-archive-subtree-default-with-confirmation)
  18036. ("@" . org-mark-subtree)
  18037. ("#" . org-toggle-comment)
  18038. ("Clock Commands")
  18039. ("I" . org-clock-in)
  18040. ("O" . org-clock-out)
  18041. ("Meta Data Editing")
  18042. ("t" . org-todo)
  18043. ("," . (org-priority))
  18044. ("0" . (org-priority ?\ ))
  18045. ("1" . (org-priority ?A))
  18046. ("2" . (org-priority ?B))
  18047. ("3" . (org-priority ?C))
  18048. (":" . org-set-tags-command)
  18049. ("e" . org-set-effort)
  18050. ("E" . org-inc-effort)
  18051. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18052. (org-entry-put (point) "APPT_WARNTIME" m)))
  18053. ("Agenda Views etc")
  18054. ("v" . org-agenda)
  18055. ("/" . org-sparse-tree)
  18056. ("Misc")
  18057. ("o" . org-open-at-point)
  18058. ("?" . org-speed-command-help)
  18059. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18060. (">" . (org-agenda-remove-restriction-lock))
  18061. )
  18062. "The default speed commands.")
  18063. (defun org-print-speed-command (e)
  18064. (if (> (length (car e)) 1)
  18065. (progn
  18066. (princ "\n")
  18067. (princ (car e))
  18068. (princ "\n")
  18069. (princ (make-string (length (car e)) ?-))
  18070. (princ "\n"))
  18071. (princ (car e))
  18072. (princ " ")
  18073. (if (symbolp (cdr e))
  18074. (princ (symbol-name (cdr e)))
  18075. (prin1 (cdr e)))
  18076. (princ "\n")))
  18077. (defun org-speed-command-help ()
  18078. "Show the available speed commands."
  18079. (interactive)
  18080. (if (not org-use-speed-commands)
  18081. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18082. (with-output-to-temp-buffer "*Help*"
  18083. (princ "User-defined Speed commands\n===========================\n")
  18084. (mapc #'org-print-speed-command org-speed-commands-user)
  18085. (princ "\n")
  18086. (princ "Built-in Speed commands\n=======================\n")
  18087. (mapc #'org-print-speed-command org-speed-commands-default))
  18088. (with-current-buffer "*Help*"
  18089. (setq truncate-lines t))))
  18090. (defun org-speed-move-safe (cmd)
  18091. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18092. If not, return to the original position and throw an error."
  18093. (interactive)
  18094. (let ((pos (point)))
  18095. (call-interactively cmd)
  18096. (unless (and (bolp) (org-at-heading-p))
  18097. (goto-char pos)
  18098. (error "Boundary reached while executing %s" cmd))))
  18099. (defvar org-self-insert-command-undo-counter 0)
  18100. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18101. (defvar org-speed-command nil)
  18102. (defun org-speed-command-activate (keys)
  18103. "Hook for activating single-letter speed commands.
  18104. `org-speed-commands-default' specifies a minimal command set.
  18105. Use `org-speed-commands-user' for further customization."
  18106. (when (or (and (bolp) (looking-at org-outline-regexp))
  18107. (and (functionp org-use-speed-commands)
  18108. (funcall org-use-speed-commands)))
  18109. (cdr (assoc keys (append org-speed-commands-user
  18110. org-speed-commands-default)))))
  18111. (defun org-babel-speed-command-activate (keys)
  18112. "Hook for activating single-letter code block commands."
  18113. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18114. (cdr (assoc keys org-babel-key-bindings))))
  18115. (defcustom org-speed-command-hook
  18116. '(org-speed-command-activate org-babel-speed-command-activate)
  18117. "Hook for activating speed commands at strategic locations.
  18118. Hook functions are called in sequence until a valid handler is
  18119. found.
  18120. Each hook takes a single argument, a user-pressed command key
  18121. which is also a `self-insert-command' from the global map.
  18122. Within the hook, examine the cursor position and the command key
  18123. and return nil or a valid handler as appropriate. Handler could
  18124. be one of an interactive command, a function, or a form.
  18125. Set `org-use-speed-commands' to non-nil value to enable this
  18126. hook. The default setting is `org-speed-command-activate'."
  18127. :group 'org-structure
  18128. :version "24.1"
  18129. :type 'hook)
  18130. (defun org-self-insert-command (N)
  18131. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18132. If the cursor is in a table looking at whitespace, the whitespace is
  18133. overwritten, and the table is not marked as requiring realignment."
  18134. (interactive "p")
  18135. (org-check-before-invisible-edit 'insert)
  18136. (cond
  18137. ((and org-use-speed-commands
  18138. (let ((kv (this-command-keys-vector)))
  18139. (setq org-speed-command
  18140. (run-hook-with-args-until-success
  18141. 'org-speed-command-hook
  18142. (make-string 1 (aref kv (1- (length kv))))))))
  18143. (cond
  18144. ((commandp org-speed-command)
  18145. (setq this-command org-speed-command)
  18146. (call-interactively org-speed-command))
  18147. ((functionp org-speed-command)
  18148. (funcall org-speed-command))
  18149. ((and org-speed-command (listp org-speed-command))
  18150. (eval org-speed-command))
  18151. (t (let (org-use-speed-commands)
  18152. (call-interactively 'org-self-insert-command)))))
  18153. ((and
  18154. (org-at-table-p)
  18155. (eq N 1)
  18156. (not (org-region-active-p))
  18157. (progn
  18158. ;; Check if we blank the field, and if that triggers align.
  18159. (and (featurep 'org-table) org-table-auto-blank-field
  18160. (memq last-command
  18161. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18162. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18163. ;; Got extra space, this field does not determine
  18164. ;; column width.
  18165. (let (org-table-may-need-update) (org-table-blank-field))
  18166. ;; No extra space, this field may determine column
  18167. ;; width.
  18168. (org-table-blank-field)))
  18169. t)
  18170. (looking-at "[^|\n]* \\( \\)|"))
  18171. ;; There is room for insertion without re-aligning the table.
  18172. (delete-region (match-beginning 1) (match-end 1))
  18173. (self-insert-command N))
  18174. (t
  18175. (setq org-table-may-need-update t)
  18176. (self-insert-command N)
  18177. (org-fix-tags-on-the-fly)
  18178. (when org-self-insert-cluster-for-undo
  18179. (if (not (eq last-command 'org-self-insert-command))
  18180. (setq org-self-insert-command-undo-counter 1)
  18181. (if (>= org-self-insert-command-undo-counter 20)
  18182. (setq org-self-insert-command-undo-counter 1)
  18183. (and (> org-self-insert-command-undo-counter 0)
  18184. buffer-undo-list (listp buffer-undo-list)
  18185. (not (cadr buffer-undo-list)) ; remove nil entry
  18186. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18187. (setq org-self-insert-command-undo-counter
  18188. (1+ org-self-insert-command-undo-counter))))))))
  18189. (defun org-check-before-invisible-edit (kind)
  18190. "Check is editing if kind KIND would be dangerous with invisible text around.
  18191. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18192. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18193. (when (and org-catch-invisible-edits
  18194. (or (not (boundp 'visible-mode)) (not visible-mode))
  18195. (or (get-char-property (point) 'invisible)
  18196. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18197. ;; OK, we need to take a closer look. Do not consider
  18198. ;; invisibility obtained through text properties (e.g., link
  18199. ;; fontification), as it cannot be toggled.
  18200. (let* ((invisible-at-point
  18201. (pcase (get-char-property-and-overlay (point) 'invisible)
  18202. (`(,_ . ,(and (pred overlayp) o)) o)))
  18203. ;; Assume that point cannot land in the middle of an
  18204. ;; overlay, or between two overlays.
  18205. (invisible-before-point
  18206. (and (not invisible-at-point)
  18207. (not (bobp))
  18208. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18209. (`(,_ . ,(and (pred overlayp) o)) o))))
  18210. (border-and-ok-direction
  18211. (or
  18212. ;; Check if we are acting predictably before invisible
  18213. ;; text.
  18214. (and invisible-at-point
  18215. (memq kind '(insert delete-backward)))
  18216. ;; Check if we are acting predictably after invisible text
  18217. ;; This works not well, and I have turned it off. It seems
  18218. ;; better to always show and stop after invisible text.
  18219. ;; (and (not invisible-at-point) invisible-before-point
  18220. ;; (memq kind '(insert delete)))
  18221. )))
  18222. (when (or invisible-at-point invisible-before-point)
  18223. (when (eq org-catch-invisible-edits 'error)
  18224. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18225. (if (and org-custom-properties-overlays
  18226. (y-or-n-p "Display invisible properties in this buffer? "))
  18227. (org-toggle-custom-properties-visibility)
  18228. ;; Make the area visible
  18229. (save-excursion
  18230. (when invisible-before-point
  18231. (goto-char
  18232. (previous-single-char-property-change (point) 'invisible)))
  18233. ;; Remove whatever overlay is currently making yet-to-be
  18234. ;; edited text invisible. Also remove nested invisibility
  18235. ;; related overlays.
  18236. (delete-overlay (or invisible-at-point invisible-before-point))
  18237. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18238. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18239. (`(,_ . ,(and (pred overlayp) o))
  18240. (delete-overlay o)
  18241. t)))))
  18242. (cond
  18243. ((eq org-catch-invisible-edits 'show)
  18244. ;; That's it, we do the edit after showing
  18245. (message
  18246. "Unfolding invisible region around point before editing")
  18247. (sit-for 1))
  18248. ((and (eq org-catch-invisible-edits 'smart)
  18249. border-and-ok-direction)
  18250. (message "Unfolding invisible region around point before editing"))
  18251. (t
  18252. ;; Don't do the edit, make the user repeat it in full visibility
  18253. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18254. (defun org-fix-tags-on-the-fly ()
  18255. "Align tags in headline at point.
  18256. Unlike to `org-set-tags', it ignores region and sorting."
  18257. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18258. (org-at-heading-p))
  18259. (let ((org-ignore-region t)
  18260. (org-tags-sort-function nil))
  18261. (org-set-tags nil t))))
  18262. (defun org-delete-backward-char (N)
  18263. "Like `delete-backward-char', insert whitespace at field end in tables.
  18264. When deleting backwards, in tables this function will insert whitespace in
  18265. front of the next \"|\" separator, to keep the table aligned. The table will
  18266. still be marked for re-alignment if the field did fill the entire column,
  18267. because, in this case the deletion might narrow the column."
  18268. (interactive "p")
  18269. (save-match-data
  18270. (org-check-before-invisible-edit 'delete-backward)
  18271. (if (and (org-at-table-p)
  18272. (eq N 1)
  18273. (not (org-region-active-p))
  18274. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18275. (looking-at ".*?|"))
  18276. (let ((pos (point))
  18277. (noalign (looking-at "[^|\n\r]* |"))
  18278. (c org-table-may-need-update))
  18279. (backward-delete-char N)
  18280. (unless overwrite-mode
  18281. (skip-chars-forward "^|")
  18282. (insert " ")
  18283. (goto-char (1- pos)))
  18284. ;; noalign: if there were two spaces at the end, this field
  18285. ;; does not determine the width of the column.
  18286. (when noalign (setq org-table-may-need-update c)))
  18287. (backward-delete-char N)
  18288. (org-fix-tags-on-the-fly))))
  18289. (defun org-delete-char (N)
  18290. "Like `delete-char', but insert whitespace at field end in tables.
  18291. When deleting characters, in tables this function will insert whitespace in
  18292. front of the next \"|\" separator, to keep the table aligned. The table will
  18293. still be marked for re-alignment if the field did fill the entire column,
  18294. because, in this case the deletion might narrow the column."
  18295. (interactive "p")
  18296. (save-match-data
  18297. (org-check-before-invisible-edit 'delete)
  18298. (if (and (org-at-table-p)
  18299. (not (bolp))
  18300. (not (= (char-after) ?|))
  18301. (eq N 1))
  18302. (if (looking-at ".*?|")
  18303. (let ((pos (point))
  18304. (noalign (looking-at "[^|\n\r]* |"))
  18305. (c org-table-may-need-update))
  18306. (replace-match
  18307. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18308. (goto-char pos)
  18309. ;; noalign: if there were two spaces at the end, this field
  18310. ;; does not determine the width of the column.
  18311. (when noalign (setq org-table-may-need-update c)))
  18312. (delete-char N))
  18313. (delete-char N)
  18314. (org-fix-tags-on-the-fly))))
  18315. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18316. (put 'org-self-insert-command 'delete-selection
  18317. (lambda ()
  18318. (not (run-hook-with-args-until-success
  18319. 'self-insert-uses-region-functions))))
  18320. (put 'orgtbl-self-insert-command 'delete-selection
  18321. (lambda ()
  18322. (not (run-hook-with-args-until-success
  18323. 'self-insert-uses-region-functions))))
  18324. (put 'org-delete-char 'delete-selection 'supersede)
  18325. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18326. (put 'org-yank 'delete-selection 'yank)
  18327. ;; Make `flyspell-mode' delay after some commands
  18328. (put 'org-self-insert-command 'flyspell-delayed t)
  18329. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18330. (put 'org-delete-char 'flyspell-delayed t)
  18331. (put 'org-delete-backward-char 'flyspell-delayed t)
  18332. ;; Make pabbrev-mode expand after Org mode commands
  18333. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18334. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18335. (defun org-transpose-words ()
  18336. "Transpose words for Org.
  18337. This uses the `org-mode-transpose-word-syntax-table' syntax
  18338. table, which interprets characters in `org-emphasis-alist' as
  18339. word constituents."
  18340. (interactive)
  18341. (with-syntax-table org-mode-transpose-word-syntax-table
  18342. (call-interactively 'transpose-words)))
  18343. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18344. (defvar org-ctrl-c-ctrl-c-hook nil
  18345. "Hook for functions attaching themselves to `C-c C-c'.
  18346. This can be used to add additional functionality to the C-c C-c
  18347. key which executes context-dependent commands. This hook is run
  18348. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18349. run after the last test.
  18350. Each function will be called with no arguments. The function
  18351. must check if the context is appropriate for it to act. If yes,
  18352. it should do its thing and then return a non-nil value. If the
  18353. context is wrong, just do nothing and return nil.")
  18354. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18355. "Hook for functions attaching themselves to `C-c C-c'.
  18356. This can be used to add additional functionality to the C-c C-c
  18357. key which executes context-dependent commands. This hook is run
  18358. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18359. before the first test.
  18360. Each function will be called with no arguments. The function
  18361. must check if the context is appropriate for it to act. If yes,
  18362. it should do its thing and then return a non-nil value. If the
  18363. context is wrong, just do nothing and return nil.")
  18364. (defvar org-tab-first-hook nil
  18365. "Hook for functions to attach themselves to TAB.
  18366. See `org-ctrl-c-ctrl-c-hook' for more information.
  18367. This hook runs as the first action when TAB is pressed, even before
  18368. `org-cycle' messes around with the `outline-regexp' to cater for
  18369. inline tasks and plain list item folding.
  18370. If any function in this hook returns t, any other actions that
  18371. would have been caused by TAB (such as table field motion or visibility
  18372. cycling) will not occur.")
  18373. (defvar org-tab-after-check-for-table-hook nil
  18374. "Hook for functions to attach themselves to TAB.
  18375. See `org-ctrl-c-ctrl-c-hook' for more information.
  18376. This hook runs after it has been established that the cursor is not in a
  18377. table, but before checking if the cursor is in a headline or if global cycling
  18378. should be done.
  18379. If any function in this hook returns t, not other actions like visibility
  18380. cycling will be done.")
  18381. (defvar org-tab-after-check-for-cycling-hook nil
  18382. "Hook for functions to attach themselves to TAB.
  18383. See `org-ctrl-c-ctrl-c-hook' for more information.
  18384. This hook runs after it has been established that not table field motion and
  18385. not visibility should be done because of current context. This is probably
  18386. the place where a package like yasnippets can hook in.")
  18387. (defvar org-tab-before-tab-emulation-hook nil
  18388. "Hook for functions to attach themselves to TAB.
  18389. See `org-ctrl-c-ctrl-c-hook' for more information.
  18390. This hook runs after every other options for TAB have been exhausted, but
  18391. before indentation and \t insertion takes place.")
  18392. (defvar org-metaleft-hook nil
  18393. "Hook for functions attaching themselves to `M-left'.
  18394. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18395. (defvar org-metaright-hook nil
  18396. "Hook for functions attaching themselves to `M-right'.
  18397. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18398. (defvar org-metaup-hook nil
  18399. "Hook for functions attaching themselves to `M-up'.
  18400. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18401. (defvar org-metadown-hook nil
  18402. "Hook for functions attaching themselves to `M-down'.
  18403. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18404. (defvar org-shiftmetaleft-hook nil
  18405. "Hook for functions attaching themselves to `M-S-left'.
  18406. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18407. (defvar org-shiftmetaright-hook nil
  18408. "Hook for functions attaching themselves to `M-S-right'.
  18409. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18410. (defvar org-shiftmetaup-hook nil
  18411. "Hook for functions attaching themselves to `M-S-up'.
  18412. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18413. (defvar org-shiftmetadown-hook nil
  18414. "Hook for functions attaching themselves to `M-S-down'.
  18415. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18416. (defvar org-metareturn-hook nil
  18417. "Hook for functions attaching themselves to `M-RET'.
  18418. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18419. (defvar org-shiftup-hook nil
  18420. "Hook for functions attaching themselves to `S-up'.
  18421. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18422. (defvar org-shiftup-final-hook nil
  18423. "Hook for functions attaching themselves to `S-up'.
  18424. This one runs after all other options except shift-select have been excluded.
  18425. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18426. (defvar org-shiftdown-hook nil
  18427. "Hook for functions attaching themselves to `S-down'.
  18428. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18429. (defvar org-shiftdown-final-hook nil
  18430. "Hook for functions attaching themselves to `S-down'.
  18431. This one runs after all other options except shift-select have been excluded.
  18432. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18433. (defvar org-shiftleft-hook nil
  18434. "Hook for functions attaching themselves to `S-left'.
  18435. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18436. (defvar org-shiftleft-final-hook nil
  18437. "Hook for functions attaching themselves to `S-left'.
  18438. This one runs after all other options except shift-select have been excluded.
  18439. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18440. (defvar org-shiftright-hook nil
  18441. "Hook for functions attaching themselves to `S-right'.
  18442. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18443. (defvar org-shiftright-final-hook nil
  18444. "Hook for functions attaching themselves to `S-right'.
  18445. This one runs after all other options except shift-select have been excluded.
  18446. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18447. (defun org-modifier-cursor-error ()
  18448. "Throw an error, a modified cursor command was applied in wrong context."
  18449. (user-error "This command is active in special context like tables, headlines or items"))
  18450. (defun org-shiftselect-error ()
  18451. "Throw an error because Shift-Cursor command was applied in wrong context."
  18452. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18453. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18454. (user-error "This command works only in special context like headlines or timestamps")))
  18455. (defun org-call-for-shift-select (cmd)
  18456. (let ((this-command-keys-shift-translated t))
  18457. (call-interactively cmd)))
  18458. (defun org-shifttab (&optional arg)
  18459. "Global visibility cycling or move to previous table field.
  18460. Call `org-table-previous-field' within a table.
  18461. When ARG is nil, cycle globally through visibility states.
  18462. When ARG is a numeric prefix, show contents of this level."
  18463. (interactive "P")
  18464. (cond
  18465. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18466. ((integerp arg)
  18467. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18468. (message "Content view to level: %d" arg)
  18469. (org-content (prefix-numeric-value arg2))
  18470. (org-cycle-show-empty-lines t)
  18471. (setq org-cycle-global-status 'overview)))
  18472. (t (call-interactively 'org-global-cycle))))
  18473. (defun org-shiftmetaleft ()
  18474. "Promote subtree or delete table column.
  18475. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18476. `org-table-delete-column', depending on context. See the
  18477. individual commands for more information."
  18478. (interactive)
  18479. (cond
  18480. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18481. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18482. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18483. ((if (not (org-region-active-p)) (org-at-item-p)
  18484. (save-excursion (goto-char (region-beginning))
  18485. (org-at-item-p)))
  18486. (call-interactively 'org-outdent-item-tree))
  18487. (t (org-modifier-cursor-error))))
  18488. (defun org-shiftmetaright ()
  18489. "Demote subtree or insert table column.
  18490. Calls `org-demote-subtree', `org-indent-item-tree', or
  18491. `org-table-insert-column', depending on context. See the
  18492. individual commands for more information."
  18493. (interactive)
  18494. (cond
  18495. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18496. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18497. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18498. ((if (not (org-region-active-p)) (org-at-item-p)
  18499. (save-excursion (goto-char (region-beginning))
  18500. (org-at-item-p)))
  18501. (call-interactively 'org-indent-item-tree))
  18502. (t (org-modifier-cursor-error))))
  18503. (defun org-shiftmetaup (&optional _arg)
  18504. "Drag the line at point up.
  18505. In a table, kill the current row.
  18506. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18507. but also adjust the previous clocked item in the clock history.
  18508. Everywhere else, drag the line at point up."
  18509. (interactive "P")
  18510. (cond
  18511. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18512. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18513. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18514. (call-interactively 'org-timestamp-up)))
  18515. (t (call-interactively 'org-drag-line-backward))))
  18516. (defun org-shiftmetadown (&optional _arg)
  18517. "Drag the line at point down.
  18518. In a table, insert an empty row at the current line.
  18519. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18520. but also adjust the previous clocked item in the clock history.
  18521. Everywhere else, drag the line at point down."
  18522. (interactive "P")
  18523. (cond
  18524. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18525. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18526. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18527. (call-interactively 'org-timestamp-down)))
  18528. (t (call-interactively 'org-drag-line-forward))))
  18529. (defsubst org-hidden-tree-error ()
  18530. (user-error
  18531. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18532. (defun org-metaleft (&optional _arg)
  18533. "Promote heading, list item at point or move table column left.
  18534. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18535. depending on context. With no specific context, calls the Emacs
  18536. default `backward-word'. See the individual commands for more
  18537. information.
  18538. This function runs the hook `org-metaleft-hook' as a first step,
  18539. and returns at first non-nil value."
  18540. (interactive "P")
  18541. (cond
  18542. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18543. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18544. ((org-with-limited-levels
  18545. (or (org-at-heading-p)
  18546. (and (org-region-active-p)
  18547. (save-excursion
  18548. (goto-char (region-beginning))
  18549. (org-at-heading-p)))))
  18550. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18551. (call-interactively 'org-do-promote))
  18552. ;; At an inline task.
  18553. ((org-at-heading-p)
  18554. (call-interactively 'org-inlinetask-promote))
  18555. ((or (org-at-item-p)
  18556. (and (org-region-active-p)
  18557. (save-excursion
  18558. (goto-char (region-beginning))
  18559. (org-at-item-p))))
  18560. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18561. (call-interactively 'org-outdent-item))
  18562. (t (call-interactively 'backward-word))))
  18563. (defun org-metaright (&optional _arg)
  18564. "Demote heading, list item at point or move table column right.
  18565. In front of a drawer or a block keyword, indent it correctly.
  18566. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18567. `org-indent-drawer' or `org-indent-block' depending on context.
  18568. With no specific context, calls the Emacs default `forward-word'.
  18569. See the individual commands for more information.
  18570. This function runs the hook `org-metaright-hook' as a first step,
  18571. and returns at first non-nil value."
  18572. (interactive "P")
  18573. (cond
  18574. ((run-hook-with-args-until-success 'org-metaright-hook))
  18575. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18576. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18577. ((org-at-block-p) (call-interactively 'org-indent-block))
  18578. ((org-with-limited-levels
  18579. (or (org-at-heading-p)
  18580. (and (org-region-active-p)
  18581. (save-excursion
  18582. (goto-char (region-beginning))
  18583. (org-at-heading-p)))))
  18584. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18585. (call-interactively 'org-do-demote))
  18586. ;; At an inline task.
  18587. ((org-at-heading-p)
  18588. (call-interactively 'org-inlinetask-demote))
  18589. ((or (org-at-item-p)
  18590. (and (org-region-active-p)
  18591. (save-excursion
  18592. (goto-char (region-beginning))
  18593. (org-at-item-p))))
  18594. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18595. (call-interactively 'org-indent-item))
  18596. (t (call-interactively 'forward-word))))
  18597. (defun org-check-for-hidden (what)
  18598. "Check if there are hidden headlines/items in the current visual line.
  18599. WHAT can be either `headlines' or `items'. If the current line is
  18600. an outline or item heading and it has a folded subtree below it,
  18601. this function returns t, nil otherwise."
  18602. (let ((re (cond
  18603. ((eq what 'headlines) org-outline-regexp-bol)
  18604. ((eq what 'items) (org-item-beginning-re))
  18605. (t (error "This should not happen"))))
  18606. beg end)
  18607. (save-excursion
  18608. (catch 'exit
  18609. (unless (org-region-active-p)
  18610. (setq beg (point-at-bol))
  18611. (beginning-of-line 2)
  18612. (while (and (not (eobp)) ;; this is like `next-line'
  18613. (get-char-property (1- (point)) 'invisible))
  18614. (beginning-of-line 2))
  18615. (setq end (point))
  18616. (goto-char beg)
  18617. (goto-char (point-at-eol))
  18618. (setq end (max end (point)))
  18619. (while (re-search-forward re end t)
  18620. (when (get-char-property (match-beginning 0) 'invisible)
  18621. (throw 'exit t))))
  18622. nil))))
  18623. (defun org-metaup (&optional _arg)
  18624. "Move subtree up or move table row up.
  18625. Calls `org-move-subtree-up' or `org-table-move-row' or
  18626. `org-move-item-up', depending on context. See the individual commands
  18627. for more information."
  18628. (interactive "P")
  18629. (cond
  18630. ((run-hook-with-args-until-success 'org-metaup-hook))
  18631. ((org-region-active-p)
  18632. (let* ((a (min (region-beginning) (region-end)))
  18633. (b (1- (max (region-beginning) (region-end))))
  18634. (c (save-excursion (goto-char a)
  18635. (move-beginning-of-line 0)))
  18636. (d (save-excursion (goto-char a)
  18637. (move-end-of-line 0) (point))))
  18638. (transpose-regions a b c d)
  18639. (goto-char c)))
  18640. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18641. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18642. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18643. (t (org-drag-element-backward))))
  18644. (defun org-metadown (&optional _arg)
  18645. "Move subtree down or move table row down.
  18646. Calls `org-move-subtree-down' or `org-table-move-row' or
  18647. `org-move-item-down', depending on context. See the individual
  18648. commands for more information."
  18649. (interactive "P")
  18650. (cond
  18651. ((run-hook-with-args-until-success 'org-metadown-hook))
  18652. ((org-region-active-p)
  18653. (let* ((a (min (region-beginning) (region-end)))
  18654. (b (max (region-beginning) (region-end)))
  18655. (c (save-excursion (goto-char b)
  18656. (move-beginning-of-line 1)))
  18657. (d (save-excursion (goto-char b)
  18658. (move-end-of-line 1) (1+ (point)))))
  18659. (transpose-regions a b c d)
  18660. (goto-char d)))
  18661. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18662. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18663. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18664. (t (org-drag-element-forward))))
  18665. (defun org-shiftup (&optional arg)
  18666. "Increase item in timestamp or increase priority of current headline.
  18667. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18668. depending on context. See the individual commands for more information."
  18669. (interactive "P")
  18670. (cond
  18671. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18672. ((and org-support-shift-select (org-region-active-p))
  18673. (org-call-for-shift-select 'previous-line))
  18674. ((org-at-timestamp-p 'lax)
  18675. (call-interactively (if org-edit-timestamp-down-means-later
  18676. 'org-timestamp-down 'org-timestamp-up)))
  18677. ((and (not (eq org-support-shift-select 'always))
  18678. org-enable-priority-commands
  18679. (org-at-heading-p))
  18680. (call-interactively 'org-priority-up))
  18681. ((and (not org-support-shift-select) (org-at-item-p))
  18682. (call-interactively 'org-previous-item))
  18683. ((org-clocktable-try-shift 'up arg))
  18684. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18685. (org-support-shift-select
  18686. (org-call-for-shift-select 'previous-line))
  18687. (t (org-shiftselect-error))))
  18688. (defun org-shiftdown (&optional arg)
  18689. "Decrease item in timestamp or decrease priority of current headline.
  18690. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18691. depending on context. See the individual commands for more information."
  18692. (interactive "P")
  18693. (cond
  18694. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18695. ((and org-support-shift-select (org-region-active-p))
  18696. (org-call-for-shift-select 'next-line))
  18697. ((org-at-timestamp-p 'lax)
  18698. (call-interactively (if org-edit-timestamp-down-means-later
  18699. 'org-timestamp-up 'org-timestamp-down)))
  18700. ((and (not (eq org-support-shift-select 'always))
  18701. org-enable-priority-commands
  18702. (org-at-heading-p))
  18703. (call-interactively 'org-priority-down))
  18704. ((and (not org-support-shift-select) (org-at-item-p))
  18705. (call-interactively 'org-next-item))
  18706. ((org-clocktable-try-shift 'down arg))
  18707. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18708. (org-support-shift-select
  18709. (org-call-for-shift-select 'next-line))
  18710. (t (org-shiftselect-error))))
  18711. (defun org-shiftright (&optional arg)
  18712. "Cycle the thing at point or in the current line, depending on context.
  18713. Depending on context, this does one of the following:
  18714. - switch a timestamp at point one day into the future
  18715. - on a headline, switch to the next TODO keyword.
  18716. - on an item, switch entire list to the next bullet type
  18717. - on a property line, switch to the next allowed value
  18718. - on a clocktable definition line, move time block into the future"
  18719. (interactive "P")
  18720. (cond
  18721. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18722. ((and org-support-shift-select (org-region-active-p))
  18723. (org-call-for-shift-select 'forward-char))
  18724. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18725. ((and (not (eq org-support-shift-select 'always))
  18726. (org-at-heading-p))
  18727. (let ((org-inhibit-logging
  18728. (not org-treat-S-cursor-todo-selection-as-state-change))
  18729. (org-inhibit-blocking
  18730. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18731. (org-call-with-arg 'org-todo 'right)))
  18732. ((or (and org-support-shift-select
  18733. (not (eq org-support-shift-select 'always))
  18734. (org-at-item-bullet-p))
  18735. (and (not org-support-shift-select) (org-at-item-p)))
  18736. (org-call-with-arg 'org-cycle-list-bullet nil))
  18737. ((and (not (eq org-support-shift-select 'always))
  18738. (org-at-property-p))
  18739. (call-interactively 'org-property-next-allowed-value))
  18740. ((org-clocktable-try-shift 'right arg))
  18741. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18742. (org-support-shift-select
  18743. (org-call-for-shift-select 'forward-char))
  18744. (t (org-shiftselect-error))))
  18745. (defun org-shiftleft (&optional arg)
  18746. "Cycle the thing at point or in the current line, depending on context.
  18747. Depending on context, this does one of the following:
  18748. - switch a timestamp at point one day into the past
  18749. - on a headline, switch to the previous TODO keyword.
  18750. - on an item, switch entire list to the previous bullet type
  18751. - on a property line, switch to the previous allowed value
  18752. - on a clocktable definition line, move time block into the past"
  18753. (interactive "P")
  18754. (cond
  18755. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18756. ((and org-support-shift-select (org-region-active-p))
  18757. (org-call-for-shift-select 'backward-char))
  18758. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18759. ((and (not (eq org-support-shift-select 'always))
  18760. (org-at-heading-p))
  18761. (let ((org-inhibit-logging
  18762. (not org-treat-S-cursor-todo-selection-as-state-change))
  18763. (org-inhibit-blocking
  18764. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18765. (org-call-with-arg 'org-todo 'left)))
  18766. ((or (and org-support-shift-select
  18767. (not (eq org-support-shift-select 'always))
  18768. (org-at-item-bullet-p))
  18769. (and (not org-support-shift-select) (org-at-item-p)))
  18770. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18771. ((and (not (eq org-support-shift-select 'always))
  18772. (org-at-property-p))
  18773. (call-interactively 'org-property-previous-allowed-value))
  18774. ((org-clocktable-try-shift 'left arg))
  18775. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18776. (org-support-shift-select
  18777. (org-call-for-shift-select 'backward-char))
  18778. (t (org-shiftselect-error))))
  18779. (defun org-shiftcontrolright ()
  18780. "Switch to next TODO set."
  18781. (interactive)
  18782. (cond
  18783. ((and org-support-shift-select (org-region-active-p))
  18784. (org-call-for-shift-select 'forward-word))
  18785. ((and (not (eq org-support-shift-select 'always))
  18786. (org-at-heading-p))
  18787. (org-call-with-arg 'org-todo 'nextset))
  18788. (org-support-shift-select
  18789. (org-call-for-shift-select 'forward-word))
  18790. (t (org-shiftselect-error))))
  18791. (defun org-shiftcontrolleft ()
  18792. "Switch to previous TODO set."
  18793. (interactive)
  18794. (cond
  18795. ((and org-support-shift-select (org-region-active-p))
  18796. (org-call-for-shift-select 'backward-word))
  18797. ((and (not (eq org-support-shift-select 'always))
  18798. (org-at-heading-p))
  18799. (org-call-with-arg 'org-todo 'previousset))
  18800. (org-support-shift-select
  18801. (org-call-for-shift-select 'backward-word))
  18802. (t (org-shiftselect-error))))
  18803. (defun org-shiftcontrolup (&optional n)
  18804. "Change timestamps synchronously up in CLOCK log lines.
  18805. Optional argument N tells to change by that many units."
  18806. (interactive "P")
  18807. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18808. (let (org-support-shift-select)
  18809. (org-clock-timestamps-up n))
  18810. (user-error "Not at a clock log")))
  18811. (defun org-shiftcontroldown (&optional n)
  18812. "Change timestamps synchronously down in CLOCK log lines.
  18813. Optional argument N tells to change by that many units."
  18814. (interactive "P")
  18815. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18816. (let (org-support-shift-select)
  18817. (org-clock-timestamps-down n))
  18818. (user-error "Not at a clock log")))
  18819. (defun org-increase-number-at-point (&optional inc)
  18820. "Increment the number at point.
  18821. With an optional prefix numeric argument INC, increment using
  18822. this numeric value."
  18823. (interactive "p")
  18824. (if (not (number-at-point))
  18825. (user-error "Not on a number")
  18826. (unless inc (setq inc 1))
  18827. (let ((pos (point))
  18828. (beg (skip-chars-backward "-+^/*0-9eE."))
  18829. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18830. (setq nap (buffer-substring-no-properties
  18831. (+ pos beg) (+ pos beg end)))
  18832. (delete-region (+ pos beg) (+ pos beg end))
  18833. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18834. (when (org-at-table-p)
  18835. (org-table-align)
  18836. (org-table-end-of-field 1))))
  18837. (defun org-decrease-number-at-point (&optional inc)
  18838. "Decrement the number at point.
  18839. With an optional prefix numeric argument INC, decrement using
  18840. this numeric value."
  18841. (interactive "p")
  18842. (org-increase-number-at-point (- (or inc 1))))
  18843. (defun org-ctrl-c-ret ()
  18844. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18845. (interactive)
  18846. (cond
  18847. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18848. (t (call-interactively 'org-insert-heading))))
  18849. (defun org-find-visible ()
  18850. (let ((s (point)))
  18851. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18852. (get-char-property s 'invisible)))
  18853. s))
  18854. (defun org-find-invisible ()
  18855. (let ((s (point)))
  18856. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18857. (not (get-char-property s 'invisible))))
  18858. s))
  18859. (defun org-copy-visible (beg end)
  18860. "Copy the visible parts of the region."
  18861. (interactive "r")
  18862. (let ((result ""))
  18863. (while (/= beg end)
  18864. (when (get-char-property beg 'invisible)
  18865. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18866. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18867. (setq result (concat result (buffer-substring beg next)))
  18868. (setq beg next)))
  18869. (kill-new result)))
  18870. (defun org-copy-special ()
  18871. "Copy region in table or copy current subtree.
  18872. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18873. context. See the individual commands for more information."
  18874. (interactive)
  18875. (call-interactively
  18876. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18877. (defun org-cut-special ()
  18878. "Cut region in table or cut current subtree.
  18879. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18880. context. See the individual commands for more information."
  18881. (interactive)
  18882. (call-interactively
  18883. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18884. (defun org-paste-special (arg)
  18885. "Paste rectangular region into table, or past subtree relative to level.
  18886. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18887. See the individual commands for more information."
  18888. (interactive "P")
  18889. (if (org-at-table-p)
  18890. (org-table-paste-rectangle)
  18891. (org-paste-subtree arg)))
  18892. (defun org-edit-special (&optional arg)
  18893. "Call a special editor for the element at point.
  18894. When at a table, call the formula editor with `org-table-edit-formulas'.
  18895. When in a source code block, call `org-edit-src-code'.
  18896. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18897. When in an export block, call `org-edit-export-block'.
  18898. When in a LaTeX environment, call `org-edit-latex-environment'.
  18899. When at an #+INCLUDE keyword, visit the included file.
  18900. When at a footnote reference, call `org-edit-footnote-reference'
  18901. On a link, call `ffap' to visit the link at point.
  18902. Otherwise, return a user error."
  18903. (interactive "P")
  18904. (let ((element (org-element-at-point)))
  18905. (barf-if-buffer-read-only)
  18906. (pcase (org-element-type element)
  18907. (`src-block
  18908. (if (not arg) (org-edit-src-code)
  18909. (let* ((info (org-babel-get-src-block-info))
  18910. (lang (nth 0 info))
  18911. (params (nth 2 info))
  18912. (session (cdr (assq :session params))))
  18913. (if (not session) (org-edit-src-code)
  18914. ;; At a src-block with a session and function called with
  18915. ;; an ARG: switch to the buffer related to the inferior
  18916. ;; process.
  18917. (switch-to-buffer
  18918. (funcall (intern (concat "org-babel-prep-session:" lang))
  18919. session params))))))
  18920. (`keyword
  18921. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18922. (org-open-link-from-string
  18923. (format "[[%s]]"
  18924. (expand-file-name
  18925. (let ((value (org-element-property :value element)))
  18926. (cond ((org-file-url-p value)
  18927. (user-error "The file is specified as a URL, cannot be edited"))
  18928. ((not (org-string-nw-p value))
  18929. (user-error "No file to edit"))
  18930. ((string-match "\\`\"\\(.*?\\)\"" value)
  18931. (match-string 1 value))
  18932. ((string-match "\\`[^ \t\"]\\S-*" value)
  18933. (match-string 0 value))
  18934. (t (user-error "No valid file specified")))))))
  18935. (user-error "No special environment to edit here")))
  18936. (`table
  18937. (if (eq (org-element-property :type element) 'table.el)
  18938. (org-edit-table.el)
  18939. (call-interactively 'org-table-edit-formulas)))
  18940. ;; Only Org tables contain `table-row' type elements.
  18941. (`table-row (call-interactively 'org-table-edit-formulas))
  18942. (`example-block (org-edit-src-code))
  18943. (`export-block (org-edit-export-block))
  18944. (`fixed-width (org-edit-fixed-width-region))
  18945. (`latex-environment (org-edit-latex-environment))
  18946. (_
  18947. ;; No notable element at point. Though, we may be at a link or
  18948. ;; a footnote reference, which are objects. Thus, scan deeper.
  18949. (let ((context (org-element-context element)))
  18950. (pcase (org-element-type context)
  18951. (`footnote-reference (org-edit-footnote-reference))
  18952. (`inline-src-block (org-edit-inline-src-code))
  18953. (`link (call-interactively #'ffap))
  18954. (_ (user-error "No special environment to edit here"))))))))
  18955. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18956. (defun org-ctrl-c-ctrl-c (&optional arg)
  18957. "Set tags in headline, or update according to changed information at point.
  18958. This command does many different things, depending on context:
  18959. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18960. this is what we do.
  18961. - If the cursor is on a statistics cookie, update it.
  18962. - If the cursor is in a headline, prompt for tags and insert them
  18963. into the current line, aligned to `org-tags-column'. When called
  18964. with prefix arg, realign all tags in the current buffer.
  18965. - If the cursor is in one of the special #+KEYWORD lines, this
  18966. triggers scanning the buffer for these lines and updating the
  18967. information.
  18968. - If the cursor is inside a table, realign the table. This command
  18969. works even if the automatic table editor has been turned off.
  18970. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18971. the entire table.
  18972. - If the cursor is at a footnote reference or definition, jump to
  18973. the corresponding definition or references, respectively.
  18974. - If the cursor is a the beginning of a dynamic block, update it.
  18975. - If the current buffer is a capture buffer, close note and file it.
  18976. - If the cursor is on a <<<target>>>, update radio targets and
  18977. corresponding links in this buffer.
  18978. - If the cursor is on a numbered item in a plain list, renumber the
  18979. ordered list.
  18980. - If the cursor is on a checkbox, toggle it.
  18981. - If the cursor is on a code block, evaluate it. The variable
  18982. `org-confirm-babel-evaluate' can be used to control prompting
  18983. before code block evaluation, by default every code block
  18984. evaluation requires confirmation. Code block evaluation can be
  18985. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18986. (interactive "P")
  18987. (cond
  18988. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18989. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18990. (org-remove-occur-highlights)
  18991. (message "Temporary highlights/overlays removed from current buffer"))
  18992. ((and (local-variable-p 'org-finish-function)
  18993. (fboundp org-finish-function))
  18994. (funcall org-finish-function))
  18995. ((org-babel-hash-at-point))
  18996. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18997. (t
  18998. (let* ((context
  18999. (org-element-lineage
  19000. (org-element-context)
  19001. ;; Limit to supported contexts.
  19002. '(babel-call clock dynamic-block footnote-definition
  19003. footnote-reference inline-babel-call inline-src-block
  19004. inlinetask item keyword node-property paragraph
  19005. plain-list planning property-drawer radio-target
  19006. src-block statistics-cookie table table-cell table-row
  19007. timestamp)
  19008. t))
  19009. (type (org-element-type context)))
  19010. ;; For convenience: at the first line of a paragraph on the same
  19011. ;; line as an item, apply function on that item instead.
  19012. (when (eq type 'paragraph)
  19013. (let ((parent (org-element-property :parent context)))
  19014. (when (and (eq (org-element-type parent) 'item)
  19015. (= (line-beginning-position)
  19016. (org-element-property :begin parent)))
  19017. (setq context parent)
  19018. (setq type 'item))))
  19019. ;; Act according to type of element or object at point.
  19020. ;;
  19021. ;; Do nothing on a blank line, except if it is contained in
  19022. ;; a src block. Hence, we first check if point is in such
  19023. ;; a block and then if it is at a blank line.
  19024. (pcase type
  19025. ((or `inline-src-block `src-block)
  19026. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19027. (org-babel-eval-wipe-error-buffer)
  19028. (org-babel-execute-src-block
  19029. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19030. ((guard (org-match-line "[ \t]*$"))
  19031. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19032. (user-error
  19033. (substitute-command-keys
  19034. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19035. ((or `babel-call `inline-babel-call)
  19036. (let ((info (org-babel-lob-get-info context)))
  19037. (when info (org-babel-execute-src-block nil info))))
  19038. (`clock (org-clock-update-time-maybe))
  19039. (`dynamic-block
  19040. (save-excursion
  19041. (goto-char (org-element-property :post-affiliated context))
  19042. (org-update-dblock)))
  19043. (`footnote-definition
  19044. (goto-char (org-element-property :post-affiliated context))
  19045. (call-interactively 'org-footnote-action))
  19046. (`footnote-reference (call-interactively #'org-footnote-action))
  19047. ((or `headline `inlinetask)
  19048. (save-excursion (goto-char (org-element-property :begin context))
  19049. (call-interactively #'org-set-tags)))
  19050. (`item
  19051. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19052. ;; unconditionally, whereas `C-u' will toggle its presence.
  19053. ;; Without a universal argument, if the item has a checkbox,
  19054. ;; toggle it. Otherwise repair the list.
  19055. (let* ((box (org-element-property :checkbox context))
  19056. (struct (org-element-property :structure context))
  19057. (old-struct (copy-tree struct))
  19058. (parents (org-list-parents-alist struct))
  19059. (prevs (org-list-prevs-alist struct))
  19060. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19061. (org-list-set-checkbox
  19062. (org-element-property :begin context) struct
  19063. (cond ((equal arg '(16)) "[-]")
  19064. ((and (not box) (equal arg '(4))) "[ ]")
  19065. ((or (not box) (equal arg '(4))) nil)
  19066. ((eq box 'on) "[ ]")
  19067. (t "[X]")))
  19068. ;; Mimic `org-list-write-struct' but with grabbing a return
  19069. ;; value from `org-list-struct-fix-box'.
  19070. (org-list-struct-fix-ind struct parents 2)
  19071. (org-list-struct-fix-item-end struct)
  19072. (org-list-struct-fix-bul struct prevs)
  19073. (org-list-struct-fix-ind struct parents)
  19074. (let ((block-item
  19075. (org-list-struct-fix-box struct parents prevs orderedp)))
  19076. (if (and box (equal struct old-struct))
  19077. (if (equal arg '(16))
  19078. (message "Checkboxes already reset")
  19079. (user-error "Cannot toggle this checkbox: %s"
  19080. (if (eq box 'on)
  19081. "all subitems checked"
  19082. "unchecked subitems")))
  19083. (org-list-struct-apply-struct struct old-struct)
  19084. (org-update-checkbox-count-maybe))
  19085. (when block-item
  19086. (message "Checkboxes were removed due to empty box at line %d"
  19087. (org-current-line block-item))))))
  19088. (`keyword
  19089. (let ((org-inhibit-startup-visibility-stuff t)
  19090. (org-startup-align-all-tables nil))
  19091. (when (boundp 'org-table-coordinate-overlays)
  19092. (mapc #'delete-overlay org-table-coordinate-overlays)
  19093. (setq org-table-coordinate-overlays nil))
  19094. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19095. (message "Local setup has been refreshed"))
  19096. (`plain-list
  19097. ;; At a plain list, with a double C-u argument, set
  19098. ;; checkboxes of each item to "[-]", whereas a single one
  19099. ;; will toggle their presence according to the state of the
  19100. ;; first item in the list. Without an argument, repair the
  19101. ;; list.
  19102. (let* ((begin (org-element-property :contents-begin context))
  19103. (beginm (move-marker (make-marker) begin))
  19104. (struct (org-element-property :structure context))
  19105. (old-struct (copy-tree struct))
  19106. (first-box (save-excursion
  19107. (goto-char begin)
  19108. (looking-at org-list-full-item-re)
  19109. (match-string-no-properties 3)))
  19110. (new-box (cond ((equal arg '(16)) "[-]")
  19111. ((equal arg '(4)) (unless first-box "[ ]"))
  19112. ((equal first-box "[X]") "[ ]")
  19113. (t "[X]"))))
  19114. (cond
  19115. (arg
  19116. (dolist (pos
  19117. (org-list-get-all-items
  19118. begin struct (org-list-prevs-alist struct)))
  19119. (org-list-set-checkbox pos struct new-box)))
  19120. ((and first-box (eq (point) begin))
  19121. ;; For convenience, when point is at bol on the first
  19122. ;; item of the list and no argument is provided, simply
  19123. ;; toggle checkbox of that item, if any.
  19124. (org-list-set-checkbox begin struct new-box)))
  19125. (org-list-write-struct
  19126. struct (org-list-parents-alist struct) old-struct)
  19127. (org-update-checkbox-count-maybe)
  19128. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19129. ((or `property-drawer `node-property)
  19130. (call-interactively #'org-property-action))
  19131. (`radio-target
  19132. (call-interactively #'org-update-radio-target-regexp))
  19133. (`statistics-cookie
  19134. (call-interactively #'org-update-statistics-cookies))
  19135. ((or `table `table-cell `table-row)
  19136. ;; At a table, recalculate every field and align it. Also
  19137. ;; send the table if necessary. If the table has
  19138. ;; a `table.el' type, just give up. At a table row or cell,
  19139. ;; maybe recalculate line but always align table.
  19140. (if (eq (org-element-property :type context) 'table.el)
  19141. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19142. Use `\\[org-edit-special]' to edit table.el tables"))
  19143. (if (or (eq type 'table)
  19144. ;; Check if point is at a TBLFM line.
  19145. (and (eq type 'table-row)
  19146. (= (point) (org-element-property :end context))))
  19147. (save-excursion
  19148. (if (org-at-TBLFM-p)
  19149. (progn (require 'org-table)
  19150. (org-table-calc-current-TBLFM))
  19151. (goto-char (org-element-property :contents-begin context))
  19152. (org-call-with-arg 'org-table-recalculate (or arg t))
  19153. (orgtbl-send-table 'maybe)))
  19154. (org-table-maybe-eval-formula)
  19155. (cond (arg (call-interactively #'org-table-recalculate))
  19156. ((org-table-maybe-recalculate-line))
  19157. (t (org-table-align))))))
  19158. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  19159. (org-timestamp-change 0 'day))
  19160. ((and `nil (guard (org-at-heading-p)))
  19161. ;; When point is on an unsupported object type, we can miss
  19162. ;; the fact that it also is at a heading. Handle it here.
  19163. (call-interactively #'org-set-tags))
  19164. ((guard
  19165. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19166. (_
  19167. (user-error
  19168. (substitute-command-keys
  19169. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19170. (defun org-mode-restart ()
  19171. (interactive)
  19172. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19173. (funcall major-mode)
  19174. (hack-local-variables)
  19175. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19176. (org-indent-mode -1))
  19177. (org-reset-file-cache))
  19178. (message "%s restarted" major-mode))
  19179. (defun org-kill-note-or-show-branches ()
  19180. "Abort storing current note, or call `outline-show-branches'."
  19181. (interactive)
  19182. (if (not org-finish-function)
  19183. (progn
  19184. (outline-hide-subtree)
  19185. (call-interactively 'outline-show-branches))
  19186. (let ((org-note-abort t))
  19187. (funcall org-finish-function))))
  19188. (defun org-delete-indentation (&optional arg)
  19189. "Join current line to previous and fix whitespace at join.
  19190. If previous line is a headline add to headline title. Otherwise
  19191. the function calls `delete-indentation'.
  19192. With a non-nil optional argument, join it to the following one."
  19193. (interactive "*P")
  19194. (if (save-excursion
  19195. (beginning-of-line (if arg 1 0))
  19196. (let ((case-fold-search nil))
  19197. (looking-at org-complex-heading-regexp)))
  19198. ;; At headline.
  19199. (let ((tags-column (when (match-beginning 5)
  19200. (save-excursion (goto-char (match-beginning 5))
  19201. (current-column))))
  19202. (string (concat " " (progn (when arg (forward-line 1))
  19203. (org-trim (delete-and-extract-region
  19204. (line-beginning-position)
  19205. (line-end-position)))))))
  19206. (unless (bobp) (delete-region (point) (1- (point))))
  19207. (goto-char (or (match-end 4)
  19208. (match-beginning 5)
  19209. (match-end 0)))
  19210. (skip-chars-backward " \t")
  19211. (save-excursion (insert string))
  19212. ;; Adjust alignment of tags.
  19213. (cond
  19214. ((not tags-column)) ;no tags
  19215. (org-auto-align-tags (org-set-tags nil t))
  19216. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19217. (delete-indentation arg)))
  19218. (defun org-open-line (n)
  19219. "Insert a new row in tables, call `open-line' elsewhere.
  19220. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19221. As a special case, when a document starts with a table, allow to
  19222. call `open-line' on the very first character."
  19223. (interactive "*p")
  19224. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19225. (org-table-insert-row)
  19226. (open-line n)))
  19227. (defun org-return (&optional indent)
  19228. "Goto next table row or insert a newline.
  19229. Calls `org-table-next-row' or `newline', depending on context.
  19230. When optional INDENT argument is non-nil, call
  19231. `newline-and-indent' instead of `newline'.
  19232. When `org-return-follows-link' is non-nil and point is on
  19233. a timestamp or a link, call `org-open-at-point'. However, it
  19234. will not happen if point is in a table or on a \"dead\"
  19235. object (e.g., within a comment). In these case, you need to use
  19236. `org-open-at-point' directly."
  19237. (interactive)
  19238. (let ((context (if org-return-follows-link (org-element-context)
  19239. (org-element-at-point))))
  19240. (cond
  19241. ;; In a table, call `org-table-next-row'. However, before first
  19242. ;; column or after last one, split the table.
  19243. ((or (and (eq (org-element-type context) 'table)
  19244. (>= (point) (org-element-property :contents-begin context))
  19245. (< (point) (org-element-property :contents-end context)))
  19246. (org-element-lineage context '(table-row table-cell) t))
  19247. (if (or (looking-at-p "[ \t]*$")
  19248. (save-excursion (skip-chars-backward " \t") (bolp)))
  19249. (insert "\n")
  19250. (org-table-justify-field-maybe)
  19251. (call-interactively #'org-table-next-row)))
  19252. ;; On a link or a timestamp, call `org-open-at-point' if
  19253. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19254. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19255. ((and org-return-follows-link
  19256. (or (org-in-regexp org-ts-regexp-both nil t)
  19257. (org-in-regexp org-tsr-regexp-both nil t)
  19258. (org-in-regexp org-any-link-re nil t)))
  19259. (call-interactively #'org-open-at-point))
  19260. ;; Insert newline in heading, but preserve tags.
  19261. ((and (not (bolp))
  19262. (save-excursion (beginning-of-line)
  19263. (let ((case-fold-search nil))
  19264. (looking-at org-complex-heading-regexp))))
  19265. ;; At headline. Split line. However, if point is on keyword,
  19266. ;; priority cookie or tags, do not break any of them: add
  19267. ;; a newline after the headline instead.
  19268. (let ((tags-column (and (match-beginning 5)
  19269. (save-excursion (goto-char (match-beginning 5))
  19270. (current-column))))
  19271. (string
  19272. (when (and (match-end 4) (org-point-in-group (point) 4))
  19273. (delete-and-extract-region (point) (match-end 4)))))
  19274. ;; Adjust tag alignment.
  19275. (cond
  19276. ((not (and tags-column string)))
  19277. (org-auto-align-tags (org-set-tags nil t))
  19278. (t (org--align-tags-here tags-column))) ;preserve tags column
  19279. (end-of-line)
  19280. (org-show-entry)
  19281. (if indent (newline-and-indent) (newline))
  19282. (when string (save-excursion (insert (org-trim string))))))
  19283. ;; In a list, make sure indenting keeps trailing text within.
  19284. ((and indent
  19285. (not (eolp))
  19286. (org-element-lineage context '(item)))
  19287. (let ((trailing-data
  19288. (delete-and-extract-region (point) (line-end-position))))
  19289. (newline-and-indent)
  19290. (save-excursion (insert trailing-data))))
  19291. (t (if indent (newline-and-indent) (newline))))))
  19292. (defun org-return-indent ()
  19293. "Goto next table row or insert a newline and indent.
  19294. Calls `org-table-next-row' or `newline-and-indent', depending on
  19295. context. See the individual commands for more information."
  19296. (interactive)
  19297. (org-return t))
  19298. (defun org-ctrl-c-star ()
  19299. "Compute table, or change heading status of lines.
  19300. Calls `org-table-recalculate' or `org-toggle-heading',
  19301. depending on context."
  19302. (interactive)
  19303. (cond
  19304. ((org-at-table-p)
  19305. (call-interactively 'org-table-recalculate))
  19306. (t
  19307. ;; Convert all lines in region to list items
  19308. (call-interactively 'org-toggle-heading))))
  19309. (defun org-ctrl-c-minus ()
  19310. "Insert separator line in table or modify bullet status of line.
  19311. Also turns a plain line or a region of lines into list items.
  19312. Calls `org-table-insert-hline', `org-toggle-item', or
  19313. `org-cycle-list-bullet', depending on context."
  19314. (interactive)
  19315. (cond
  19316. ((org-at-table-p)
  19317. (call-interactively 'org-table-insert-hline))
  19318. ((org-region-active-p)
  19319. (call-interactively 'org-toggle-item))
  19320. ((org-in-item-p)
  19321. (call-interactively 'org-cycle-list-bullet))
  19322. (t
  19323. (call-interactively 'org-toggle-item))))
  19324. (defun org-toggle-heading (&optional nstars)
  19325. "Convert headings to normal text, or items or text to headings.
  19326. If there is no active region, only convert the current line.
  19327. With a `\\[universal-argument]' prefix, convert the whole list at
  19328. point into heading.
  19329. In a region:
  19330. - If the first non blank line is a headline, remove the stars
  19331. from all headlines in the region.
  19332. - If it is a normal line, turn each and every normal line (i.e.,
  19333. not an heading or an item) in the region into headings. If you
  19334. want to convert only the first line of this region, use one
  19335. universal prefix argument.
  19336. - If it is a plain list item, turn all plain list items into headings.
  19337. When converting a line into a heading, the number of stars is chosen
  19338. such that the lines become children of the current entry. However,
  19339. when a numeric prefix argument is given, its value determines the
  19340. number of stars to add."
  19341. (interactive "P")
  19342. (let ((skip-blanks
  19343. (function
  19344. ;; Return beginning of first non-blank line, starting from
  19345. ;; line at POS.
  19346. (lambda (pos)
  19347. (save-excursion
  19348. (goto-char pos)
  19349. (while (org-at-comment-p) (forward-line))
  19350. (skip-chars-forward " \r\t\n")
  19351. (point-at-bol)))))
  19352. beg end toggled)
  19353. ;; Determine boundaries of changes. If a universal prefix has
  19354. ;; been given, put the list in a region. If region ends at a bol,
  19355. ;; do not consider the last line to be in the region.
  19356. (when (and current-prefix-arg (org-at-item-p))
  19357. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19358. (org-mark-element))
  19359. (if (org-region-active-p)
  19360. (setq beg (funcall skip-blanks (region-beginning))
  19361. end (copy-marker (save-excursion
  19362. (goto-char (region-end))
  19363. (if (bolp) (point) (point-at-eol)))))
  19364. (setq beg (funcall skip-blanks (point-at-bol))
  19365. end (copy-marker (point-at-eol))))
  19366. ;; Ensure inline tasks don't count as headings.
  19367. (org-with-limited-levels
  19368. (save-excursion
  19369. (goto-char beg)
  19370. (cond
  19371. ;; Case 1. Started at an heading: de-star headings.
  19372. ((org-at-heading-p)
  19373. (while (< (point) end)
  19374. (when (org-at-heading-p t)
  19375. (looking-at org-outline-regexp) (replace-match "")
  19376. (setq toggled t))
  19377. (forward-line)))
  19378. ;; Case 2. Started at an item: change items into headlines.
  19379. ;; One star will be added by `org-list-to-subtree'.
  19380. ((org-at-item-p)
  19381. (while (< (point) end)
  19382. (when (org-at-item-p)
  19383. ;; Pay attention to cases when region ends before list.
  19384. (let* ((struct (org-list-struct))
  19385. (list-end
  19386. (min (org-list-get-bottom-point struct) (1+ end))))
  19387. (save-restriction
  19388. (narrow-to-region (point) list-end)
  19389. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19390. (setq toggled t))
  19391. (forward-line)))
  19392. ;; Case 3. Started at normal text: make every line an heading,
  19393. ;; skipping headlines and items.
  19394. (t (let* ((stars
  19395. (make-string
  19396. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19397. (add-stars
  19398. (cond (nstars "") ; stars from prefix only
  19399. ((equal stars "") "*") ; before first heading
  19400. (org-odd-levels-only "**") ; inside heading, odd
  19401. (t "*"))) ; inside heading, oddeven
  19402. (rpl (concat stars add-stars " "))
  19403. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19404. (while (< (point) (if (equal nstars '(4)) lend end))
  19405. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19406. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19407. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19408. (forward-line)))))))
  19409. (unless toggled (message "Cannot toggle heading from here"))))
  19410. (defun org-meta-return (&optional arg)
  19411. "Insert a new heading or wrap a region in a table.
  19412. Calls `org-insert-heading', `org-insert-item' or
  19413. `org-table-wrap-region', depending on context. When called with
  19414. an argument, unconditionally call `org-insert-heading'."
  19415. (interactive "P")
  19416. (org-check-before-invisible-edit 'insert)
  19417. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19418. (call-interactively (cond (arg #'org-insert-heading)
  19419. ((org-at-table-p) #'org-table-wrap-region)
  19420. ((org-in-item-p) #'org-insert-item)
  19421. (t #'org-insert-heading)))))
  19422. ;;; Menu entries
  19423. (defsubst org-in-subtree-not-table-p ()
  19424. "Are we in a subtree and not in a table?"
  19425. (and (not (org-before-first-heading-p))
  19426. (not (org-at-table-p))))
  19427. ;; Define the Org mode menus
  19428. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19429. '("Tbl"
  19430. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19431. ["Next Field" org-cycle (org-at-table-p)]
  19432. ["Previous Field" org-shifttab (org-at-table-p)]
  19433. ["Next Row" org-return (org-at-table-p)]
  19434. "--"
  19435. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19436. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19437. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19438. "--"
  19439. ("Column"
  19440. ["Move Column Left" org-metaleft (org-at-table-p)]
  19441. ["Move Column Right" org-metaright (org-at-table-p)]
  19442. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19443. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19444. ("Row"
  19445. ["Move Row Up" org-metaup (org-at-table-p)]
  19446. ["Move Row Down" org-metadown (org-at-table-p)]
  19447. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19448. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19449. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19450. "--"
  19451. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19452. ("Rectangle"
  19453. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19454. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19455. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19456. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19457. "--"
  19458. ("Calculate"
  19459. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19460. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19461. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19462. "--"
  19463. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19464. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19465. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19466. "--"
  19467. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19468. "--"
  19469. ["Sum Column/Rectangle" org-table-sum
  19470. (or (org-at-table-p) (org-region-active-p))]
  19471. ["Which Column?" org-table-current-column (org-at-table-p)])
  19472. ["Debug Formulas"
  19473. org-table-toggle-formula-debugger
  19474. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19475. ["Show Col/Row Numbers"
  19476. org-table-toggle-coordinate-overlays
  19477. :style toggle
  19478. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19479. "--"
  19480. ["Create" org-table-create (not (org-at-table-p))]
  19481. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19482. ["Import from File" org-table-import (not (org-at-table-p))]
  19483. ["Export to File" org-table-export (org-at-table-p)]
  19484. "--"
  19485. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19486. "--"
  19487. ("Plot"
  19488. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19489. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19490. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19491. '("Org"
  19492. ("Show/Hide"
  19493. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19494. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19495. ["Sparse Tree..." org-sparse-tree t]
  19496. ["Reveal Context" org-reveal t]
  19497. ["Show All" outline-show-all t]
  19498. "--"
  19499. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19500. "--"
  19501. ["New Heading" org-insert-heading t]
  19502. ("Navigate Headings"
  19503. ["Up" outline-up-heading t]
  19504. ["Next" outline-next-visible-heading t]
  19505. ["Previous" outline-previous-visible-heading t]
  19506. ["Next Same Level" outline-forward-same-level t]
  19507. ["Previous Same Level" outline-backward-same-level t]
  19508. "--"
  19509. ["Jump" org-goto t])
  19510. ("Edit Structure"
  19511. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19512. "--"
  19513. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19514. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19515. "--"
  19516. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19517. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19518. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19519. "--"
  19520. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19521. "--"
  19522. ["Copy visible text" org-copy-visible t]
  19523. "--"
  19524. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19525. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19526. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19527. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19528. "--"
  19529. ["Sort Region/Children" org-sort t]
  19530. "--"
  19531. ["Convert to odd levels" org-convert-to-odd-levels t]
  19532. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19533. ("Editing"
  19534. ["Emphasis..." org-emphasize t]
  19535. ["Edit Source Example" org-edit-special t]
  19536. "--"
  19537. ["Footnote new/jump" org-footnote-action t]
  19538. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19539. ("Archive"
  19540. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19541. "--"
  19542. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19543. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19544. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19545. )
  19546. "--"
  19547. ("Hyperlinks"
  19548. ["Store Link (Global)" org-store-link t]
  19549. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19550. ["Insert Link" org-insert-link t]
  19551. ["Follow Link" org-open-at-point t]
  19552. "--"
  19553. ["Next link" org-next-link t]
  19554. ["Previous link" org-previous-link t]
  19555. "--"
  19556. ["Descriptive Links"
  19557. org-toggle-link-display
  19558. :style radio
  19559. :selected org-descriptive-links
  19560. ]
  19561. ["Literal Links"
  19562. org-toggle-link-display
  19563. :style radio
  19564. :selected (not org-descriptive-links)])
  19565. "--"
  19566. ("TODO Lists"
  19567. ["TODO/DONE/-" org-todo t]
  19568. ("Select keyword"
  19569. ["Next keyword" org-shiftright (org-at-heading-p)]
  19570. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19571. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19572. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19573. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19574. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19575. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19576. "--"
  19577. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19578. :selected org-enforce-todo-dependencies :style toggle :active t]
  19579. "Settings for tree at point"
  19580. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19581. :selected (org-entry-get nil "ORDERED")
  19582. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19583. ["Do Children parallel" org-toggle-ordered-property :style radio
  19584. :selected (not (org-entry-get nil "ORDERED"))
  19585. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19586. "--"
  19587. ["Set Priority" org-priority t]
  19588. ["Priority Up" org-shiftup t]
  19589. ["Priority Down" org-shiftdown t]
  19590. "--"
  19591. ["Get news from all feeds" org-feed-update-all t]
  19592. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19593. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19594. ("TAGS and Properties"
  19595. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19596. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19597. "--"
  19598. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19599. ["Column view of properties" org-columns t]
  19600. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19601. ("Dates and Scheduling"
  19602. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19603. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19604. ("Change Date"
  19605. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19606. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19607. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19608. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19609. ["Compute Time Range" org-evaluate-time-range t]
  19610. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19611. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19612. "--"
  19613. ["Custom time format" org-toggle-time-stamp-overlays
  19614. :style radio :selected org-display-custom-times]
  19615. "--"
  19616. ["Goto Calendar" org-goto-calendar t]
  19617. ["Date from Calendar" org-date-from-calendar t]
  19618. "--"
  19619. ["Start/Restart Timer" org-timer-start t]
  19620. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19621. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19622. ["Insert Timer String" org-timer t]
  19623. ["Insert Timer Item" org-timer-item t])
  19624. ("Logging work"
  19625. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19626. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19627. ["Clock out" org-clock-out t]
  19628. ["Clock cancel" org-clock-cancel t]
  19629. "--"
  19630. ["Mark as default task" org-clock-mark-default-task t]
  19631. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19632. ["Goto running clock" org-clock-goto t]
  19633. "--"
  19634. ["Display times" org-clock-display t]
  19635. ["Create clock table" org-clock-report t]
  19636. "--"
  19637. ["Record DONE time"
  19638. (progn (setq org-log-done (not org-log-done))
  19639. (message "Switching to %s will %s record a timestamp"
  19640. (car org-done-keywords)
  19641. (if org-log-done "automatically" "not")))
  19642. :style toggle :selected org-log-done])
  19643. "--"
  19644. ["Agenda Command..." org-agenda t]
  19645. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19646. ("File List for Agenda")
  19647. ("Special views current file"
  19648. ["TODO Tree" org-show-todo-tree t]
  19649. ["Check Deadlines" org-check-deadlines t]
  19650. ["Tags/Property tree" org-match-sparse-tree t])
  19651. "--"
  19652. ["Export/Publish..." org-export-dispatch t]
  19653. ("LaTeX"
  19654. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19655. :style toggle :selected org-cdlatex-mode]
  19656. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19657. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19658. ["Modify math symbol" org-cdlatex-math-modify
  19659. (org-inside-LaTeX-fragment-p)]
  19660. ["Insert citation" org-reftex-citation t])
  19661. "--"
  19662. ("MobileOrg"
  19663. ["Push Files and Views" org-mobile-push t]
  19664. ["Get Captured and Flagged" org-mobile-pull t]
  19665. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19666. "--"
  19667. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19668. "--"
  19669. ("Documentation"
  19670. ["Show Version" org-version t]
  19671. ["Info Documentation" org-info t])
  19672. ("Customize"
  19673. ["Browse Org Group" org-customize t]
  19674. "--"
  19675. ["Expand This Menu" org-create-customize-menu
  19676. (fboundp 'customize-menu-create)])
  19677. ["Send bug report" org-submit-bug-report t]
  19678. "--"
  19679. ("Refresh/Reload"
  19680. ["Refresh setup current buffer" org-mode-restart t]
  19681. ["Reload Org (after update)" org-reload t]
  19682. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19683. ))
  19684. (defun org-info (&optional node)
  19685. "Read documentation for Org in the info system.
  19686. With optional NODE, go directly to that node."
  19687. (interactive)
  19688. (info (format "(org)%s" (or node ""))))
  19689. ;;;###autoload
  19690. (defun org-submit-bug-report ()
  19691. "Submit a bug report on Org via mail.
  19692. Don't hesitate to report any problems or inaccurate documentation.
  19693. If you don't have setup sending mail from (X)Emacs, please copy the
  19694. output buffer into your mail program, as it gives us important
  19695. information about your Org version and configuration."
  19696. (interactive)
  19697. (require 'reporter)
  19698. (defvar reporter-prompt-for-summary-p)
  19699. (org-load-modules-maybe)
  19700. (org-require-autoloaded-modules)
  19701. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19702. (reporter-submit-bug-report
  19703. "emacs-orgmode@gnu.org"
  19704. (org-version nil 'full)
  19705. (let (list)
  19706. (save-window-excursion
  19707. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19708. (delete-other-windows)
  19709. (erase-buffer)
  19710. (insert "You are about to submit a bug report to the Org mailing list.
  19711. We would like to add your full Org and Outline configuration to the
  19712. bug report. This greatly simplifies the work of the maintainer and
  19713. other experts on the mailing list.
  19714. HOWEVER, some variables you have customized may contain private
  19715. information. The names of customers, colleagues, or friends, might
  19716. appear in the form of file names, tags, todo states, or search strings.
  19717. If you answer yes to the prompt, you might want to check and remove
  19718. such private information before sending the email.")
  19719. (add-text-properties (point-min) (point-max) '(face org-warning))
  19720. (when (yes-or-no-p "Include your Org configuration ")
  19721. (mapatoms
  19722. (lambda (v)
  19723. (and (boundp v)
  19724. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19725. (or (and (symbol-value v)
  19726. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19727. (and
  19728. (get v 'custom-type) (get v 'standard-value)
  19729. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19730. (push v list)))))
  19731. (kill-buffer (get-buffer "*Warn about privacy*"))
  19732. list))
  19733. nil nil
  19734. "Remember to cover the basics, that is, what you expected to happen and
  19735. what in fact did happen. You don't know how to make a good report? See
  19736. http://orgmode.org/manual/Feedback.html#Feedback
  19737. Your bug report will be posted to the Org mailing list.
  19738. ------------------------------------------------------------------------")
  19739. (save-excursion
  19740. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19741. (replace-match "\\1Bug: \\3 [\\2]")))))
  19742. (defun org-install-agenda-files-menu ()
  19743. (let ((bl (buffer-list)))
  19744. (save-excursion
  19745. (while bl
  19746. (set-buffer (pop bl))
  19747. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19748. (when (derived-mode-p 'org-mode)
  19749. (easy-menu-change
  19750. '("Org") "File List for Agenda"
  19751. (append
  19752. (list
  19753. ["Edit File List" (org-edit-agenda-file-list) t]
  19754. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19755. ["Remove Current File from List" org-remove-file t]
  19756. ["Cycle through agenda files" org-cycle-agenda-files t]
  19757. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19758. "--")
  19759. (mapcar 'org-file-menu-entry
  19760. ;; Prevent initialization from failing.
  19761. (ignore-errors (org-agenda-files t)))))))))
  19762. ;;;; Documentation
  19763. (defun org-require-autoloaded-modules ()
  19764. (interactive)
  19765. (mapc #'require
  19766. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19767. org-table org-timer)))
  19768. ;;;###autoload
  19769. (defun org-reload (&optional uncompiled)
  19770. "Reload all org lisp files.
  19771. With prefix arg UNCOMPILED, load the uncompiled versions."
  19772. (interactive "P")
  19773. (require 'loadhist)
  19774. (let* ((org-dir (org-find-library-dir "org"))
  19775. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19776. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19777. (remove-re (format "\\`%s\\'"
  19778. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19779. (feats (delete-dups
  19780. (mapcar 'file-name-sans-extension
  19781. (mapcar 'file-name-nondirectory
  19782. (delq nil
  19783. (mapcar 'feature-file
  19784. features))))))
  19785. (lfeat (append
  19786. (sort
  19787. (setq feats
  19788. (delq nil (mapcar
  19789. (lambda (f)
  19790. (if (and (string-match feature-re f)
  19791. (not (string-match remove-re f)))
  19792. f nil))
  19793. feats)))
  19794. 'string-lessp)
  19795. (list "org-version" "org")))
  19796. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19797. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19798. load-uncore load-misses)
  19799. (setq load-misses
  19800. (delq 't
  19801. (mapcar (lambda (f)
  19802. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19803. (and (string= org-dir contrib-dir)
  19804. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19805. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19806. (add-to-list 'load-uncore f 'append)
  19807. 't)
  19808. f))
  19809. lfeat)))
  19810. (when load-uncore
  19811. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19812. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19813. (if load-misses
  19814. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19815. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19816. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19817. ;;;###autoload
  19818. (defun org-customize ()
  19819. "Call the customize function with org as argument."
  19820. (interactive)
  19821. (org-load-modules-maybe)
  19822. (org-require-autoloaded-modules)
  19823. (customize-browse 'org))
  19824. (defun org-create-customize-menu ()
  19825. "Create a full customization menu for Org mode, insert it into the menu."
  19826. (interactive)
  19827. (org-load-modules-maybe)
  19828. (org-require-autoloaded-modules)
  19829. (if (fboundp 'customize-menu-create)
  19830. (progn
  19831. (easy-menu-change
  19832. '("Org") "Customize"
  19833. `(["Browse Org group" org-customize t]
  19834. "--"
  19835. ,(customize-menu-create 'org)
  19836. ["Set" Custom-set t]
  19837. ["Save" Custom-save t]
  19838. ["Reset to Current" Custom-reset-current t]
  19839. ["Reset to Saved" Custom-reset-saved t]
  19840. ["Reset to Standard Settings" Custom-reset-standard t]))
  19841. (message "\"Org\"-menu now contains full customization menu"))
  19842. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19843. ;;;; Miscellaneous stuff
  19844. ;;; Generally useful functions
  19845. (defun org-get-at-eol (property n)
  19846. "Get text property PROPERTY at the end of line less N characters."
  19847. (get-text-property (- (point-at-eol) n) property))
  19848. (defun org-find-text-property-in-string (prop s)
  19849. "Return the first non-nil value of property PROP in string S."
  19850. (or (get-text-property 0 prop s)
  19851. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19852. prop s)))
  19853. (defun org-display-warning (message)
  19854. "Display the given MESSAGE as a warning."
  19855. (display-warning 'org message :warning))
  19856. (defun org-eval (form)
  19857. "Eval FORM and return result."
  19858. (condition-case error
  19859. (eval form)
  19860. (error (format "%%![Error: %s]" error))))
  19861. (defun org-in-clocktable-p ()
  19862. "Check if the cursor is in a clocktable."
  19863. (let ((pos (point)) start)
  19864. (save-excursion
  19865. (end-of-line 1)
  19866. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19867. (setq start (match-beginning 0))
  19868. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19869. (>= (match-end 0) pos)
  19870. start))))
  19871. (defun org-in-verbatim-emphasis ()
  19872. (save-match-data
  19873. (and (org-in-regexp org-verbatim-re 2)
  19874. (>= (point) (match-beginning 3))
  19875. (<= (point) (match-end 4)))))
  19876. (defun org-overlay-display (ovl text &optional face evap)
  19877. "Make overlay OVL display TEXT with face FACE."
  19878. (overlay-put ovl 'display text)
  19879. (if face (overlay-put ovl 'face face))
  19880. (if evap (overlay-put ovl 'evaporate t)))
  19881. (defun org-overlay-before-string (ovl text &optional face evap)
  19882. "Make overlay OVL display TEXT with face FACE."
  19883. (if face (org-add-props text nil 'face face))
  19884. (overlay-put ovl 'before-string text)
  19885. (if evap (overlay-put ovl 'evaporate t)))
  19886. (defun org-find-overlays (prop &optional pos delete)
  19887. "Find all overlays specifying PROP at POS or point.
  19888. If DELETE is non-nil, delete all those overlays."
  19889. (let (found)
  19890. (dolist (ov (overlays-at (or pos (point))) found)
  19891. (cond ((not (overlay-get ov prop)))
  19892. (delete (delete-overlay ov))
  19893. (t (push ov found))))))
  19894. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19895. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19896. (if (and marker (marker-buffer marker)
  19897. (buffer-live-p (marker-buffer marker)))
  19898. (progn
  19899. (pop-to-buffer-same-window (marker-buffer marker))
  19900. (when (or (> marker (point-max)) (< marker (point-min)))
  19901. (widen))
  19902. (goto-char marker)
  19903. (org-show-context 'org-goto))
  19904. (if bookmark
  19905. (bookmark-jump bookmark)
  19906. (error "Cannot find location"))))
  19907. (defun org-quote-csv-field (s)
  19908. "Quote field for inclusion in CSV material."
  19909. (if (string-match "[\",]" s)
  19910. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19911. s))
  19912. (defun org-force-self-insert (N)
  19913. "Needed to enforce self-insert under remapping."
  19914. (interactive "p")
  19915. (self-insert-command N))
  19916. (defun org-shorten-string (s maxlength)
  19917. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19918. If the string is shorter or has length MAXLENGTH, just return the
  19919. original string. If it is longer, the functions finds a space in the
  19920. string, breaks this string off at that locations and adds three dots
  19921. as ellipsis. Including the ellipsis, the string will not be longer
  19922. than MAXLENGTH. If finding a good breaking point in the string does
  19923. not work, the string is just chopped off in the middle of a word
  19924. if necessary."
  19925. (if (<= (length s) maxlength)
  19926. s
  19927. (let* ((n (max (- maxlength 4) 1))
  19928. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19929. (if (string-match re s)
  19930. (concat (match-string 1 s) "...")
  19931. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19932. (defun org-get-indentation (&optional line)
  19933. "Get the indentation of the current line, interpreting tabs.
  19934. When LINE is given, assume it represents a line and compute its indentation."
  19935. (if line
  19936. (when (string-match "^ *" (org-remove-tabs line))
  19937. (match-end 0))
  19938. (save-excursion
  19939. (beginning-of-line 1)
  19940. (skip-chars-forward " \t")
  19941. (current-column))))
  19942. (defun org-get-string-indentation (s)
  19943. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19944. (let ((n -1) (i 0) (w tab-width) c)
  19945. (catch 'exit
  19946. (while (< (setq n (1+ n)) (length s))
  19947. (setq c (aref s n))
  19948. (cond ((= c ?\ ) (setq i (1+ i)))
  19949. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19950. (t (throw 'exit t)))))
  19951. i))
  19952. (defun org-remove-tabs (s &optional width)
  19953. "Replace tabulators in S with spaces.
  19954. Assumes that s is a single line, starting in column 0."
  19955. (setq width (or width tab-width))
  19956. (while (string-match "\t" s)
  19957. (setq s (replace-match
  19958. (make-string
  19959. (- (* width (/ (+ (match-beginning 0) width) width))
  19960. (match-beginning 0)) ?\ )
  19961. t t s)))
  19962. s)
  19963. (defun org-fix-indentation (line ind)
  19964. "Fix indentation in LINE.
  19965. IND is a cons cell with target and minimum indentation.
  19966. If the current indentation in LINE is smaller than the minimum,
  19967. leave it alone. If it is larger than ind, set it to the target."
  19968. (let* ((l (org-remove-tabs line))
  19969. (i (org-get-indentation l))
  19970. (i1 (car ind)) (i2 (cdr ind)))
  19971. (when (>= i i2) (setq l (substring line i2)))
  19972. (if (> i1 0)
  19973. (concat (make-string i1 ?\ ) l)
  19974. l)))
  19975. (defun org-remove-indentation (code &optional n)
  19976. "Remove maximum common indentation in string CODE and return it.
  19977. N may optionally be the number of columns to remove. Return CODE
  19978. as-is if removal failed."
  19979. (with-temp-buffer
  19980. (insert code)
  19981. (if (org-do-remove-indentation n) (buffer-string) code)))
  19982. (defun org-do-remove-indentation (&optional n)
  19983. "Remove the maximum common indentation from the buffer.
  19984. When optional argument N is a positive integer, remove exactly
  19985. that much characters from indentation, if possible. Return nil
  19986. if it fails."
  19987. (catch :exit
  19988. (goto-char (point-min))
  19989. ;; Find maximum common indentation, if not specified.
  19990. (let ((n (or n
  19991. (let ((min-ind (point-max)))
  19992. (save-excursion
  19993. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19994. (let ((ind (1- (current-column))))
  19995. (if (zerop ind) (throw :exit nil)
  19996. (setq min-ind (min min-ind ind))))))
  19997. min-ind))))
  19998. (if (zerop n) (throw :exit nil)
  19999. ;; Remove exactly N indentation, but give up if not possible.
  20000. (while (not (eobp))
  20001. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20002. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20003. ((< ind n) (throw :exit nil))
  20004. (t (indent-line-to (- ind n))))
  20005. (forward-line)))
  20006. ;; Signal success.
  20007. t))))
  20008. (defun org-fill-template (template alist)
  20009. "Find each %key of ALIST in TEMPLATE and replace it."
  20010. (let ((case-fold-search nil))
  20011. (dolist (entry (sort (copy-sequence alist)
  20012. (lambda (a b) (< (length (car a)) (length (car b))))))
  20013. (setq template
  20014. (replace-regexp-in-string
  20015. (concat "%" (regexp-quote (car entry)))
  20016. (or (cdr entry) "") template t t)))
  20017. template))
  20018. (defun org-base-buffer (buffer)
  20019. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20020. (if (not buffer)
  20021. buffer
  20022. (or (buffer-base-buffer buffer)
  20023. buffer)))
  20024. (defun org-wrap (string &optional width lines)
  20025. "Wrap string to either a number of lines, or a width in characters.
  20026. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20027. that costs. If there is a word longer than WIDTH, the text is actually
  20028. wrapped to the length of that word.
  20029. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20030. many lines, whatever width that takes.
  20031. The return value is a list of lines, without newlines at the end."
  20032. (let* ((words (split-string string))
  20033. (maxword (apply 'max (mapcar 'org-string-width words)))
  20034. w ll)
  20035. (cond (width
  20036. (org-do-wrap words (max maxword width)))
  20037. (lines
  20038. (setq w maxword)
  20039. (setq ll (org-do-wrap words maxword))
  20040. (if (<= (length ll) lines)
  20041. ll
  20042. (setq ll words)
  20043. (while (> (length ll) lines)
  20044. (setq w (1+ w))
  20045. (setq ll (org-do-wrap words w)))
  20046. ll))
  20047. (t (error "Cannot wrap this")))))
  20048. (defun org-do-wrap (words width)
  20049. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20050. (let (lines line)
  20051. (while words
  20052. (setq line (pop words))
  20053. (while (and words (< (+ (length line) (length (car words))) width))
  20054. (setq line (concat line " " (pop words))))
  20055. (setq lines (push line lines)))
  20056. (nreverse lines)))
  20057. (defun org-quote-vert (s)
  20058. "Replace \"|\" with \"\\vert\"."
  20059. (while (string-match "|" s)
  20060. (setq s (replace-match "\\vert" t t s)))
  20061. s)
  20062. (defun org-uuidgen-p (s)
  20063. "Is S an ID created by UUIDGEN?"
  20064. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20065. (defun org-in-src-block-p (&optional inside)
  20066. "Whether point is in a code source block.
  20067. When INSIDE is non-nil, don't consider we are within a src block
  20068. when point is at #+BEGIN_SRC or #+END_SRC."
  20069. (let ((case-fold-search t))
  20070. (or (and (eq (get-char-property (point) 'src-block) t))
  20071. (and (not inside)
  20072. (save-match-data
  20073. (save-excursion
  20074. (beginning-of-line)
  20075. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20076. (defun org-context ()
  20077. "Return a list of contexts of the current cursor position.
  20078. If several contexts apply, all are returned.
  20079. Each context entry is a list with a symbol naming the context, and
  20080. two positions indicating start and end of the context. Possible
  20081. contexts are:
  20082. :headline anywhere in a headline
  20083. :headline-stars on the leading stars in a headline
  20084. :todo-keyword on a TODO keyword (including DONE) in a headline
  20085. :tags on the TAGS in a headline
  20086. :priority on the priority cookie in a headline
  20087. :item on the first line of a plain list item
  20088. :item-bullet on the bullet/number of a plain list item
  20089. :checkbox on the checkbox in a plain list item
  20090. :table in an Org table
  20091. :table-special on a special filed in a table
  20092. :table-table in a table.el table
  20093. :clocktable in a clocktable
  20094. :src-block in a source block
  20095. :link on a hyperlink
  20096. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20097. :target on a <<target>>
  20098. :radio-target on a <<<radio-target>>>
  20099. :latex-fragment on a LaTeX fragment
  20100. :latex-preview on a LaTeX fragment with overlaid preview image
  20101. This function expects the position to be visible because it uses font-lock
  20102. faces as a help to recognize the following contexts: :table-special, :link,
  20103. and :keyword."
  20104. (let* ((f (get-text-property (point) 'face))
  20105. (faces (if (listp f) f (list f)))
  20106. (case-fold-search t)
  20107. (p (point)) clist o)
  20108. ;; First the large context
  20109. (cond
  20110. ((org-at-heading-p t)
  20111. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20112. (when (progn
  20113. (beginning-of-line 1)
  20114. (looking-at org-todo-line-tags-regexp))
  20115. (push (org-point-in-group p 1 :headline-stars) clist)
  20116. (push (org-point-in-group p 2 :todo-keyword) clist)
  20117. (push (org-point-in-group p 4 :tags) clist))
  20118. (goto-char p)
  20119. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20120. (when (looking-at "\\[#[A-Z0-9]\\]")
  20121. (push (org-point-in-group p 0 :priority) clist)))
  20122. ((org-at-item-p)
  20123. (push (org-point-in-group p 2 :item-bullet) clist)
  20124. (push (list :item (point-at-bol)
  20125. (save-excursion (org-end-of-item) (point)))
  20126. clist)
  20127. (and (org-at-item-checkbox-p)
  20128. (push (org-point-in-group p 0 :checkbox) clist)))
  20129. ((org-at-table-p)
  20130. (push (list :table (org-table-begin) (org-table-end)) clist)
  20131. (when (memq 'org-formula faces)
  20132. (push (list :table-special
  20133. (previous-single-property-change p 'face)
  20134. (next-single-property-change p 'face)) clist)))
  20135. ((org-at-table-p 'any)
  20136. (push (list :table-table) clist)))
  20137. (goto-char p)
  20138. (let ((case-fold-search t))
  20139. ;; New the "medium" contexts: clocktables, source blocks
  20140. (cond ((org-in-clocktable-p)
  20141. (push (list :clocktable
  20142. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20143. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20144. (match-beginning 1))
  20145. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20146. (match-end 0))) clist))
  20147. ((org-in-src-block-p)
  20148. (push (list :src-block
  20149. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20150. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20151. (match-beginning 1))
  20152. (and (search-forward "#+END_SRC" nil t)
  20153. (match-beginning 0))) clist))))
  20154. (goto-char p)
  20155. ;; Now the small context
  20156. (cond
  20157. ((org-at-timestamp-p)
  20158. (push (org-point-in-group p 0 :timestamp) clist))
  20159. ((memq 'org-link faces)
  20160. (push (list :link
  20161. (previous-single-property-change p 'face)
  20162. (next-single-property-change p 'face)) clist))
  20163. ((memq 'org-special-keyword faces)
  20164. (push (list :keyword
  20165. (previous-single-property-change p 'face)
  20166. (next-single-property-change p 'face)) clist))
  20167. ((org-at-target-p)
  20168. (push (org-point-in-group p 0 :target) clist)
  20169. (goto-char (1- (match-beginning 0)))
  20170. (when (looking-at org-radio-target-regexp)
  20171. (push (org-point-in-group p 0 :radio-target) clist))
  20172. (goto-char p))
  20173. ((setq o (cl-some
  20174. (lambda (o)
  20175. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20176. o))
  20177. (overlays-at (point))))
  20178. (push (list :latex-fragment
  20179. (overlay-start o) (overlay-end o)) clist)
  20180. (push (list :latex-preview
  20181. (overlay-start o) (overlay-end o)) clist))
  20182. ((org-inside-LaTeX-fragment-p)
  20183. ;; FIXME: positions wrong.
  20184. (push (list :latex-fragment (point) (point)) clist)))
  20185. (setq clist (nreverse (delq nil clist)))
  20186. clist))
  20187. (defun org-in-regexp (regexp &optional nlines visually)
  20188. "Check if point is inside a match of REGEXP.
  20189. Normally only the current line is checked, but you can include
  20190. NLINES extra lines around point into the search. If VISUALLY is
  20191. set, require that the cursor is not after the match but really
  20192. on, so that the block visually is on the match.
  20193. Return nil or a cons cell (BEG . END) where BEG and END are,
  20194. respectively, the positions at the beginning and the end of the
  20195. match."
  20196. (catch :exit
  20197. (let ((pos (point))
  20198. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20199. (save-excursion
  20200. (beginning-of-line (- 1 (or nlines 0)))
  20201. (while (and (re-search-forward regexp eol t)
  20202. (<= (match-beginning 0) pos))
  20203. (let ((end (match-end 0)))
  20204. (when (or (> end pos) (and (= end pos) (not visually)))
  20205. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20206. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20207. "Non-nil when point is between matches of START-RE and END-RE.
  20208. Also return a non-nil value when point is on one of the matches.
  20209. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20210. buffer positions. Default values are the positions of headlines
  20211. surrounding the point.
  20212. The functions returns a cons cell whose car (resp. cdr) is the
  20213. position before START-RE (resp. after END-RE)."
  20214. (save-match-data
  20215. (let ((pos (point))
  20216. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20217. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20218. beg end)
  20219. (save-excursion
  20220. ;; Point is on a block when on START-RE or if START-RE can be
  20221. ;; found before it...
  20222. (and (or (org-in-regexp start-re)
  20223. (re-search-backward start-re limit-up t))
  20224. (setq beg (match-beginning 0))
  20225. ;; ... and END-RE after it...
  20226. (goto-char (match-end 0))
  20227. (re-search-forward end-re limit-down t)
  20228. (> (setq end (match-end 0)) pos)
  20229. ;; ... without another START-RE in-between.
  20230. (goto-char (match-beginning 0))
  20231. (not (re-search-backward start-re (1+ beg) t))
  20232. ;; Return value.
  20233. (cons beg end))))))
  20234. (defun org-in-block-p (names)
  20235. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20236. NAMES is a list of strings containing names of blocks.
  20237. Return first block name matched, or nil. Beware that in case of
  20238. nested blocks, the returned name may not belong to the closest
  20239. block from point."
  20240. (save-match-data
  20241. (catch 'exit
  20242. (let ((case-fold-search t)
  20243. (lim-up (save-excursion (outline-previous-heading)))
  20244. (lim-down (save-excursion (outline-next-heading))))
  20245. (dolist (name names)
  20246. (let ((n (regexp-quote name)))
  20247. (when (org-between-regexps-p
  20248. (concat "^[ \t]*#\\+begin_" n)
  20249. (concat "^[ \t]*#\\+end_" n)
  20250. lim-up lim-down)
  20251. (throw 'exit n)))))
  20252. nil)))
  20253. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20254. "Call `multi-occur' with buffers for all agenda files."
  20255. (interactive "sOrg-files matching: ")
  20256. (let* ((files (org-agenda-files))
  20257. (tnames (mapcar #'file-truename files))
  20258. (extra org-agenda-text-search-extra-files))
  20259. (when (eq (car extra) 'agenda-archives)
  20260. (setq extra (cdr extra))
  20261. (setq files (org-add-archive-files files)))
  20262. (dolist (f extra)
  20263. (unless (member (file-truename f) tnames)
  20264. (unless (member f files) (setq files (append files (list f))))
  20265. (setq tnames (append tnames (list (file-truename f))))))
  20266. (multi-occur
  20267. (mapcar (lambda (x)
  20268. (with-current-buffer
  20269. ;; FIXME: Why not just (find-file-noselect x)?
  20270. ;; Is it to avoid the "revert buffer" prompt?
  20271. (or (get-file-buffer x) (find-file-noselect x))
  20272. (widen)
  20273. (current-buffer)))
  20274. files)
  20275. regexp)))
  20276. (add-hook 'occur-mode-find-occurrence-hook
  20277. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20278. (defun org-occur-link-in-agenda-files ()
  20279. "Create a link and search for it in the agendas.
  20280. The link is not stored in `org-stored-links', it is just created
  20281. for the search purpose."
  20282. (interactive)
  20283. (let ((link (condition-case nil
  20284. (org-store-link nil)
  20285. (error "Unable to create a link to here"))))
  20286. (org-occur-in-agenda-files (regexp-quote link))))
  20287. (defun org-reverse-string (string)
  20288. "Return the reverse of STRING."
  20289. (apply 'string (reverse (string-to-list string))))
  20290. ;; defsubst org-uniquify must be defined before first use
  20291. (defun org-uniquify-alist (alist)
  20292. "Merge elements of ALIST with the same key.
  20293. For example, in this alist:
  20294. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20295. => \\='((a 1 3) (b 2))
  20296. merge (a 1) and (a 3) into (a 1 3).
  20297. The function returns the new ALIST."
  20298. (let (rtn)
  20299. (dolist (e alist rtn)
  20300. (let (n)
  20301. (if (not (assoc (car e) rtn))
  20302. (push e rtn)
  20303. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20304. (setq rtn (assq-delete-all (car e) rtn))
  20305. (push n rtn))))))
  20306. (defun org-delete-all (elts list)
  20307. "Remove all elements in ELTS from LIST.
  20308. Comparison is done with `equal'. It is a destructive operation
  20309. that may remove elements by altering the list structure."
  20310. (while elts
  20311. (setq list (delete (pop elts) list)))
  20312. list)
  20313. (defun org-back-over-empty-lines ()
  20314. "Move backwards over whitespace, to the beginning of the first empty line.
  20315. Returns the number of empty lines passed."
  20316. (let ((pos (point)))
  20317. (if (cdr (assq 'heading org-blank-before-new-entry))
  20318. (skip-chars-backward " \t\n\r")
  20319. (unless (eobp)
  20320. (forward-line -1)))
  20321. (beginning-of-line 2)
  20322. (goto-char (min (point) pos))
  20323. (count-lines (point) pos)))
  20324. (defun org-skip-whitespace ()
  20325. (skip-chars-forward " \t\n\r"))
  20326. (defun org-point-in-group (point group &optional context)
  20327. "Check if POINT is in match-group GROUP.
  20328. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20329. match. If the match group does not exist or point is not inside it,
  20330. return nil."
  20331. (and (match-beginning group)
  20332. (>= point (match-beginning group))
  20333. (<= point (match-end group))
  20334. (if context
  20335. (list context (match-beginning group) (match-end group))
  20336. t)))
  20337. (defun org-switch-to-buffer-other-window (&rest args)
  20338. "Switch to buffer in a second window on the current frame.
  20339. In particular, do not allow pop-up frames.
  20340. Returns the newly created buffer."
  20341. (org-no-popups
  20342. (apply 'switch-to-buffer-other-window args)))
  20343. (defun org-combine-plists (&rest plists)
  20344. "Create a single property list from all plists in PLISTS.
  20345. The process starts by copying the first list, and then setting properties
  20346. from the other lists. Settings in the last list are the most significant
  20347. ones and overrule settings in the other lists."
  20348. (let ((rtn (copy-sequence (pop plists)))
  20349. p v ls)
  20350. (while plists
  20351. (setq ls (pop plists))
  20352. (while ls
  20353. (setq p (pop ls) v (pop ls))
  20354. (setq rtn (plist-put rtn p v))))
  20355. rtn))
  20356. (defun org-replace-escapes (string table)
  20357. "Replace %-escapes in STRING with values in TABLE.
  20358. TABLE is an association list with keys like \"%a\" and string values.
  20359. The sequences in STRING may contain normal field width and padding information,
  20360. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20361. so values can contain further %-escapes if they are define later in TABLE."
  20362. (let ((tbl (copy-alist table))
  20363. (case-fold-search nil)
  20364. (pchg 0)
  20365. re rpl)
  20366. (dolist (e tbl)
  20367. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20368. (when (and (cdr e) (string-match re (cdr e)))
  20369. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20370. (safe "SREF"))
  20371. (add-text-properties 0 3 (list 'sref sref) safe)
  20372. (setcdr e (replace-match safe t t (cdr e)))))
  20373. (while (string-match re string)
  20374. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20375. (cdr e)))
  20376. (setq string (replace-match rpl t t string))))
  20377. (while (setq pchg (next-property-change pchg string))
  20378. (let ((sref (get-text-property pchg 'sref string)))
  20379. (when (and sref (string-match "SREF" string pchg))
  20380. (setq string (replace-match sref t t string)))))
  20381. string))
  20382. (defun org-find-base-buffer-visiting (file)
  20383. "Like `find-buffer-visiting' but always return the base buffer and
  20384. not an indirect buffer."
  20385. (let ((buf (or (get-file-buffer file)
  20386. (find-buffer-visiting file))))
  20387. (if buf
  20388. (or (buffer-base-buffer buf) buf)
  20389. nil)))
  20390. ;;; TODO: Only called once, from ox-odt which should probably use
  20391. ;;; org-export-inline-image-p or something.
  20392. (defun org-file-image-p (file)
  20393. "Return non-nil if FILE is an image."
  20394. (save-match-data
  20395. (string-match (image-file-name-regexp) file)))
  20396. (defun org-get-cursor-date (&optional with-time)
  20397. "Return the date at cursor in as a time.
  20398. This works in the calendar and in the agenda, anywhere else it just
  20399. returns the current time.
  20400. If WITH-TIME is non-nil, returns the time of the event at point (in
  20401. the agenda) or the current time of the day."
  20402. (let (date day defd tp hod mod)
  20403. (when with-time
  20404. (setq tp (get-text-property (point) 'time))
  20405. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20406. (setq hod (string-to-number (match-string 1 tp))
  20407. mod (string-to-number (match-string 2 tp))))
  20408. (or tp (let ((now (decode-time)))
  20409. (setq hod (nth 2 now)
  20410. mod (nth 1 now)))))
  20411. (cond
  20412. ((eq major-mode 'calendar-mode)
  20413. (setq date (calendar-cursor-to-date)
  20414. defd (encode-time 0 (or mod 0) (or hod 0)
  20415. (nth 1 date) (nth 0 date) (nth 2 date))))
  20416. ((eq major-mode 'org-agenda-mode)
  20417. (setq day (get-text-property (point) 'day))
  20418. (when day
  20419. (setq date (calendar-gregorian-from-absolute day)
  20420. defd (encode-time 0 (or mod 0) (or hod 0)
  20421. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20422. (or defd (current-time))))
  20423. (defun org-mark-subtree (&optional up)
  20424. "Mark the current subtree.
  20425. This puts point at the start of the current subtree, and mark at
  20426. the end. If a numeric prefix UP is given, move up into the
  20427. hierarchy of headlines by UP levels before marking the subtree."
  20428. (interactive "P")
  20429. (org-with-limited-levels
  20430. (cond ((org-at-heading-p) (beginning-of-line))
  20431. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20432. (t (outline-previous-visible-heading 1))))
  20433. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20434. (if (called-interactively-p 'any)
  20435. (call-interactively 'org-mark-element)
  20436. (org-mark-element)))
  20437. (defun org-file-newer-than-p (file time)
  20438. "Non-nil if FILE is newer than TIME.
  20439. FILE is a filename, as a string, TIME is a list of integers, as
  20440. returned by, e.g., `current-time'."
  20441. (and (file-exists-p file)
  20442. ;; Only compare times up to whole seconds as some file-systems
  20443. ;; (e.g. HFS+) do not retain any finer granularity. As
  20444. ;; a consequence, make sure we return non-nil when the two
  20445. ;; times are equal.
  20446. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20447. (cl-subseq time 0 2)))))
  20448. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20449. "Compile a SOURCE file using PROCESS.
  20450. PROCESS is either a function or a list of shell commands, as
  20451. strings. EXT is a file extension, without the leading dot, as
  20452. a string. It is used to check if the process actually succeeded.
  20453. PROCESS must create a file with the same base name and directory
  20454. as SOURCE, but ending with EXT. The function then returns its
  20455. filename. Otherwise, it raises an error. The error message can
  20456. then be refined by providing string ERR-MSG, which is appended to
  20457. the standard message.
  20458. If PROCESS is a function, it is called with a single argument:
  20459. the SOURCE file.
  20460. If it is a list of commands, each of them is called using
  20461. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20462. %O are replaced with, respectively, SOURCE base name, name, full
  20463. name, directory and absolute output file name. It is possible,
  20464. however, to use more place-holders by specifying them in optional
  20465. argument SPEC, as an alist following the pattern
  20466. (CHARACTER . REPLACEMENT-STRING).
  20467. When PROCESS is a list of commands, optional argument LOG-BUF can
  20468. be set to a buffer or a buffer name. `shell-command' then uses
  20469. it for output."
  20470. (let* ((base-name (file-name-base source))
  20471. (full-name (file-truename source))
  20472. (out-dir (or (file-name-directory source) "./"))
  20473. (output (expand-file-name (concat base-name "." ext) out-dir))
  20474. (time (current-time))
  20475. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20476. (save-window-excursion
  20477. (pcase process
  20478. ((pred functionp) (funcall process (shell-quote-argument source)))
  20479. ((pred consp)
  20480. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20481. (spec (append spec
  20482. `((?b . ,(shell-quote-argument base-name))
  20483. (?f . ,(shell-quote-argument source))
  20484. (?F . ,(shell-quote-argument full-name))
  20485. (?o . ,(shell-quote-argument out-dir))
  20486. (?O . ,(shell-quote-argument output))))))
  20487. (dolist (command process)
  20488. (shell-command (format-spec command spec) log-buf))
  20489. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20490. (_ (error "No valid command to process %S%s" source err-msg))))
  20491. ;; Check for process failure. Output file is expected to be
  20492. ;; located in the same directory as SOURCE.
  20493. (unless (org-file-newer-than-p output time)
  20494. (error (format "File %S wasn't produced%s" output err-msg)))
  20495. output))
  20496. ;;; Indentation
  20497. (defvar org-element-greater-elements)
  20498. (defun org--get-expected-indentation (element contentsp)
  20499. "Expected indentation column for current line, according to ELEMENT.
  20500. ELEMENT is an element containing point. CONTENTSP is non-nil
  20501. when indentation is to be computed according to contents of
  20502. ELEMENT."
  20503. (let ((type (org-element-type element))
  20504. (start (org-element-property :begin element))
  20505. (post-affiliated (org-element-property :post-affiliated element)))
  20506. (org-with-wide-buffer
  20507. (cond
  20508. (contentsp
  20509. (cl-case type
  20510. ((diary-sexp footnote-definition) 0)
  20511. ((headline inlinetask nil)
  20512. (if (not org-adapt-indentation) 0
  20513. (let ((level (org-current-level)))
  20514. (if level (1+ level) 0))))
  20515. ((item plain-list) (org-list-item-body-column post-affiliated))
  20516. (t
  20517. (goto-char start)
  20518. (org-get-indentation))))
  20519. ((memq type '(headline inlinetask nil))
  20520. (if (org-match-line "[ \t]*$")
  20521. (org--get-expected-indentation element t)
  20522. 0))
  20523. ((memq type '(diary-sexp footnote-definition)) 0)
  20524. ;; First paragraph of a footnote definition or an item.
  20525. ;; Indent like parent.
  20526. ((< (line-beginning-position) start)
  20527. (org--get-expected-indentation
  20528. (org-element-property :parent element) t))
  20529. ;; At first line: indent according to previous sibling, if any,
  20530. ;; ignoring footnote definitions and inline tasks, or parent's
  20531. ;; contents.
  20532. ((= (line-beginning-position) start)
  20533. (catch 'exit
  20534. (while t
  20535. (if (= (point-min) start) (throw 'exit 0)
  20536. (goto-char (1- start))
  20537. (let* ((previous (org-element-at-point))
  20538. (parent previous))
  20539. (while (and parent (<= (org-element-property :end parent) start))
  20540. (setq previous parent
  20541. parent (org-element-property :parent parent)))
  20542. (cond
  20543. ((not previous) (throw 'exit 0))
  20544. ((> (org-element-property :end previous) start)
  20545. (throw 'exit (org--get-expected-indentation previous t)))
  20546. ((memq (org-element-type previous)
  20547. '(footnote-definition inlinetask))
  20548. (setq start (org-element-property :begin previous)))
  20549. (t (goto-char (org-element-property :begin previous))
  20550. (throw 'exit
  20551. (if (bolp) (org-get-indentation)
  20552. ;; At first paragraph in an item or
  20553. ;; a footnote definition.
  20554. (org--get-expected-indentation
  20555. (org-element-property :parent previous) t))))))))))
  20556. ;; Otherwise, move to the first non-blank line above.
  20557. (t
  20558. (beginning-of-line)
  20559. (let ((pos (point)))
  20560. (skip-chars-backward " \r\t\n")
  20561. (cond
  20562. ;; Two blank lines end a footnote definition or a plain
  20563. ;; list. When we indent an empty line after them, the
  20564. ;; containing list or footnote definition is over, so it
  20565. ;; qualifies as a previous sibling. Therefore, we indent
  20566. ;; like its first line.
  20567. ((and (memq type '(footnote-definition plain-list))
  20568. (> (count-lines (point) pos) 2))
  20569. (goto-char start)
  20570. (org-get-indentation))
  20571. ;; Line above is the first one of a paragraph at the
  20572. ;; beginning of an item or a footnote definition. Indent
  20573. ;; like parent.
  20574. ((< (line-beginning-position) start)
  20575. (org--get-expected-indentation
  20576. (org-element-property :parent element) t))
  20577. ;; Line above is the beginning of an element, i.e., point
  20578. ;; was originally on the blank lines between element's start
  20579. ;; and contents.
  20580. ((= (line-beginning-position) post-affiliated)
  20581. (org--get-expected-indentation element t))
  20582. ;; POS is after contents in a greater element. Indent like
  20583. ;; the beginning of the element.
  20584. ((and (memq type org-element-greater-elements)
  20585. (let ((cend (org-element-property :contents-end element)))
  20586. (and cend (<= cend pos))))
  20587. ;; As a special case, if point is at the end of a footnote
  20588. ;; definition or an item, indent like the very last element
  20589. ;; within. If that last element is an item, indent like
  20590. ;; its contents.
  20591. (if (memq type '(footnote-definition item plain-list))
  20592. (let ((last (org-element-at-point)))
  20593. (goto-char pos)
  20594. (org--get-expected-indentation
  20595. last (eq (org-element-type last) 'item)))
  20596. (goto-char start)
  20597. (org-get-indentation)))
  20598. ;; In any other case, indent like the current line.
  20599. (t (org-get-indentation)))))))))
  20600. (defun org--align-node-property ()
  20601. "Align node property at point.
  20602. Alignment is done according to `org-property-format', which see."
  20603. (when (save-excursion
  20604. (beginning-of-line)
  20605. (looking-at org-property-re))
  20606. (replace-match
  20607. (concat (match-string 4)
  20608. (org-trim
  20609. (format org-property-format (match-string 1) (match-string 3))))
  20610. t t)))
  20611. (defun org-indent-line ()
  20612. "Indent line depending on context.
  20613. Indentation is done according to the following rules:
  20614. - Footnote definitions, diary sexps, headlines and inline tasks
  20615. have to start at column 0.
  20616. - On the very first line of an element, consider, in order, the
  20617. next rules until one matches:
  20618. 1. If there's a sibling element before, ignoring footnote
  20619. definitions and inline tasks, indent like its first line.
  20620. 2. If element has a parent, indent like its contents. More
  20621. precisely, if parent is an item, indent after the
  20622. description part, if any, or the bullet (see
  20623. `org-list-description-max-indent'). Else, indent like
  20624. parent's first line.
  20625. 3. Otherwise, indent relatively to current level, if
  20626. `org-adapt-indentation' is non-nil, or to left margin.
  20627. - On a blank line at the end of an element, indent according to
  20628. the type of the element. More precisely
  20629. 1. If element is a plain list, an item, or a footnote
  20630. definition, indent like the very last element within.
  20631. 2. If element is a paragraph, indent like its last non blank
  20632. line.
  20633. 3. Otherwise, indent like its very first line.
  20634. - In the code part of a source block, use language major mode
  20635. to indent current line if `org-src-tab-acts-natively' is
  20636. non-nil. If it is nil, do nothing.
  20637. - Otherwise, indent like the first non-blank line above.
  20638. The function doesn't indent an item as it could break the whole
  20639. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20640. `\\[org-shiftmetaright]'.
  20641. Also align node properties according to `org-property-format'."
  20642. (interactive)
  20643. (cond
  20644. (orgstruct-is-++
  20645. (let ((indent-line-function
  20646. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20647. (indent-according-to-mode)))
  20648. ((org-at-heading-p) 'noindent)
  20649. (t
  20650. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20651. (type (org-element-type element)))
  20652. (cond ((and (memq type '(plain-list item))
  20653. (= (line-beginning-position)
  20654. (org-element-property :post-affiliated element)))
  20655. 'noindent)
  20656. ((and (eq type 'latex-environment)
  20657. (>= (point) (org-element-property :post-affiliated element))
  20658. (< (point) (org-with-wide-buffer
  20659. (goto-char (org-element-property :end element))
  20660. (skip-chars-backward " \r\t\n")
  20661. (line-beginning-position 2))))
  20662. 'noindent)
  20663. ((and (eq type 'src-block)
  20664. org-src-tab-acts-natively
  20665. (> (line-beginning-position)
  20666. (org-element-property :post-affiliated element))
  20667. (< (line-beginning-position)
  20668. (org-with-wide-buffer
  20669. (goto-char (org-element-property :end element))
  20670. (skip-chars-backward " \r\t\n")
  20671. (line-beginning-position))))
  20672. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20673. (t
  20674. (let ((column (org--get-expected-indentation element nil)))
  20675. ;; Preserve current column.
  20676. (if (<= (current-column) (current-indentation))
  20677. (indent-line-to column)
  20678. (save-excursion (indent-line-to column))))
  20679. ;; Align node property. Also preserve current column.
  20680. (when (eq type 'node-property)
  20681. (let ((column (current-column)))
  20682. (org--align-node-property)
  20683. (org-move-to-column column)))))))))
  20684. (defun org-indent-region (start end)
  20685. "Indent each non-blank line in the region.
  20686. Called from a program, START and END specify the region to
  20687. indent. The function will not indent contents of example blocks,
  20688. verse blocks and export blocks as leading white spaces are
  20689. assumed to be significant there."
  20690. (interactive "r")
  20691. (save-excursion
  20692. (goto-char start)
  20693. (skip-chars-forward " \r\t\n")
  20694. (unless (eobp) (beginning-of-line))
  20695. (let ((indent-to
  20696. (lambda (ind pos)
  20697. ;; Set IND as indentation for all lines between point and
  20698. ;; POS. Blank lines are ignored. Leave point after POS
  20699. ;; once done.
  20700. (let ((limit (copy-marker pos)))
  20701. (while (< (point) limit)
  20702. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20703. (forward-line))
  20704. (set-marker limit nil))))
  20705. (end (copy-marker end)))
  20706. (while (< (point) end)
  20707. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20708. (let* ((element (org-element-at-point))
  20709. (type (org-element-type element))
  20710. (element-end (copy-marker (org-element-property :end element)))
  20711. (ind (org--get-expected-indentation element nil)))
  20712. (cond
  20713. ;; Element indented as a single block. Example blocks
  20714. ;; preserving indentation are a special case since the
  20715. ;; "contents" must not be indented whereas the block
  20716. ;; boundaries can.
  20717. ((or (memq type '(export-block latex-environment))
  20718. (and (eq type 'example-block)
  20719. (not
  20720. (or org-src-preserve-indentation
  20721. (org-element-property :preserve-indent element)))))
  20722. (let ((offset (- ind (org-get-indentation))))
  20723. (unless (zerop offset)
  20724. (indent-rigidly (org-element-property :begin element)
  20725. (org-element-property :end element)
  20726. offset)))
  20727. (goto-char element-end))
  20728. ;; Elements indented line wise. Be sure to exclude
  20729. ;; example blocks (preserving indentation) and source
  20730. ;; blocks from this category as they are treated
  20731. ;; specially later.
  20732. ((or (memq type '(paragraph table table-row))
  20733. (not (or (org-element-property :contents-begin element)
  20734. (memq type '(example-block src-block)))))
  20735. (when (eq type 'node-property)
  20736. (org--align-node-property)
  20737. (beginning-of-line))
  20738. (funcall indent-to ind (min element-end end)))
  20739. ;; Elements consisting of three parts: before the
  20740. ;; contents, the contents, and after the contents. The
  20741. ;; contents are treated specially, according to the
  20742. ;; element type, or not indented at all. Other parts are
  20743. ;; indented as a single block.
  20744. (t
  20745. (let* ((post (copy-marker
  20746. (org-element-property :post-affiliated element)))
  20747. (cbeg
  20748. (copy-marker
  20749. (cond
  20750. ((not (org-element-property :contents-begin element))
  20751. ;; Fake contents for source blocks.
  20752. (org-with-wide-buffer
  20753. (goto-char post)
  20754. (line-beginning-position 2)))
  20755. ((memq type '(footnote-definition item plain-list))
  20756. ;; Contents in these elements could start on
  20757. ;; the same line as the beginning of the
  20758. ;; element. Make sure we start indenting
  20759. ;; from the second line.
  20760. (org-with-wide-buffer
  20761. (goto-char post)
  20762. (end-of-line)
  20763. (skip-chars-forward " \r\t\n")
  20764. (if (eobp) (point) (line-beginning-position))))
  20765. (t (org-element-property :contents-begin element)))))
  20766. (cend (copy-marker
  20767. (or (org-element-property :contents-end element)
  20768. ;; Fake contents for source blocks.
  20769. (org-with-wide-buffer
  20770. (goto-char element-end)
  20771. (skip-chars-backward " \r\t\n")
  20772. (line-beginning-position)))
  20773. t)))
  20774. ;; Do not change items indentation individually as it
  20775. ;; might break the list as a whole. On the other
  20776. ;; hand, when at a plain list, indent it as a whole.
  20777. (cond ((eq type 'plain-list)
  20778. (let ((offset (- ind (org-get-indentation))))
  20779. (unless (zerop offset)
  20780. (indent-rigidly (org-element-property :begin element)
  20781. (org-element-property :end element)
  20782. offset))
  20783. (goto-char cbeg)))
  20784. ((eq type 'item) (goto-char cbeg))
  20785. (t (funcall indent-to ind (min cbeg end))))
  20786. (when (< (point) end)
  20787. (cl-case type
  20788. ((example-block verse-block))
  20789. (src-block
  20790. ;; In a source block, indent source code
  20791. ;; according to language major mode, but only if
  20792. ;; `org-src-tab-acts-natively' is non-nil.
  20793. (when (and (< (point) end) org-src-tab-acts-natively)
  20794. (ignore-errors
  20795. (org-babel-do-in-edit-buffer
  20796. (indent-region (point-min) (point-max))))))
  20797. (t (org-indent-region (point) (min cend end))))
  20798. (goto-char (min cend end))
  20799. (when (< (point) end)
  20800. (funcall indent-to ind (min element-end end))))
  20801. (set-marker post nil)
  20802. (set-marker cbeg nil)
  20803. (set-marker cend nil))))
  20804. (set-marker element-end nil))))
  20805. (set-marker end nil))))
  20806. (defun org-indent-drawer ()
  20807. "Indent the drawer at point."
  20808. (interactive)
  20809. (unless (save-excursion
  20810. (beginning-of-line)
  20811. (looking-at-p org-drawer-regexp))
  20812. (user-error "Not at a drawer"))
  20813. (let ((element (org-element-at-point)))
  20814. (unless (memq (org-element-type element) '(drawer property-drawer))
  20815. (user-error "Not at a drawer"))
  20816. (org-with-wide-buffer
  20817. (org-indent-region (org-element-property :begin element)
  20818. (org-element-property :end element))))
  20819. (message "Drawer at point indented"))
  20820. (defun org-indent-block ()
  20821. "Indent the block at point."
  20822. (interactive)
  20823. (unless (save-excursion
  20824. (beginning-of-line)
  20825. (let ((case-fold-search t))
  20826. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20827. (user-error "Not at a block"))
  20828. (let ((element (org-element-at-point)))
  20829. (unless (memq (org-element-type element)
  20830. '(comment-block center-block dynamic-block example-block
  20831. export-block quote-block special-block
  20832. src-block verse-block))
  20833. (user-error "Not at a block"))
  20834. (org-with-wide-buffer
  20835. (org-indent-region (org-element-property :begin element)
  20836. (org-element-property :end element))))
  20837. (message "Block at point indented"))
  20838. ;;; Filling
  20839. ;; We use our own fill-paragraph and auto-fill functions.
  20840. ;; `org-fill-paragraph' relies on adaptive filling and context
  20841. ;; checking. Appropriate `fill-prefix' is computed with
  20842. ;; `org-adaptive-fill-function'.
  20843. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20844. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20845. ;; `org-adaptive-fill-function' value. Internally,
  20846. ;; `org-comment-line-break-function' breaks the line.
  20847. ;; `org-setup-filling' installs filling and auto-filling related
  20848. ;; variables during `org-mode' initialization.
  20849. (defun org-setup-filling ()
  20850. (require 'org-element)
  20851. ;; Prevent auto-fill from inserting unwanted new items.
  20852. (when (boundp 'fill-nobreak-predicate)
  20853. (setq-local
  20854. fill-nobreak-predicate
  20855. (org-uniquify
  20856. (append fill-nobreak-predicate
  20857. '(org-fill-line-break-nobreak-p
  20858. org-fill-n-macro-as-item-nobreak-p
  20859. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20860. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20861. (setq-local paragraph-start paragraph-ending)
  20862. (setq-local paragraph-separate paragraph-ending))
  20863. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20864. (setq-local auto-fill-inhibit-regexp nil)
  20865. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20866. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20867. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20868. (defun org-fill-line-break-nobreak-p ()
  20869. "Non-nil when a new line at point would create an Org line break."
  20870. (save-excursion
  20871. (skip-chars-backward "[ \t]")
  20872. (skip-chars-backward "\\\\")
  20873. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20874. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20875. "Non-nil when a new line at point would split a timestamp."
  20876. (and (org-at-timestamp-p 'lax)
  20877. (not (looking-at org-ts-regexp-both))))
  20878. (defun org-fill-n-macro-as-item-nobreak-p ()
  20879. "Non-nil when a new line at point would create a new list."
  20880. ;; During export, a "n" macro followed by a dot or a closing
  20881. ;; parenthesis can end up being parsed as a new list item.
  20882. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20883. (declare-function message-in-body-p "message" ())
  20884. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20885. (defun org-adaptive-fill-function ()
  20886. "Compute a fill prefix for the current line.
  20887. Return fill prefix, as a string, or nil if current line isn't
  20888. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20889. matches in paragraphs or comments, use it."
  20890. (catch 'exit
  20891. (when (derived-mode-p 'message-mode)
  20892. (save-excursion
  20893. (beginning-of-line)
  20894. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20895. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20896. ((looking-at message-cite-prefix-regexp)
  20897. (throw 'exit (match-string-no-properties 0)))
  20898. ((looking-at org-outline-regexp)
  20899. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20900. (org-with-wide-buffer
  20901. (unless (org-at-heading-p)
  20902. (let* ((p (line-beginning-position))
  20903. (element (save-excursion
  20904. (beginning-of-line)
  20905. (org-element-at-point)))
  20906. (type (org-element-type element))
  20907. (post-affiliated (org-element-property :post-affiliated element)))
  20908. (unless (< p post-affiliated)
  20909. (cl-case type
  20910. (comment
  20911. (save-excursion
  20912. (beginning-of-line)
  20913. (looking-at "[ \t]*")
  20914. (concat (match-string 0) "# ")))
  20915. (footnote-definition "")
  20916. ((item plain-list)
  20917. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20918. (paragraph
  20919. ;; Fill prefix is usually the same as the current line,
  20920. ;; unless the paragraph is at the beginning of an item.
  20921. (let ((parent (org-element-property :parent element)))
  20922. (save-excursion
  20923. (beginning-of-line)
  20924. (cond ((eq (org-element-type parent) 'item)
  20925. (make-string (org-list-item-body-column
  20926. (org-element-property :begin parent))
  20927. ?\s))
  20928. ((and adaptive-fill-regexp
  20929. ;; Locally disable
  20930. ;; `adaptive-fill-function' to let
  20931. ;; `fill-context-prefix' handle
  20932. ;; `adaptive-fill-regexp' variable.
  20933. (let (adaptive-fill-function)
  20934. (fill-context-prefix
  20935. post-affiliated
  20936. (org-element-property :end element)))))
  20937. ((looking-at "[ \t]+") (match-string 0))
  20938. (t "")))))
  20939. (comment-block
  20940. ;; Only fill contents if P is within block boundaries.
  20941. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20942. (forward-line)
  20943. (point)))
  20944. (cend (save-excursion
  20945. (goto-char (org-element-property :end element))
  20946. (skip-chars-backward " \r\t\n")
  20947. (line-beginning-position))))
  20948. (when (and (>= p cbeg) (< p cend))
  20949. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20950. (match-string 0)
  20951. "")))))))))))
  20952. (declare-function message-goto-body "message" ())
  20953. (defvar message-cite-prefix-regexp) ; From message.el
  20954. (defun org-fill-element (&optional justify)
  20955. "Fill element at point, when applicable.
  20956. This function only applies to comment blocks, comments, example
  20957. blocks and paragraphs. Also, as a special case, re-align table
  20958. when point is at one.
  20959. If JUSTIFY is non-nil (interactively, with prefix argument),
  20960. justify as well. If `sentence-end-double-space' is non-nil, then
  20961. period followed by one space does not end a sentence, so don't
  20962. break a line there. The variable `fill-column' controls the
  20963. width for filling.
  20964. For convenience, when point is at a plain list, an item or
  20965. a footnote definition, try to fill the first paragraph within."
  20966. (with-syntax-table org-mode-transpose-word-syntax-table
  20967. ;; Move to end of line in order to get the first paragraph within
  20968. ;; a plain list or a footnote definition.
  20969. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20970. ;; First check if point is in a blank line at the beginning of
  20971. ;; the buffer. In that case, ignore filling.
  20972. (cl-case (org-element-type element)
  20973. ;; Use major mode filling function is src blocks.
  20974. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20975. ;; Align Org tables, leave table.el tables as-is.
  20976. (table-row (org-table-align) t)
  20977. (table
  20978. (when (eq (org-element-property :type element) 'org)
  20979. (save-excursion
  20980. (goto-char (org-element-property :post-affiliated element))
  20981. (org-table-align)))
  20982. t)
  20983. (paragraph
  20984. ;; Paragraphs may contain `line-break' type objects.
  20985. (let ((beg (max (point-min)
  20986. (org-element-property :contents-begin element)))
  20987. (end (min (point-max)
  20988. (org-element-property :contents-end element))))
  20989. ;; Do nothing if point is at an affiliated keyword.
  20990. (if (< (line-end-position) beg) t
  20991. (when (derived-mode-p 'message-mode)
  20992. ;; In `message-mode', do not fill following citation
  20993. ;; in current paragraph nor text before message body.
  20994. (let ((body-start (save-excursion (message-goto-body))))
  20995. (when body-start (setq beg (max body-start beg))))
  20996. (when (save-excursion
  20997. (re-search-forward
  20998. (concat "^" message-cite-prefix-regexp) end t))
  20999. (setq end (match-beginning 0))))
  21000. ;; Fill paragraph, taking line breaks into account.
  21001. (save-excursion
  21002. (goto-char beg)
  21003. (let ((cuts (list beg)))
  21004. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21005. (when (eq 'line-break
  21006. (org-element-type
  21007. (save-excursion (backward-char)
  21008. (org-element-context))))
  21009. (push (point) cuts)))
  21010. (dolist (c (delq end cuts))
  21011. (fill-region-as-paragraph c end justify)
  21012. (setq end c))))
  21013. t)))
  21014. ;; Contents of `comment-block' type elements should be
  21015. ;; filled as plain text, but only if point is within block
  21016. ;; markers.
  21017. (comment-block
  21018. (let* ((case-fold-search t)
  21019. (beg (save-excursion
  21020. (goto-char (org-element-property :begin element))
  21021. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21022. (forward-line)
  21023. (point)))
  21024. (end (save-excursion
  21025. (goto-char (org-element-property :end element))
  21026. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21027. (line-beginning-position))))
  21028. (if (or (< (point) beg) (> (point) end)) t
  21029. (fill-region-as-paragraph
  21030. (save-excursion (end-of-line)
  21031. (re-search-backward "^[ \t]*$" beg 'move)
  21032. (line-beginning-position))
  21033. (save-excursion (beginning-of-line)
  21034. (re-search-forward "^[ \t]*$" end 'move)
  21035. (line-beginning-position))
  21036. justify))))
  21037. ;; Fill comments.
  21038. (comment
  21039. (let ((begin (org-element-property :post-affiliated element))
  21040. (end (org-element-property :end element)))
  21041. (when (and (>= (point) begin) (<= (point) end))
  21042. (let ((begin (save-excursion
  21043. (end-of-line)
  21044. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21045. (progn (forward-line) (point))
  21046. begin)))
  21047. (end (save-excursion
  21048. (end-of-line)
  21049. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21050. (1- (line-beginning-position))
  21051. (skip-chars-backward " \r\t\n")
  21052. (line-end-position)))))
  21053. ;; Do not fill comments when at a blank line.
  21054. (when (> end begin)
  21055. (let ((fill-prefix
  21056. (save-excursion
  21057. (beginning-of-line)
  21058. (looking-at "[ \t]*#")
  21059. (let ((comment-prefix (match-string 0)))
  21060. (goto-char (match-end 0))
  21061. (if (looking-at adaptive-fill-regexp)
  21062. (concat comment-prefix (match-string 0))
  21063. (concat comment-prefix " "))))))
  21064. (save-excursion
  21065. (fill-region-as-paragraph begin end justify))))))
  21066. t))
  21067. ;; Ignore every other element.
  21068. (otherwise t)))))
  21069. (defun org-fill-paragraph (&optional justify region)
  21070. "Fill element at point, when applicable.
  21071. This function only applies to comment blocks, comments, example
  21072. blocks and paragraphs. Also, as a special case, re-align table
  21073. when point is at one.
  21074. For convenience, when point is at a plain list, an item or
  21075. a footnote definition, try to fill the first paragraph within.
  21076. If JUSTIFY is non-nil (interactively, with prefix argument),
  21077. justify as well. If `sentence-end-double-space' is non-nil, then
  21078. period followed by one space does not end a sentence, so don't
  21079. break a line there. The variable `fill-column' controls the
  21080. width for filling.
  21081. The REGION argument is non-nil if called interactively; in that
  21082. case, if Transient Mark mode is enabled and the mark is active,
  21083. fill each of the elements in the active region, instead of just
  21084. filling the current element."
  21085. (interactive (progn
  21086. (barf-if-buffer-read-only)
  21087. (list (if current-prefix-arg 'full) t)))
  21088. (cond
  21089. ((and (derived-mode-p 'message-mode)
  21090. (or (not (message-in-body-p))
  21091. (save-excursion (move-beginning-of-line 1)
  21092. (looking-at message-cite-prefix-regexp))))
  21093. ;; First ensure filling is correct in message-mode.
  21094. (let ((fill-paragraph-function
  21095. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21096. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21097. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21098. (paragraph-separate
  21099. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21100. (fill-paragraph nil)))
  21101. ((and region transient-mark-mode mark-active
  21102. (not (eq (region-beginning) (region-end))))
  21103. (let ((origin (point-marker))
  21104. (start (region-beginning)))
  21105. (unwind-protect
  21106. (progn
  21107. (goto-char (region-end))
  21108. (while (> (point) start)
  21109. (org-backward-paragraph)
  21110. (org-fill-element justify)))
  21111. (goto-char origin)
  21112. (set-marker origin nil))))
  21113. (t (org-fill-element justify))))
  21114. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21115. (defun org-auto-fill-function ()
  21116. "Auto-fill function."
  21117. ;; Check if auto-filling is meaningful.
  21118. (let ((fc (current-fill-column)))
  21119. (when (and fc (> (current-column) fc))
  21120. (let* ((fill-prefix (org-adaptive-fill-function))
  21121. ;; Enforce empty fill prefix, if required. Otherwise, it
  21122. ;; will be computed again.
  21123. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21124. (when fill-prefix (do-auto-fill))))))
  21125. (defun org-comment-line-break-function (&optional soft)
  21126. "Break line at point and indent, continuing comment if within one.
  21127. The inserted newline is marked hard if variable
  21128. `use-hard-newlines' is true, unless optional argument SOFT is
  21129. non-nil."
  21130. (if soft (insert-and-inherit ?\n) (newline 1))
  21131. (save-excursion (forward-char -1) (delete-horizontal-space))
  21132. (delete-horizontal-space)
  21133. (indent-to-left-margin)
  21134. (insert-before-markers-and-inherit fill-prefix))
  21135. ;;; Fixed Width Areas
  21136. (defun org-toggle-fixed-width ()
  21137. "Toggle fixed-width markup.
  21138. Add or remove fixed-width markup on current line, whenever it
  21139. makes sense. Return an error otherwise.
  21140. If a region is active and if it contains only fixed-width areas
  21141. or blank lines, remove all fixed-width markup in it. If the
  21142. region contains anything else, convert all non-fixed-width lines
  21143. to fixed-width ones.
  21144. Blank lines at the end of the region are ignored unless the
  21145. region only contains such lines."
  21146. (interactive)
  21147. (if (not (org-region-active-p))
  21148. ;; No region:
  21149. ;;
  21150. ;; Remove fixed width marker only in a fixed-with element.
  21151. ;;
  21152. ;; Add fixed width maker in paragraphs, in blank lines after
  21153. ;; elements or at the beginning of a headline or an inlinetask,
  21154. ;; and before any one-line elements (e.g., a clock).
  21155. (progn
  21156. (beginning-of-line)
  21157. (let* ((element (org-element-at-point))
  21158. (type (org-element-type element)))
  21159. (cond
  21160. ((and (eq type 'fixed-width)
  21161. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21162. (replace-match
  21163. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21164. ((and (memq type '(babel-call clock comment diary-sexp headline
  21165. horizontal-rule keyword paragraph
  21166. planning))
  21167. (<= (org-element-property :post-affiliated element) (point)))
  21168. (skip-chars-forward " \t")
  21169. (insert ": "))
  21170. ((and (looking-at-p "[ \t]*$")
  21171. (or (eq type 'inlinetask)
  21172. (save-excursion
  21173. (skip-chars-forward " \r\t\n")
  21174. (<= (org-element-property :end element) (point)))))
  21175. (delete-region (point) (line-end-position))
  21176. (org-indent-line)
  21177. (insert ": "))
  21178. (t (user-error "Cannot insert a fixed-width line here")))))
  21179. ;; Region active.
  21180. (let* ((begin (save-excursion
  21181. (goto-char (region-beginning))
  21182. (line-beginning-position)))
  21183. (end (copy-marker
  21184. (save-excursion
  21185. (goto-char (region-end))
  21186. (unless (eolp) (beginning-of-line))
  21187. (if (save-excursion (re-search-backward "\\S-" begin t))
  21188. (progn (skip-chars-backward " \r\t\n") (point))
  21189. (point)))))
  21190. (all-fixed-width-p
  21191. (catch 'not-all-p
  21192. (save-excursion
  21193. (goto-char begin)
  21194. (skip-chars-forward " \r\t\n")
  21195. (when (eobp) (throw 'not-all-p nil))
  21196. (while (< (point) end)
  21197. (let ((element (org-element-at-point)))
  21198. (if (eq (org-element-type element) 'fixed-width)
  21199. (goto-char (org-element-property :end element))
  21200. (throw 'not-all-p nil))))
  21201. t))))
  21202. (if all-fixed-width-p
  21203. (save-excursion
  21204. (goto-char begin)
  21205. (while (< (point) end)
  21206. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21207. (replace-match
  21208. "" nil nil nil
  21209. (if (= (line-end-position) (match-end 0)) 0 1)))
  21210. (forward-line)))
  21211. (let ((min-ind (point-max)))
  21212. ;; Find minimum indentation across all lines.
  21213. (save-excursion
  21214. (goto-char begin)
  21215. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21216. (setq min-ind 0)
  21217. (catch 'zerop
  21218. (while (< (point) end)
  21219. (unless (looking-at-p "[ \t]*$")
  21220. (let ((ind (org-get-indentation)))
  21221. (setq min-ind (min min-ind ind))
  21222. (when (zerop ind) (throw 'zerop t))))
  21223. (forward-line)))))
  21224. ;; Loop over all lines and add fixed-width markup everywhere
  21225. ;; but in fixed-width lines.
  21226. (save-excursion
  21227. (goto-char begin)
  21228. (while (< (point) end)
  21229. (cond
  21230. ((org-at-heading-p)
  21231. (insert ": ")
  21232. (forward-line)
  21233. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21234. (insert ":")
  21235. (forward-line)))
  21236. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21237. (let* ((element (org-element-at-point))
  21238. (element-end (org-element-property :end element)))
  21239. (if (eq (org-element-type element) 'fixed-width)
  21240. (progn (goto-char element-end)
  21241. (skip-chars-backward " \r\t\n")
  21242. (forward-line))
  21243. (let ((limit (min end element-end)))
  21244. (while (< (point) limit)
  21245. (org-move-to-column min-ind t)
  21246. (insert ": ")
  21247. (forward-line))))))
  21248. (t
  21249. (org-move-to-column min-ind t)
  21250. (insert ": ")
  21251. (forward-line)))))))
  21252. (set-marker end nil))))
  21253. ;;; Comments
  21254. ;; Org comments syntax is quite complex. It requires the entire line
  21255. ;; to be just a comment. Also, even with the right syntax at the
  21256. ;; beginning of line, some elements (e.g., verse-block or
  21257. ;; example-block) don't accept comments. Usual Emacs comment commands
  21258. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21259. ;; Org still relies on `comment-dwim', but cannot trust
  21260. ;; `comment-only-p'. So, `comment-region-function' and
  21261. ;; `uncomment-region-function' both point
  21262. ;; to`org-comment-or-uncomment-region'. Eventually,
  21263. ;; `org-insert-comment' takes care of insertion of comments at the
  21264. ;; beginning of line.
  21265. ;; `org-setup-comments-handling' install comments related variables
  21266. ;; during `org-mode' initialization.
  21267. (defun org-setup-comments-handling ()
  21268. (interactive)
  21269. (setq-local comment-use-syntax nil)
  21270. (setq-local comment-start "# ")
  21271. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21272. (setq-local comment-insert-comment-function 'org-insert-comment)
  21273. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21274. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21275. (defun org-insert-comment ()
  21276. "Insert an empty comment above current line.
  21277. If the line is empty, insert comment at its beginning. When
  21278. point is within a source block, comment according to the related
  21279. major mode."
  21280. (if (let ((element (org-element-at-point)))
  21281. (and (eq (org-element-type element) 'src-block)
  21282. (< (save-excursion
  21283. (goto-char (org-element-property :post-affiliated element))
  21284. (line-end-position))
  21285. (point))
  21286. (> (save-excursion
  21287. (goto-char (org-element-property :end element))
  21288. (skip-chars-backward " \r\t\n")
  21289. (line-beginning-position))
  21290. (point))))
  21291. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21292. (beginning-of-line)
  21293. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21294. (open-line 1))
  21295. (org-indent-line)
  21296. (insert "# ")))
  21297. (defvar comment-empty-lines) ; From newcomment.el.
  21298. (defun org-comment-or-uncomment-region (beg end &rest _)
  21299. "Comment or uncomment each non-blank line in the region.
  21300. Uncomment each non-blank line between BEG and END if it only
  21301. contains commented lines. Otherwise, comment them. If region is
  21302. strictly within a source block, use appropriate comment syntax."
  21303. (if (let ((element (org-element-at-point)))
  21304. (and (eq (org-element-type element) 'src-block)
  21305. (< (save-excursion
  21306. (goto-char (org-element-property :post-affiliated element))
  21307. (line-end-position))
  21308. beg)
  21309. (>= (save-excursion
  21310. (goto-char (org-element-property :end element))
  21311. (skip-chars-backward " \r\t\n")
  21312. (line-beginning-position))
  21313. end)))
  21314. ;; Translate region boundaries for the Org buffer to the source
  21315. ;; buffer.
  21316. (let ((offset (- end beg)))
  21317. (save-excursion
  21318. (goto-char beg)
  21319. (org-babel-do-in-edit-buffer
  21320. (comment-or-uncomment-region (point) (+ offset (point))))))
  21321. (save-restriction
  21322. ;; Restrict region
  21323. (narrow-to-region (save-excursion (goto-char beg)
  21324. (skip-chars-forward " \r\t\n" end)
  21325. (line-beginning-position))
  21326. (save-excursion (goto-char end)
  21327. (skip-chars-backward " \r\t\n" beg)
  21328. (line-end-position)))
  21329. (let ((uncommentp
  21330. ;; UNCOMMENTP is non-nil when every non blank line between
  21331. ;; BEG and END is a comment.
  21332. (save-excursion
  21333. (goto-char (point-min))
  21334. (while (and (not (eobp))
  21335. (let ((element (org-element-at-point)))
  21336. (and (eq (org-element-type element) 'comment)
  21337. (goto-char (min (point-max)
  21338. (org-element-property
  21339. :end element)))))))
  21340. (eobp))))
  21341. (if uncommentp
  21342. ;; Only blank lines and comments in region: uncomment it.
  21343. (save-excursion
  21344. (goto-char (point-min))
  21345. (while (not (eobp))
  21346. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21347. (replace-match "" nil nil nil 1))
  21348. (forward-line)))
  21349. ;; Comment each line in region.
  21350. (let ((min-indent (point-max)))
  21351. ;; First find the minimum indentation across all lines.
  21352. (save-excursion
  21353. (goto-char (point-min))
  21354. (while (and (not (eobp)) (not (zerop min-indent)))
  21355. (unless (looking-at "[ \t]*$")
  21356. (setq min-indent (min min-indent (current-indentation))))
  21357. (forward-line)))
  21358. ;; Then loop over all lines.
  21359. (save-excursion
  21360. (goto-char (point-min))
  21361. (while (not (eobp))
  21362. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21363. ;; Don't get fooled by invisible text (e.g. link path)
  21364. ;; when moving to column MIN-INDENT.
  21365. (let ((buffer-invisibility-spec nil))
  21366. (org-move-to-column min-indent t))
  21367. (insert comment-start))
  21368. (forward-line)))))))))
  21369. (defun org-comment-dwim (_arg)
  21370. "Call `comment-dwim' within a source edit buffer if needed."
  21371. (interactive "*P")
  21372. (if (org-in-src-block-p)
  21373. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21374. (call-interactively 'comment-dwim)))
  21375. ;;; Timestamps API
  21376. ;; This section contains tools to operate on timestamp objects, as
  21377. ;; returned by, e.g. `org-element-context'.
  21378. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21379. "Encode TIMESTAMP object into Emacs internal time.
  21380. Use end of date range or time range when END is non-nil."
  21381. (apply #'encode-time
  21382. (cons 0
  21383. (mapcar
  21384. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21385. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21386. '(:minute-start :hour-start :day-start :month-start
  21387. :year-start))))))
  21388. (defun org-timestamp-has-time-p (timestamp)
  21389. "Non-nil when TIMESTAMP has a time specified."
  21390. (org-element-property :hour-start timestamp))
  21391. (defun org-timestamp-format (timestamp format &optional end utc)
  21392. "Format a TIMESTAMP object into a string.
  21393. FORMAT is a format specifier to be passed to
  21394. `format-time-string'.
  21395. When optional argument END is non-nil, use end of date-range or
  21396. time-range, if possible.
  21397. When optional argument UTC is non-nil, time will be expressed as
  21398. Universal Time."
  21399. (format-time-string
  21400. format (org-timestamp--to-internal-time timestamp end)
  21401. (and utc t)))
  21402. (defun org-timestamp-split-range (timestamp &optional end)
  21403. "Extract a TIMESTAMP object from a date or time range.
  21404. END, when non-nil, means extract the end of the range.
  21405. Otherwise, extract its start.
  21406. Return a new timestamp object."
  21407. (let ((type (org-element-property :type timestamp)))
  21408. (if (memq type '(active inactive diary)) timestamp
  21409. (let ((split-ts (org-element-copy timestamp)))
  21410. ;; Set new type.
  21411. (org-element-put-property
  21412. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21413. ;; Copy start properties over end properties if END is
  21414. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21415. (let ((p-alist '((:minute-start . :minute-end)
  21416. (:hour-start . :hour-end)
  21417. (:day-start . :day-end)
  21418. (:month-start . :month-end)
  21419. (:year-start . :year-end))))
  21420. (dolist (p-cell p-alist)
  21421. (org-element-put-property
  21422. split-ts
  21423. (funcall (if end #'car #'cdr) p-cell)
  21424. (org-element-property
  21425. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21426. ;; Eventually refresh `:raw-value'.
  21427. (org-element-put-property split-ts :raw-value nil)
  21428. (org-element-put-property
  21429. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21430. (defun org-timestamp-translate (timestamp &optional boundary)
  21431. "Translate TIMESTAMP object to custom format.
  21432. Format string is defined in `org-time-stamp-custom-formats',
  21433. which see.
  21434. When optional argument BOUNDARY is non-nil, it is either the
  21435. symbol `start' or `end'. In this case, only translate the
  21436. starting or ending part of TIMESTAMP if it is a date or time
  21437. range. Otherwise, translate both parts.
  21438. Return timestamp as-is if `org-display-custom-times' is nil or if
  21439. it has a `diary' type."
  21440. (let ((type (org-element-property :type timestamp)))
  21441. (if (or (not org-display-custom-times) (eq type 'diary))
  21442. (org-element-interpret-data timestamp)
  21443. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21444. org-time-stamp-custom-formats)))
  21445. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21446. (concat (org-timestamp-format timestamp fmt)
  21447. "--"
  21448. (org-timestamp-format timestamp fmt t))
  21449. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21450. ;;; Other stuff.
  21451. (defvar reftex-docstruct-symbol)
  21452. (defvar org--rds)
  21453. (defun org-reftex-citation ()
  21454. "Use reftex-citation to insert a citation into the buffer.
  21455. This looks for a line like
  21456. #+BIBLIOGRAPHY: foo plain option:-d
  21457. and derives from it that foo.bib is the bibliography file relevant
  21458. for this document. It then installs the necessary environment for RefTeX
  21459. to work in this buffer and calls `reftex-citation' to insert a citation
  21460. into the buffer.
  21461. Export of such citations to both LaTeX and HTML is handled by the contributed
  21462. package ox-bibtex by Taru Karttunen."
  21463. (interactive)
  21464. (let ((reftex-docstruct-symbol 'org--rds)
  21465. org--rds bib)
  21466. (org-with-wide-buffer
  21467. (let ((case-fold-search t)
  21468. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21469. (if (not (save-excursion
  21470. (or (re-search-forward re nil t)
  21471. (re-search-backward re nil t))))
  21472. (user-error "No bibliography defined in file")
  21473. (setq bib (concat (match-string 1) ".bib")
  21474. org--rds (list (list 'bib bib))))))
  21475. (call-interactively 'reftex-citation)))
  21476. ;;;; Functions extending outline functionality
  21477. (defun org-beginning-of-line (&optional n)
  21478. "Go to the beginning of the current visible line.
  21479. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21480. tags on the first attempt, and only move to after the tags when
  21481. the cursor is already beyond the end of the headline.
  21482. With argument N not nil or 1, move forward N - 1 lines first."
  21483. (interactive "^p")
  21484. (let ((origin (point))
  21485. (special (pcase org-special-ctrl-a/e
  21486. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21487. deactivate-mark)
  21488. ;; First move to a visible line.
  21489. (if (bound-and-true-p visual-line-mode)
  21490. (beginning-of-visual-line n)
  21491. (move-beginning-of-line n)
  21492. ;; `move-beginning-of-line' may leave point after invisible
  21493. ;; characters if line starts with such of these (e.g., with
  21494. ;; a link at column 0). Really move to the beginning of the
  21495. ;; current visible line.
  21496. (beginning-of-line))
  21497. (cond
  21498. ;; No special behavior. Point is already at the beginning of
  21499. ;; a line, logical or visual.
  21500. ((not special))
  21501. ;; `beginning-of-visual-line' left point before logical beginning
  21502. ;; of line: point is at the beginning of a visual line. Bail
  21503. ;; out.
  21504. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21505. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21506. ;; At a headline, special position is before the title, but
  21507. ;; after any TODO keyword or priority cookie.
  21508. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21509. (line-end-position)))
  21510. (bol (point)))
  21511. (if (eq special 'reversed)
  21512. (when (and (= origin bol) (eq last-command this-command))
  21513. (goto-char refpos))
  21514. (when (or (> origin refpos) (= origin bol))
  21515. (goto-char refpos)))))
  21516. ((and (looking-at org-list-full-item-re)
  21517. (memq (org-element-type (save-match-data (org-element-at-point)))
  21518. '(item plain-list)))
  21519. ;; Set special position at first white space character after
  21520. ;; bullet, and check-box, if any.
  21521. (let ((after-bullet
  21522. (let ((box (match-end 3)))
  21523. (cond ((not box) (match-end 1))
  21524. ((eq (char-after box) ?\s) (1+ box))
  21525. (t box)))))
  21526. (if (eq special 'reversed)
  21527. (when (and (= (point) origin) (eq last-command this-command))
  21528. (goto-char after-bullet))
  21529. (when (or (> origin after-bullet) (= (point) origin))
  21530. (goto-char after-bullet)))))
  21531. ;; No special context. Point is already at beginning of line.
  21532. (t nil))))
  21533. (defun org-end-of-line (&optional n)
  21534. "Go to the end of the line, but before ellipsis, if any.
  21535. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21536. tags on the first attempt, and only move to after the tags when
  21537. the cursor is already beyond the end of the headline.
  21538. With argument N not nil or 1, move forward N - 1 lines first."
  21539. (interactive "^p")
  21540. (let ((origin (point))
  21541. (special (pcase org-special-ctrl-a/e
  21542. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21543. deactivate-mark)
  21544. ;; First move to a visible line.
  21545. (if (bound-and-true-p visual-line-mode)
  21546. (beginning-of-visual-line n)
  21547. (move-beginning-of-line n))
  21548. (cond
  21549. ;; At a headline, with tags.
  21550. ((and special
  21551. (save-excursion
  21552. (beginning-of-line)
  21553. (let ((case-fold-search nil))
  21554. (looking-at org-complex-heading-regexp)))
  21555. (match-end 5))
  21556. (let ((tags (save-excursion
  21557. (goto-char (match-beginning 5))
  21558. (skip-chars-backward " \t")
  21559. (point)))
  21560. (visual-end (and (bound-and-true-p visual-line-mode)
  21561. (save-excursion
  21562. (end-of-visual-line)
  21563. (point)))))
  21564. ;; If `end-of-visual-line' brings us before end of line or
  21565. ;; even tags, i.e., the headline spans over multiple visual
  21566. ;; lines, move there.
  21567. (cond ((and visual-end
  21568. (< visual-end tags)
  21569. (<= origin visual-end))
  21570. (goto-char visual-end))
  21571. ((eq special 'reversed)
  21572. (if (and (= origin (line-end-position))
  21573. (eq this-command last-command))
  21574. (goto-char tags)
  21575. (end-of-line)))
  21576. (t
  21577. (if (or (< origin tags) (= origin (line-end-position)))
  21578. (goto-char tags)
  21579. (end-of-line))))))
  21580. ((bound-and-true-p visual-line-mode)
  21581. (let ((bol (line-beginning-position)))
  21582. (end-of-visual-line)
  21583. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21584. ;; end of a line, backtrack and use `end-of-line' instead.
  21585. (when (/= bol (line-beginning-position))
  21586. (goto-char bol)
  21587. (end-of-line))))
  21588. (t (end-of-line)))))
  21589. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21590. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21591. (defun org-backward-sentence (&optional _arg)
  21592. "Go to beginning of sentence, or beginning of table field.
  21593. This will call `backward-sentence' or `org-table-beginning-of-field',
  21594. depending on context."
  21595. (interactive)
  21596. (let* ((element (org-element-at-point))
  21597. (contents-begin (org-element-property :contents-begin element))
  21598. (table (org-element-lineage element '(table) t)))
  21599. (if (and table
  21600. (> (point) contents-begin)
  21601. (<= (point) (org-element-property :contents-end table)))
  21602. (call-interactively #'org-table-beginning-of-field)
  21603. (save-restriction
  21604. (when (and contents-begin
  21605. (< (point-min) contents-begin)
  21606. (> (point) contents-begin))
  21607. (narrow-to-region contents-begin
  21608. (org-element-property :contents-end element)))
  21609. (call-interactively #'backward-sentence)))))
  21610. (defun org-forward-sentence (&optional _arg)
  21611. "Go to end of sentence, or end of table field.
  21612. This will call `forward-sentence' or `org-table-end-of-field',
  21613. depending on context."
  21614. (interactive)
  21615. (if (and (org-at-heading-p)
  21616. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21617. (save-restriction
  21618. (narrow-to-region (line-beginning-position) (line-end-position))
  21619. (call-interactively #'forward-sentence))
  21620. (let* ((element (org-element-at-point))
  21621. (contents-end (org-element-property :contents-end element))
  21622. (table (org-element-lineage element '(table) t)))
  21623. (if (and table
  21624. (>= (point) (org-element-property :contents-begin table))
  21625. (< (point) contents-end))
  21626. (call-interactively #'org-table-end-of-field)
  21627. (save-restriction
  21628. (when (and contents-end
  21629. (> (point-max) contents-end)
  21630. ;; Skip blank lines between elements.
  21631. (< (org-element-property :end element)
  21632. (save-excursion (goto-char contents-end)
  21633. (skip-chars-forward " \r\t\n"))))
  21634. (narrow-to-region (org-element-property :contents-begin element)
  21635. contents-end))
  21636. ;; End of heading is considered as the end of a sentence.
  21637. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21638. (call-interactively #'forward-sentence)))))))
  21639. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21640. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21641. (defun org-kill-line (&optional _arg)
  21642. "Kill line, to tags or end of line."
  21643. (interactive)
  21644. (cond
  21645. ((or (not org-special-ctrl-k)
  21646. (bolp)
  21647. (not (org-at-heading-p)))
  21648. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21649. org-ctrl-k-protect-subtree
  21650. (or (eq org-ctrl-k-protect-subtree 'error)
  21651. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21652. (user-error "C-k aborted as it would kill a hidden subtree"))
  21653. (call-interactively
  21654. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21655. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21656. (kill-region (point) (match-beginning 1))
  21657. (org-set-tags nil t))
  21658. (t (kill-region (point) (point-at-eol)))))
  21659. (define-key org-mode-map "\C-k" 'org-kill-line)
  21660. (defun org-yank (&optional arg)
  21661. "Yank. If the kill is a subtree, treat it specially.
  21662. This command will look at the current kill and check if is a single
  21663. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21664. cursor is at the beginning of a line or after the stars of a currently
  21665. empty headline, then the yank is handled specially. How exactly depends
  21666. on the value of the following variables.
  21667. `org-yank-folded-subtrees'
  21668. By default, this variable is non-nil, which results in
  21669. subtree(s) being folded after insertion, except if doing so
  21670. would swallow text after the yanked text.
  21671. `org-yank-adjusted-subtrees'
  21672. When non-nil (the default value is nil), the subtree will be
  21673. promoted or demoted in order to fit into the local outline tree
  21674. structure, which means that the level will be adjusted so that it
  21675. becomes the smaller one of the two *visible* surrounding headings.
  21676. Any prefix to this command will cause `yank' to be called directly with
  21677. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21678. will just
  21679. plainly yank the text as it is.
  21680. \[1] The test checks if the first non-white line is a heading
  21681. and if there are no other headings with fewer stars."
  21682. (interactive "P")
  21683. (org-yank-generic 'yank arg))
  21684. (defun org-yank-generic (command arg)
  21685. "Perform some yank-like command.
  21686. This function implements the behavior described in the `org-yank'
  21687. documentation. However, it has been generalized to work for any
  21688. interactive command with similar behavior."
  21689. ;; pretend to be command COMMAND
  21690. (setq this-command command)
  21691. (if arg
  21692. (call-interactively command)
  21693. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21694. (and (org-kill-is-subtree-p)
  21695. (or (bolp)
  21696. (and (looking-at "[ \t]*$")
  21697. (string-match
  21698. "\\`\\*+\\'"
  21699. (buffer-substring (point-at-bol) (point)))))))
  21700. swallowp)
  21701. (cond
  21702. ((and subtreep org-yank-folded-subtrees)
  21703. (let ((beg (point))
  21704. end)
  21705. (if (and subtreep org-yank-adjusted-subtrees)
  21706. (org-paste-subtree nil nil 'for-yank)
  21707. (call-interactively command))
  21708. (setq end (point))
  21709. (goto-char beg)
  21710. (when (and (bolp) subtreep
  21711. (not (setq swallowp
  21712. (org-yank-folding-would-swallow-text beg end))))
  21713. (org-with-limited-levels
  21714. (or (looking-at org-outline-regexp)
  21715. (re-search-forward org-outline-regexp-bol end t))
  21716. (while (and (< (point) end) (looking-at org-outline-regexp))
  21717. (outline-hide-subtree)
  21718. (org-cycle-show-empty-lines 'folded)
  21719. (condition-case nil
  21720. (outline-forward-same-level 1)
  21721. (error (goto-char end))))))
  21722. (when swallowp
  21723. (message
  21724. "Inserted text not folded because that would swallow text"))
  21725. (goto-char end)
  21726. (skip-chars-forward " \t\n\r")
  21727. (beginning-of-line 1)
  21728. (push-mark beg 'nomsg)))
  21729. ((and subtreep org-yank-adjusted-subtrees)
  21730. (let ((beg (point-at-bol)))
  21731. (org-paste-subtree nil nil 'for-yank)
  21732. (push-mark beg 'nomsg)))
  21733. (t
  21734. (call-interactively command))))))
  21735. (defun org-yank-folding-would-swallow-text (beg end)
  21736. "Would hide-subtree at BEG swallow any text after END?"
  21737. (let (level)
  21738. (org-with-limited-levels
  21739. (save-excursion
  21740. (goto-char beg)
  21741. (when (or (looking-at org-outline-regexp)
  21742. (re-search-forward org-outline-regexp-bol end t))
  21743. (setq level (org-outline-level)))
  21744. (goto-char end)
  21745. (skip-chars-forward " \t\r\n\v\f")
  21746. (not (or (eobp)
  21747. (and (bolp) (looking-at-p org-outline-regexp)
  21748. (<= (org-outline-level) level))))))))
  21749. (define-key org-mode-map "\C-y" 'org-yank)
  21750. (defun org-truely-invisible-p ()
  21751. "Check if point is at a character currently not visible.
  21752. This version does not only check the character property, but also
  21753. `visible-mode'."
  21754. (unless (bound-and-true-p visible-mode)
  21755. (org-invisible-p)))
  21756. (defun org-invisible-p2 ()
  21757. "Check if point is at a character currently not visible.
  21758. If the point is at EOL (and not at the beginning of a buffer too),
  21759. move it back by one char before doing this check."
  21760. (save-excursion
  21761. (when (and (eolp) (not (bobp)))
  21762. (backward-char 1))
  21763. (org-invisible-p)))
  21764. (defun org-back-to-heading (&optional invisible-ok)
  21765. "Call `outline-back-to-heading', but provide a better error message."
  21766. (condition-case nil
  21767. (outline-back-to-heading invisible-ok)
  21768. (error (error "Before first headline at position %d in buffer %s"
  21769. (point) (current-buffer)))))
  21770. (defun org-before-first-heading-p ()
  21771. "Before first heading?"
  21772. (save-excursion
  21773. (end-of-line)
  21774. (null (re-search-backward org-outline-regexp-bol nil t))))
  21775. (defun org-at-heading-p (&optional ignored)
  21776. (outline-on-heading-p t))
  21777. (defun org-in-commented-heading-p (&optional no-inheritance)
  21778. "Non-nil if point is under a commented heading.
  21779. This function also checks ancestors of the current headline,
  21780. unless optional argument NO-INHERITANCE is non-nil."
  21781. (cond
  21782. ((org-before-first-heading-p) nil)
  21783. ((let ((headline (nth 4 (org-heading-components))))
  21784. (and headline
  21785. (let ((case-fold-search nil))
  21786. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21787. headline)))))
  21788. (no-inheritance nil)
  21789. (t
  21790. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21791. (defun org-at-comment-p nil
  21792. "Is cursor in a commented line?"
  21793. (save-excursion
  21794. (save-match-data
  21795. (beginning-of-line)
  21796. (looking-at "^[ \t]*# "))))
  21797. (defun org-at-drawer-p nil
  21798. "Is cursor at a drawer keyword?"
  21799. (save-excursion
  21800. (move-beginning-of-line 1)
  21801. (looking-at org-drawer-regexp)))
  21802. (defun org-at-block-p nil
  21803. "Is cursor at a block keyword?"
  21804. (save-excursion
  21805. (move-beginning-of-line 1)
  21806. (looking-at org-block-regexp)))
  21807. (defun org-point-at-end-of-empty-headline ()
  21808. "If point is at the end of an empty headline, return t, else nil.
  21809. If the heading only contains a TODO keyword, it is still still considered
  21810. empty."
  21811. (let ((case-fold-search nil))
  21812. (and (looking-at "[ \t]*$")
  21813. org-todo-line-regexp
  21814. (save-excursion
  21815. (beginning-of-line)
  21816. (looking-at org-todo-line-regexp)
  21817. (string= (match-string 3) "")))))
  21818. (defun org-at-heading-or-item-p ()
  21819. (or (org-at-heading-p) (org-at-item-p)))
  21820. (defun org-at-target-p ()
  21821. (or (org-in-regexp org-radio-target-regexp)
  21822. (org-in-regexp org-target-regexp)))
  21823. ;; Compatibility alias with Org versions < 7.8.03
  21824. (defalias 'org-on-target-p 'org-at-target-p)
  21825. (defun org-up-heading-all (arg)
  21826. "Move to the heading line of which the present line is a subheading.
  21827. This function considers both visible and invisible heading lines.
  21828. With argument, move up ARG levels."
  21829. (outline-up-heading arg t))
  21830. (defun org-up-heading-safe ()
  21831. "Move to the heading line of which the present line is a subheading.
  21832. This version will not throw an error. It will return the level of the
  21833. headline found, or nil if no higher level is found.
  21834. Also, this function will be a lot faster than `outline-up-heading',
  21835. because it relies on stars being the outline starters. This can really
  21836. make a significant difference in outlines with very many siblings."
  21837. (when (ignore-errors (org-back-to-heading t))
  21838. (let ((level-up (1- (funcall outline-level))))
  21839. (and (> level-up 0)
  21840. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21841. (funcall outline-level)))))
  21842. (defun org-first-sibling-p ()
  21843. "Is this heading the first child of its parents?"
  21844. (interactive)
  21845. (let ((re org-outline-regexp-bol)
  21846. level l)
  21847. (unless (org-at-heading-p t)
  21848. (user-error "Not at a heading"))
  21849. (setq level (funcall outline-level))
  21850. (save-excursion
  21851. (if (not (re-search-backward re nil t))
  21852. t
  21853. (setq l (funcall outline-level))
  21854. (< l level)))))
  21855. (defun org-goto-sibling (&optional previous)
  21856. "Goto the next sibling, even if it is invisible.
  21857. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21858. when a sibling was found. When none is found, return nil and don't
  21859. move point."
  21860. (let ((fun (if previous 're-search-backward 're-search-forward))
  21861. (pos (point))
  21862. (re org-outline-regexp-bol)
  21863. level l)
  21864. (when (ignore-errors (org-back-to-heading t))
  21865. (setq level (funcall outline-level))
  21866. (catch 'exit
  21867. (or previous (forward-char 1))
  21868. (while (funcall fun re nil t)
  21869. (setq l (funcall outline-level))
  21870. (when (< l level) (goto-char pos) (throw 'exit nil))
  21871. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21872. (goto-char pos)
  21873. nil))))
  21874. (defun org-show-siblings ()
  21875. "Show all siblings of the current headline."
  21876. (save-excursion
  21877. (while (org-goto-sibling) (org-flag-heading nil)))
  21878. (save-excursion
  21879. (while (org-goto-sibling 'previous)
  21880. (org-flag-heading nil))))
  21881. (defun org-goto-first-child ()
  21882. "Goto the first child, even if it is invisible.
  21883. Return t when a child was found. Otherwise don't move point and
  21884. return nil."
  21885. (let (level (pos (point)) (re org-outline-regexp-bol))
  21886. (when (ignore-errors (org-back-to-heading t))
  21887. (setq level (outline-level))
  21888. (forward-char 1)
  21889. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21890. (progn (goto-char (match-beginning 0)) t)
  21891. (goto-char pos) nil))))
  21892. (defun org-show-hidden-entry ()
  21893. "Show an entry where even the heading is hidden."
  21894. (save-excursion
  21895. (org-show-entry)))
  21896. (defun org-flag-heading (flag &optional entry)
  21897. "Flag the current heading. FLAG non-nil means make invisible.
  21898. When ENTRY is non-nil, show the entire entry."
  21899. (save-excursion
  21900. (org-back-to-heading t)
  21901. ;; Check if we should show the entire entry
  21902. (if entry
  21903. (progn
  21904. (org-show-entry)
  21905. (save-excursion
  21906. (and (outline-next-heading)
  21907. (org-flag-heading nil))))
  21908. (outline-flag-region (max (point-min) (1- (point)))
  21909. (save-excursion (outline-end-of-heading) (point))
  21910. flag))))
  21911. (defun org-get-next-sibling ()
  21912. "Move to next heading of the same level, and return point.
  21913. If there is no such heading, return nil.
  21914. This is like outline-next-sibling, but invisible headings are ok."
  21915. (let ((level (funcall outline-level)))
  21916. (outline-next-heading)
  21917. (while (and (not (eobp)) (> (funcall outline-level) level))
  21918. (outline-next-heading))
  21919. (unless (or (eobp) (< (funcall outline-level) level))
  21920. (point))))
  21921. (defun org-get-last-sibling ()
  21922. "Move to previous heading of the same level, and return point.
  21923. If there is no such heading, return nil."
  21924. (let ((opoint (point))
  21925. (level (funcall outline-level)))
  21926. (outline-previous-heading)
  21927. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21928. (while (and (> (funcall outline-level) level)
  21929. (not (bobp)))
  21930. (outline-previous-heading))
  21931. (unless (< (funcall outline-level) level)
  21932. (point)))))
  21933. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21934. "Goto to the end of a subtree."
  21935. ;; This contains an exact copy of the original function, but it uses
  21936. ;; `org-back-to-heading', to make it work also in invisible
  21937. ;; trees. And is uses an invisible-ok argument.
  21938. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21939. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21940. ;; with many children and grandchildren etc, this can be much faster
  21941. ;; than the outline version.
  21942. (org-back-to-heading invisible-ok)
  21943. (let ((first t)
  21944. (level (funcall outline-level)))
  21945. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21946. ;; A true heading (not a plain list item), in Org
  21947. ;; This means we can easily find the end by looking
  21948. ;; only for the right number of stars. Using a regexp to do
  21949. ;; this is so much faster than using a Lisp loop.
  21950. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21951. (forward-char 1)
  21952. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21953. ;; something else, do it the slow way
  21954. (while (and (not (eobp))
  21955. (or first (> (funcall outline-level) level)))
  21956. (setq first nil)
  21957. (outline-next-heading)))
  21958. (unless to-heading
  21959. (when (memq (preceding-char) '(?\n ?\^M))
  21960. ;; Go to end of line before heading
  21961. (forward-char -1)
  21962. (when (memq (preceding-char) '(?\n ?\^M))
  21963. ;; leave blank line before heading
  21964. (forward-char -1)))))
  21965. (point))
  21966. (defun org-end-of-meta-data (&optional full)
  21967. "Skip planning line and properties drawer in current entry.
  21968. When optional argument FULL is non-nil, also skip empty lines,
  21969. clocking lines and regular drawers at the beginning of the
  21970. entry."
  21971. (org-back-to-heading t)
  21972. (forward-line)
  21973. (when (looking-at-p org-planning-line-re) (forward-line))
  21974. (when (looking-at org-property-drawer-re)
  21975. (goto-char (match-end 0))
  21976. (forward-line))
  21977. (when (and full (not (org-at-heading-p)))
  21978. (catch 'exit
  21979. (let ((end (save-excursion (outline-next-heading) (point)))
  21980. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21981. (while (not (eobp))
  21982. (cond ((looking-at-p org-drawer-regexp)
  21983. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21984. (forward-line)
  21985. (throw 'exit t)))
  21986. ((looking-at-p re) (forward-line))
  21987. (t (throw 'exit t))))))))
  21988. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21989. "Move forward to the ARG'th subheading at same level as this one.
  21990. Stop at the first and last subheadings of a superior heading.
  21991. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21992. non-nil it will also look at invisible ones."
  21993. (interactive "p")
  21994. (let ((backward? (and arg (< arg 0))))
  21995. (if (org-before-first-heading-p)
  21996. (if backward? (goto-char (point-min)) (outline-next-heading))
  21997. (org-back-to-heading invisible-ok)
  21998. (unless backward? (end-of-line)) ;do not match current headline
  21999. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22000. (f (if backward? #'re-search-backward #'re-search-forward))
  22001. (count (if arg (abs arg) 1))
  22002. (result (point)))
  22003. (while (and (> count 0)
  22004. (funcall f org-outline-regexp-bol nil 'move))
  22005. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22006. (cond ((< l level) (setq count 0))
  22007. ((and (= l level)
  22008. (or invisible-ok
  22009. (not (org-invisible-p
  22010. (line-beginning-position)))))
  22011. (cl-decf count)
  22012. (when (= l level) (setq result (point)))))))
  22013. (goto-char result))
  22014. (beginning-of-line))))
  22015. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22016. "Move backward to the ARG'th subheading at same level as this one.
  22017. Stop at the first and last subheadings of a superior heading."
  22018. (interactive "p")
  22019. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22020. (defun org-next-visible-heading (arg)
  22021. "Move to the next visible heading.
  22022. This function wraps `outline-next-visible-heading' with
  22023. `org-with-limited-levels' in order to skip over inline tasks and
  22024. respect customization of `org-odd-levels-only'."
  22025. (interactive "p")
  22026. (org-with-limited-levels
  22027. (outline-next-visible-heading arg)))
  22028. (defun org-previous-visible-heading (arg)
  22029. "Move to the previous visible heading.
  22030. This function wraps `outline-previous-visible-heading' with
  22031. `org-with-limited-levels' in order to skip over inline tasks and
  22032. respect customization of `org-odd-levels-only'."
  22033. (interactive "p")
  22034. (org-with-limited-levels
  22035. (outline-previous-visible-heading arg)))
  22036. (defun org-next-block (arg &optional backward block-regexp)
  22037. "Jump to the next block.
  22038. With a prefix argument ARG, jump forward ARG many blocks.
  22039. When BACKWARD is non-nil, jump to the previous block.
  22040. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22041. Match data is set according to this regexp when the function
  22042. returns.
  22043. Return point at beginning of the opening line of found block.
  22044. Throw an error if no block is found."
  22045. (interactive "p")
  22046. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22047. (case-fold-search t)
  22048. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22049. (count (or arg 1))
  22050. (origin (point))
  22051. last-element)
  22052. (if backward (beginning-of-line) (end-of-line))
  22053. (while (and (> count 0) (funcall search-fn re nil t))
  22054. (let ((element (save-excursion
  22055. (goto-char (match-beginning 0))
  22056. (save-match-data (org-element-at-point)))))
  22057. (when (and (memq (org-element-type element)
  22058. '(center-block comment-block dynamic-block
  22059. example-block export-block quote-block
  22060. special-block src-block verse-block))
  22061. (<= (match-beginning 0)
  22062. (org-element-property :post-affiliated element)))
  22063. (setq last-element element)
  22064. (cl-decf count))))
  22065. (if (= count 0)
  22066. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22067. (save-match-data (org-show-context)))
  22068. (goto-char origin)
  22069. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22070. (defun org-previous-block (arg &optional block-regexp)
  22071. "Jump to the previous block.
  22072. With a prefix argument ARG, jump backward ARG many source blocks.
  22073. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22074. (interactive "p")
  22075. (org-next-block arg t block-regexp))
  22076. (defun org-forward-paragraph ()
  22077. "Move forward to beginning of next paragraph or equivalent.
  22078. The function moves point to the beginning of the next visible
  22079. structural element, which can be a paragraph, a table, a list
  22080. item, etc. It also provides some special moves for convenience:
  22081. - On an affiliated keyword, jump to the beginning of the
  22082. relative element.
  22083. - On an item or a footnote definition, move to the second
  22084. element inside, if any.
  22085. - On a table or a property drawer, jump after it.
  22086. - On a verse or source block, stop after blank lines."
  22087. (interactive)
  22088. (unless (eobp)
  22089. (let* ((deactivate-mark nil)
  22090. (element (org-element-at-point))
  22091. (type (org-element-type element))
  22092. (post-affiliated (org-element-property :post-affiliated element))
  22093. (contents-begin (org-element-property :contents-begin element))
  22094. (contents-end (org-element-property :contents-end element))
  22095. (end (let ((end (org-element-property :end element)) (parent element))
  22096. (while (and (setq parent (org-element-property :parent parent))
  22097. (= (org-element-property :contents-end parent) end))
  22098. (setq end (org-element-property :end parent)))
  22099. end)))
  22100. (cond ((not element)
  22101. (skip-chars-forward " \r\t\n")
  22102. (or (eobp) (beginning-of-line)))
  22103. ;; On affiliated keywords, move to element's beginning.
  22104. ((< (point) post-affiliated)
  22105. (goto-char post-affiliated))
  22106. ;; At a table row, move to the end of the table. Similarly,
  22107. ;; at a node property, move to the end of the property
  22108. ;; drawer.
  22109. ((memq type '(node-property table-row))
  22110. (goto-char (org-element-property
  22111. :end (org-element-property :parent element))))
  22112. ((memq type '(property-drawer table)) (goto-char end))
  22113. ;; Consider blank lines as separators in verse and source
  22114. ;; blocks to ease editing.
  22115. ((memq type '(src-block verse-block))
  22116. (when (eq type 'src-block)
  22117. (setq contents-end
  22118. (save-excursion (goto-char end)
  22119. (skip-chars-backward " \r\t\n")
  22120. (line-beginning-position))))
  22121. (beginning-of-line)
  22122. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22123. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22124. (goto-char end)
  22125. (skip-chars-forward " \r\t\n")
  22126. (if (= (point) contents-end) (goto-char end)
  22127. (beginning-of-line))))
  22128. ;; With no contents, just skip element.
  22129. ((not contents-begin) (goto-char end))
  22130. ;; If contents are invisible, skip the element altogether.
  22131. ((org-invisible-p (line-end-position))
  22132. (cl-case type
  22133. (headline
  22134. (org-with-limited-levels (outline-next-visible-heading 1)))
  22135. ;; At a plain list, make sure we move to the next item
  22136. ;; instead of skipping the whole list.
  22137. (plain-list (forward-char)
  22138. (org-forward-paragraph))
  22139. (otherwise (goto-char end))))
  22140. ((>= (point) contents-end) (goto-char end))
  22141. ((>= (point) contents-begin)
  22142. ;; This can only happen on paragraphs and plain lists.
  22143. (cl-case type
  22144. (paragraph (goto-char end))
  22145. ;; At a plain list, try to move to second element in
  22146. ;; first item, if possible.
  22147. (plain-list (end-of-line)
  22148. (org-forward-paragraph))))
  22149. ;; When contents start on the middle of a line (e.g. in
  22150. ;; items and footnote definitions), try to reach first
  22151. ;; element starting after current line.
  22152. ((> (line-end-position) contents-begin)
  22153. (end-of-line)
  22154. (org-forward-paragraph))
  22155. (t (goto-char contents-begin))))))
  22156. (defun org-backward-paragraph ()
  22157. "Move backward to start of previous paragraph or equivalent.
  22158. The function moves point to the beginning of the current
  22159. structural element, which can be a paragraph, a table, a list
  22160. item, etc., or to the beginning of the previous visible one if
  22161. point is already there. It also provides some special moves for
  22162. convenience:
  22163. - On an affiliated keyword, jump to the first one.
  22164. - On a table or a property drawer, move to its beginning.
  22165. - On comment, example, export, src and verse blocks, stop
  22166. before blank lines."
  22167. (interactive)
  22168. (unless (bobp)
  22169. (let* ((deactivate-mark nil)
  22170. (element (org-element-at-point))
  22171. (type (org-element-type element))
  22172. (contents-end (org-element-property :contents-end element))
  22173. (post-affiliated (org-element-property :post-affiliated element))
  22174. (begin (org-element-property :begin element))
  22175. (special? ;blocks handled specially
  22176. (memq type '(comment-block example-block export-block src-block
  22177. verse-block)))
  22178. (contents-begin
  22179. (if special?
  22180. ;; These types have no proper contents. Fake line
  22181. ;; below the block opening line as contents beginning.
  22182. (save-excursion (goto-char begin) (line-beginning-position 2))
  22183. (org-element-property :contents-begin element))))
  22184. (cond
  22185. ((not element) (goto-char (point-min)))
  22186. ((= (point) begin)
  22187. (backward-char)
  22188. (org-backward-paragraph))
  22189. ((<= (point) post-affiliated) (goto-char begin))
  22190. ;; Special behavior: on a table or a property drawer, move to
  22191. ;; its beginning.
  22192. ((memq type '(node-property table-row))
  22193. (goto-char (org-element-property
  22194. :post-affiliated (org-element-property :parent element))))
  22195. (special?
  22196. (if (<= (point) contents-begin) (goto-char post-affiliated)
  22197. ;; Inside a verse block, see blank lines as paragraph
  22198. ;; separators.
  22199. (let ((origin (point)))
  22200. (skip-chars-backward " \r\t\n" contents-begin)
  22201. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22202. (skip-chars-forward " \r\t\n" origin)
  22203. (if (= (point) origin) (goto-char contents-begin)
  22204. (beginning-of-line))))))
  22205. ((eq type 'paragraph) (goto-char contents-begin)
  22206. ;; When at first paragraph in an item or a footnote definition,
  22207. ;; move directly to beginning of line.
  22208. (let ((parent-contents
  22209. (org-element-property
  22210. :contents-begin (org-element-property :parent element))))
  22211. (when (and parent-contents (= parent-contents contents-begin))
  22212. (beginning-of-line))))
  22213. ;; At the end of a greater element, move to the beginning of
  22214. ;; the last element within.
  22215. ((and contents-end (>= (point) contents-end))
  22216. (goto-char (1- contents-end))
  22217. (org-backward-paragraph))
  22218. (t (goto-char (or post-affiliated begin))))
  22219. ;; Ensure we never leave point invisible.
  22220. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  22221. (defun org-forward-element ()
  22222. "Move forward by one element.
  22223. Move to the next element at the same level, when possible."
  22224. (interactive)
  22225. (cond ((eobp) (user-error "Cannot move further down"))
  22226. ((org-with-limited-levels (org-at-heading-p))
  22227. (let ((origin (point)))
  22228. (goto-char (org-end-of-subtree nil t))
  22229. (unless (org-with-limited-levels (org-at-heading-p))
  22230. (goto-char origin)
  22231. (user-error "Cannot move further down"))))
  22232. (t
  22233. (let* ((elem (org-element-at-point))
  22234. (end (org-element-property :end elem))
  22235. (parent (org-element-property :parent elem)))
  22236. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22237. (goto-char (org-element-property :end parent)))
  22238. ((integer-or-marker-p end) (goto-char end))
  22239. (t (message "No element at point")))))))
  22240. (defun org-backward-element ()
  22241. "Move backward by one element.
  22242. Move to the previous element at the same level, when possible."
  22243. (interactive)
  22244. (cond ((bobp) (user-error "Cannot move further up"))
  22245. ((org-with-limited-levels (org-at-heading-p))
  22246. ;; At a headline, move to the previous one, if any, or stay
  22247. ;; here.
  22248. (let ((origin (point)))
  22249. (org-with-limited-levels (org-backward-heading-same-level 1))
  22250. ;; When current headline has no sibling above, move to its
  22251. ;; parent.
  22252. (when (= (point) origin)
  22253. (or (org-with-limited-levels (org-up-heading-safe))
  22254. (progn (goto-char origin)
  22255. (user-error "Cannot move further up"))))))
  22256. (t
  22257. (let* ((elem (org-element-at-point))
  22258. (beg (org-element-property :begin elem)))
  22259. (cond
  22260. ;; Move to beginning of current element if point isn't
  22261. ;; there already.
  22262. ((null beg) (message "No element at point"))
  22263. ((/= (point) beg) (goto-char beg))
  22264. (t (goto-char beg)
  22265. (skip-chars-backward " \r\t\n")
  22266. (unless (bobp)
  22267. (let ((prev (org-element-at-point)))
  22268. (goto-char (org-element-property :begin prev))
  22269. (while (and (setq prev (org-element-property :parent prev))
  22270. (<= (org-element-property :end prev) beg))
  22271. (goto-char (org-element-property :begin prev)))))))))))
  22272. (defun org-up-element ()
  22273. "Move to upper element."
  22274. (interactive)
  22275. (if (org-with-limited-levels (org-at-heading-p))
  22276. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22277. (let* ((elem (org-element-at-point))
  22278. (parent (org-element-property :parent elem)))
  22279. (if parent (goto-char (org-element-property :begin parent))
  22280. (if (org-with-limited-levels (org-before-first-heading-p))
  22281. (user-error "No surrounding element")
  22282. (org-with-limited-levels (org-back-to-heading)))))))
  22283. (defun org-down-element ()
  22284. "Move to inner element."
  22285. (interactive)
  22286. (let ((element (org-element-at-point)))
  22287. (cond
  22288. ((memq (org-element-type element) '(plain-list table))
  22289. (goto-char (org-element-property :contents-begin element))
  22290. (forward-char))
  22291. ((memq (org-element-type element) org-element-greater-elements)
  22292. ;; If contents are hidden, first disclose them.
  22293. (when (org-invisible-p (line-end-position)) (org-cycle))
  22294. (goto-char (or (org-element-property :contents-begin element)
  22295. (user-error "No content for this element"))))
  22296. (t (user-error "No inner element")))))
  22297. (defun org-drag-element-backward ()
  22298. "Move backward element at point."
  22299. (interactive)
  22300. (let ((elem (or (org-element-at-point)
  22301. (user-error "No element at point"))))
  22302. (if (eq (org-element-type elem) 'headline)
  22303. ;; Preserve point when moving a whole tree, even if point was
  22304. ;; on blank lines below the headline.
  22305. (let ((offset (skip-chars-backward " \t\n")))
  22306. (unwind-protect (org-move-subtree-up)
  22307. (forward-char (- offset))))
  22308. (let ((prev-elem
  22309. (save-excursion
  22310. (goto-char (org-element-property :begin elem))
  22311. (skip-chars-backward " \r\t\n")
  22312. (unless (bobp)
  22313. (let* ((beg (org-element-property :begin elem))
  22314. (prev (org-element-at-point))
  22315. (up prev))
  22316. (while (and (setq up (org-element-property :parent up))
  22317. (<= (org-element-property :end up) beg))
  22318. (setq prev up))
  22319. prev)))))
  22320. ;; Error out if no previous element or previous element is
  22321. ;; a parent of the current one.
  22322. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22323. (user-error "Cannot drag element backward")
  22324. (let ((pos (point)))
  22325. (org-element-swap-A-B prev-elem elem)
  22326. (goto-char (+ (org-element-property :begin prev-elem)
  22327. (- pos (org-element-property :begin elem))))))))))
  22328. (defun org-drag-element-forward ()
  22329. "Move forward element at point."
  22330. (interactive)
  22331. (let* ((pos (point))
  22332. (elem (or (org-element-at-point)
  22333. (user-error "No element at point"))))
  22334. (when (= (point-max) (org-element-property :end elem))
  22335. (user-error "Cannot drag element forward"))
  22336. (goto-char (org-element-property :end elem))
  22337. (let ((next-elem (org-element-at-point)))
  22338. (when (or (org-element-nested-p elem next-elem)
  22339. (and (eq (org-element-type next-elem) 'headline)
  22340. (not (eq (org-element-type elem) 'headline))))
  22341. (goto-char pos)
  22342. (user-error "Cannot drag element forward"))
  22343. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22344. ;; body's length (without final blanks) and by the length of
  22345. ;; blanks between ELEM and NEXT-ELEM.
  22346. (let ((size-next (- (save-excursion
  22347. (goto-char (org-element-property :end next-elem))
  22348. (skip-chars-backward " \r\t\n")
  22349. (forward-line)
  22350. ;; Small correction if buffer doesn't end
  22351. ;; with a newline character.
  22352. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22353. (org-element-property :begin next-elem)))
  22354. (size-blank (- (org-element-property :end elem)
  22355. (save-excursion
  22356. (goto-char (org-element-property :end elem))
  22357. (skip-chars-backward " \r\t\n")
  22358. (forward-line)
  22359. (point)))))
  22360. (org-element-swap-A-B elem next-elem)
  22361. (goto-char (+ pos size-next size-blank))))))
  22362. (defun org-drag-line-forward (arg)
  22363. "Drag the line at point ARG lines forward."
  22364. (interactive "p")
  22365. (dotimes (_ (abs arg))
  22366. (let ((c (current-column)))
  22367. (if (< 0 arg)
  22368. (progn
  22369. (beginning-of-line 2)
  22370. (transpose-lines 1)
  22371. (beginning-of-line 0))
  22372. (transpose-lines 1)
  22373. (beginning-of-line -1))
  22374. (org-move-to-column c))))
  22375. (defun org-drag-line-backward (arg)
  22376. "Drag the line at point ARG lines backward."
  22377. (interactive "p")
  22378. (org-drag-line-forward (- arg)))
  22379. (defun org-mark-element ()
  22380. "Put point at beginning of this element, mark at end.
  22381. Interactively, if this command is repeated or (in Transient Mark
  22382. mode) if the mark is active, it marks the next element after the
  22383. ones already marked."
  22384. (interactive)
  22385. (let (deactivate-mark)
  22386. (if (and (called-interactively-p 'any)
  22387. (or (and (eq last-command this-command) (mark t))
  22388. (and transient-mark-mode mark-active)))
  22389. (set-mark
  22390. (save-excursion
  22391. (goto-char (mark))
  22392. (goto-char (org-element-property :end (org-element-at-point)))))
  22393. (let ((element (org-element-at-point)))
  22394. (end-of-line)
  22395. (push-mark (org-element-property :end element) t t)
  22396. (goto-char (org-element-property :begin element))))))
  22397. (defun org-narrow-to-element ()
  22398. "Narrow buffer to current element."
  22399. (interactive)
  22400. (let ((elem (org-element-at-point)))
  22401. (cond
  22402. ((eq (car elem) 'headline)
  22403. (narrow-to-region
  22404. (org-element-property :begin elem)
  22405. (org-element-property :end elem)))
  22406. ((memq (car elem) org-element-greater-elements)
  22407. (narrow-to-region
  22408. (org-element-property :contents-begin elem)
  22409. (org-element-property :contents-end elem)))
  22410. (t
  22411. (narrow-to-region
  22412. (org-element-property :begin elem)
  22413. (org-element-property :end elem))))))
  22414. (defun org-transpose-element ()
  22415. "Transpose current and previous elements, keeping blank lines between.
  22416. Point is moved after both elements."
  22417. (interactive)
  22418. (org-skip-whitespace)
  22419. (let ((end (org-element-property :end (org-element-at-point))))
  22420. (org-drag-element-backward)
  22421. (goto-char end)))
  22422. (defun org-unindent-buffer ()
  22423. "Un-indent the visible part of the buffer.
  22424. Relative indentation (between items, inside blocks, etc.) isn't
  22425. modified."
  22426. (interactive)
  22427. (unless (eq major-mode 'org-mode)
  22428. (user-error "Cannot un-indent a buffer not in Org mode"))
  22429. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22430. (unindent-tree
  22431. (lambda (contents)
  22432. (dolist (element (reverse contents))
  22433. (if (memq (org-element-type element) '(headline section))
  22434. (funcall unindent-tree (org-element-contents element))
  22435. (save-excursion
  22436. (save-restriction
  22437. (narrow-to-region
  22438. (org-element-property :begin element)
  22439. (org-element-property :end element))
  22440. (org-do-remove-indentation))))))))
  22441. (funcall unindent-tree (org-element-contents parse-tree))))
  22442. (defun org-show-children (&optional level)
  22443. "Show all direct subheadings of this heading.
  22444. Prefix arg LEVEL is how many levels below the current level
  22445. should be shown. Default is enough to cause the following
  22446. heading to appear."
  22447. (interactive "p")
  22448. ;; If `orgstruct-mode' is active, use the slower version.
  22449. (if orgstruct-mode (call-interactively #'outline-show-children)
  22450. (save-excursion
  22451. (org-back-to-heading t)
  22452. (let* ((current-level (funcall outline-level))
  22453. (max-level (org-get-valid-level
  22454. current-level
  22455. (if level (prefix-numeric-value level) 1)))
  22456. (end (save-excursion (org-end-of-subtree t t)))
  22457. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22458. (past-first-child nil)
  22459. ;; Make sure to skip inlinetasks.
  22460. (re (format regexp-fmt
  22461. current-level
  22462. (cond
  22463. ((not (featurep 'org-inlinetask)) "")
  22464. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22465. 3))
  22466. (t (1- org-inlinetask-min-level))))))
  22467. ;; Display parent heading.
  22468. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22469. (forward-line)
  22470. ;; Display children. First child may be deeper than expected
  22471. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22472. ;; MAX-LEVEL accordingly.
  22473. (while (re-search-forward re end t)
  22474. (unless past-first-child
  22475. (setq re (format regexp-fmt
  22476. current-level
  22477. (max (funcall outline-level) max-level)))
  22478. (setq past-first-child t))
  22479. (outline-flag-region
  22480. (line-end-position 0) (line-end-position) nil))))))
  22481. (defun org-show-subtree ()
  22482. "Show everything after this heading at deeper levels."
  22483. (interactive)
  22484. (outline-flag-region
  22485. (point)
  22486. (save-excursion
  22487. (org-end-of-subtree t t))
  22488. nil))
  22489. (defun org-show-entry ()
  22490. "Show the body directly following this heading.
  22491. Show the heading too, if it is currently invisible."
  22492. (interactive)
  22493. (save-excursion
  22494. (ignore-errors
  22495. (org-back-to-heading t)
  22496. (outline-flag-region
  22497. (max (point-min) (1- (point)))
  22498. (save-excursion
  22499. (if (re-search-forward
  22500. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22501. (match-beginning 1)
  22502. (point-max)))
  22503. nil)
  22504. (org-cycle-hide-drawers 'children))))
  22505. (defun org-make-options-regexp (kwds &optional extra)
  22506. "Make a regular expression for keyword lines.
  22507. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22508. when non-nil, is a regexp matching keywords names."
  22509. (concat "^[ \t]*#\\+\\("
  22510. (regexp-opt kwds)
  22511. (and extra (concat (and kwds "\\|") extra))
  22512. "\\):[ \t]*\\(.*\\)"))
  22513. ;;;; Integration with and fixes for other packages
  22514. ;;; Imenu support
  22515. (defvar-local org-imenu-markers nil
  22516. "All markers currently used by Imenu.")
  22517. (defun org-imenu-new-marker (&optional pos)
  22518. "Return a new marker for use by Imenu, and remember the marker."
  22519. (let ((m (make-marker)))
  22520. (move-marker m (or pos (point)))
  22521. (push m org-imenu-markers)
  22522. m))
  22523. (defun org-imenu-get-tree ()
  22524. "Produce the index for Imenu."
  22525. (dolist (x org-imenu-markers) (move-marker x nil))
  22526. (setq org-imenu-markers nil)
  22527. (let* ((case-fold-search nil)
  22528. (n org-imenu-depth)
  22529. (re (concat "^" (org-get-limited-outline-regexp)))
  22530. (subs (make-vector (1+ n) nil))
  22531. (last-level 0)
  22532. m level head0 head)
  22533. (org-with-wide-buffer
  22534. (goto-char (point-max))
  22535. (while (re-search-backward re nil t)
  22536. (setq level (org-reduced-level (funcall outline-level)))
  22537. (when (and (<= level n)
  22538. (looking-at org-complex-heading-regexp)
  22539. (setq head0 (match-string-no-properties 4)))
  22540. (setq head (org-link-display-format head0)
  22541. m (org-imenu-new-marker))
  22542. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22543. (if (>= level last-level)
  22544. (push (cons head m) (aref subs level))
  22545. (push (cons head (aref subs (1+ level))) (aref subs level))
  22546. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22547. (setq last-level level))))
  22548. (aref subs 1)))
  22549. (eval-after-load "imenu"
  22550. '(progn
  22551. (add-hook 'imenu-after-jump-hook
  22552. (lambda ()
  22553. (when (derived-mode-p 'org-mode)
  22554. (org-show-context 'org-goto))))))
  22555. (defun org-link-display-format (s)
  22556. "Replace links in string S with their description.
  22557. If there is no description, use the link target."
  22558. (save-match-data
  22559. (replace-regexp-in-string
  22560. org-bracket-link-analytic-regexp
  22561. (lambda (m)
  22562. (if (match-end 5) (match-string 5 m)
  22563. (concat (match-string 1 m) (match-string 3 m))))
  22564. s nil t)))
  22565. (defun org-toggle-link-display ()
  22566. "Toggle the literal or descriptive display of links."
  22567. (interactive)
  22568. (if org-descriptive-links
  22569. (progn (org-remove-from-invisibility-spec '(org-link))
  22570. (org-restart-font-lock)
  22571. (setq org-descriptive-links nil))
  22572. (progn (add-to-invisibility-spec '(org-link))
  22573. (org-restart-font-lock)
  22574. (setq org-descriptive-links t))))
  22575. ;; Speedbar support
  22576. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22577. "Overlay marking the agenda restriction line in speedbar.")
  22578. (overlay-put org-speedbar-restriction-lock-overlay
  22579. 'face 'org-agenda-restriction-lock)
  22580. (overlay-put org-speedbar-restriction-lock-overlay
  22581. 'help-echo "Agendas are currently limited to this item.")
  22582. (delete-overlay org-speedbar-restriction-lock-overlay)
  22583. (defun org-speedbar-set-agenda-restriction ()
  22584. "Restrict future agenda commands to the location at point in speedbar.
  22585. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22586. (interactive)
  22587. (require 'org-agenda)
  22588. (let (p m tp np dir txt)
  22589. (cond
  22590. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22591. 'org-imenu t))
  22592. (setq m (get-text-property p 'org-imenu-marker))
  22593. (with-current-buffer (marker-buffer m)
  22594. (goto-char m)
  22595. (org-agenda-set-restriction-lock 'subtree)))
  22596. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22597. 'speedbar-function 'speedbar-find-file))
  22598. (setq tp (previous-single-property-change
  22599. (1+ p) 'speedbar-function)
  22600. np (next-single-property-change
  22601. tp 'speedbar-function)
  22602. dir (speedbar-line-directory)
  22603. txt (buffer-substring-no-properties (or tp (point-min))
  22604. (or np (point-max))))
  22605. (with-current-buffer (find-file-noselect
  22606. (let ((default-directory dir))
  22607. (expand-file-name txt)))
  22608. (unless (derived-mode-p 'org-mode)
  22609. (user-error "Cannot restrict to non-Org mode file"))
  22610. (org-agenda-set-restriction-lock 'file)))
  22611. (t (user-error "Don't know how to restrict Org mode agenda")))
  22612. (move-overlay org-speedbar-restriction-lock-overlay
  22613. (point-at-bol) (point-at-eol))
  22614. (setq current-prefix-arg nil)
  22615. (org-agenda-maybe-redo)))
  22616. (defvar speedbar-file-key-map)
  22617. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22618. (eval-after-load "speedbar"
  22619. '(progn
  22620. (speedbar-add-supported-extension ".org")
  22621. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22622. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22623. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22624. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22625. (add-hook 'speedbar-visiting-tag-hook
  22626. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22627. ;;; Fixes and Hacks for problems with other packages
  22628. (defun org--flyspell-object-check-p (element)
  22629. "Non-nil when Flyspell can check object at point.
  22630. ELEMENT is the element at point."
  22631. (let ((object (save-excursion
  22632. (when (looking-at-p "\\>") (backward-char))
  22633. (org-element-context element))))
  22634. (cl-case (org-element-type object)
  22635. ;; Prevent checks in links due to keybinding conflict with
  22636. ;; Flyspell.
  22637. ((code entity export-snippet inline-babel-call
  22638. inline-src-block line-break latex-fragment link macro
  22639. statistics-cookie target timestamp verbatim)
  22640. nil)
  22641. (footnote-reference
  22642. ;; Only in inline footnotes, within the definition.
  22643. (and (eq (org-element-property :type object) 'inline)
  22644. (< (save-excursion
  22645. (goto-char (org-element-property :begin object))
  22646. (search-forward ":" nil t 2))
  22647. (point))))
  22648. (otherwise t))))
  22649. (defun org-mode-flyspell-verify ()
  22650. "Function used for `flyspell-generic-check-word-predicate'."
  22651. (if (org-at-heading-p)
  22652. ;; At a headline or an inlinetask, check title only. This is
  22653. ;; faster than relying on `org-element-at-point'.
  22654. (and (save-excursion (beginning-of-line)
  22655. (and (let ((case-fold-search t))
  22656. (not (looking-at-p "\\*+ END[ \t]*$")))
  22657. (let ((case-fold-search nil))
  22658. (looking-at org-complex-heading-regexp))))
  22659. (match-beginning 4)
  22660. (>= (point) (match-beginning 4))
  22661. (or (not (match-beginning 5))
  22662. (< (point) (match-beginning 5))))
  22663. (let* ((element (org-element-at-point))
  22664. (post-affiliated (org-element-property :post-affiliated element)))
  22665. (cond
  22666. ;; Ignore checks in all affiliated keywords but captions.
  22667. ((< (point) post-affiliated)
  22668. (and (save-excursion
  22669. (beginning-of-line)
  22670. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22671. (> (point) (match-end 0))
  22672. (org--flyspell-object-check-p element)))
  22673. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22674. ((let ((log (org-log-into-drawer)))
  22675. (and log
  22676. (let ((drawer (org-element-lineage element '(drawer))))
  22677. (and drawer
  22678. (eq (compare-strings
  22679. log nil nil
  22680. (org-element-property :drawer-name drawer) nil nil t)
  22681. t)))))
  22682. nil)
  22683. (t
  22684. (cl-case (org-element-type element)
  22685. ((comment quote-section) t)
  22686. (comment-block
  22687. ;; Allow checks between block markers, not on them.
  22688. (and (> (line-beginning-position) post-affiliated)
  22689. (save-excursion
  22690. (end-of-line)
  22691. (skip-chars-forward " \r\t\n")
  22692. (< (point) (org-element-property :end element)))))
  22693. ;; Arbitrary list of keywords where checks are meaningful.
  22694. ;; Make sure point is on the value part of the element.
  22695. (keyword
  22696. (and (member (org-element-property :key element)
  22697. '("DESCRIPTION" "TITLE"))
  22698. (save-excursion
  22699. (search-backward ":" (line-beginning-position) t))))
  22700. ;; Check is globally allowed in paragraphs verse blocks and
  22701. ;; table rows (after affiliated keywords) but some objects
  22702. ;; must not be affected.
  22703. ((paragraph table-row verse-block)
  22704. (let ((cbeg (org-element-property :contents-begin element))
  22705. (cend (org-element-property :contents-end element)))
  22706. (and cbeg (>= (point) cbeg) (< (point) cend)
  22707. (org--flyspell-object-check-p element))))))))))
  22708. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22709. (defun org-remove-flyspell-overlays-in (beg end)
  22710. "Remove flyspell overlays in region."
  22711. (and (bound-and-true-p flyspell-mode)
  22712. (fboundp 'flyspell-delete-region-overlays)
  22713. (flyspell-delete-region-overlays beg end)))
  22714. (defvar flyspell-delayed-commands)
  22715. (eval-after-load "flyspell"
  22716. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22717. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22718. (eval-after-load "bookmark"
  22719. '(if (boundp 'bookmark-after-jump-hook)
  22720. ;; We can use the hook
  22721. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22722. ;; Hook not available, use advice
  22723. (defadvice bookmark-jump (after org-make-visible activate)
  22724. "Make the position visible."
  22725. (org-bookmark-jump-unhide))))
  22726. ;; Make sure saveplace shows the location if it was hidden
  22727. (eval-after-load "saveplace"
  22728. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22729. "Make the position visible."
  22730. (org-bookmark-jump-unhide)))
  22731. ;; Make sure ecb shows the location if it was hidden
  22732. (eval-after-load "ecb"
  22733. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22734. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22735. (when (derived-mode-p 'org-mode)
  22736. (org-show-context))))
  22737. (defun org-bookmark-jump-unhide ()
  22738. "Unhide the current position, to show the bookmark location."
  22739. (and (derived-mode-p 'org-mode)
  22740. (or (org-invisible-p)
  22741. (save-excursion (goto-char (max (point-min) (1- (point))))
  22742. (org-invisible-p)))
  22743. (org-show-context 'bookmark-jump)))
  22744. (defun org-mark-jump-unhide ()
  22745. "Make the point visible with `org-show-context' after jumping to the mark."
  22746. (when (and (derived-mode-p 'org-mode)
  22747. (org-invisible-p))
  22748. (org-show-context 'mark-goto)))
  22749. (eval-after-load "simple"
  22750. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22751. "Make the point visible with `org-show-context'."
  22752. (org-mark-jump-unhide)))
  22753. (eval-after-load "simple"
  22754. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22755. "Make the point visible with `org-show-context'."
  22756. (org-mark-jump-unhide)))
  22757. (eval-after-load "simple"
  22758. '(defadvice pop-global-mark (after org-make-visible activate)
  22759. "Make the point visible with `org-show-context'."
  22760. (org-mark-jump-unhide)))
  22761. ;; Make session.el ignore our circular variable
  22762. (defvar session-globals-exclude)
  22763. (eval-after-load "session"
  22764. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22765. ;;;; Finish up
  22766. (provide 'org)
  22767. (run-hooks 'org-load-hook)
  22768. ;;; org.el ends here