org.el 951 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://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-clocktable-shift "org-clock" (dir n))
  118. (declare-function org-element-at-point "org-element" ())
  119. (declare-function org-element-cache-refresh "org-element" (pos))
  120. (declare-function org-element-cache-reset "org-element" (&optional all))
  121. (declare-function org-element-contents "org-element" (element))
  122. (declare-function org-element-context "org-element" (&optional element))
  123. (declare-function org-element-copy "org-element" (datum))
  124. (declare-function org-element-interpret-data "org-element" (data))
  125. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  126. (declare-function org-element-link-parser "org-element" ())
  127. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  128. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  129. (declare-function org-element-property "org-element" (property element))
  130. (declare-function org-element-put-property "org-element" (element property value))
  131. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  132. (declare-function org-element-type "org-element" (element))
  133. (declare-function org-element-update-syntax "org-element" ())
  134. (declare-function org-id-find-id-file "org-id" (id))
  135. (declare-function org-id-get-create "org-id" (&optional force))
  136. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  137. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  138. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  139. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  140. (declare-function org-table-align "org-table" ())
  141. (declare-function org-table-begin "org-table" (&optional table-type))
  142. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  143. (declare-function org-table-blank-field "org-table" ())
  144. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  145. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  146. (declare-function org-table-cut-region "org-table" (beg end))
  147. (declare-function org-table-edit-field "org-table" (arg))
  148. (declare-function org-table-end "org-table" (&optional table-type))
  149. (declare-function org-table-end-of-field "org-table" (&optional n))
  150. (declare-function org-table-insert-row "org-table" (&optional arg))
  151. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  152. (declare-function org-table-maybe-eval-formula "org-table" ())
  153. (declare-function org-table-maybe-recalculate-line "org-table" ())
  154. (declare-function org-table-next-row "org-table" ())
  155. (declare-function org-table-paste-rectangle "org-table" ())
  156. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  157. (declare-function org-table-wrap-region "org-table" (arg))
  158. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  159. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  160. (declare-function orgtbl-mode "org-table" (&optional arg))
  161. (declare-function org-export-get-backend "ox" (name))
  162. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  163. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (defsubst org-uniquify (list)
  165. "Non-destructively remove duplicate elements from LIST."
  166. (let ((res (copy-sequence list))) (delete-dups res)))
  167. (defsubst org-get-at-bol (property)
  168. "Get text property PROPERTY at the beginning of line."
  169. (get-text-property (point-at-bol) property))
  170. (defsubst org-trim (s &optional keep-lead)
  171. "Remove whitespace at the beginning and the end of string S.
  172. When optional argument KEEP-LEAD is non-nil, removing blank lines
  173. at the beginning of the string does not affect leading indentation."
  174. (replace-regexp-in-string
  175. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  176. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  177. ;; load languages based on value of `org-babel-load-languages'
  178. (defvar org-babel-load-languages)
  179. ;;;###autoload
  180. (defun org-babel-do-load-languages (sym value)
  181. "Load the languages defined in `org-babel-load-languages'."
  182. (set-default sym value)
  183. (dolist (pair org-babel-load-languages)
  184. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  185. (if active
  186. (require (intern (concat "ob-" lang)))
  187. (funcall 'fmakunbound
  188. (intern (concat "org-babel-execute:" lang)))
  189. (funcall 'fmakunbound
  190. (intern (concat "org-babel-expand-body:" lang)))))))
  191. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  192. ;;;###autoload
  193. (defun org-babel-load-file (file &optional compile)
  194. "Load Emacs Lisp source code blocks in the Org FILE.
  195. This function exports the source code using `org-babel-tangle'
  196. and then loads the resulting file using `load-file'. With prefix
  197. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  198. file to byte-code before it is loaded."
  199. (interactive "fFile to load: \nP")
  200. (let* ((age (lambda (file)
  201. (float-time
  202. (time-subtract (current-time)
  203. (nth 5 (or (file-attributes (file-truename file))
  204. (file-attributes file)))))))
  205. (base-name (file-name-sans-extension file))
  206. (exported-file (concat base-name ".el")))
  207. ;; tangle if the Org file is newer than the elisp file
  208. (unless (and (file-exists-p exported-file)
  209. (> (funcall age file) (funcall age exported-file)))
  210. ;; Tangle-file traversal returns reversed list of tangled files
  211. ;; and we want to evaluate the first target.
  212. (setq exported-file
  213. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  214. (message "%s %s"
  215. (if compile
  216. (progn (byte-compile-file exported-file 'load)
  217. "Compiled and loaded")
  218. (progn (load-file exported-file) "Loaded"))
  219. exported-file)))
  220. (defcustom org-babel-load-languages '((emacs-lisp . t))
  221. "Languages which can be evaluated in Org buffers.
  222. This list can be used to load support for any of the languages
  223. below, note that each language will depend on a different set of
  224. system executables and/or Emacs modes. When a language is
  225. \"loaded\", then code blocks in that language can be evaluated
  226. with `org-babel-execute-src-block' bound by default to C-c
  227. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  228. be set to remove code block evaluation from the C-c C-c
  229. keybinding. By default only Emacs Lisp (which has no
  230. requirements) is loaded."
  231. :group 'org-babel
  232. :set 'org-babel-do-load-languages
  233. :version "24.1"
  234. :type '(alist :tag "Babel Languages"
  235. :key-type
  236. (choice
  237. (const :tag "Awk" awk)
  238. (const :tag "C" C)
  239. (const :tag "R" R)
  240. (const :tag "Asymptote" asymptote)
  241. (const :tag "Calc" calc)
  242. (const :tag "Clojure" clojure)
  243. (const :tag "CSS" css)
  244. (const :tag "Ditaa" ditaa)
  245. (const :tag "Dot" dot)
  246. (const :tag "Emacs Lisp" emacs-lisp)
  247. (const :tag "Forth" forth)
  248. (const :tag "Fortran" fortran)
  249. (const :tag "Gnuplot" gnuplot)
  250. (const :tag "Haskell" haskell)
  251. (const :tag "IO" io)
  252. (const :tag "J" J)
  253. (const :tag "Java" java)
  254. (const :tag "Javascript" js)
  255. (const :tag "LaTeX" latex)
  256. (const :tag "Ledger" ledger)
  257. (const :tag "Lilypond" lilypond)
  258. (const :tag "Lisp" lisp)
  259. (const :tag "Makefile" makefile)
  260. (const :tag "Maxima" maxima)
  261. (const :tag "Matlab" matlab)
  262. (const :tag "Mscgen" mscgen)
  263. (const :tag "Ocaml" ocaml)
  264. (const :tag "Octave" octave)
  265. (const :tag "Org" org)
  266. (const :tag "Perl" perl)
  267. (const :tag "Pico Lisp" picolisp)
  268. (const :tag "PlantUML" plantuml)
  269. (const :tag "Python" python)
  270. (const :tag "Ruby" ruby)
  271. (const :tag "Sass" sass)
  272. (const :tag "Scala" scala)
  273. (const :tag "Scheme" scheme)
  274. (const :tag "Screen" screen)
  275. (const :tag "Shell Script" shell)
  276. (const :tag "Shen" shen)
  277. (const :tag "Sql" sql)
  278. (const :tag "Sqlite" sqlite)
  279. (const :tag "Stan" stan)
  280. (const :tag "ebnf2ps" ebnf2ps))
  281. :value-type (boolean :tag "Activate" :value t)))
  282. ;;;; Customization variables
  283. (defcustom org-clone-delete-id nil
  284. "Remove ID property of clones of a subtree.
  285. When non-nil, clones of a subtree don't inherit the ID property.
  286. Otherwise they inherit the ID property with a new unique
  287. identifier."
  288. :type 'boolean
  289. :version "24.1"
  290. :group 'org-id)
  291. ;;; Version
  292. (org-check-version)
  293. ;;;###autoload
  294. (defun org-version (&optional here full message)
  295. "Show the Org version.
  296. Interactively, or when MESSAGE is non-nil, show it in echo area.
  297. With prefix argument, or when HERE is non-nil, insert it at point.
  298. In non-interactive uses, a reduced version string is output unless
  299. FULL is given."
  300. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  301. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  302. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  303. (load-suffixes (list ".el"))
  304. (org-install-dir
  305. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  306. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  307. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  308. (let* ((load-suffixes save-load-suffixes)
  309. (release (org-release))
  310. (git-version (org-git-version))
  311. (version (format "Org mode version %s (%s @ %s)"
  312. release
  313. git-version
  314. (if org-install-dir
  315. (if (string= org-dir org-install-dir)
  316. org-install-dir
  317. (concat "mixed installation! "
  318. org-install-dir
  319. " and "
  320. org-dir))
  321. "org-loaddefs.el can not be found!")))
  322. (version1 (if full version release)))
  323. (when here (insert version1))
  324. (when message (message "%s" version1))
  325. version1)))
  326. (defconst org-version (org-version))
  327. ;;; Syntax Constants
  328. ;;;; Block
  329. (defconst org-block-regexp
  330. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  331. "Regular expression for hiding blocks.")
  332. (defconst org-dblock-start-re
  333. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  334. "Matches the start line of a dynamic block, with parameters.")
  335. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  336. "Matches the end of a dynamic block.")
  337. ;;;; Clock and Planning
  338. (defconst org-clock-string "CLOCK:"
  339. "String used as prefix for timestamps clocking work hours on an item.")
  340. (defvar org-closed-string "CLOSED:"
  341. "String used as the prefix for timestamps logging closing a TODO entry.")
  342. (defvar org-deadline-string "DEADLINE:"
  343. "String to mark deadline entries.
  344. \\<org-mode-map>
  345. A deadline is this string, followed by a time stamp. It must be
  346. a word, terminated by a colon. You can insert a schedule keyword
  347. and a timestamp with `\\[org-deadline]'.")
  348. (defvar org-scheduled-string "SCHEDULED:"
  349. "String to mark scheduled TODO entries.
  350. \\<org-mode-map>
  351. A schedule is this string, followed by a time stamp. It must be
  352. a word, terminated by a colon. You can insert a schedule keyword
  353. and a timestamp with `\\[org-schedule]'.")
  354. (defconst org-ds-keyword-length
  355. (+ 2
  356. (apply #'max
  357. (mapcar #'length
  358. (list org-deadline-string org-scheduled-string
  359. org-clock-string org-closed-string))))
  360. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  361. (defconst org-planning-line-re
  362. (concat "^[ \t]*"
  363. (regexp-opt
  364. (list org-closed-string org-deadline-string org-scheduled-string)
  365. t))
  366. "Matches a line with planning info.
  367. Matched keyword is in group 1.")
  368. (defconst org-clock-line-re
  369. (concat "^[ \t]*" org-clock-string)
  370. "Matches a line with clock info.")
  371. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  372. "Matches the DEADLINE keyword.")
  373. (defconst org-deadline-time-regexp
  374. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  375. "Matches the DEADLINE keyword together with a time stamp.")
  376. (defconst org-deadline-time-hour-regexp
  377. (concat "\\<" org-deadline-string
  378. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  379. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  380. (defconst org-deadline-line-regexp
  381. (concat "\\<\\(" org-deadline-string "\\).*")
  382. "Matches the DEADLINE keyword and the rest of the line.")
  383. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  384. "Matches the SCHEDULED keyword.")
  385. (defconst org-scheduled-time-regexp
  386. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  387. "Matches the SCHEDULED keyword together with a time stamp.")
  388. (defconst org-scheduled-time-hour-regexp
  389. (concat "\\<" org-scheduled-string
  390. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  391. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  392. (defconst org-closed-time-regexp
  393. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  394. "Matches the CLOSED keyword together with a time stamp.")
  395. (defconst org-keyword-time-regexp
  396. (concat "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string
  399. org-clock-string)
  400. t)
  401. " *[[<]\\([^]>]+\\)[]>]")
  402. "Matches any of the 4 keywords, together with the time stamp.")
  403. (defconst org-keyword-time-not-clock-regexp
  404. (concat
  405. "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string) t)
  408. " *[[<]\\([^]>]+\\)[]>]")
  409. "Matches any of the 3 keywords, together with the time stamp.")
  410. (defconst org-maybe-keyword-time-regexp
  411. (concat "\\(\\<"
  412. (regexp-opt
  413. (list org-scheduled-string org-deadline-string org-closed-string
  414. org-clock-string)
  415. t)
  416. "\\)?"
  417. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  418. "\\|"
  419. "<%%([^\r\n>]*>\\)")
  420. "Matches a timestamp, possibly preceded by a keyword.")
  421. (defconst org-all-time-keywords
  422. (mapcar (lambda (w) (substring w 0 -1))
  423. (list org-scheduled-string org-deadline-string
  424. org-clock-string org-closed-string))
  425. "List of time keywords.")
  426. ;;;; Drawer
  427. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  428. "Matches first or last line of a hidden block.
  429. Group 1 contains drawer's name or \"END\".")
  430. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  431. "Regular expression matching the first line of a property drawer.")
  432. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  433. "Regular expression matching the last line of a property drawer.")
  434. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  435. "Regular expression matching the first line of a clock drawer.")
  436. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a clock drawer.")
  438. (defconst org-property-drawer-re
  439. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  440. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  441. "[ \t]*:END:[ \t]*$")
  442. "Matches an entire property drawer.")
  443. (defconst org-clock-drawer-re
  444. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  445. org-clock-drawer-end-re "\\)\n?")
  446. "Matches an entire clock drawer.")
  447. ;;;; Headline
  448. (defconst org-heading-keyword-regexp-format
  449. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  450. "Printf format for a regexp matching a headline with some keyword.
  451. This regexp will match the headline of any node which has the
  452. exact keyword that is put into the format. The keyword isn't in
  453. any group by default, but the stars and the body are.")
  454. (defconst org-heading-keyword-maybe-regexp-format
  455. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  456. "Printf format for a regexp matching a headline, possibly with some keyword.
  457. This regexp can match any headline with the specified keyword, or
  458. without a keyword. The keyword isn't in any group by default,
  459. but the stars and the body are.")
  460. (defconst org-archive-tag "ARCHIVE"
  461. "The tag that marks a subtree as archived.
  462. An archived subtree does not open during visibility cycling, and does
  463. not contribute to the agenda listings.")
  464. (defconst org-comment-string "COMMENT"
  465. "Entries starting with this keyword will never be exported.
  466. \\<org-mode-map>
  467. An entry can be toggled between COMMENT and normal with
  468. `\\[org-toggle-comment]'.")
  469. ;;;; LaTeX Environments and Fragments
  470. (defconst org-latex-regexps
  471. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  472. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  473. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  474. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  476. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  477. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  478. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  479. "Regular expressions for matching embedded LaTeX.")
  480. ;;;; Node Property
  481. (defconst org-effort-property "Effort"
  482. "The property that is being used to keep track of effort estimates.
  483. Effort estimates given in this property need to have the format H:MM.")
  484. ;;;; Table
  485. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  486. "Detect an org-type or table-type table.")
  487. (defconst org-table-line-regexp "^[ \t]*|"
  488. "Detect an org-type table line.")
  489. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  490. "Detect an org-type table line.")
  491. (defconst org-table-hline-regexp "^[ \t]*|-"
  492. "Detect an org-type table hline.")
  493. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  494. "Detect a table-type table hline.")
  495. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  496. "Detect the first line outside a table when searching from within it.
  497. This works for both table types.")
  498. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  499. "Detect a #+TBLFM line.")
  500. ;;;; Timestamp
  501. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  502. "Regular expression for fast time stamp matching.")
  503. (defconst org-ts-regexp-inactive
  504. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  505. "Regular expression for fast inactive time stamp matching.")
  506. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  507. "Regular expression for fast time stamp matching.")
  508. (defconst org-ts-regexp0
  509. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.
  511. This one does not require the space after the date, so it can be used
  512. on a string that terminates immediately after the date.")
  513. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  514. "Regular expression matching time strings for analysis.")
  515. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  516. "Regular expression matching time stamps, with groups.")
  517. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  518. "Regular expression matching time stamps (also [..]), with groups.")
  519. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tr-regexp-both
  522. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  523. "Regular expression matching a time stamp range.")
  524. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  525. org-ts-regexp "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.")
  527. (defconst org-tsr-regexp-both
  528. (concat org-ts-regexp-both "\\(--?-?"
  529. org-ts-regexp-both "\\)?")
  530. "Regular expression matching a time stamp or time stamp range.
  531. The time stamps may be either active or inactive.")
  532. (defconst org-repeat-re
  533. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  534. "Regular expression for specifying repeated events.
  535. After a match, group 1 contains the repeat expression.")
  536. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  537. "Formats for `format-time-string' which are used for time stamps.")
  538. ;;; The custom variables
  539. (defgroup org nil
  540. "Outline-based notes management and organizer."
  541. :tag "Org"
  542. :group 'outlines
  543. :group 'calendar)
  544. (defcustom org-mode-hook nil
  545. "Mode hook for Org mode, run after the mode was turned on."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-load-hook nil
  549. "Hook that is run after org.el has been loaded."
  550. :group 'org
  551. :type 'hook)
  552. (defcustom org-log-buffer-setup-hook nil
  553. "Hook that is run after an Org log buffer is created."
  554. :group 'org
  555. :version "24.1"
  556. :type 'hook)
  557. (defvar org-modules) ; defined below
  558. (defvar org-modules-loaded nil
  559. "Have the modules been loaded already?")
  560. (defun org-load-modules-maybe (&optional force)
  561. "Load all extensions listed in `org-modules'."
  562. (when (or force (not org-modules-loaded))
  563. (dolist (ext org-modules)
  564. (condition-case nil (require ext)
  565. (error (message "Problems while trying to load feature `%s'" ext))))
  566. (setq org-modules-loaded t)))
  567. (defun org-set-modules (var value)
  568. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  569. (set var value)
  570. (when (featurep 'org)
  571. (org-load-modules-maybe 'force)
  572. (org-element-cache-reset 'all)))
  573. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  574. "Modules that should always be loaded together with org.el.
  575. If a description starts with <C>, the file is not part of Emacs
  576. and loading it will require that you have downloaded and properly
  577. installed the Org mode distribution.
  578. You can also use this system to load external packages (i.e. neither Org
  579. core modules, nor modules from the CONTRIB directory). Just add symbols
  580. to the end of the list. If the package is called org-xyz.el, then you need
  581. to add the symbol `xyz', and the package must have a call to:
  582. (provide \\='org-xyz)
  583. For export specific modules, see also `org-export-backends'."
  584. :group 'org
  585. :set 'org-set-modules
  586. :version "24.4"
  587. :package-version '(Org . "8.0")
  588. :type
  589. '(set :greedy t
  590. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  591. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  592. (const :tag " crypt: Encryption of subtrees" org-crypt)
  593. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  594. (const :tag " docview: Links to doc-view buffers" org-docview)
  595. (const :tag " eww: Store link to url of eww" org-eww)
  596. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  597. (const :tag " habit: Track your consistency with habits" org-habit)
  598. (const :tag " id: Global IDs for identifying entries" org-id)
  599. (const :tag " info: Links to Info nodes" org-info)
  600. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  601. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  602. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  603. (const :tag " mouse: Additional mouse support" org-mouse)
  604. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  605. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  606. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  607. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  608. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  609. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  610. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  611. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  612. (const :tag "C collector: Collect properties into tables" org-collector)
  613. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  614. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  615. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  616. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  617. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  618. (const :tag "C eval: Include command output as text" org-eval)
  619. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  620. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  621. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  622. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  623. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  624. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  625. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  626. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  627. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  628. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  629. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  630. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  631. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  632. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  633. (const :tag "C registry: A registry for Org links" org-registry)
  634. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  635. (const :tag "C secretary: Team management with org-mode" org-secretary)
  636. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  637. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  638. (const :tag "C track: Keep up with Org mode development" org-track)
  639. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  640. (const :tag "C vm: Links to VM folders/messages" org-vm)
  641. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  642. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  643. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  644. (defvar org-export-registered-backends) ; From ox.el.
  645. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  646. (declare-function org-export-backend-name "ox" (backend) t)
  647. (defcustom org-export-backends '(ascii html icalendar latex odt)
  648. "List of export back-ends that should be always available.
  649. If a description starts with <C>, the file is not part of Emacs
  650. and loading it will require that you have downloaded and properly
  651. installed the Org mode distribution.
  652. Unlike to `org-modules', libraries in this list will not be
  653. loaded along with Org, but only once the export framework is
  654. needed.
  655. This variable needs to be set before org.el is loaded. If you
  656. need to make a change while Emacs is running, use the customize
  657. interface or run the following code, where VAL stands for the new
  658. value of the variable, after updating it:
  659. (progn
  660. (setq org-export-registered-backends
  661. (cl-remove-if-not
  662. (lambda (backend)
  663. (let ((name (org-export-backend-name backend)))
  664. (or (memq name val)
  665. (catch \\='parentp
  666. (dolist (b val)
  667. (and (org-export-derived-backend-p b name)
  668. (throw \\='parentp t)))))))
  669. org-export-registered-backends))
  670. (let ((new-list (mapcar #\\='org-export-backend-name
  671. org-export-registered-backends)))
  672. (dolist (backend val)
  673. (cond
  674. ((not (load (format \"ox-%s\" backend) t t))
  675. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  676. backend))
  677. ((not (memq backend new-list)) (push backend new-list))))
  678. (set-default \\='org-export-backends new-list)))
  679. Adding a back-end to this list will also pull the back-end it
  680. depends on, if any."
  681. :group 'org
  682. :group 'org-export
  683. :version "26.1"
  684. :package-version '(Org . "9.0")
  685. :initialize 'custom-initialize-set
  686. :set (lambda (var val)
  687. (if (not (featurep 'ox)) (set-default var val)
  688. ;; Any back-end not required anymore (not present in VAL and not
  689. ;; a parent of any back-end in the new value) is removed from the
  690. ;; list of registered back-ends.
  691. (setq org-export-registered-backends
  692. (cl-remove-if-not
  693. (lambda (backend)
  694. (let ((name (org-export-backend-name backend)))
  695. (or (memq name val)
  696. (catch 'parentp
  697. (dolist (b val)
  698. (and (org-export-derived-backend-p b name)
  699. (throw 'parentp t)))))))
  700. org-export-registered-backends))
  701. ;; Now build NEW-LIST of both new back-ends and required
  702. ;; parents.
  703. (let ((new-list (mapcar #'org-export-backend-name
  704. org-export-registered-backends)))
  705. (dolist (backend val)
  706. (cond
  707. ((not (load (format "ox-%s" backend) t t))
  708. (message "Problems while trying to load export back-end `%s'"
  709. backend))
  710. ((not (memq backend new-list)) (push backend new-list))))
  711. ;; Set VAR to that list with fixed dependencies.
  712. (set-default var new-list))))
  713. :type '(set :greedy t
  714. (const :tag " ascii Export buffer to ASCII format" ascii)
  715. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  716. (const :tag " html Export buffer to HTML format" html)
  717. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  718. (const :tag " latex Export buffer to LaTeX format" latex)
  719. (const :tag " man Export buffer to MAN format" man)
  720. (const :tag " md Export buffer to Markdown format" md)
  721. (const :tag " odt Export buffer to ODT format" odt)
  722. (const :tag " org Export buffer to Org format" org)
  723. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  724. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  725. (const :tag "C deck Export buffer to deck.js presentations" deck)
  726. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  727. (const :tag "C groff Export buffer to Groff format" groff)
  728. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  729. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  730. (const :tag "C s5 Export buffer to s5 presentations" s5)
  731. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  732. (eval-after-load 'ox
  733. '(dolist (backend org-export-backends)
  734. (condition-case nil (require (intern (format "ox-%s" backend)))
  735. (error (message "Problems while trying to load export back-end `%s'"
  736. backend)))))
  737. (defcustom org-support-shift-select nil
  738. "Non-nil means make shift-cursor commands select text when possible.
  739. \\<org-mode-map>\
  740. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  741. start selecting a region, or enlarge regions started in this way.
  742. In Org mode, in special contexts, these same keys are used for
  743. other purposes, important enough to compete with shift selection.
  744. Org tries to balance these needs by supporting `shift-select-mode'
  745. outside these special contexts, under control of this variable.
  746. The default of this variable is nil, to avoid confusing behavior. Shifted
  747. cursor keys will then execute Org commands in the following contexts:
  748. - on a headline, changing TODO state (left/right) and priority (up/down)
  749. - on a time stamp, changing the time
  750. - in a plain list item, changing the bullet type
  751. - in a property definition line, switching between allowed values
  752. - in the BEGIN line of a clock table (changing the time block).
  753. Outside these contexts, the commands will throw an error.
  754. When this variable is t and the cursor is not in a special
  755. context, Org mode will support shift-selection for making and
  756. enlarging regions. To make this more effective, the bullet
  757. cycling will no longer happen anywhere in an item line, but only
  758. if the cursor is exactly on the bullet.
  759. If you set this variable to the symbol `always', then the keys
  760. will not be special in headlines, property lines, and item lines,
  761. to make shift selection work there as well. If this is what you
  762. want, you can use the following alternative commands:
  763. `\\[org-todo]' and `\\[org-priority]' \
  764. to change TODO state and priority,
  765. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  766. can be used to switch TODO sets,
  767. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  768. and properties can be edited by hand or in column view.
  769. However, when the cursor is on a timestamp, shift-cursor commands
  770. will still edit the time stamp - this is just too good to give up."
  771. :group 'org
  772. :type '(choice
  773. (const :tag "Never" nil)
  774. (const :tag "When outside special context" t)
  775. (const :tag "Everywhere except timestamps" always)))
  776. (defcustom org-loop-over-headlines-in-active-region nil
  777. "Shall some commands act upon headlines in the active region?
  778. When set to t, some commands will be performed in all headlines
  779. within the active region.
  780. When set to `start-level', some commands will be performed in all
  781. headlines within the active region, provided that these headlines
  782. are of the same level than the first one.
  783. When set to a string, those commands will be performed on the
  784. matching headlines within the active region. Such string must be
  785. a tags/property/todo match as it is used in the agenda tags view.
  786. The list of commands is: `org-schedule', `org-deadline',
  787. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  788. `org-archive-to-archive-sibling'. The archiving commands skip
  789. already archived entries."
  790. :type '(choice (const :tag "Don't loop" nil)
  791. (const :tag "All headlines in active region" t)
  792. (const :tag "In active region, headlines at the same level than the first one" start-level)
  793. (string :tag "Tags/Property/Todo matcher"))
  794. :version "24.1"
  795. :group 'org-todo
  796. :group 'org-archive)
  797. (defgroup org-startup nil
  798. "Options concerning startup of Org mode."
  799. :tag "Org Startup"
  800. :group 'org)
  801. (defcustom org-startup-folded t
  802. "Non-nil means entering Org mode will switch to OVERVIEW.
  803. This can also be configured on a per-file basis by adding one of
  804. the following lines anywhere in the buffer:
  805. #+STARTUP: fold (or `overview', this is equivalent)
  806. #+STARTUP: nofold (or `showall', this is equivalent)
  807. #+STARTUP: content
  808. #+STARTUP: showeverything
  809. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  810. to ignore this option when Org opens agenda files for the first
  811. time."
  812. :group 'org-startup
  813. :type '(choice
  814. (const :tag "nofold: show all" nil)
  815. (const :tag "fold: overview" t)
  816. (const :tag "content: all headlines" content)
  817. (const :tag "show everything, even drawers" showeverything)))
  818. (defcustom org-startup-truncated t
  819. "Non-nil means entering Org mode will set `truncate-lines'.
  820. This is useful since some lines containing links can be very long and
  821. uninteresting. Also tables look terrible when wrapped.
  822. The variable `org-startup-truncated' allows to configure
  823. truncation for Org mode different to the other modes that use the
  824. variable `truncate-lines' and as a shortcut instead of putting
  825. the variable `truncate-lines' into the `org-mode-hook'. If one
  826. wants to configure truncation for Org mode not statically but
  827. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  828. the variable `truncate-lines' has to be used because in such a
  829. case it is too late to set the variable `org-startup-truncated'."
  830. :group 'org-startup
  831. :type 'boolean)
  832. (defcustom org-startup-indented nil
  833. "Non-nil means turn on `org-indent-mode' on startup.
  834. This can also be configured on a per-file basis by adding one of
  835. the following lines anywhere in the buffer:
  836. #+STARTUP: indent
  837. #+STARTUP: noindent"
  838. :group 'org-structure
  839. :type '(choice
  840. (const :tag "Not" nil)
  841. (const :tag "Globally (slow on startup in large files)" t)))
  842. (defcustom org-use-sub-superscripts t
  843. "Non-nil means interpret \"_\" and \"^\" for display.
  844. If you want to control how Org exports those characters, see
  845. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  846. used to be an alias for `org-export-with-sub-superscripts' in
  847. Org <8.0, it is not anymore.
  848. When this option is turned on, you can use TeX-like syntax for
  849. sub- and superscripts within the buffer. Several characters after
  850. \"_\" or \"^\" will be considered as a single item - so grouping
  851. with {} is normally not needed. For example, the following things
  852. will be parsed as single sub- or superscripts:
  853. 10^24 or 10^tau several digits will be considered 1 item.
  854. 10^-12 or 10^-tau a leading sign with digits or a word
  855. x^2-y^3 will be read as x^2 - y^3, because items are
  856. terminated by almost any nonword/nondigit char.
  857. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  858. Still, ambiguity is possible. So when in doubt, use {} to enclose
  859. the sub/superscript. If you set this variable to the symbol `{}',
  860. the braces are *required* in order to trigger interpretations as
  861. sub/superscript. This can be helpful in documents that need \"_\"
  862. frequently in plain text."
  863. :group 'org-startup
  864. :version "24.4"
  865. :package-version '(Org . "8.0")
  866. :type '(choice
  867. (const :tag "Always interpret" t)
  868. (const :tag "Only with braces" {})
  869. (const :tag "Never interpret" nil)))
  870. (defcustom org-startup-with-beamer-mode nil
  871. "Non-nil means turn on `org-beamer-mode' on startup.
  872. This can also be configured on a per-file basis by adding one of
  873. the following lines anywhere in the buffer:
  874. #+STARTUP: beamer"
  875. :group 'org-startup
  876. :version "24.1"
  877. :type 'boolean)
  878. (defcustom org-startup-align-all-tables nil
  879. "Non-nil means align all tables when visiting a file.
  880. This is useful when the column width in tables is forced with <N> cookies
  881. in table fields. Such tables will look correct only after the first re-align.
  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: align
  885. #+STARTUP: noalign"
  886. :group 'org-startup
  887. :type 'boolean)
  888. (defcustom org-startup-with-inline-images nil
  889. "Non-nil means show inline images when loading a new Org file.
  890. This can also be configured on a per-file basis by adding one of
  891. the following lines anywhere in the buffer:
  892. #+STARTUP: inlineimages
  893. #+STARTUP: noinlineimages"
  894. :group 'org-startup
  895. :version "24.1"
  896. :type 'boolean)
  897. (defcustom org-startup-with-latex-preview nil
  898. "Non-nil means preview LaTeX fragments when loading a new Org file.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: latexpreview
  902. #+STARTUP: nolatexpreview"
  903. :group 'org-startup
  904. :version "24.4"
  905. :package-version '(Org . "8.0")
  906. :type 'boolean)
  907. (defcustom org-insert-mode-line-in-empty-file nil
  908. "Non-nil means insert the first line setting Org mode in empty files.
  909. When the function `org-mode' is called interactively in an empty file, this
  910. normally means that the file name does not automatically trigger Org mode.
  911. To ensure that the file will always be in Org mode in the future, a
  912. line enforcing Org mode will be inserted into the buffer, if this option
  913. has been set."
  914. :group 'org-startup
  915. :type 'boolean)
  916. (defcustom org-replace-disputed-keys nil
  917. "Non-nil means use alternative key bindings for some keys.
  918. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  919. These keys are also used by other packages like shift-selection-mode'
  920. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  921. If you want to use Org mode together with one of these other modes,
  922. or more generally if you would like to move some Org mode commands to
  923. other keys, set this variable and configure the keys with the variable
  924. `org-disputed-keys'.
  925. This option is only relevant at load-time of Org mode, and must be set
  926. *before* org.el is loaded. Changing it requires a restart of Emacs to
  927. become effective."
  928. :group 'org-startup
  929. :type 'boolean)
  930. (defcustom org-use-extra-keys nil
  931. "Non-nil means use extra key sequence definitions for certain commands.
  932. This happens automatically if `window-system' is nil. This
  933. variable lets you do the same manually. You must set it before
  934. loading Org."
  935. :group 'org-startup
  936. :type 'boolean)
  937. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  938. (defcustom org-disputed-keys
  939. '(([(shift up)] . [(meta p)])
  940. ([(shift down)] . [(meta n)])
  941. ([(shift left)] . [(meta -)])
  942. ([(shift right)] . [(meta +)])
  943. ([(control shift right)] . [(meta shift +)])
  944. ([(control shift left)] . [(meta shift -)]))
  945. "Keys for which Org mode and other modes compete.
  946. This is an alist, cars are the default keys, second element specifies
  947. the alternative to use when `org-replace-disputed-keys' is t.
  948. Keys can be specified in any syntax supported by `define-key'.
  949. The value of this option takes effect only at Org mode startup,
  950. therefore you'll have to restart Emacs to apply it after changing."
  951. :group 'org-startup
  952. :type 'alist)
  953. (defun org-key (key)
  954. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  955. Or return the original if not disputed."
  956. (when org-replace-disputed-keys
  957. (let* ((nkey (key-description key))
  958. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  959. org-disputed-keys)))
  960. (setq key (if x (cdr x) key))))
  961. key)
  962. (defun org-defkey (keymap key def)
  963. "Define a key, possibly translated, as returned by `org-key'."
  964. (define-key keymap (org-key key) def))
  965. (defcustom org-ellipsis nil
  966. "The ellipsis to use in the Org mode outline.
  967. When nil, just use the standard three dots. When a non-empty string,
  968. use that string instead.
  969. The change affects only Org mode (which will then use its own display table).
  970. Changing this requires executing `\\[org-mode]' in a buffer to become
  971. effective."
  972. :group 'org-startup
  973. :type '(choice (const :tag "Default" nil)
  974. (string :tag "String" :value "...#"))
  975. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  976. (defvar org-display-table nil
  977. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  978. (defgroup org-keywords nil
  979. "Keywords in Org mode."
  980. :tag "Org Keywords"
  981. :group 'org)
  982. (defcustom org-closed-keep-when-no-todo nil
  983. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  984. :group 'org-todo
  985. :group 'org-keywords
  986. :version "24.4"
  987. :package-version '(Org . "8.0")
  988. :type 'boolean)
  989. (defgroup org-structure nil
  990. "Options concerning the general structure of Org files."
  991. :tag "Org Structure"
  992. :group 'org)
  993. (defgroup org-reveal-location nil
  994. "Options about how to make context of a location visible."
  995. :tag "Org Reveal Location"
  996. :group 'org-structure)
  997. (defcustom org-show-context-detail '((agenda . local)
  998. (bookmark-jump . lineage)
  999. (isearch . lineage)
  1000. (default . ancestors))
  1001. "Alist between context and visibility span when revealing a location.
  1002. \\<org-mode-map>Some actions may move point into invisible
  1003. locations. As a consequence, Org always expose a neighborhood
  1004. around point. How much is shown depends on the initial action,
  1005. or context. Valid contexts are
  1006. agenda when exposing an entry from the agenda
  1007. org-goto when using the command `org-goto' (`\\[org-goto]')
  1008. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1009. tags-tree when constructing a sparse tree based on tags matches
  1010. link-search when exposing search matches associated with a link
  1011. mark-goto when exposing the jump goal of a mark
  1012. bookmark-jump when exposing a bookmark location
  1013. isearch when exiting from an incremental search
  1014. default default for all contexts not set explicitly
  1015. Allowed visibility spans are
  1016. minimal show current headline; if point is not on headline,
  1017. also show entry
  1018. local show current headline, entry and next headline
  1019. ancestors show current headline and its direct ancestors; if
  1020. point is not on headline, also show entry
  1021. lineage show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and first child
  1024. tree show current headline, its direct ancestors and all
  1025. their children; if point is not on headline, also show
  1026. entry and all children
  1027. canonical show current headline, its direct ancestors along with
  1028. their entries and children; if point is not located on
  1029. the headline, also show current entry and all children
  1030. As special cases, a nil or t value means show all contexts in
  1031. `minimal' or `canonical' view, respectively.
  1032. Some views can make displayed information very compact, but also
  1033. make it harder to edit the location of the match. In such
  1034. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1035. more context."
  1036. :group 'org-reveal-location
  1037. :version "26.1"
  1038. :package-version '(Org . "9.0")
  1039. :type '(choice
  1040. (const :tag "Canonical" t)
  1041. (const :tag "Minimal" nil)
  1042. (repeat :greedy t :tag "Individual contexts"
  1043. (cons
  1044. (choice :tag "Context"
  1045. (const agenda)
  1046. (const org-goto)
  1047. (const occur-tree)
  1048. (const tags-tree)
  1049. (const link-search)
  1050. (const mark-goto)
  1051. (const bookmark-jump)
  1052. (const isearch)
  1053. (const default))
  1054. (choice :tag "Detail level"
  1055. (const minimal)
  1056. (const local)
  1057. (const ancestors)
  1058. (const lineage)
  1059. (const tree)
  1060. (const canonical))))))
  1061. (defcustom org-indirect-buffer-display 'other-window
  1062. "How should indirect tree buffers be displayed?
  1063. This applies to indirect buffers created with the commands
  1064. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1065. Valid values are:
  1066. current-window Display in the current window
  1067. other-window Just display in another window.
  1068. dedicated-frame Create one new frame, and re-use it each time.
  1069. new-frame Make a new frame each time. Note that in this case
  1070. previously-made indirect buffers are kept, and you need to
  1071. kill these buffers yourself."
  1072. :group 'org-structure
  1073. :group 'org-agenda-windows
  1074. :type '(choice
  1075. (const :tag "In current window" current-window)
  1076. (const :tag "In current frame, other window" other-window)
  1077. (const :tag "Each time a new frame" new-frame)
  1078. (const :tag "One dedicated frame" dedicated-frame)))
  1079. (defcustom org-use-speed-commands nil
  1080. "Non-nil means activate single letter commands at beginning of a headline.
  1081. This may also be a function to test for appropriate locations where speed
  1082. commands should be active.
  1083. For example, to activate speed commands when the point is on any
  1084. star at the beginning of the headline, you can do this:
  1085. (setq org-use-speed-commands
  1086. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1087. :group 'org-structure
  1088. :type '(choice
  1089. (const :tag "Never" nil)
  1090. (const :tag "At beginning of headline stars" t)
  1091. (function)))
  1092. (defcustom org-speed-commands-user nil
  1093. "Alist of additional speed commands.
  1094. This list will be checked before `org-speed-commands-default'
  1095. when the variable `org-use-speed-commands' is non-nil
  1096. and when the cursor is at the beginning of a headline.
  1097. The car if each entry is a string with a single letter, which must
  1098. be assigned to `self-insert-command' in the global map.
  1099. The cdr is either a command to be called interactively, a function
  1100. to be called, or a form to be evaluated.
  1101. An entry that is just a list with a single string will be interpreted
  1102. as a descriptive headline that will be added when listing the speed
  1103. commands in the Help buffer using the `?' speed command."
  1104. :group 'org-structure
  1105. :type '(repeat :value ("k" . ignore)
  1106. (choice :value ("k" . ignore)
  1107. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1108. (cons :tag "Letter and Command"
  1109. (string :tag "Command letter")
  1110. (choice
  1111. (function)
  1112. (sexp))))))
  1113. (defcustom org-bookmark-names-plist
  1114. '(:last-capture "org-capture-last-stored"
  1115. :last-refile "org-refile-last-stored"
  1116. :last-capture-marker "org-capture-last-stored-marker")
  1117. "Names for bookmarks automatically set by some Org commands.
  1118. This can provide strings as names for a number of bookmarks Org sets
  1119. automatically. The following keys are currently implemented:
  1120. :last-capture
  1121. :last-capture-marker
  1122. :last-refile
  1123. When a key does not show up in the property list, the corresponding bookmark
  1124. is not set."
  1125. :group 'org-structure
  1126. :type 'plist)
  1127. (defgroup org-cycle nil
  1128. "Options concerning visibility cycling in Org mode."
  1129. :tag "Org Cycle"
  1130. :group 'org-structure)
  1131. (defcustom org-cycle-skip-children-state-if-no-children t
  1132. "Non-nil means skip CHILDREN state in entries that don't have any."
  1133. :group 'org-cycle
  1134. :type 'boolean)
  1135. (defcustom org-cycle-max-level nil
  1136. "Maximum level which should still be subject to visibility cycling.
  1137. Levels higher than this will, for cycling, be treated as text, not a headline.
  1138. When `org-odd-levels-only' is set, a value of N in this variable actually
  1139. means 2N-1 stars as the limiting headline.
  1140. When nil, cycle all levels.
  1141. Note that the limiting level of cycling is also influenced by
  1142. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1143. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1144. than its value."
  1145. :group 'org-cycle
  1146. :type '(choice
  1147. (const :tag "No limit" nil)
  1148. (integer :tag "Maximum level")))
  1149. (defcustom org-hide-block-startup nil
  1150. "Non-nil means entering Org mode will fold all blocks.
  1151. This can also be set in on a per-file basis with
  1152. #+STARTUP: hideblocks
  1153. #+STARTUP: showblocks"
  1154. :group 'org-startup
  1155. :group 'org-cycle
  1156. :type 'boolean)
  1157. (defcustom org-cycle-global-at-bob nil
  1158. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1159. This makes it possible to do global cycling without having to use `S-TAB'
  1160. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1161. line of the buffer
  1162. must not be a headline -- it may be empty or some other text.
  1163. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1164. sure the cursor stays at the beginning of the buffer.
  1165. When this option is nil, don't do anything special at the beginning of
  1166. the buffer."
  1167. :group 'org-cycle
  1168. :type 'boolean)
  1169. (defcustom org-cycle-level-after-item/entry-creation t
  1170. "Non-nil means cycle entry level or item indentation in new empty entries.
  1171. When the cursor is at the end of an empty headline, i.e., with only stars
  1172. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1173. and then all possible ancestor states, before returning to the original state.
  1174. This makes data entry extremely fast: M-RET to create a new headline,
  1175. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1176. When the cursor is at the end of an empty plain list item, one TAB will
  1177. make it a subitem, two or more tabs will back up to make this an item
  1178. higher up in the item hierarchy."
  1179. :group 'org-cycle
  1180. :type 'boolean)
  1181. (defcustom org-cycle-emulate-tab t
  1182. "Where should `org-cycle' emulate TAB.
  1183. nil Never
  1184. white Only in completely white lines
  1185. whitestart Only at the beginning of lines, before the first non-white char
  1186. t Everywhere except in headlines
  1187. exc-hl-bol Everywhere except at the start of a headline
  1188. If TAB is used in a place where it does not emulate TAB, the current subtree
  1189. visibility is cycled."
  1190. :group 'org-cycle
  1191. :type '(choice (const :tag "Never" nil)
  1192. (const :tag "Only in completely white lines" white)
  1193. (const :tag "Before first char in a line" whitestart)
  1194. (const :tag "Everywhere except in headlines" t)
  1195. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1196. (defcustom org-cycle-separator-lines 2
  1197. "Number of empty lines needed to keep an empty line between collapsed trees.
  1198. If you leave an empty line between the end of a subtree and the following
  1199. headline, this empty line is hidden when the subtree is folded.
  1200. Org mode will leave (exactly) one empty line visible if the number of
  1201. empty lines is equal or larger to the number given in this variable.
  1202. So the default 2 means at least 2 empty lines after the end of a subtree
  1203. are needed to produce free space between a collapsed subtree and the
  1204. following headline.
  1205. If the number is negative, and the number of empty lines is at least -N,
  1206. all empty lines are shown.
  1207. Special case: when 0, never leave empty lines in collapsed view."
  1208. :group 'org-cycle
  1209. :type 'integer)
  1210. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1211. (defcustom org-pre-cycle-hook nil
  1212. "Hook that is run before visibility cycling is happening.
  1213. The function(s) in this hook must accept a single argument which indicates
  1214. the new state that will be set right after running this hook. The
  1215. argument is a symbol. Before a global state change, it can have the values
  1216. `overview', `content', or `all'. Before a local state change, it can have
  1217. the values `folded', `children', or `subtree'."
  1218. :group 'org-cycle
  1219. :type 'hook)
  1220. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1221. org-cycle-hide-drawers
  1222. org-cycle-show-empty-lines
  1223. org-optimize-window-after-visibility-change)
  1224. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1225. The function(s) in this hook must accept a single argument which indicates
  1226. the new state that was set by the most recent `org-cycle' command. The
  1227. argument is a symbol. After a global state change, it can have the values
  1228. `overview', `contents', or `all'. After a local state change, it can have
  1229. the values `folded', `children', or `subtree'."
  1230. :group 'org-cycle
  1231. :type 'hook
  1232. :version "26.1"
  1233. :package-version '(Org . "8.3"))
  1234. (defgroup org-edit-structure nil
  1235. "Options concerning structure editing in Org mode."
  1236. :tag "Org Edit Structure"
  1237. :group 'org-structure)
  1238. (defcustom org-odd-levels-only nil
  1239. "Non-nil means skip even levels and only use odd levels for the outline.
  1240. This has the effect that two stars are being added/taken away in
  1241. promotion/demotion commands. It also influences how levels are
  1242. handled by the exporters.
  1243. Changing it requires restart of `font-lock-mode' to become effective
  1244. for fontification also in regions already fontified.
  1245. You may also set this on a per-file basis by adding one of the following
  1246. lines to the buffer:
  1247. #+STARTUP: odd
  1248. #+STARTUP: oddeven"
  1249. :group 'org-edit-structure
  1250. :group 'org-appearance
  1251. :type 'boolean)
  1252. (defcustom org-adapt-indentation t
  1253. "Non-nil means adapt indentation to outline node level.
  1254. When this variable is set, Org assumes that you write outlines by
  1255. indenting text in each node to align with the headline (after the
  1256. stars). The following issues are influenced by this variable:
  1257. - The indentation is increased by one space in a demotion
  1258. command, and decreased by one in a promotion command. However,
  1259. in the latter case, if shifting some line in the entry body
  1260. would alter document structure (e.g., insert a new headline),
  1261. indentation is not changed at all.
  1262. - Property drawers and planning information is inserted indented
  1263. when this variable is set. When nil, they will not be indented.
  1264. - TAB indents a line relative to current level. The lines below
  1265. a headline will be indented when this variable is set.
  1266. Note that this is all about true indentation, by adding and
  1267. removing space characters. See also `org-indent.el' which does
  1268. level-dependent indentation in a virtual way, i.e. at display
  1269. time in Emacs."
  1270. :group 'org-edit-structure
  1271. :type 'boolean)
  1272. (defcustom org-special-ctrl-a/e nil
  1273. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1274. When t, `C-a' will bring back the cursor to the beginning of the
  1275. headline text, i.e. after the stars and after a possible TODO
  1276. keyword. In an item, this will be the position after bullet and
  1277. check-box, if any. When the cursor is already at that position,
  1278. another `C-a' will bring it to the beginning of the line.
  1279. `C-e' will jump to the end of the headline, ignoring the presence
  1280. of tags in the headline. A second `C-e' will then jump to the
  1281. true end of the line, after any tags. This also means that, when
  1282. this variable is non-nil, `C-e' also will never jump beyond the
  1283. end of the heading of a folded section, i.e. not after the
  1284. ellipses.
  1285. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1286. normally, going to the true line boundary first. Only a directly
  1287. following, identical keypress will bring the cursor to the
  1288. special positions.
  1289. This may also be a cons cell where the behavior for `C-a' and
  1290. `C-e' is set separately."
  1291. :group 'org-edit-structure
  1292. :type '(choice
  1293. (const :tag "off" nil)
  1294. (const :tag "on: after stars/bullet and before tags first" t)
  1295. (const :tag "reversed: true line boundary first" reversed)
  1296. (cons :tag "Set C-a and C-e separately"
  1297. (choice :tag "Special C-a"
  1298. (const :tag "off" nil)
  1299. (const :tag "on: after stars/bullet first" t)
  1300. (const :tag "reversed: before stars/bullet first" reversed))
  1301. (choice :tag "Special C-e"
  1302. (const :tag "off" nil)
  1303. (const :tag "on: before tags first" t)
  1304. (const :tag "reversed: after tags first" reversed)))))
  1305. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1306. (defcustom org-special-ctrl-k nil
  1307. "Non-nil means `C-k' will behave specially in headlines.
  1308. When nil, `C-k' will call the default `kill-line' command.
  1309. When t, the following will happen while the cursor is in the headline:
  1310. - When the cursor is at the beginning of a headline, kill the entire
  1311. line and possible the folded subtree below the line.
  1312. - When in the middle of the headline text, kill the headline up to the tags.
  1313. - When after the headline text, kill the tags."
  1314. :group 'org-edit-structure
  1315. :type 'boolean)
  1316. (defcustom org-ctrl-k-protect-subtree nil
  1317. "Non-nil means, do not delete a hidden subtree with C-k.
  1318. When set to the symbol `error', simply throw an error when C-k is
  1319. used to kill (part-of) a headline that has hidden text behind it.
  1320. Any other non-nil value will result in a query to the user, if it is
  1321. OK to kill that hidden subtree. When nil, kill without remorse."
  1322. :group 'org-edit-structure
  1323. :version "24.1"
  1324. :type '(choice
  1325. (const :tag "Do not protect hidden subtrees" nil)
  1326. (const :tag "Protect hidden subtrees with a security query" t)
  1327. (const :tag "Never kill a hidden subtree with C-k" error)))
  1328. (defcustom org-special-ctrl-o t
  1329. "Non-nil means, make `C-o' insert a row in tables."
  1330. :group 'org-edit-structure
  1331. :type 'boolean)
  1332. (defcustom org-catch-invisible-edits nil
  1333. "Check if in invisible region before inserting or deleting a character.
  1334. Valid values are:
  1335. nil Do not check, so just do invisible edits.
  1336. error Throw an error and do nothing.
  1337. show Make point visible, and do the requested edit.
  1338. show-and-error Make point visible, then throw an error and abort the edit.
  1339. smart Make point visible, and do insertion/deletion if it is
  1340. adjacent to visible text and the change feels predictable.
  1341. Never delete a previously invisible character or add in the
  1342. middle or right after an invisible region. Basically, this
  1343. allows insertion and backward-delete right before ellipses.
  1344. FIXME: maybe in this case we should not even show?"
  1345. :group 'org-edit-structure
  1346. :version "24.1"
  1347. :type '(choice
  1348. (const :tag "Do not check" nil)
  1349. (const :tag "Throw error when trying to edit" error)
  1350. (const :tag "Unhide, but do not do the edit" show-and-error)
  1351. (const :tag "Show invisible part and do the edit" show)
  1352. (const :tag "Be smart and do the right thing" smart)))
  1353. (defcustom org-yank-folded-subtrees t
  1354. "Non-nil means when yanking subtrees, fold them.
  1355. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1356. it starts with a heading and all other headings in it are either children
  1357. or siblings, then fold all the subtrees. However, do this only if no
  1358. text after the yank would be swallowed into a folded tree by this action."
  1359. :group 'org-edit-structure
  1360. :type 'boolean)
  1361. (defcustom org-yank-adjusted-subtrees nil
  1362. "Non-nil means when yanking subtrees, adjust the level.
  1363. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1364. this function for details."
  1365. :group 'org-edit-structure
  1366. :type 'boolean)
  1367. (defcustom org-M-RET-may-split-line '((default . t))
  1368. "Non-nil means M-RET will split the line at the cursor position.
  1369. When nil, it will go to the end of the line before making a
  1370. new line.
  1371. You may also set this option in a different way for different
  1372. contexts. Valid contexts are:
  1373. headline when creating a new headline
  1374. item when creating a new item
  1375. table in a table field
  1376. default the value to be used for all contexts not explicitly
  1377. customized"
  1378. :group 'org-structure
  1379. :group 'org-table
  1380. :type '(choice
  1381. (const :tag "Always" t)
  1382. (const :tag "Never" nil)
  1383. (repeat :greedy t :tag "Individual contexts"
  1384. (cons
  1385. (choice :tag "Context"
  1386. (const headline)
  1387. (const item)
  1388. (const table)
  1389. (const default))
  1390. (boolean)))))
  1391. (defcustom org-insert-heading-respect-content nil
  1392. "Non-nil means insert new headings after the current subtree.
  1393. \\<org-mode-map>
  1394. When nil, the new heading is created directly after the current line.
  1395. The commands `\\[org-insert-heading-respect-content]' and \
  1396. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1397. for the duration of the command."
  1398. :group 'org-structure
  1399. :type 'boolean)
  1400. (defcustom org-blank-before-new-entry '((heading . auto)
  1401. (plain-list-item . auto))
  1402. "Should `org-insert-heading' leave a blank line before new heading/item?
  1403. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1404. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1405. which case Org will look at the surrounding headings/items and try to
  1406. make an intelligent decision whether to insert a blank line or not."
  1407. :group 'org-edit-structure
  1408. :type '(list
  1409. (cons (const heading)
  1410. (choice (const :tag "Never" nil)
  1411. (const :tag "Always" t)
  1412. (const :tag "Auto" auto)))
  1413. (cons (const plain-list-item)
  1414. (choice (const :tag "Never" nil)
  1415. (const :tag "Always" t)
  1416. (const :tag "Auto" auto)))))
  1417. (defcustom org-insert-heading-hook nil
  1418. "Hook being run after inserting a new heading."
  1419. :group 'org-edit-structure
  1420. :type 'hook)
  1421. (defcustom org-enable-fixed-width-editor t
  1422. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1423. This currently only means they are never auto-wrapped.
  1424. When nil, such lines will be treated like ordinary lines."
  1425. :group 'org-edit-structure
  1426. :type 'boolean)
  1427. (defcustom org-goto-auto-isearch t
  1428. "Non-nil means typing characters in `org-goto' starts incremental search.
  1429. When nil, you can use these keybindings to navigate the buffer:
  1430. q Quit the org-goto interface
  1431. n Go to the next visible heading
  1432. p Go to the previous visible heading
  1433. f Go one heading forward on same level
  1434. b Go one heading backward on same level
  1435. u Go one heading up"
  1436. :group 'org-edit-structure
  1437. :type 'boolean)
  1438. (defgroup org-sparse-trees nil
  1439. "Options concerning sparse trees in Org mode."
  1440. :tag "Org Sparse Trees"
  1441. :group 'org-structure)
  1442. (defcustom org-highlight-sparse-tree-matches t
  1443. "Non-nil means highlight all matches that define a sparse tree.
  1444. The highlights will automatically disappear the next time the buffer is
  1445. changed by an edit command."
  1446. :group 'org-sparse-trees
  1447. :type 'boolean)
  1448. (defcustom org-remove-highlights-with-change t
  1449. "Non-nil means any change to the buffer will remove temporary highlights.
  1450. \\<org-mode-map>\
  1451. Such highlights are created by `org-occur' and `org-clock-display'.
  1452. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1453. to get rid of the highlights.
  1454. The highlights created by `org-toggle-latex-fragment' always need
  1455. `\\[org-toggle-latex-fragment]' to be removed."
  1456. :group 'org-sparse-trees
  1457. :group 'org-time
  1458. :type 'boolean)
  1459. (defcustom org-occur-case-fold-search t
  1460. "Non-nil means `org-occur' should be case-insensitive.
  1461. If set to `smart' the search will be case-insensitive only if it
  1462. doesn't specify any upper case character."
  1463. :group 'org-sparse-trees
  1464. :version "26.1"
  1465. :type '(choice
  1466. (const :tag "Case-sensitive" nil)
  1467. (const :tag "Case-insensitive" t)
  1468. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1469. (defcustom org-occur-hook '(org-first-headline-recenter)
  1470. "Hook that is run after `org-occur' has constructed a sparse tree.
  1471. This can be used to recenter the window to show as much of the structure
  1472. as possible."
  1473. :group 'org-sparse-trees
  1474. :type 'hook)
  1475. (defgroup org-imenu-and-speedbar nil
  1476. "Options concerning imenu and speedbar in Org mode."
  1477. :tag "Org Imenu and Speedbar"
  1478. :group 'org-structure)
  1479. (defcustom org-imenu-depth 2
  1480. "The maximum level for Imenu access to Org headlines.
  1481. This also applied for speedbar access."
  1482. :group 'org-imenu-and-speedbar
  1483. :type 'integer)
  1484. (defgroup org-table nil
  1485. "Options concerning tables in Org mode."
  1486. :tag "Org Table"
  1487. :group 'org)
  1488. (defcustom org-enable-table-editor 'optimized
  1489. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1490. When nil, such lines will be treated like ordinary lines.
  1491. When equal to the symbol `optimized', the table editor will be optimized to
  1492. do the following:
  1493. - Automatic overwrite mode in front of whitespace in table fields.
  1494. This makes the structure of the table stay in tact as long as the edited
  1495. field does not exceed the column width.
  1496. - Minimize the number of realigns. Normally, the table is aligned each time
  1497. TAB or RET are pressed to move to another field. With optimization this
  1498. happens only if changes to a field might have changed the column width.
  1499. Optimization requires replacing the functions `self-insert-command',
  1500. `delete-char', and `backward-delete-char' in Org buffers, with a
  1501. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1502. good at guessing when a re-align will be necessary, but you can always
  1503. force one with `\\[org-ctrl-c-ctrl-c]'.
  1504. If you would like to use the optimized version in Org mode, but the
  1505. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1506. This variable can be used to turn on and off the table editor during a session,
  1507. but in order to toggle optimization, a restart is required.
  1508. See also the variable `org-table-auto-blank-field'."
  1509. :group 'org-table
  1510. :type '(choice
  1511. (const :tag "off" nil)
  1512. (const :tag "on" t)
  1513. (const :tag "on, optimized" optimized)))
  1514. (defcustom org-self-insert-cluster-for-undo nil
  1515. "Non-nil means cluster self-insert commands for undo when possible.
  1516. If this is set, then, like in the Emacs command loop, 20 consecutive
  1517. characters will be undone together.
  1518. This is configurable, because there is some impact on typing performance."
  1519. :group 'org-table
  1520. :type 'boolean)
  1521. (defcustom org-table-tab-recognizes-table.el t
  1522. "Non-nil means TAB will automatically notice a table.el table.
  1523. When it sees such a table, it moves point into it and - if necessary -
  1524. calls `table-recognize-table'."
  1525. :group 'org-table-editing
  1526. :type 'boolean)
  1527. (defgroup org-link nil
  1528. "Options concerning links in Org mode."
  1529. :tag "Org Link"
  1530. :group 'org)
  1531. (defvar-local org-link-abbrev-alist-local nil
  1532. "Buffer-local version of `org-link-abbrev-alist', which see.
  1533. The value of this is taken from the #+LINK lines.")
  1534. (defcustom org-link-parameters
  1535. '(("doi" :follow org--open-doi-link)
  1536. ("elisp" :follow org--open-elisp-link)
  1537. ("file" :complete org-file-complete-link)
  1538. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1539. ("help" :follow org--open-help-link)
  1540. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1541. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1542. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1543. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1544. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1545. ("shell" :follow org--open-shell-link))
  1546. "An alist of properties that defines all the links in Org mode.
  1547. The key in each association is a string of the link type.
  1548. Subsequent optional elements make up a p-list of link properties.
  1549. :follow - A function that takes the link path as an argument.
  1550. :export - A function that takes the link path, description and
  1551. export-backend as arguments.
  1552. :store - A function responsible for storing the link. See the
  1553. function `org-store-link-functions'.
  1554. :complete - A function that inserts a link with completion. The
  1555. function takes one optional prefix arg.
  1556. :face - A face for the link, or a function that returns a face.
  1557. The function takes one argument which is the link path. The
  1558. default face is `org-link'.
  1559. :mouse-face - The mouse-face. The default is `highlight'.
  1560. :display - `full' will not fold the link in descriptive
  1561. display. Default is `org-link'.
  1562. :help-echo - A string or function that takes (window object position)
  1563. as arguments and returns a string.
  1564. :keymap - A keymap that is active on the link. The default is
  1565. `org-mouse-map'.
  1566. :htmlize-link - A function for the htmlize-link. Defaults
  1567. to (list :uri \"type:path\")
  1568. :activate-func - A function to run at the end of font-lock
  1569. activation. The function must accept (link-start link-end path bracketp)
  1570. as arguments."
  1571. :group 'org-link
  1572. :type '(alist :tag "Link display parameters"
  1573. :value-type plist))
  1574. (defun org-link-get-parameter (type key)
  1575. "Get TYPE link property for KEY.
  1576. TYPE is a string and KEY is a plist keyword."
  1577. (plist-get
  1578. (cdr (assoc type org-link-parameters))
  1579. key))
  1580. (defun org-link-set-parameters (type &rest parameters)
  1581. "Set link TYPE properties to PARAMETERS.
  1582. PARAMETERS should be :key val pairs."
  1583. (let ((data (assoc type org-link-parameters)))
  1584. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1585. (push (cons type parameters) org-link-parameters)
  1586. (org-make-link-regexps)
  1587. (org-element-update-syntax))))
  1588. (defun org-link-types ()
  1589. "Return a list of known link types."
  1590. (mapcar #'car org-link-parameters))
  1591. (defcustom org-link-abbrev-alist nil
  1592. "Alist of link abbreviations.
  1593. The car of each element is a string, to be replaced at the start of a link.
  1594. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1595. links in Org buffers can have an optional tag after a double colon, e.g.,
  1596. [[linkkey:tag][description]]
  1597. The `linkkey' must be a single word, starting with a letter, followed
  1598. by letters, numbers, `-' or `_'.
  1599. If REPLACE is a string, the tag will simply be appended to create the link.
  1600. If the string contains \"%s\", the tag will be inserted there. If the string
  1601. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1602. at that point (see the function `url-hexify-string'). If the string contains
  1603. the specifier \"%(my-function)\", then the custom function `my-function' will
  1604. be invoked: this function takes the tag as its only argument and must return
  1605. a string.
  1606. REPLACE may also be a function that will be called with the tag as the
  1607. only argument to create the link, which should be returned as a string.
  1608. See the manual for examples."
  1609. :group 'org-link
  1610. :type '(repeat
  1611. (cons
  1612. (string :tag "Protocol")
  1613. (choice
  1614. (string :tag "Format")
  1615. (function)))))
  1616. (defcustom org-descriptive-links t
  1617. "Non-nil means Org will display descriptive links.
  1618. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1619. \"Org Website\", hiding the link itself and just displaying its
  1620. description. When set to nil, Org will display the full links
  1621. literally.
  1622. You can interactively set the value of this variable by calling
  1623. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1624. :group 'org-link
  1625. :type 'boolean)
  1626. (defcustom org-link-file-path-type 'adaptive
  1627. "How the path name in file links should be stored.
  1628. Valid values are:
  1629. relative Relative to the current directory, i.e. the directory of the file
  1630. into which the link is being inserted.
  1631. absolute Absolute path, if possible with ~ for home directory.
  1632. noabbrev Absolute path, no abbreviation of home directory.
  1633. adaptive Use relative path for files in the current directory and sub-
  1634. directories of it. For other files, use an absolute path."
  1635. :group 'org-link
  1636. :type '(choice
  1637. (const relative)
  1638. (const absolute)
  1639. (const noabbrev)
  1640. (const adaptive)))
  1641. (defvaralias 'org-activate-links 'org-highlight-links)
  1642. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1643. "Types of links that should be highlighted in Org files.
  1644. This is a list of symbols, each one of them leading to the
  1645. highlighting of a certain link type.
  1646. You can still open links that are not highlighted.
  1647. In principle, it does not hurt to turn on highlighting for all
  1648. link types. There may be a small gain when turning off unused
  1649. link types. The types are:
  1650. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1651. angle Links in angular brackets that may contain whitespace like
  1652. <bbdb:Carsten Dominik>.
  1653. plain Plain links in normal text, no whitespace, like http://google.com.
  1654. radio Text that is matched by a radio target, see manual for details.
  1655. tag Tag settings in a headline (link to tag search).
  1656. date Time stamps (link to calendar).
  1657. footnote Footnote labels.
  1658. If you set this variable during an Emacs session, use `org-mode-restart'
  1659. in the Org buffer so that the change takes effect."
  1660. :group 'org-link
  1661. :group 'org-appearance
  1662. :type '(set :greedy t
  1663. (const :tag "Double bracket links" bracket)
  1664. (const :tag "Angular bracket links" angle)
  1665. (const :tag "Plain text links" plain)
  1666. (const :tag "Radio target matches" radio)
  1667. (const :tag "Tags" tag)
  1668. (const :tag "Timestamps" date)
  1669. (const :tag "Footnotes" footnote)))
  1670. (defcustom org-make-link-description-function nil
  1671. "Function to use for generating link descriptions from links.
  1672. When nil, the link location will be used. This function must take
  1673. two parameters: the first one is the link, the second one is the
  1674. description generated by `org-insert-link'. The function should
  1675. return the description to use."
  1676. :group 'org-link
  1677. :type '(choice (const nil) (function)))
  1678. (defgroup org-link-store nil
  1679. "Options concerning storing links in Org mode."
  1680. :tag "Org Store Link"
  1681. :group 'org-link)
  1682. (defcustom org-url-hexify-p t
  1683. "When non-nil, hexify URL when creating a link."
  1684. :type 'boolean
  1685. :version "24.3"
  1686. :group 'org-link-store)
  1687. (defcustom org-email-link-description-format "Email %c: %.30s"
  1688. "Format of the description part of a link to an email or usenet message.
  1689. The following %-escapes will be replaced by corresponding information:
  1690. %F full \"From\" field
  1691. %f name, taken from \"From\" field, address if no name
  1692. %T full \"To\" field
  1693. %t first name in \"To\" field, address if no name
  1694. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1695. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1696. %s subject
  1697. %d date
  1698. %m message-id.
  1699. You may use normal field width specification between the % and the letter.
  1700. This is for example useful to limit the length of the subject.
  1701. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1702. :group 'org-link-store
  1703. :type 'string)
  1704. (defcustom org-from-is-user-regexp
  1705. (let (r1 r2)
  1706. (when (and user-mail-address (not (string= user-mail-address "")))
  1707. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1708. (when (and user-full-name (not (string= user-full-name "")))
  1709. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1710. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1711. "Regexp matched against the \"From:\" header of an email or usenet message.
  1712. It should match if the message is from the user him/herself."
  1713. :group 'org-link-store
  1714. :type 'regexp)
  1715. (defcustom org-context-in-file-links t
  1716. "Non-nil means file links from `org-store-link' contain context.
  1717. \\<org-mode-map>
  1718. A search string will be added to the file name with :: as separator
  1719. and used to find the context when the link is activated by the command
  1720. `org-open-at-point'. When this option is t, the entire active region
  1721. will be placed in the search string of the file link. If set to a
  1722. positive integer, only the first n lines of context will be stored.
  1723. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1724. \\[org-store-link]')
  1725. negates this setting for the duration of the command."
  1726. :group 'org-link-store
  1727. :type '(choice boolean integer))
  1728. (defcustom org-keep-stored-link-after-insertion nil
  1729. "Non-nil means keep link in list for entire session.
  1730. \\<org-mode-map>
  1731. The command `org-store-link' adds a link pointing to the current
  1732. location to an internal list. These links accumulate during a session.
  1733. The command `org-insert-link' can be used to insert links into any
  1734. Org file (offering completion for all stored links).
  1735. When this option is nil, every link which has been inserted once using
  1736. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1737. unused
  1738. links more efficient."
  1739. :group 'org-link-store
  1740. :type 'boolean)
  1741. (defgroup org-link-follow nil
  1742. "Options concerning following links in Org mode."
  1743. :tag "Org Follow Link"
  1744. :group 'org-link)
  1745. (defcustom org-link-translation-function nil
  1746. "Function to translate links with different syntax to Org syntax.
  1747. This can be used to translate links created for example by the Planner
  1748. or emacs-wiki packages to Org syntax.
  1749. The function must accept two parameters, a TYPE containing the link
  1750. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1751. which is everything after the link protocol. It should return a cons
  1752. with possibly modified values of type and path.
  1753. Org contains a function for this, so if you set this variable to
  1754. `org-translate-link-from-planner', you should be able follow many
  1755. links created by planner."
  1756. :group 'org-link-follow
  1757. :type '(choice (const nil) (function)))
  1758. (defcustom org-follow-link-hook nil
  1759. "Hook that is run after a link has been followed."
  1760. :group 'org-link-follow
  1761. :type 'hook)
  1762. (defcustom org-tab-follows-link nil
  1763. "Non-nil means on links TAB will follow the link.
  1764. Needs to be set before org.el is loaded.
  1765. This really should not be used, it does not make sense, and the
  1766. implementation is bad."
  1767. :group 'org-link-follow
  1768. :type 'boolean)
  1769. (defcustom org-return-follows-link nil
  1770. "Non-nil means on links RET will follow the link.
  1771. In tables, the special behavior of RET has precedence."
  1772. :group 'org-link-follow
  1773. :type 'boolean)
  1774. (defcustom org-mouse-1-follows-link
  1775. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1776. "Non-nil means mouse-1 on a link will follow the link.
  1777. A longer mouse click will still set point. Needs to be set
  1778. before org.el is loaded."
  1779. :group 'org-link-follow
  1780. :version "24.4"
  1781. :package-version '(Org . "8.3")
  1782. :type '(choice
  1783. (const :tag "A double click follows the link" double)
  1784. (const :tag "Unconditionally follow the link with mouse-1" t)
  1785. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1786. (defcustom org-mark-ring-length 4
  1787. "Number of different positions to be recorded in the ring.
  1788. Changing this requires a restart of Emacs to work correctly."
  1789. :group 'org-link-follow
  1790. :type 'integer)
  1791. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1792. "Non-nil means internal fuzzy links can only match headlines.
  1793. When nil, the a fuzzy link may point to a target or a named
  1794. construct in the document. When set to the special value
  1795. `query-to-create', offer to create a new headline when none
  1796. matched.
  1797. Spaces and statistics cookies are ignored during heading searches."
  1798. :group 'org-link-follow
  1799. :version "24.1"
  1800. :type '(choice
  1801. (const :tag "Use fuzzy text search" nil)
  1802. (const :tag "Match only exact headline" t)
  1803. (const :tag "Match exact headline or query to create it"
  1804. query-to-create))
  1805. :safe #'symbolp)
  1806. (defcustom org-link-frame-setup
  1807. '((vm . vm-visit-folder-other-frame)
  1808. (vm-imap . vm-visit-imap-folder-other-frame)
  1809. (gnus . org-gnus-no-new-news)
  1810. (file . find-file-other-window)
  1811. (wl . wl-other-frame))
  1812. "Setup the frame configuration for following links.
  1813. When following a link with Emacs, it may often be useful to display
  1814. this link in another window or frame. This variable can be used to
  1815. set this up for the different types of links.
  1816. For VM, use any of
  1817. `vm-visit-folder'
  1818. `vm-visit-folder-other-window'
  1819. `vm-visit-folder-other-frame'
  1820. For Gnus, use any of
  1821. `gnus'
  1822. `gnus-other-frame'
  1823. `org-gnus-no-new-news'
  1824. For FILE, use any of
  1825. `find-file'
  1826. `find-file-other-window'
  1827. `find-file-other-frame'
  1828. For Wanderlust use any of
  1829. `wl'
  1830. `wl-other-frame'
  1831. For the calendar, use the variable `calendar-setup'.
  1832. For BBDB, it is currently only possible to display the matches in
  1833. another window."
  1834. :group 'org-link-follow
  1835. :type '(list
  1836. (cons (const vm)
  1837. (choice
  1838. (const vm-visit-folder)
  1839. (const vm-visit-folder-other-window)
  1840. (const vm-visit-folder-other-frame)))
  1841. (cons (const vm-imap)
  1842. (choice
  1843. (const vm-visit-imap-folder)
  1844. (const vm-visit-imap-folder-other-window)
  1845. (const vm-visit-imap-folder-other-frame)))
  1846. (cons (const gnus)
  1847. (choice
  1848. (const gnus)
  1849. (const gnus-other-frame)
  1850. (const org-gnus-no-new-news)))
  1851. (cons (const file)
  1852. (choice
  1853. (const find-file)
  1854. (const find-file-other-window)
  1855. (const find-file-other-frame)))
  1856. (cons (const wl)
  1857. (choice
  1858. (const wl)
  1859. (const wl-other-frame)))))
  1860. (defcustom org-display-internal-link-with-indirect-buffer nil
  1861. "Non-nil means use indirect buffer to display infile links.
  1862. Activating internal links (from one location in a file to another location
  1863. in the same file) normally just jumps to the location. When the link is
  1864. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1865. is displayed in
  1866. another window. When this option is set, the other window actually displays
  1867. an indirect buffer clone of the current buffer, to avoid any visibility
  1868. changes to the current buffer."
  1869. :group 'org-link-follow
  1870. :type 'boolean)
  1871. (defcustom org-open-non-existing-files nil
  1872. "Non-nil means `org-open-file' will open non-existing files.
  1873. When nil, an error will be generated.
  1874. This variable applies only to external applications because they
  1875. might choke on non-existing files. If the link is to a file that
  1876. will be opened in Emacs, the variable is ignored."
  1877. :group 'org-link-follow
  1878. :type 'boolean)
  1879. (defcustom org-open-directory-means-index-dot-org nil
  1880. "Non-nil means a link to a directory really means to index.org.
  1881. When nil, following a directory link will run dired or open a finder/explorer
  1882. window on that directory."
  1883. :group 'org-link-follow
  1884. :type 'boolean)
  1885. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1886. "Non-nil means ask for confirmation before executing shell links.
  1887. Shell links can be dangerous: just think about a link
  1888. [[shell:rm -rf ~/*][Google Search]]
  1889. This link would show up in your Org document as \"Google Search\",
  1890. but really it would remove your entire home directory.
  1891. Therefore we advise against setting this variable to nil.
  1892. Just change it to `y-or-n-p' if you want to confirm with a
  1893. single keystroke rather than having to type \"yes\"."
  1894. :group 'org-link-follow
  1895. :type '(choice
  1896. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1897. (const :tag "with y-or-n (faster)" y-or-n-p)
  1898. (const :tag "no confirmation (dangerous)" nil)))
  1899. (put 'org-confirm-shell-link-function
  1900. 'safe-local-variable
  1901. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1902. (defcustom org-confirm-shell-link-not-regexp ""
  1903. "A regexp to skip confirmation for shell links."
  1904. :group 'org-link-follow
  1905. :version "24.1"
  1906. :type 'regexp)
  1907. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1908. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1909. Elisp links can be dangerous: just think about a link
  1910. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1911. This link would show up in your Org document as \"Google Search\",
  1912. but really it would remove your entire home directory.
  1913. Therefore we advise against setting this variable to nil.
  1914. Just change it to `y-or-n-p' if you want to confirm with a
  1915. single keystroke rather than having to type \"yes\"."
  1916. :group 'org-link-follow
  1917. :type '(choice
  1918. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1919. (const :tag "with y-or-n (faster)" y-or-n-p)
  1920. (const :tag "no confirmation (dangerous)" nil)))
  1921. (put 'org-confirm-shell-link-function
  1922. 'safe-local-variable
  1923. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1924. (defcustom org-confirm-elisp-link-not-regexp ""
  1925. "A regexp to skip confirmation for Elisp links."
  1926. :group 'org-link-follow
  1927. :version "24.1"
  1928. :type 'regexp)
  1929. (defconst org-file-apps-defaults-gnu
  1930. '((remote . emacs)
  1931. (system . mailcap)
  1932. (t . mailcap))
  1933. "Default file applications on a UNIX or GNU/Linux system.
  1934. See `org-file-apps'.")
  1935. (defconst org-file-apps-defaults-macosx
  1936. '((remote . emacs)
  1937. (system . "open %s")
  1938. ("ps.gz" . "gv %s")
  1939. ("eps.gz" . "gv %s")
  1940. ("dvi" . "xdvi %s")
  1941. ("fig" . "xfig %s")
  1942. (t . "open %s"))
  1943. "Default file applications on a macOS system.
  1944. The system \"open\" is known as a default, but we use X11 applications
  1945. for some files for which the OS does not have a good default.
  1946. See `org-file-apps'.")
  1947. (defconst org-file-apps-defaults-windowsnt
  1948. (list '(remote . emacs)
  1949. (cons 'system (lambda (file _path)
  1950. (with-no-warnings (w32-shell-execute "open" file))))
  1951. (cons t (lambda (file _path)
  1952. (with-no-warnings (w32-shell-execute "open" file)))))
  1953. "Default file applications on a Windows NT system.
  1954. The system \"open\" is used for most files.
  1955. See `org-file-apps'.")
  1956. (defcustom org-file-apps
  1957. '((auto-mode . emacs)
  1958. ("\\.mm\\'" . default)
  1959. ("\\.x?html?\\'" . default)
  1960. ("\\.pdf\\'" . default))
  1961. "External applications for opening `file:path' items in a document.
  1962. \\<org-mode-map>\
  1963. Org mode uses system defaults for different file types, but
  1964. you can use this variable to set the application for a given file
  1965. extension. The entries in this list are cons cells where the car identifies
  1966. files and the cdr the corresponding command.
  1967. Possible values for the file identifier are:
  1968. \"string\" A string as a file identifier can be interpreted in different
  1969. ways, depending on its contents:
  1970. - Alphanumeric characters only:
  1971. Match links with this file extension.
  1972. Example: (\"pdf\" . \"evince %s\")
  1973. to open PDFs with evince.
  1974. - Regular expression: Match links where the
  1975. filename matches the regexp. If you want to
  1976. use groups here, use shy groups.
  1977. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1978. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1979. to open *.html and *.xhtml with firefox.
  1980. - Regular expression which contains (non-shy) groups:
  1981. Match links where the whole link, including \"::\", and
  1982. anything after that, matches the regexp.
  1983. In a custom command string, %1, %2, etc. are replaced with
  1984. the parts of the link that were matched by the groups.
  1985. For backwards compatibility, if a command string is given
  1986. that does not use any of the group matches, this case is
  1987. handled identically to the second one (i.e. match against
  1988. file name only).
  1989. In a custom function, you can access the group matches with
  1990. (match-string n link).
  1991. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1992. \"evince -p %1 %s\")
  1993. to open [[file:document.pdf::5]] with evince at page 5.
  1994. `directory' Matches a directory
  1995. `remote' Matches a remote file, accessible through tramp or efs.
  1996. Remote files most likely should be visited through Emacs
  1997. because external applications cannot handle such paths.
  1998. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1999. so all files Emacs knows how to handle. Using this with
  2000. command `emacs' will open most files in Emacs. Beware that this
  2001. will also open html files inside Emacs, unless you add
  2002. (\"html\" . default) to the list as well.
  2003. `system' The system command to open files, like `open' on Windows
  2004. and macOS, and mailcap under GNU/Linux. This is the command
  2005. that will be selected if you call `org-open-at-point' with a
  2006. double prefix argument (`\\[universal-argument] \
  2007. \\[universal-argument] \\[org-open-at-point]').
  2008. t Default for files not matched by any of the other options.
  2009. Possible values for the command are:
  2010. `emacs' The file will be visited by the current Emacs process.
  2011. `default' Use the default application for this file type, which is the
  2012. association for t in the list, most likely in the system-specific
  2013. part. This can be used to overrule an unwanted setting in the
  2014. system-specific variable.
  2015. `system' Use the system command for opening files, like \"open\".
  2016. This command is specified by the entry whose car is `system'.
  2017. Most likely, the system-specific version of this variable
  2018. does define this command, but you can overrule/replace it
  2019. here.
  2020. `mailcap' Use command specified in the mailcaps.
  2021. string A command to be executed by a shell; %s will be replaced
  2022. by the path to the file.
  2023. function A Lisp function, which will be called with two arguments:
  2024. the file path and the original link string, without the
  2025. \"file:\" prefix.
  2026. For more examples, see the system specific constants
  2027. `org-file-apps-defaults-macosx'
  2028. `org-file-apps-defaults-windowsnt'
  2029. `org-file-apps-defaults-gnu'."
  2030. :group 'org-link-follow
  2031. :type '(repeat
  2032. (cons (choice :value ""
  2033. (string :tag "Extension")
  2034. (const :tag "System command to open files" system)
  2035. (const :tag "Default for unrecognized files" t)
  2036. (const :tag "Remote file" remote)
  2037. (const :tag "Links to a directory" directory)
  2038. (const :tag "Any files that have Emacs modes"
  2039. auto-mode))
  2040. (choice :value ""
  2041. (const :tag "Visit with Emacs" emacs)
  2042. (const :tag "Use default" default)
  2043. (const :tag "Use the system command" system)
  2044. (string :tag "Command")
  2045. (function :tag "Function")))))
  2046. (defcustom org-doi-server-url "http://dx.doi.org/"
  2047. "The URL of the DOI server."
  2048. :type 'string
  2049. :version "24.3"
  2050. :group 'org-link-follow)
  2051. (defgroup org-refile nil
  2052. "Options concerning refiling entries in Org mode."
  2053. :tag "Org Refile"
  2054. :group 'org)
  2055. (defcustom org-directory "~/org"
  2056. "Directory with Org files.
  2057. This is just a default location to look for Org files. There is no need
  2058. at all to put your files into this directory. It is used in the
  2059. following situations:
  2060. 1. When a capture template specifies a target file that is not an
  2061. absolute path. The path will then be interpreted relative to
  2062. `org-directory'
  2063. 2. When the value of variable `org-agenda-files' is a single file, any
  2064. relative paths in this file will be taken as relative to
  2065. `org-directory'."
  2066. :group 'org-refile
  2067. :group 'org-capture
  2068. :type 'directory)
  2069. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2070. "Default target for storing notes.
  2071. Used as a fall back file for org-capture.el, for templates that
  2072. do not specify a target file."
  2073. :group 'org-refile
  2074. :group 'org-capture
  2075. :type 'file)
  2076. (defcustom org-goto-interface 'outline
  2077. "The default interface to be used for `org-goto'.
  2078. Allowed values are:
  2079. outline The interface shows an outline of the relevant file
  2080. and the correct heading is found by moving through
  2081. the outline or by searching with incremental search.
  2082. outline-path-completion Headlines in the current buffer are offered via
  2083. completion. This is the interface also used by
  2084. the refile command."
  2085. :group 'org-refile
  2086. :type '(choice
  2087. (const :tag "Outline" outline)
  2088. (const :tag "Outline-path-completion" outline-path-completion)))
  2089. (defcustom org-goto-max-level 5
  2090. "Maximum target level when running `org-goto' with refile interface."
  2091. :group 'org-refile
  2092. :type 'integer)
  2093. (defcustom org-reverse-note-order nil
  2094. "Non-nil means store new notes at the beginning of a file or entry.
  2095. When nil, new notes will be filed to the end of a file or entry.
  2096. This can also be a list with cons cells of regular expressions that
  2097. are matched against file names, and values."
  2098. :group 'org-capture
  2099. :group 'org-refile
  2100. :type '(choice
  2101. (const :tag "Reverse always" t)
  2102. (const :tag "Reverse never" nil)
  2103. (repeat :tag "By file name regexp"
  2104. (cons regexp boolean))))
  2105. (defcustom org-log-refile nil
  2106. "Information to record when a task is refiled.
  2107. Possible values are:
  2108. nil Don't add anything
  2109. time Add a time stamp to the task
  2110. note Prompt for a note and add it with template `org-log-note-headings'
  2111. This option can also be set with on a per-file-basis with
  2112. #+STARTUP: nologrefile
  2113. #+STARTUP: logrefile
  2114. #+STARTUP: lognoterefile
  2115. You can have local logging settings for a subtree by setting the LOGGING
  2116. property to one or more of these keywords.
  2117. When bulk-refiling from the agenda, the value `note' is forbidden and
  2118. will temporarily be changed to `time'."
  2119. :group 'org-refile
  2120. :group 'org-progress
  2121. :version "24.1"
  2122. :type '(choice
  2123. (const :tag "No logging" nil)
  2124. (const :tag "Record timestamp" time)
  2125. (const :tag "Record timestamp with note." note)))
  2126. (defcustom org-refile-targets nil
  2127. "Targets for refiling entries with `\\[org-refile]'.
  2128. This is a list of cons cells. Each cell contains:
  2129. - a specification of the files to be considered, either a list of files,
  2130. or a symbol whose function or variable value will be used to retrieve
  2131. a file name or a list of file names. If you use `org-agenda-files' for
  2132. that, all agenda files will be scanned for targets. Nil means consider
  2133. headings in the current buffer.
  2134. - A specification of how to find candidate refile targets. This may be
  2135. any of:
  2136. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2137. This tag has to be present in all target headlines, inheritance will
  2138. not be considered.
  2139. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2140. todo keyword.
  2141. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2142. headlines that are refiling targets.
  2143. - a cons cell (:level . N). Any headline of level N is considered a target.
  2144. Note that, when `org-odd-levels-only' is set, level corresponds to
  2145. order in hierarchy, not to the number of stars.
  2146. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2147. Note that, when `org-odd-levels-only' is set, level corresponds to
  2148. order in hierarchy, not to the number of stars.
  2149. Each element of this list generates a set of possible targets.
  2150. The union of these sets is presented (with completion) to
  2151. the user by `org-refile'.
  2152. You can set the variable `org-refile-target-verify-function' to a function
  2153. to verify each headline found by the simple criteria above.
  2154. When this variable is nil, all top-level headlines in the current buffer
  2155. are used, equivalent to the value `((nil . (:level . 1))'."
  2156. :group 'org-refile
  2157. :type '(repeat
  2158. (cons
  2159. (choice :value org-agenda-files
  2160. (const :tag "All agenda files" org-agenda-files)
  2161. (const :tag "Current buffer" nil)
  2162. (function) (variable) (file))
  2163. (choice :tag "Identify target headline by"
  2164. (cons :tag "Specific tag" (const :value :tag) (string))
  2165. (cons :tag "TODO keyword" (const :value :todo) (string))
  2166. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2167. (cons :tag "Level number" (const :value :level) (integer))
  2168. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2169. (defcustom org-refile-target-verify-function nil
  2170. "Function to verify if the headline at point should be a refile target.
  2171. The function will be called without arguments, with point at the
  2172. beginning of the headline. It should return t and leave point
  2173. where it is if the headline is a valid target for refiling.
  2174. If the target should not be selected, the function must return nil.
  2175. In addition to this, it may move point to a place from where the search
  2176. should be continued. For example, the function may decide that the entire
  2177. subtree of the current entry should be excluded and move point to the end
  2178. of the subtree."
  2179. :group 'org-refile
  2180. :type '(choice
  2181. (const nil)
  2182. (function)))
  2183. (defcustom org-refile-use-cache nil
  2184. "Non-nil means cache refile targets to speed up the process.
  2185. \\<org-mode-map>\
  2186. The cache for a particular file will be updated automatically when
  2187. the buffer has been killed, or when any of the marker used for flagging
  2188. refile targets no longer points at a live buffer.
  2189. If you have added new entries to a buffer that might themselves be targets,
  2190. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2191. if you find that easier, \
  2192. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2193. \\[org-refile]'."
  2194. :group 'org-refile
  2195. :version "24.1"
  2196. :type 'boolean)
  2197. (defcustom org-refile-use-outline-path nil
  2198. "Non-nil means provide refile targets as paths.
  2199. So a level 3 headline will be available as level1/level2/level3.
  2200. When the value is `file', also include the file name (without directory)
  2201. into the path. In this case, you can also stop the completion after
  2202. the file name, to get entries inserted as top level in the file.
  2203. When `full-file-path', include the full file path."
  2204. :group 'org-refile
  2205. :type '(choice
  2206. (const :tag "Not" nil)
  2207. (const :tag "Yes" t)
  2208. (const :tag "Start with file name" file)
  2209. (const :tag "Start with full file path" full-file-path)))
  2210. (defcustom org-outline-path-complete-in-steps t
  2211. "Non-nil means complete the outline path in hierarchical steps.
  2212. When Org uses the refile interface to select an outline path (see
  2213. `org-refile-use-outline-path'), the completion of the path can be
  2214. done in a single go, or it can be done in steps down the headline
  2215. hierarchy. Going in steps is probably the best if you do not use
  2216. a special completion package like `ido' or `icicles'. However,
  2217. when using these packages, going in one step can be very fast,
  2218. while still showing the whole path to the entry."
  2219. :group 'org-refile
  2220. :type 'boolean)
  2221. (defcustom org-refile-allow-creating-parent-nodes nil
  2222. "Non-nil means allow the creation of new nodes as refile targets.
  2223. New nodes are then created by adding \"/new node name\" to the completion
  2224. of an existing node. When the value of this variable is `confirm',
  2225. new node creation must be confirmed by the user (recommended).
  2226. When nil, the completion must match an existing entry.
  2227. Note that, if the new heading is not seen by the criteria
  2228. listed in `org-refile-targets', multiple instances of the same
  2229. heading would be created by trying again to file under the new
  2230. heading."
  2231. :group 'org-refile
  2232. :type '(choice
  2233. (const :tag "Never" nil)
  2234. (const :tag "Always" t)
  2235. (const :tag "Prompt for confirmation" confirm)))
  2236. (defcustom org-refile-active-region-within-subtree nil
  2237. "Non-nil means also refile active region within a subtree.
  2238. By default `org-refile' doesn't allow refiling regions if they
  2239. don't contain a set of subtrees, but it might be convenient to
  2240. do so sometimes: in that case, the first line of the region is
  2241. converted to a headline before refiling."
  2242. :group 'org-refile
  2243. :version "24.1"
  2244. :type 'boolean)
  2245. (defgroup org-todo nil
  2246. "Options concerning TODO items in Org mode."
  2247. :tag "Org TODO"
  2248. :group 'org)
  2249. (defgroup org-progress nil
  2250. "Options concerning Progress logging in Org mode."
  2251. :tag "Org Progress"
  2252. :group 'org-time)
  2253. (defvar org-todo-interpretation-widgets
  2254. '((:tag "Sequence (cycling hits every state)" sequence)
  2255. (:tag "Type (cycling directly to DONE)" type))
  2256. "The available interpretation symbols for customizing `org-todo-keywords'.
  2257. Interested libraries should add to this list.")
  2258. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2259. "List of TODO entry keyword sequences and their interpretation.
  2260. \\<org-mode-map>This is a list of sequences.
  2261. Each sequence starts with a symbol, either `sequence' or `type',
  2262. indicating if the keywords should be interpreted as a sequence of
  2263. action steps, or as different types of TODO items. The first
  2264. keywords are states requiring action - these states will select a headline
  2265. for inclusion into the global TODO list Org produces. If one of the
  2266. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2267. signify that no further action is necessary. If \"|\" is not found,
  2268. the last keyword is treated as the only DONE state of the sequence.
  2269. The command `\\[org-todo]' cycles an entry through these states, and one
  2270. additional state where no keyword is present. For details about this
  2271. cycling, see the manual.
  2272. TODO keywords and interpretation can also be set on a per-file basis with
  2273. the special #+SEQ_TODO and #+TYP_TODO lines.
  2274. Each keyword can optionally specify a character for fast state selection
  2275. \(in combination with the variable `org-use-fast-todo-selection')
  2276. and specifiers for state change logging, using the same syntax that
  2277. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2278. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2279. indicates to record a time stamp each time this state is selected.
  2280. Each keyword may also specify if a timestamp or a note should be
  2281. recorded when entering or leaving the state, by adding additional
  2282. characters in the parenthesis after the keyword. This looks like this:
  2283. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2284. record only the time of the state change. With X and Y being either
  2285. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2286. Y when leaving the state if and only if the *target* state does not
  2287. define X. You may omit any of the fast-selection key or X or /Y,
  2288. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2289. For backward compatibility, this variable may also be just a list
  2290. of keywords. In this case the interpretation (sequence or type) will be
  2291. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2292. :group 'org-todo
  2293. :group 'org-keywords
  2294. :type '(choice
  2295. (repeat :tag "Old syntax, just keywords"
  2296. (string :tag "Keyword"))
  2297. (repeat :tag "New syntax"
  2298. (cons
  2299. (choice
  2300. :tag "Interpretation"
  2301. ;;Quick and dirty way to see
  2302. ;;`org-todo-interpretations'. This takes the
  2303. ;;place of item arguments
  2304. :convert-widget
  2305. (lambda (widget)
  2306. (widget-put widget
  2307. :args (mapcar
  2308. (lambda (x)
  2309. (widget-convert
  2310. (cons 'const x)))
  2311. org-todo-interpretation-widgets))
  2312. widget))
  2313. (repeat
  2314. (string :tag "Keyword"))))))
  2315. (defvar-local org-todo-keywords-1 nil
  2316. "All TODO and DONE keywords active in a buffer.")
  2317. (defvar org-todo-keywords-for-agenda nil)
  2318. (defvar org-done-keywords-for-agenda nil)
  2319. (defvar org-todo-keyword-alist-for-agenda nil)
  2320. (defvar org-tag-alist-for-agenda nil
  2321. "Alist of all tags from all agenda files.")
  2322. (defvar org-tag-groups-alist-for-agenda nil
  2323. "Alist of all groups tags from all current agenda files.")
  2324. (defvar-local org-tag-groups-alist nil)
  2325. (defvar org-agenda-contributing-files nil)
  2326. (defvar-local org-current-tag-alist nil
  2327. "Alist of all tag groups in current buffer.
  2328. This variable takes into consideration `org-tag-alist',
  2329. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2330. (defvar-local org-not-done-keywords nil)
  2331. (defvar-local org-done-keywords nil)
  2332. (defvar-local org-todo-heads nil)
  2333. (defvar-local org-todo-sets nil)
  2334. (defvar-local org-todo-log-states nil)
  2335. (defvar-local org-todo-kwd-alist nil)
  2336. (defvar-local org-todo-key-alist nil)
  2337. (defvar-local org-todo-key-trigger nil)
  2338. (defcustom org-todo-interpretation 'sequence
  2339. "Controls how TODO keywords are interpreted.
  2340. This variable is in principle obsolete and is only used for
  2341. backward compatibility, if the interpretation of todo keywords is
  2342. not given already in `org-todo-keywords'. See that variable for
  2343. more information."
  2344. :group 'org-todo
  2345. :group 'org-keywords
  2346. :type '(choice (const sequence)
  2347. (const type)))
  2348. (defcustom org-use-fast-todo-selection t
  2349. "\\<org-mode-map>\
  2350. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2351. This variable describes if and under what circumstances the cycling
  2352. mechanism for TODO keywords will be replaced by a single-key, direct
  2353. selection scheme.
  2354. When nil, fast selection is never used.
  2355. When the symbol `prefix', it will be used when `org-todo' is called
  2356. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2357. in an Org buffer, and
  2358. `\\[universal-argument] t' in an agenda buffer.
  2359. When t, fast selection is used by default. In this case, the prefix
  2360. argument forces cycling instead.
  2361. In all cases, the special interface is only used if access keys have
  2362. actually been assigned by the user, i.e. if keywords in the configuration
  2363. are followed by a letter in parenthesis, like TODO(t)."
  2364. :group 'org-todo
  2365. :type '(choice
  2366. (const :tag "Never" nil)
  2367. (const :tag "By default" t)
  2368. (const :tag "Only with C-u C-c C-t" prefix)))
  2369. (defcustom org-provide-todo-statistics t
  2370. "Non-nil means update todo statistics after insert and toggle.
  2371. ALL-HEADLINES means update todo statistics by including headlines
  2372. with no TODO keyword as well, counting them as not done.
  2373. A list of TODO keywords means the same, but skip keywords that are
  2374. not in this list.
  2375. When set to a list of two lists, the first list contains keywords
  2376. to consider as TODO keywords, the second list contains keywords
  2377. to consider as DONE keywords.
  2378. When this is set, todo statistics is updated in the parent of the
  2379. current entry each time a todo state is changed."
  2380. :group 'org-todo
  2381. :type '(choice
  2382. (const :tag "Yes, only for TODO entries" t)
  2383. (const :tag "Yes, including all entries" all-headlines)
  2384. (repeat :tag "Yes, for TODOs in this list"
  2385. (string :tag "TODO keyword"))
  2386. (list :tag "Yes, for TODOs and DONEs in these lists"
  2387. (repeat (string :tag "TODO keyword"))
  2388. (repeat (string :tag "DONE keyword")))
  2389. (other :tag "No TODO statistics" nil)))
  2390. (defcustom org-hierarchical-todo-statistics t
  2391. "Non-nil means TODO statistics covers just direct children.
  2392. When nil, all entries in the subtree are considered.
  2393. This has only an effect if `org-provide-todo-statistics' is set.
  2394. To set this to nil for only a single subtree, use a COOKIE_DATA
  2395. property and include the word \"recursive\" into the value."
  2396. :group 'org-todo
  2397. :type 'boolean)
  2398. (defcustom org-after-todo-state-change-hook nil
  2399. "Hook which is run after the state of a TODO item was changed.
  2400. The new state (a string with a TODO keyword, or nil) is available in the
  2401. Lisp variable `org-state'."
  2402. :group 'org-todo
  2403. :type 'hook)
  2404. (defvar org-blocker-hook nil
  2405. "Hook for functions that are allowed to block a state change.
  2406. Functions in this hook should not modify the buffer.
  2407. Each function gets as its single argument a property list,
  2408. see `org-trigger-hook' for more information about this list.
  2409. If any of the functions in this hook returns nil, the state change
  2410. is blocked.")
  2411. (defvar org-trigger-hook nil
  2412. "Hook for functions that are triggered by a state change.
  2413. Each function gets as its single argument a property list with at
  2414. least the following elements:
  2415. (:type type-of-change :position pos-at-entry-start
  2416. :from old-state :to new-state)
  2417. Depending on the type, more properties may be present.
  2418. This mechanism is currently implemented for:
  2419. TODO state changes
  2420. ------------------
  2421. :type todo-state-change
  2422. :from previous state (keyword as a string), or nil, or a symbol
  2423. `todo' or `done', to indicate the general type of state.
  2424. :to new state, like in :from")
  2425. (defcustom org-enforce-todo-dependencies nil
  2426. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2427. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2428. be blocked if any prior sibling is not yet done.
  2429. Finally, if the parent is blocked because of ordered siblings of its own,
  2430. the child will also be blocked."
  2431. :set (lambda (var val)
  2432. (set var val)
  2433. (if val
  2434. (add-hook 'org-blocker-hook
  2435. 'org-block-todo-from-children-or-siblings-or-parent)
  2436. (remove-hook 'org-blocker-hook
  2437. 'org-block-todo-from-children-or-siblings-or-parent)))
  2438. :group 'org-todo
  2439. :type 'boolean)
  2440. (defcustom org-enforce-todo-checkbox-dependencies nil
  2441. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2442. When this is nil, checkboxes have no influence on switching TODO states.
  2443. When non-nil, you first need to check off all check boxes before the TODO
  2444. entry can be switched to DONE.
  2445. This variable needs to be set before org.el is loaded, and you need to
  2446. restart Emacs after a change to make the change effective. The only way
  2447. to change is while Emacs is running is through the customize interface."
  2448. :set (lambda (var val)
  2449. (set var val)
  2450. (if val
  2451. (add-hook 'org-blocker-hook
  2452. 'org-block-todo-from-checkboxes)
  2453. (remove-hook 'org-blocker-hook
  2454. 'org-block-todo-from-checkboxes)))
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2458. "Non-nil means inserting a TODO heading is treated as state change.
  2459. So when the command `\\[org-insert-todo-heading]' is used, state change
  2460. logging will apply if appropriate. When nil, the new TODO item will
  2461. be inserted directly, and no logging will take place."
  2462. :group 'org-todo
  2463. :type 'boolean)
  2464. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2465. "Non-nil means switching TODO states with S-cursor counts as state change.
  2466. This is the default behavior. However, setting this to nil allows a
  2467. convenient way to select a TODO state and bypass any logging associated
  2468. with that."
  2469. :group 'org-todo
  2470. :type 'boolean)
  2471. (defcustom org-todo-state-tags-triggers nil
  2472. "Tag changes that should be triggered by TODO state changes.
  2473. This is a list. Each entry is
  2474. (state-change (tag . flag) .......)
  2475. State-change can be a string with a state, and empty string to indicate the
  2476. state that has no TODO keyword, or it can be one of the symbols `todo'
  2477. or `done', meaning any not-done or done state, respectively."
  2478. :group 'org-todo
  2479. :group 'org-tags
  2480. :type '(repeat
  2481. (cons (choice :tag "When changing to"
  2482. (const :tag "Not-done state" todo)
  2483. (const :tag "Done state" done)
  2484. (string :tag "State"))
  2485. (repeat
  2486. (cons :tag "Tag action"
  2487. (string :tag "Tag")
  2488. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2489. (defcustom org-log-done nil
  2490. "Information to record when a task moves to the DONE state.
  2491. Possible values are:
  2492. nil Don't add anything, just change the keyword
  2493. time Add a time stamp to the task
  2494. note Prompt for a note and add it with template `org-log-note-headings'
  2495. This option can also be set with on a per-file-basis with
  2496. #+STARTUP: nologdone
  2497. #+STARTUP: logdone
  2498. #+STARTUP: lognotedone
  2499. You can have local logging settings for a subtree by setting the LOGGING
  2500. property to one or more of these keywords."
  2501. :group 'org-todo
  2502. :group 'org-progress
  2503. :type '(choice
  2504. (const :tag "No logging" nil)
  2505. (const :tag "Record CLOSED timestamp" time)
  2506. (const :tag "Record CLOSED timestamp with note." note)))
  2507. ;; Normalize old uses of org-log-done.
  2508. (cond
  2509. ((eq org-log-done t) (setq org-log-done 'time))
  2510. ((and (listp org-log-done) (memq 'done org-log-done))
  2511. (setq org-log-done 'note)))
  2512. (defcustom org-log-reschedule nil
  2513. "Information to record when the scheduling date of a tasks is modified.
  2514. Possible values are:
  2515. nil Don't add anything, just change the date
  2516. time Add a time stamp to the task
  2517. note Prompt for a note and add it with template `org-log-note-headings'
  2518. This option can also be set with on a per-file-basis with
  2519. #+STARTUP: nologreschedule
  2520. #+STARTUP: logreschedule
  2521. #+STARTUP: lognotereschedule"
  2522. :group 'org-todo
  2523. :group 'org-progress
  2524. :type '(choice
  2525. (const :tag "No logging" nil)
  2526. (const :tag "Record timestamp" time)
  2527. (const :tag "Record timestamp with note." note)))
  2528. (defcustom org-log-redeadline nil
  2529. "Information to record when the deadline date of a tasks is modified.
  2530. Possible values are:
  2531. nil Don't add anything, just change the date
  2532. time Add a time stamp to the task
  2533. note Prompt for a note and add it with template `org-log-note-headings'
  2534. This option can also be set with on a per-file-basis with
  2535. #+STARTUP: nologredeadline
  2536. #+STARTUP: logredeadline
  2537. #+STARTUP: lognoteredeadline
  2538. You can have local logging settings for a subtree by setting the LOGGING
  2539. property to one or more of these keywords."
  2540. :group 'org-todo
  2541. :group 'org-progress
  2542. :type '(choice
  2543. (const :tag "No logging" nil)
  2544. (const :tag "Record timestamp" time)
  2545. (const :tag "Record timestamp with note." note)))
  2546. (defcustom org-log-note-clock-out nil
  2547. "Non-nil means record a note when clocking out of an item.
  2548. This can also be configured on a per-file basis by adding one of
  2549. the following lines anywhere in the buffer:
  2550. #+STARTUP: lognoteclock-out
  2551. #+STARTUP: nolognoteclock-out"
  2552. :group 'org-todo
  2553. :group 'org-progress
  2554. :type 'boolean)
  2555. (defcustom org-log-done-with-time t
  2556. "Non-nil means the CLOSED time stamp will contain date and time.
  2557. When nil, only the date will be recorded."
  2558. :group 'org-progress
  2559. :type 'boolean)
  2560. (defcustom org-log-note-headings
  2561. '((done . "CLOSING NOTE %t")
  2562. (state . "State %-12s from %-12S %t")
  2563. (note . "Note taken on %t")
  2564. (reschedule . "Rescheduled from %S on %t")
  2565. (delschedule . "Not scheduled, was %S on %t")
  2566. (redeadline . "New deadline from %S on %t")
  2567. (deldeadline . "Removed deadline, was %S on %t")
  2568. (refile . "Refiled on %t")
  2569. (clock-out . ""))
  2570. "Headings for notes added to entries.
  2571. The value is an alist, with the car being a symbol indicating the
  2572. note context, and the cdr is the heading to be used. The heading
  2573. may also be the empty string. The following placeholders can be
  2574. used:
  2575. %t a time stamp.
  2576. %T an active time stamp instead the default inactive one
  2577. %d a short-format time stamp.
  2578. %D an active short-format time stamp.
  2579. %s the new TODO state or time stamp (inactive), in double quotes.
  2580. %S the old TODO state or time stamp (inactive), in double quotes.
  2581. %u the user name.
  2582. %U full user name.
  2583. In fact, it is not a good idea to change the `state' entry,
  2584. because Agenda Log mode depends on the format of these entries."
  2585. :group 'org-todo
  2586. :group 'org-progress
  2587. :type '(list :greedy t
  2588. (cons (const :tag "Heading when closing an item" done) string)
  2589. (cons (const :tag
  2590. "Heading when changing todo state (todo sequence only)"
  2591. state) string)
  2592. (cons (const :tag "Heading when just taking a note" note) string)
  2593. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2594. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2595. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2596. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2597. (cons (const :tag "Heading when refiling" refile) string)
  2598. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2599. (unless (assq 'note org-log-note-headings)
  2600. (push '(note . "%t") org-log-note-headings))
  2601. (defcustom org-log-into-drawer nil
  2602. "Non-nil means insert state change notes and time stamps into a drawer.
  2603. When nil, state changes notes will be inserted after the headline and
  2604. any scheduling and clock lines, but not inside a drawer.
  2605. The value of this variable should be the name of the drawer to use.
  2606. LOGBOOK is proposed as the default drawer for this purpose, you can
  2607. also set this to a string to define the drawer of your choice.
  2608. A value of t is also allowed, representing \"LOGBOOK\".
  2609. A value of t or nil can also be set with on a per-file-basis with
  2610. #+STARTUP: logdrawer
  2611. #+STARTUP: nologdrawer
  2612. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2613. will be ignored.
  2614. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2615. a subtree.
  2616. Do not check directly this variable in a Lisp program. Call
  2617. function `org-log-into-drawer' instead."
  2618. :group 'org-todo
  2619. :group 'org-progress
  2620. :type '(choice
  2621. (const :tag "Not into a drawer" nil)
  2622. (const :tag "LOGBOOK" t)
  2623. (string :tag "Other")))
  2624. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2625. (defun org-log-into-drawer ()
  2626. "Name of the log drawer, as a string, or nil.
  2627. This is the value of `org-log-into-drawer'. However, if the
  2628. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2629. be used instead of the default value."
  2630. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2631. (cond ((equal p "nil") nil)
  2632. ((equal p "t") "LOGBOOK")
  2633. ((stringp p) p)
  2634. (p "LOGBOOK")
  2635. ((stringp org-log-into-drawer) org-log-into-drawer)
  2636. (org-log-into-drawer "LOGBOOK"))))
  2637. (defcustom org-log-state-notes-insert-after-drawers nil
  2638. "Non-nil means insert state change notes after any drawers in entry.
  2639. Only the drawers that *immediately* follow the headline and the
  2640. deadline/scheduled line are skipped.
  2641. When nil, insert notes right after the heading and perhaps the line
  2642. with deadline/scheduling if present.
  2643. This variable will have no effect if `org-log-into-drawer' is
  2644. set."
  2645. :group 'org-todo
  2646. :group 'org-progress
  2647. :type 'boolean)
  2648. (defcustom org-log-states-order-reversed t
  2649. "Non-nil means the latest state note will be directly after heading.
  2650. When nil, the state change notes will be ordered according to time.
  2651. This option can also be set with on a per-file-basis with
  2652. #+STARTUP: logstatesreversed
  2653. #+STARTUP: nologstatesreversed"
  2654. :group 'org-todo
  2655. :group 'org-progress
  2656. :type 'boolean)
  2657. (defcustom org-todo-repeat-to-state nil
  2658. "The TODO state to which a repeater should return the repeating task.
  2659. By default this is the first task in a TODO sequence, or the previous state
  2660. in a TODO_TYP set. But you can specify another task here.
  2661. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2662. :group 'org-todo
  2663. :version "24.1"
  2664. :type '(choice (const :tag "Head of sequence" nil)
  2665. (string :tag "Specific state")))
  2666. (defcustom org-log-repeat 'time
  2667. "Non-nil means record moving through the DONE state when triggering repeat.
  2668. An auto-repeating task is immediately switched back to TODO when
  2669. marked DONE. If you are not logging state changes (by adding \"@\"
  2670. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2671. record a closing note, there will be no record of the task moving
  2672. through DONE. This variable forces taking a note anyway.
  2673. nil Don't force a record
  2674. time Record a time stamp
  2675. note Prompt for a note and add it with template `org-log-note-headings'
  2676. This option can also be set with on a per-file-basis with
  2677. #+STARTUP: nologrepeat
  2678. #+STARTUP: logrepeat
  2679. #+STARTUP: lognoterepeat
  2680. You can have local logging settings for a subtree by setting the LOGGING
  2681. property to one or more of these keywords."
  2682. :group 'org-todo
  2683. :group 'org-progress
  2684. :type '(choice
  2685. (const :tag "Don't force a record" nil)
  2686. (const :tag "Force recording the DONE state" time)
  2687. (const :tag "Force recording a note with the DONE state" note)))
  2688. (defgroup org-priorities nil
  2689. "Priorities in Org mode."
  2690. :tag "Org Priorities"
  2691. :group 'org-todo)
  2692. (defcustom org-enable-priority-commands t
  2693. "Non-nil means priority commands are active.
  2694. When nil, these commands will be disabled, so that you never accidentally
  2695. set a priority."
  2696. :group 'org-priorities
  2697. :type 'boolean)
  2698. (defcustom org-highest-priority ?A
  2699. "The highest priority of TODO items. A character like ?A, ?B etc.
  2700. Must have a smaller ASCII number than `org-lowest-priority'."
  2701. :group 'org-priorities
  2702. :type 'character)
  2703. (defcustom org-lowest-priority ?C
  2704. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2705. Must have a larger ASCII number than `org-highest-priority'."
  2706. :group 'org-priorities
  2707. :type 'character)
  2708. (defcustom org-default-priority ?B
  2709. "The default priority of TODO items.
  2710. This is the priority an item gets if no explicit priority is given.
  2711. When starting to cycle on an empty priority the first step in the cycle
  2712. depends on `org-priority-start-cycle-with-default'. The resulting first
  2713. step priority must not exceed the range from `org-highest-priority' to
  2714. `org-lowest-priority' which means that `org-default-priority' has to be
  2715. in this range exclusive or inclusive the range boundaries. Else the
  2716. first step refuses to set the default and the second will fall back
  2717. to (depending on the command used) the highest or lowest priority."
  2718. :group 'org-priorities
  2719. :type 'character)
  2720. (defcustom org-priority-start-cycle-with-default t
  2721. "Non-nil means start with default priority when starting to cycle.
  2722. When this is nil, the first step in the cycle will be (depending on the
  2723. command used) one higher or lower than the default priority.
  2724. See also `org-default-priority'."
  2725. :group 'org-priorities
  2726. :type 'boolean)
  2727. (defcustom org-get-priority-function nil
  2728. "Function to extract the priority from a string.
  2729. The string is normally the headline. If this is nil Org computes the
  2730. priority from the priority cookie like [#A] in the headline. It returns
  2731. an integer, increasing by 1000 for each priority level.
  2732. The user can set a different function here, which should take a string
  2733. as an argument and return the numeric priority."
  2734. :group 'org-priorities
  2735. :version "24.1"
  2736. :type '(choice
  2737. (const nil)
  2738. (function)))
  2739. (defgroup org-time nil
  2740. "Options concerning time stamps and deadlines in Org mode."
  2741. :tag "Org Time"
  2742. :group 'org)
  2743. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2744. "Number of minutes to round time stamps to.
  2745. \\<org-mode-map>\
  2746. These are two values, the first applies when first creating a time stamp.
  2747. The second applies when changing it with the commands `S-up' and `S-down'.
  2748. When changing the time stamp, this means that it will change in steps
  2749. of N minutes, as given by the second value.
  2750. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2751. numbers should be factors of 60, so for example 5, 10, 15.
  2752. When this is larger than 1, you can still force an exact time stamp by using
  2753. a double prefix argument to a time stamp command like \
  2754. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2755. and by using a prefix arg to `S-up/down' to specify the exact number
  2756. of minutes to shift."
  2757. :group 'org-time
  2758. :get (lambda (var) ; Make sure both elements are there
  2759. (if (integerp (default-value var))
  2760. (list (default-value var) 5)
  2761. (default-value var)))
  2762. :type '(list
  2763. (integer :tag "when inserting times")
  2764. (integer :tag "when modifying times")))
  2765. ;; Normalize old customizations of this variable.
  2766. (when (integerp org-time-stamp-rounding-minutes)
  2767. (setq org-time-stamp-rounding-minutes
  2768. (list org-time-stamp-rounding-minutes
  2769. org-time-stamp-rounding-minutes)))
  2770. (defcustom org-display-custom-times nil
  2771. "Non-nil means overlay custom formats over all time stamps.
  2772. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2773. To turn this on on a per-file basis, insert anywhere in the file:
  2774. #+STARTUP: customtime"
  2775. :group 'org-time
  2776. :set 'set-default
  2777. :type 'sexp)
  2778. (make-variable-buffer-local 'org-display-custom-times)
  2779. (defcustom org-time-stamp-custom-formats
  2780. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2781. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2782. These are overlaid over the default ISO format if the variable
  2783. `org-display-custom-times' is set. Time like %H:%M should be at the
  2784. end of the second format. The custom formats are also honored by export
  2785. commands, if custom time display is turned on at the time of export."
  2786. :group 'org-time
  2787. :type 'sexp)
  2788. (defun org-time-stamp-format (&optional long inactive)
  2789. "Get the right format for a time string."
  2790. (let ((f (if long (cdr org-time-stamp-formats)
  2791. (car org-time-stamp-formats))))
  2792. (if inactive
  2793. (concat "[" (substring f 1 -1) "]")
  2794. f)))
  2795. (defcustom org-time-clocksum-format
  2796. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2797. "The format string used when creating CLOCKSUM lines.
  2798. This is also used when Org mode generates a time duration.
  2799. The value can be a single format string containing two
  2800. %-sequences, which will be filled with the number of hours and
  2801. minutes in that order.
  2802. Alternatively, the value can be a plist associating any of the
  2803. keys :years, :months, :weeks, :days, :hours or :minutes with
  2804. format strings. The time duration is formatted using only the
  2805. time components that are needed and concatenating the results.
  2806. If a time unit in absent, it falls back to the next smallest
  2807. unit.
  2808. The keys :require-years, :require-months, :require-days,
  2809. :require-weeks, :require-hours, :require-minutes are also
  2810. meaningful. A non-nil value for these keys indicates that the
  2811. corresponding time component should always be included, even if
  2812. its value is 0.
  2813. For example,
  2814. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2815. :require-minutes t)
  2816. means durations longer than a day will be expressed in days,
  2817. hours and minutes, and durations less than a day will always be
  2818. expressed in hours and minutes (even for durations less than an
  2819. hour).
  2820. The value
  2821. (:days \"%dd\" :minutes \"%dm\")
  2822. means durations longer than a day will be expressed in days and
  2823. minutes, and durations less than a day will be expressed entirely
  2824. in minutes (even for durations longer than an hour)."
  2825. :group 'org-time
  2826. :group 'org-clock
  2827. :version "24.4"
  2828. :package-version '(Org . "8.0")
  2829. :type '(choice (string :tag "Format string")
  2830. (set :tag "Plist"
  2831. (group :inline t (const :tag "Years" :years)
  2832. (string :tag "Format string"))
  2833. (group :inline t
  2834. (const :tag "Always show years" :require-years)
  2835. (const t))
  2836. (group :inline t (const :tag "Months" :months)
  2837. (string :tag "Format string"))
  2838. (group :inline t
  2839. (const :tag "Always show months" :require-months)
  2840. (const t))
  2841. (group :inline t (const :tag "Weeks" :weeks)
  2842. (string :tag "Format string"))
  2843. (group :inline t
  2844. (const :tag "Always show weeks" :require-weeks)
  2845. (const t))
  2846. (group :inline t (const :tag "Days" :days)
  2847. (string :tag "Format string"))
  2848. (group :inline t
  2849. (const :tag "Always show days" :require-days)
  2850. (const t))
  2851. (group :inline t (const :tag "Hours" :hours)
  2852. (string :tag "Format string"))
  2853. (group :inline t
  2854. (const :tag "Always show hours" :require-hours)
  2855. (const t))
  2856. (group :inline t (const :tag "Minutes" :minutes)
  2857. (string :tag "Format string"))
  2858. (group :inline t
  2859. (const :tag "Always show minutes" :require-minutes)
  2860. (const t)))))
  2861. (defcustom org-time-clocksum-use-fractional nil
  2862. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2863. See `org-time-clocksum-format' for more on time clock formats."
  2864. :group 'org-time
  2865. :group 'org-clock
  2866. :version "24.3"
  2867. :type 'boolean)
  2868. (defcustom org-time-clocksum-use-effort-durations nil
  2869. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2870. E.g. by default, one day is considered to be a 8 hours effort,
  2871. so a task that has been clocked for 16 hours will be displayed
  2872. as during 2 days in the clock display or in the clocktable.
  2873. See `org-effort-durations' on how to set effort durations
  2874. and `org-time-clocksum-format' for more on time clock formats."
  2875. :group 'org-time
  2876. :group 'org-clock
  2877. :version "24.4"
  2878. :package-version '(Org . "8.0")
  2879. :type 'boolean)
  2880. (defcustom org-time-clocksum-fractional-format "%.2f"
  2881. "The format string used when creating CLOCKSUM lines,
  2882. or when Org mode generates a time duration, if
  2883. `org-time-clocksum-use-fractional' is enabled.
  2884. The value can be a single format string containing one
  2885. %-sequence, which will be filled with the number of hours as
  2886. a float.
  2887. Alternatively, the value can be a plist associating any of the
  2888. keys :years, :months, :weeks, :days, :hours or :minutes with
  2889. a format string. The time duration is formatted using the
  2890. largest time unit which gives a non-zero integer part. If all
  2891. specified formats have zero integer part, the smallest time unit
  2892. is used."
  2893. :group 'org-time
  2894. :type '(choice (string :tag "Format string")
  2895. (set (group :inline t (const :tag "Years" :years)
  2896. (string :tag "Format string"))
  2897. (group :inline t (const :tag "Months" :months)
  2898. (string :tag "Format string"))
  2899. (group :inline t (const :tag "Weeks" :weeks)
  2900. (string :tag "Format string"))
  2901. (group :inline t (const :tag "Days" :days)
  2902. (string :tag "Format string"))
  2903. (group :inline t (const :tag "Hours" :hours)
  2904. (string :tag "Format string"))
  2905. (group :inline t (const :tag "Minutes" :minutes)
  2906. (string :tag "Format string")))))
  2907. (defcustom org-deadline-warning-days 14
  2908. "Number of days before expiration during which a deadline becomes active.
  2909. This variable governs the display in sparse trees and in the agenda.
  2910. When 0 or negative, it means use this number (the absolute value of it)
  2911. even if a deadline has a different individual lead time specified.
  2912. Custom commands can set this variable in the options section."
  2913. :group 'org-time
  2914. :group 'org-agenda-daily/weekly
  2915. :type 'integer)
  2916. (defcustom org-scheduled-delay-days 0
  2917. "Number of days before a scheduled item becomes active.
  2918. This variable governs the display in sparse trees and in the agenda.
  2919. The default value (i.e. 0) means: don't delay scheduled item.
  2920. When negative, it means use this number (the absolute value of it)
  2921. even if a scheduled item has a different individual delay time
  2922. specified.
  2923. Custom commands can set this variable in the options section."
  2924. :group 'org-time
  2925. :group 'org-agenda-daily/weekly
  2926. :version "24.4"
  2927. :package-version '(Org . "8.0")
  2928. :type 'integer)
  2929. (defcustom org-read-date-prefer-future t
  2930. "Non-nil means assume future for incomplete date input from user.
  2931. This affects the following situations:
  2932. 1. The user gives a month but not a year.
  2933. For example, if it is April and you enter \"feb 2\", this will be read
  2934. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2935. 2. The user gives a day, but no month.
  2936. For example, if today is the 15th, and you enter \"3\", Org will read
  2937. this as the third of *next* month. However, if you enter \"17\",
  2938. it will be considered as *this* month.
  2939. If you set this variable to the symbol `time', then also the following
  2940. will work:
  2941. 3. If the user gives a time.
  2942. If the time is before now, it will be interpreted as tomorrow.
  2943. Currently none of this works for ISO week specifications.
  2944. When this option is nil, the current day, month and year will always be
  2945. used as defaults.
  2946. See also `org-agenda-jump-prefer-future'."
  2947. :group 'org-time
  2948. :type '(choice
  2949. (const :tag "Never" nil)
  2950. (const :tag "Check month and day" t)
  2951. (const :tag "Check month, day, and time" time)))
  2952. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2953. "Should the agenda jump command prefer the future for incomplete dates?
  2954. The default is to do the same as configured in `org-read-date-prefer-future'.
  2955. But you can also set a deviating value here.
  2956. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2957. :group 'org-agenda
  2958. :group 'org-time
  2959. :version "24.1"
  2960. :type '(choice
  2961. (const :tag "Use org-read-date-prefer-future"
  2962. org-read-date-prefer-future)
  2963. (const :tag "Never" nil)
  2964. (const :tag "Always" t)))
  2965. (defcustom org-read-date-force-compatible-dates t
  2966. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2967. Depending on the system Emacs is running on, certain dates cannot
  2968. be represented with the type used internally to represent time.
  2969. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2970. correctly. Some systems allow for earlier dates, some for later,
  2971. some for both. One way to find out it to insert any date into an
  2972. Org buffer, putting the cursor on the year and hitting S-up and
  2973. S-down to test the range.
  2974. When this variable is set to t, the date/time prompt will not let
  2975. you specify dates outside the 1970-2037 range, so it is certain that
  2976. these dates will work in whatever version of Emacs you are
  2977. running, and also that you can move a file from one Emacs implementation
  2978. to another. WHenever Org is forcing the year for you, it will display
  2979. a message and beep.
  2980. When this variable is nil, Org will check if the date is
  2981. representable in the specific Emacs implementation you are using.
  2982. If not, it will force a year, usually the current year, and beep
  2983. to remind you. Currently this setting is not recommended because
  2984. the likelihood that you will open your Org files in an Emacs that
  2985. has limited date range is not negligible.
  2986. A workaround for this problem is to use diary sexp dates for time
  2987. stamps outside of this range."
  2988. :group 'org-time
  2989. :version "24.1"
  2990. :type 'boolean)
  2991. (defcustom org-read-date-display-live t
  2992. "Non-nil means display current interpretation of date prompt live.
  2993. This display will be in an overlay, in the minibuffer."
  2994. :group 'org-time
  2995. :type 'boolean)
  2996. (defcustom org-read-date-popup-calendar t
  2997. "Non-nil means pop up a calendar when prompting for a date.
  2998. In the calendar, the date can be selected with mouse-1. However, the
  2999. minibuffer will also be active, and you can simply enter the date as well.
  3000. When nil, only the minibuffer will be available."
  3001. :group 'org-time
  3002. :type 'boolean)
  3003. (defvaralias 'org-popup-calendar-for-date-prompt
  3004. 'org-read-date-popup-calendar)
  3005. (defcustom org-extend-today-until 0
  3006. "The hour when your day really ends. Must be an integer.
  3007. This has influence for the following applications:
  3008. - When switching the agenda to \"today\". It it is still earlier than
  3009. the time given here, the day recognized as TODAY is actually yesterday.
  3010. - When a date is read from the user and it is still before the time given
  3011. here, the current date and time will be assumed to be yesterday, 23:59.
  3012. Also, timestamps inserted in capture templates follow this rule.
  3013. IMPORTANT: This is a feature whose implementation is and likely will
  3014. remain incomplete. Really, it is only here because past midnight seems to
  3015. be the favorite working time of John Wiegley :-)"
  3016. :group 'org-time
  3017. :type 'integer)
  3018. (defcustom org-use-effective-time nil
  3019. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3020. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3021. \"effective time\" of any timestamps between midnight and 8am will be
  3022. 23:59 of the previous day."
  3023. :group 'org-time
  3024. :version "24.1"
  3025. :type 'boolean)
  3026. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3027. "When non-nil, use the last clock out time for `org-todo'.
  3028. Note that this option has precedence over the combined use of
  3029. `org-use-effective-time' and `org-extend-today-until'."
  3030. :group 'org-time
  3031. :version "24.4"
  3032. :package-version '(Org . "8.0")
  3033. :type 'boolean)
  3034. (defcustom org-edit-timestamp-down-means-later nil
  3035. "Non-nil means S-down will increase the time in a time stamp.
  3036. When nil, S-up will increase."
  3037. :group 'org-time
  3038. :type 'boolean)
  3039. (defcustom org-calendar-follow-timestamp-change t
  3040. "Non-nil means make the calendar window follow timestamp changes.
  3041. When a timestamp is modified and the calendar window is visible, it will be
  3042. moved to the new date."
  3043. :group 'org-time
  3044. :type 'boolean)
  3045. (defgroup org-tags nil
  3046. "Options concerning tags in Org mode."
  3047. :tag "Org Tags"
  3048. :group 'org)
  3049. (defcustom org-tag-alist nil
  3050. "Default tags available in Org files.
  3051. The value of this variable is an alist. Associations either:
  3052. (TAG)
  3053. (TAG . SELECT)
  3054. (SPECIAL)
  3055. where TAG is a tag as a string, SELECT is character, used to
  3056. select that tag through the fast tag selection interface, and
  3057. SPECIAL is one of the following keywords: `:startgroup',
  3058. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3059. `:newline'. These keywords are used to define a hierarchy of
  3060. tags. See manual for details.
  3061. When this variable is nil, Org mode bases tag input on what is
  3062. already in the buffer. The value can be overridden locally by
  3063. using a TAGS keyword, e.g.,
  3064. #+TAGS: tag1 tag2
  3065. See also `org-tag-persistent-alist' to sidestep this behavior."
  3066. :group 'org-tags
  3067. :type '(repeat
  3068. (choice
  3069. (cons (string :tag "Tag name")
  3070. (character :tag "Access char"))
  3071. (const :tag "Start radio group" (:startgroup))
  3072. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3073. (const :tag "Group tags delimiter" (:grouptags))
  3074. (const :tag "End radio group" (:endgroup))
  3075. (const :tag "End tag group, non distinct" (:endgrouptag))
  3076. (const :tag "New line" (:newline)))))
  3077. (defcustom org-tag-persistent-alist nil
  3078. "Tags always available in Org files.
  3079. The value of this variable is an alist. Associations either:
  3080. (TAG)
  3081. (TAG . SELECT)
  3082. (SPECIAL)
  3083. where TAG is a tag as a string, SELECT is a character, used to
  3084. select that tag through the fast tag selection interface, and
  3085. SPECIAL is one of the following keywords: `:startgroup',
  3086. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3087. `:newline'. These keywords are used to define a hierarchy of
  3088. tags. See manual for details.
  3089. Unlike to `org-tag-alist', tags defined in this variable do not
  3090. depend on a local TAGS keyword. Instead, to disable these tags
  3091. on a per-file basis, insert anywhere in the file:
  3092. #+STARTUP: noptag"
  3093. :group 'org-tags
  3094. :type '(repeat
  3095. (choice
  3096. (cons (string :tag "Tag name")
  3097. (character :tag "Access char"))
  3098. (const :tag "Start radio group" (:startgroup))
  3099. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3100. (const :tag "Group tags delimiter" (:grouptags))
  3101. (const :tag "End radio group" (:endgroup))
  3102. (const :tag "End tag group, non distinct" (:endgrouptag))
  3103. (const :tag "New line" (:newline)))))
  3104. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3105. "If non-nil, always offer completion for all tags of all agenda files.
  3106. Instead of customizing this variable directly, you might want to
  3107. set it locally for capture buffers, because there no list of
  3108. tags in that file can be created dynamically (there are none).
  3109. (add-hook \\='org-capture-mode-hook
  3110. (lambda ()
  3111. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3112. :group 'org-tags
  3113. :version "24.1"
  3114. :type 'boolean)
  3115. (defvar org-file-tags nil
  3116. "List of tags that can be inherited by all entries in the file.
  3117. The tags will be inherited if the variable `org-use-tag-inheritance'
  3118. says they should be.
  3119. This variable is populated from #+FILETAGS lines.")
  3120. (defcustom org-use-fast-tag-selection 'auto
  3121. "Non-nil means use fast tag selection scheme.
  3122. This is a special interface to select and deselect tags with single keys.
  3123. When nil, fast selection is never used.
  3124. When the symbol `auto', fast selection is used if and only if selection
  3125. characters for tags have been configured, either through the variable
  3126. `org-tag-alist' or through a #+TAGS line in the buffer.
  3127. When t, fast selection is always used and selection keys are assigned
  3128. automatically if necessary."
  3129. :group 'org-tags
  3130. :type '(choice
  3131. (const :tag "Always" t)
  3132. (const :tag "Never" nil)
  3133. (const :tag "When selection characters are configured" auto)))
  3134. (defcustom org-fast-tag-selection-single-key nil
  3135. "Non-nil means fast tag selection exits after first change.
  3136. When nil, you have to press RET to exit it.
  3137. During fast tag selection, you can toggle this flag with `C-c'.
  3138. This variable can also have the value `expert'. In this case, the window
  3139. displaying the tags menu is not even shown, until you press C-c again."
  3140. :group 'org-tags
  3141. :type '(choice
  3142. (const :tag "No" nil)
  3143. (const :tag "Yes" t)
  3144. (const :tag "Expert" expert)))
  3145. (defvar org-fast-tag-selection-include-todo nil
  3146. "Non-nil means fast tags selection interface will also offer TODO states.
  3147. This is an undocumented feature, you should not rely on it.")
  3148. (defcustom org-tags-column -77
  3149. "The column to which tags should be indented in a headline.
  3150. If this number is positive, it specifies the column. If it is negative,
  3151. it means that the tags should be flushright to that column. For example,
  3152. -80 works well for a normal 80 character screen.
  3153. When 0, place tags directly after headline text, with only one space in
  3154. between."
  3155. :group 'org-tags
  3156. :type 'integer)
  3157. (defcustom org-auto-align-tags t
  3158. "Non-nil keeps tags aligned when modifying headlines.
  3159. Some operations (i.e. demoting) change the length of a headline and
  3160. therefore shift the tags around. With this option turned on, after
  3161. each such operation the tags are again aligned to `org-tags-column'."
  3162. :group 'org-tags
  3163. :type 'boolean)
  3164. (defcustom org-use-tag-inheritance t
  3165. "Non-nil means tags in levels apply also for sublevels.
  3166. When nil, only the tags directly given in a specific line apply there.
  3167. This may also be a list of tags that should be inherited, or a regexp that
  3168. matches tags that should be inherited. Additional control is possible
  3169. with the variable `org-tags-exclude-from-inheritance' which gives an
  3170. explicit list of tags to be excluded from inheritance, even if the value of
  3171. `org-use-tag-inheritance' would select it for inheritance.
  3172. If this option is t, a match early-on in a tree can lead to a large
  3173. number of matches in the subtree when constructing the agenda or creating
  3174. a sparse tree. If you only want to see the first match in a tree during
  3175. a search, check out the variable `org-tags-match-list-sublevels'."
  3176. :group 'org-tags
  3177. :type '(choice
  3178. (const :tag "Not" nil)
  3179. (const :tag "Always" t)
  3180. (repeat :tag "Specific tags" (string :tag "Tag"))
  3181. (regexp :tag "Tags matched by regexp")))
  3182. (defcustom org-tags-exclude-from-inheritance nil
  3183. "List of tags that should never be inherited.
  3184. This is a way to exclude a few tags from inheritance. For way to do
  3185. the opposite, to actively allow inheritance for selected tags,
  3186. see the variable `org-use-tag-inheritance'."
  3187. :group 'org-tags
  3188. :type '(repeat (string :tag "Tag")))
  3189. (defun org-tag-inherit-p (tag)
  3190. "Check if TAG is one that should be inherited."
  3191. (cond
  3192. ((member tag org-tags-exclude-from-inheritance) nil)
  3193. ((eq org-use-tag-inheritance t) t)
  3194. ((not org-use-tag-inheritance) nil)
  3195. ((stringp org-use-tag-inheritance)
  3196. (string-match org-use-tag-inheritance tag))
  3197. ((listp org-use-tag-inheritance)
  3198. (member tag org-use-tag-inheritance))
  3199. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3200. (defcustom org-tags-match-list-sublevels t
  3201. "Non-nil means list also sublevels of headlines matching a search.
  3202. This variable applies to tags/property searches, and also to stuck
  3203. projects because this search is based on a tags match as well.
  3204. When set to the symbol `indented', sublevels are indented with
  3205. leading dots.
  3206. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3207. the sublevels of a headline matching a tag search often also match
  3208. the same search. Listing all of them can create very long lists.
  3209. Setting this variable to nil causes subtrees of a match to be skipped.
  3210. This variable is semi-obsolete and probably should always be true. It
  3211. is better to limit inheritance to certain tags using the variables
  3212. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3213. :group 'org-tags
  3214. :type '(choice
  3215. (const :tag "No, don't list them" nil)
  3216. (const :tag "Yes, do list them" t)
  3217. (const :tag "List them, indented with leading dots" indented)))
  3218. (defcustom org-tags-sort-function nil
  3219. "When set, tags are sorted using this function as a comparator."
  3220. :group 'org-tags
  3221. :type '(choice
  3222. (const :tag "No sorting" nil)
  3223. (const :tag "Alphabetical" string<)
  3224. (const :tag "Reverse alphabetical" string>)
  3225. (function :tag "Custom function" nil)))
  3226. (defvar org-tags-history nil
  3227. "History of minibuffer reads for tags.")
  3228. (defvar org-last-tags-completion-table nil
  3229. "The last used completion table for tags.")
  3230. (defvar org-after-tags-change-hook nil
  3231. "Hook that is run after the tags in a line have changed.")
  3232. (defgroup org-properties nil
  3233. "Options concerning properties in Org mode."
  3234. :tag "Org Properties"
  3235. :group 'org)
  3236. (defcustom org-property-format "%-10s %s"
  3237. "How property key/value pairs should be formatted by `indent-line'.
  3238. When `indent-line' hits a property definition, it will format the line
  3239. according to this format, mainly to make sure that the values are
  3240. lined-up with respect to each other."
  3241. :group 'org-properties
  3242. :type 'string)
  3243. (defcustom org-properties-postprocess-alist nil
  3244. "Alist of properties and functions to adjust inserted values.
  3245. Elements of this alist must be of the form
  3246. ([string] [function])
  3247. where [string] must be a property name and [function] must be a
  3248. lambda expression: this lambda expression must take one argument,
  3249. the value to adjust, and return the new value as a string.
  3250. For example, this element will allow the property \"Remaining\"
  3251. to be updated wrt the relation between the \"Effort\" property
  3252. and the clock summary:
  3253. ((\"Remaining\" (lambda(value)
  3254. (let ((clocksum (org-clock-sum-current-item))
  3255. (effort (org-duration-string-to-minutes
  3256. (org-entry-get (point) \"Effort\"))))
  3257. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3258. :group 'org-properties
  3259. :version "24.1"
  3260. :type '(alist :key-type (string :tag "Property")
  3261. :value-type (function :tag "Function")))
  3262. (defcustom org-use-property-inheritance nil
  3263. "Non-nil means properties apply also for sublevels.
  3264. This setting is chiefly used during property searches. Turning it on can
  3265. cause significant overhead when doing a search, which is why it is not
  3266. on by default.
  3267. When nil, only the properties directly given in the current entry count.
  3268. When t, every property is inherited. The value may also be a list of
  3269. properties that should have inheritance, or a regular expression matching
  3270. properties that should be inherited.
  3271. However, note that some special properties use inheritance under special
  3272. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3273. and the properties ending in \"_ALL\" when they are used as descriptor
  3274. for valid values of a property.
  3275. Note for programmers:
  3276. When querying an entry with `org-entry-get', you can control if inheritance
  3277. should be used. By default, `org-entry-get' looks only at the local
  3278. properties. You can request inheritance by setting the inherit argument
  3279. to t (to force inheritance) or to `selective' (to respect the setting
  3280. in this variable)."
  3281. :group 'org-properties
  3282. :type '(choice
  3283. (const :tag "Not" nil)
  3284. (const :tag "Always" t)
  3285. (repeat :tag "Specific properties" (string :tag "Property"))
  3286. (regexp :tag "Properties matched by regexp")))
  3287. (defun org-property-inherit-p (property)
  3288. "Return a non-nil value if PROPERTY should be inherited."
  3289. (cond
  3290. ((eq org-use-property-inheritance t) t)
  3291. ((not org-use-property-inheritance) nil)
  3292. ((stringp org-use-property-inheritance)
  3293. (string-match org-use-property-inheritance property))
  3294. ((listp org-use-property-inheritance)
  3295. (member-ignore-case property org-use-property-inheritance))
  3296. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3297. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3298. "The default column format, if no other format has been defined.
  3299. This variable can be set on the per-file basis by inserting a line
  3300. #+COLUMNS: %25ITEM ....."
  3301. :group 'org-properties
  3302. :type 'string)
  3303. (defcustom org-columns-ellipses ".."
  3304. "The ellipses to be used when a field in column view is truncated.
  3305. When this is the empty string, as many characters as possible are shown,
  3306. but then there will be no visual indication that the field has been truncated.
  3307. When this is a string of length N, the last N characters of a truncated
  3308. field are replaced by this string. If the column is narrower than the
  3309. ellipses string, only part of the ellipses string will be shown."
  3310. :group 'org-properties
  3311. :type 'string)
  3312. (defconst org-global-properties-fixed
  3313. '(("VISIBILITY_ALL" . "folded children content all")
  3314. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3315. "List of property/value pairs that can be inherited by any entry.
  3316. These are fixed values, for the preset properties. The user variable
  3317. that can be used to add to this list is `org-global-properties'.
  3318. The entries in this list are cons cells where the car is a property
  3319. name and cdr is a string with the value. If the value represents
  3320. multiple items like an \"_ALL\" property, separate the items by
  3321. spaces.")
  3322. (defcustom org-global-properties nil
  3323. "List of property/value pairs that can be inherited by any entry.
  3324. This list will be combined with the constant `org-global-properties-fixed'.
  3325. The entries in this list are cons cells where the car is a property
  3326. name and cdr is a string with the value.
  3327. You can set buffer-local values for the same purpose in the variable
  3328. `org-file-properties' this by adding lines like
  3329. #+PROPERTY: NAME VALUE"
  3330. :group 'org-properties
  3331. :type '(repeat
  3332. (cons (string :tag "Property")
  3333. (string :tag "Value"))))
  3334. (defvar-local org-file-properties nil
  3335. "List of property/value pairs that can be inherited by any entry.
  3336. Valid for the current buffer.
  3337. This variable is populated from #+PROPERTY lines.")
  3338. (defgroup org-agenda nil
  3339. "Options concerning agenda views in Org mode."
  3340. :tag "Org Agenda"
  3341. :group 'org)
  3342. (defvar-local org-category nil
  3343. "Variable used by org files to set a category for agenda display.
  3344. Such files should use a file variable to set it, for example
  3345. # -*- mode: org; org-category: \"ELisp\"
  3346. or contain a special line
  3347. #+CATEGORY: ELisp
  3348. If the file does not specify a category, then file's base name
  3349. is used instead.")
  3350. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3351. (defcustom org-agenda-files nil
  3352. "The files to be used for agenda display.
  3353. If an entry is a directory, all files in that directory that are matched
  3354. by `org-agenda-file-regexp' will be part of the file list.
  3355. If the value of the variable is not a list but a single file name, then
  3356. the list of agenda files is actually stored and maintained in that file,
  3357. one agenda file per line. In this file paths can be given relative to
  3358. `org-directory'. Tilde expansion and environment variable substitution
  3359. are also made.
  3360. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3361. and removed with `\\[org-remove-file]'."
  3362. :group 'org-agenda
  3363. :type '(choice
  3364. (repeat :tag "List of files and directories" file)
  3365. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3366. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3367. "Regular expression to match files for `org-agenda-files'.
  3368. If any element in the list in that variable contains a directory instead
  3369. of a normal file, all files in that directory that are matched by this
  3370. regular expression will be included."
  3371. :group 'org-agenda
  3372. :type 'regexp)
  3373. (defcustom org-agenda-text-search-extra-files nil
  3374. "List of extra files to be searched by text search commands.
  3375. These files will be searched in addition to the agenda files by the
  3376. commands `org-search-view' (`\\[org-agenda] s') \
  3377. and `org-occur-in-agenda-files'.
  3378. Note that these files will only be searched for text search commands,
  3379. not for the other agenda views like todo lists, tag searches or the weekly
  3380. agenda. This variable is intended to list notes and possibly archive files
  3381. that should also be searched by these two commands.
  3382. In fact, if the first element in the list is the symbol `agenda-archives',
  3383. then all archive files of all agenda files will be added to the search
  3384. scope."
  3385. :group 'org-agenda
  3386. :type '(set :greedy t
  3387. (const :tag "Agenda Archives" agenda-archives)
  3388. (repeat :inline t (file))))
  3389. (defvaralias 'org-agenda-multi-occur-extra-files
  3390. 'org-agenda-text-search-extra-files)
  3391. (defcustom org-agenda-skip-unavailable-files nil
  3392. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3393. A nil value means to remove them, after a query, from the list."
  3394. :group 'org-agenda
  3395. :type 'boolean)
  3396. (defcustom org-calendar-to-agenda-key [?c]
  3397. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3398. The command `org-calendar-goto-agenda' will be bound to this key. The
  3399. default is the character `c' because then `c' can be used to switch back and
  3400. forth between agenda and calendar."
  3401. :group 'org-agenda
  3402. :type 'sexp)
  3403. (defcustom org-calendar-insert-diary-entry-key [?i]
  3404. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3405. This option is irrelevant until `org-agenda-diary-file' has been configured
  3406. to point to an Org file. When that is the case, the command
  3407. `org-agenda-diary-entry' will be bound to the key given here, by default
  3408. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3409. if you want to continue doing this, you need to change this to a different
  3410. key."
  3411. :group 'org-agenda
  3412. :type 'sexp)
  3413. (defcustom org-agenda-diary-file 'diary-file
  3414. "File to which to add new entries with the `i' key in agenda and calendar.
  3415. When this is the symbol `diary-file', the functionality in the Emacs
  3416. calendar will be used to add entries to the `diary-file'. But when this
  3417. points to a file, `org-agenda-diary-entry' will be used instead."
  3418. :group 'org-agenda
  3419. :type '(choice
  3420. (const :tag "The standard Emacs diary file" diary-file)
  3421. (file :tag "Special Org file diary entries")))
  3422. (eval-after-load "calendar"
  3423. '(progn
  3424. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3425. 'org-calendar-goto-agenda)
  3426. (add-hook 'calendar-mode-hook
  3427. (lambda ()
  3428. (unless (eq org-agenda-diary-file 'diary-file)
  3429. (define-key calendar-mode-map
  3430. org-calendar-insert-diary-entry-key
  3431. 'org-agenda-diary-entry))))))
  3432. (defgroup org-latex nil
  3433. "Options for embedding LaTeX code into Org mode."
  3434. :tag "Org LaTeX"
  3435. :group 'org)
  3436. (defcustom org-format-latex-options
  3437. '(:foreground default :background default :scale 1.0
  3438. :html-foreground "Black" :html-background "Transparent"
  3439. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3440. "Options for creating images from LaTeX fragments.
  3441. This is a property list with the following properties:
  3442. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3443. `default' means use the foreground of the default face.
  3444. `auto' means use the foreground from the text face.
  3445. :background the background color, or \"Transparent\".
  3446. `default' means use the background of the default face.
  3447. `auto' means use the background from the text face.
  3448. :scale a scaling factor for the size of the images, to get more pixels
  3449. :html-foreground, :html-background, :html-scale
  3450. the same numbers for HTML export.
  3451. :matchers a list indicating which matchers should be used to
  3452. find LaTeX fragments. Valid members of this list are:
  3453. \"begin\" find environments
  3454. \"$1\" find single characters surrounded by $.$
  3455. \"$\" find math expressions surrounded by $...$
  3456. \"$$\" find math expressions surrounded by $$....$$
  3457. \"\\(\" find math expressions surrounded by \\(...\\)
  3458. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3459. :group 'org-latex
  3460. :type 'plist)
  3461. (defcustom org-format-latex-signal-error t
  3462. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3463. When nil, just push out a message."
  3464. :group 'org-latex
  3465. :version "24.1"
  3466. :type 'boolean)
  3467. (defcustom org-latex-to-mathml-jar-file nil
  3468. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3469. Use this to specify additional executable file say a jar file.
  3470. When using MathToWeb as the converter, specify the full-path to
  3471. your mathtoweb.jar file."
  3472. :group 'org-latex
  3473. :version "24.1"
  3474. :type '(choice
  3475. (const :tag "None" nil)
  3476. (file :tag "JAR file" :must-match t)))
  3477. (defcustom org-latex-to-mathml-convert-command nil
  3478. "Command to convert LaTeX fragments to MathML.
  3479. Replace format-specifiers in the command as noted below and use
  3480. `shell-command' to convert LaTeX to MathML.
  3481. %j: Executable file in fully expanded form as specified by
  3482. `org-latex-to-mathml-jar-file'.
  3483. %I: Input LaTeX file in fully expanded form.
  3484. %i: The latex fragment to be converted.
  3485. %o: Output MathML file.
  3486. This command is used by `org-create-math-formula'.
  3487. When using MathToWeb as the converter, set this option to
  3488. \"java -jar %j -unicode -force -df %o %I\".
  3489. When using LaTeXML set this option to
  3490. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3491. :group 'org-latex
  3492. :version "24.1"
  3493. :type '(choice
  3494. (const :tag "None" nil)
  3495. (string :tag "\nShell command")))
  3496. (defcustom org-preview-latex-default-process 'dvipng
  3497. "The default process to convert LaTeX fragments to image files.
  3498. All available processes and theirs documents can be found in
  3499. `org-preview-latex-process-alist', which see."
  3500. :group 'org-latex
  3501. :version "26.1"
  3502. :package-version '(Org . "9.0")
  3503. :type 'symbol)
  3504. (defcustom org-preview-latex-process-alist
  3505. '((dvipng
  3506. :programs ("latex" "dvipng")
  3507. :description "dvi > png"
  3508. :message "you need to install the programs: latex and dvipng."
  3509. :image-input-type "dvi"
  3510. :image-output-type "png"
  3511. :image-size-adjust (1.0 . 1.0)
  3512. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3513. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3514. (dvisvgm
  3515. :programs ("latex" "dvisvgm")
  3516. :description "dvi > svg"
  3517. :message "you need to install the programs: latex and dvisvgm."
  3518. :use-xcolor t
  3519. :image-input-type "dvi"
  3520. :image-output-type "svg"
  3521. :image-size-adjust (1.7 . 1.5)
  3522. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3523. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3524. (imagemagick
  3525. :programs ("latex" "convert")
  3526. :description "pdf > png"
  3527. :message "you need to install the programs: latex and imagemagick."
  3528. :use-xcolor t
  3529. :image-input-type "pdf"
  3530. :image-output-type "png"
  3531. :image-size-adjust (1.0 . 1.0)
  3532. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3533. :image-converter
  3534. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3535. "Definitions of external processes for LaTeX previewing.
  3536. Org mode can use some external commands to generate TeX snippet's images for
  3537. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3538. `org-create-formula-image' how to call them.
  3539. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3540. PROPERTIES accepts the following attributes:
  3541. :programs list of strings, required programs.
  3542. :description string, describe the process.
  3543. :message string, message it when required programs cannot be found.
  3544. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3545. :image-output-type string, output file type of image converter (e.g., \"png\").
  3546. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3547. deal with background and foreground color of image.
  3548. Otherwise, dvipng style background and foregroud color
  3549. format are generated. You may then refer to them in
  3550. command options with \"%F\" and \"%B\".
  3551. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3552. image size showed in buffer and the cdr element is for
  3553. HTML file. This option is only useful for process
  3554. developers, users should use variable
  3555. `org-format-latex-options' instead.
  3556. :post-clean list of strings, files matched are to be cleaned up once
  3557. the image is generated. When nil, the files with \".dvi\",
  3558. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3559. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3560. be cleaned up.
  3561. :latex-header list of strings, the LaTeX header of the snippet file.
  3562. When nil, the fallback value is used instead, which is
  3563. controlled by `org-format-latex-header',
  3564. `org-latex-default-packages-alist' and
  3565. `org-latex-packages-alist', which see.
  3566. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3567. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3568. replaced with values defined below.
  3569. :image-converter list of image converter commands strings. Each of them is
  3570. given to the shell and supports any of the following
  3571. place-holders defined below.
  3572. Place-holders used by `:image-converter' and `:latex-compiler':
  3573. %f input file name
  3574. %b base name of input file
  3575. %o base directory of input file
  3576. %O absolute output file name
  3577. Place-holders only used by `:image-converter':
  3578. %F foreground of image
  3579. %B background of image
  3580. %D dpi, which is used to adjust image size by some processing commands.
  3581. %S the image size scale ratio, which is used to adjust image size by some
  3582. processing commands."
  3583. :group 'org-latex
  3584. :version "26.1"
  3585. :package-version '(Org . "9.0")
  3586. :type '(alist :tag "LaTeX to image backends"
  3587. :value-type (plist)))
  3588. (defcustom org-preview-latex-image-directory "ltximg/"
  3589. "Path to store latex preview images.
  3590. A relative path here creates many directories relative to the
  3591. processed org files paths. An absolute path puts all preview
  3592. images at the same place."
  3593. :group 'org-latex
  3594. :version "26.1"
  3595. :package-version '(Org . "9.0")
  3596. :type 'string)
  3597. (defun org-format-latex-mathml-available-p ()
  3598. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3599. (save-match-data
  3600. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3601. org-latex-to-mathml-convert-command)
  3602. (let ((executable (car (split-string
  3603. org-latex-to-mathml-convert-command))))
  3604. (when (executable-find executable)
  3605. (if (string-match
  3606. "%j" org-latex-to-mathml-convert-command)
  3607. (file-readable-p org-latex-to-mathml-jar-file)
  3608. t))))))
  3609. (defcustom org-format-latex-header "\\documentclass{article}
  3610. \\usepackage[usenames]{color}
  3611. \[PACKAGES]
  3612. \[DEFAULT-PACKAGES]
  3613. \\pagestyle{empty} % do not remove
  3614. % The settings below are copied from fullpage.sty
  3615. \\setlength{\\textwidth}{\\paperwidth}
  3616. \\addtolength{\\textwidth}{-3cm}
  3617. \\setlength{\\oddsidemargin}{1.5cm}
  3618. \\addtolength{\\oddsidemargin}{-2.54cm}
  3619. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3620. \\setlength{\\textheight}{\\paperheight}
  3621. \\addtolength{\\textheight}{-\\headheight}
  3622. \\addtolength{\\textheight}{-\\headsep}
  3623. \\addtolength{\\textheight}{-\\footskip}
  3624. \\addtolength{\\textheight}{-3cm}
  3625. \\setlength{\\topmargin}{1.5cm}
  3626. \\addtolength{\\topmargin}{-2.54cm}"
  3627. "The document header used for processing LaTeX fragments.
  3628. It is imperative that this header make sure that no page number
  3629. appears on the page. The package defined in the variables
  3630. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3631. will either replace the placeholder \"[PACKAGES]\" in this
  3632. header, or they will be appended."
  3633. :group 'org-latex
  3634. :type 'string)
  3635. (defun org-set-packages-alist (var val)
  3636. "Set the packages alist and make sure it has 3 elements per entry."
  3637. (set var (mapcar (lambda (x)
  3638. (if (and (consp x) (= (length x) 2))
  3639. (list (car x) (nth 1 x) t)
  3640. x))
  3641. val)))
  3642. (defun org-get-packages-alist (var)
  3643. "Get the packages alist and make sure it has 3 elements per entry."
  3644. (mapcar (lambda (x)
  3645. (if (and (consp x) (= (length x) 2))
  3646. (list (car x) (nth 1 x) t)
  3647. x))
  3648. (default-value var)))
  3649. (defcustom org-latex-default-packages-alist
  3650. '(("AUTO" "inputenc" t ("pdflatex"))
  3651. ("T1" "fontenc" t ("pdflatex"))
  3652. ("" "graphicx" t)
  3653. ("" "grffile" t)
  3654. ("" "longtable" nil)
  3655. ("" "wrapfig" nil)
  3656. ("" "rotating" nil)
  3657. ("normalem" "ulem" t)
  3658. ("" "amsmath" t)
  3659. ("" "textcomp" t)
  3660. ("" "amssymb" t)
  3661. ("" "capt-of" nil)
  3662. ("" "hyperref" nil))
  3663. "Alist of default packages to be inserted in the header.
  3664. Change this only if one of the packages here causes an
  3665. incompatibility with another package you are using.
  3666. The packages in this list are needed by one part or another of
  3667. Org mode to function properly:
  3668. - inputenc, fontenc: for basic font and character selection
  3669. - graphicx: for including images
  3670. - grffile: allow periods and spaces in graphics file names
  3671. - longtable: For multipage tables
  3672. - wrapfig: for figure placement
  3673. - rotating: for sideways figures and tables
  3674. - ulem: for underline and strike-through
  3675. - amsmath: for subscript and superscript and math environments
  3676. - textcomp, amssymb: for various symbols used
  3677. for interpreting the entities in `org-entities'. You can skip
  3678. some of these packages if you don't use any of their symbols.
  3679. - capt-of: for captions outside of floats
  3680. - hyperref: for cross references
  3681. Therefore you should not modify this variable unless you know
  3682. what you are doing. The one reason to change it anyway is that
  3683. you might be loading some other package that conflicts with one
  3684. of the default packages. Each element is either a cell or
  3685. a string.
  3686. A cell is of the format
  3687. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3688. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3689. when compiling LaTeX snippets into images for inclusion into
  3690. non-LaTeX output. COMPILERS is a list of compilers that should
  3691. include the package, see `org-latex-compiler'. If the document
  3692. compiler is not in the list, and the list is non-nil, the package
  3693. will not be inserted in the final document.
  3694. A string will be inserted as-is in the header of the document."
  3695. :group 'org-latex
  3696. :group 'org-export-latex
  3697. :set 'org-set-packages-alist
  3698. :get 'org-get-packages-alist
  3699. :version "26.1"
  3700. :package-version '(Org . "8.3")
  3701. :type '(repeat
  3702. (choice
  3703. (list :tag "options/package pair"
  3704. (string :tag "options")
  3705. (string :tag "package")
  3706. (boolean :tag "Snippet"))
  3707. (string :tag "A line of LaTeX"))))
  3708. (defcustom org-latex-packages-alist nil
  3709. "Alist of packages to be inserted in every LaTeX header.
  3710. These will be inserted after `org-latex-default-packages-alist'.
  3711. Each element is either a cell or a string.
  3712. A cell is of the format:
  3713. (\"options\" \"package\" SNIPPET-FLAG)
  3714. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3715. needed when turning LaTeX snippets into images for inclusion into
  3716. non-LaTeX output.
  3717. A string will be inserted as-is in the header of the document.
  3718. Make sure that you only list packages here which:
  3719. - you want in every file;
  3720. - do not conflict with the setup in `org-format-latex-header';
  3721. - do not conflict with the default packages in
  3722. `org-latex-default-packages-alist'."
  3723. :group 'org-latex
  3724. :group 'org-export-latex
  3725. :set 'org-set-packages-alist
  3726. :get 'org-get-packages-alist
  3727. :type '(repeat
  3728. (choice
  3729. (list :tag "options/package pair"
  3730. (string :tag "options")
  3731. (string :tag "package")
  3732. (boolean :tag "Snippet"))
  3733. (string :tag "A line of LaTeX"))))
  3734. (defgroup org-appearance nil
  3735. "Settings for Org mode appearance."
  3736. :tag "Org Appearance"
  3737. :group 'org)
  3738. (defcustom org-level-color-stars-only nil
  3739. "Non-nil means fontify only the stars in each headline.
  3740. When nil, the entire headline is fontified.
  3741. Changing it requires restart of `font-lock-mode' to become effective
  3742. also in regions already fontified."
  3743. :group 'org-appearance
  3744. :type 'boolean)
  3745. (defcustom org-hide-leading-stars nil
  3746. "Non-nil means hide the first N-1 stars in a headline.
  3747. This works by using the face `org-hide' for these stars. This
  3748. face is white for a light background, and black for a dark
  3749. background. You may have to customize the face `org-hide' to
  3750. make this work.
  3751. Changing it requires restart of `font-lock-mode' to become effective
  3752. also in regions already fontified.
  3753. You may also set this on a per-file basis by adding one of the following
  3754. lines to the buffer:
  3755. #+STARTUP: hidestars
  3756. #+STARTUP: showstars"
  3757. :group 'org-appearance
  3758. :type 'boolean)
  3759. (defcustom org-hidden-keywords nil
  3760. "List of symbols corresponding to keywords to be hidden the org buffer.
  3761. For example, a value \\='(title) for this list will make the document's title
  3762. appear in the buffer without the initial #+TITLE: keyword."
  3763. :group 'org-appearance
  3764. :version "24.1"
  3765. :type '(set (const :tag "#+AUTHOR" author)
  3766. (const :tag "#+DATE" date)
  3767. (const :tag "#+EMAIL" email)
  3768. (const :tag "#+TITLE" title)))
  3769. (defcustom org-custom-properties nil
  3770. "List of properties (as strings) with a special meaning.
  3771. The default use of these custom properties is to let the user
  3772. hide them with `org-toggle-custom-properties-visibility'."
  3773. :group 'org-properties
  3774. :group 'org-appearance
  3775. :version "24.3"
  3776. :type '(repeat (string :tag "Property Name")))
  3777. (defcustom org-fontify-done-headline nil
  3778. "Non-nil means change the face of a headline if it is marked DONE.
  3779. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3780. When this is non-nil, the headline after the keyword is set to the
  3781. `org-headline-done' as an additional indication."
  3782. :group 'org-appearance
  3783. :type 'boolean)
  3784. (defcustom org-fontify-emphasized-text t
  3785. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3786. Changing this variable requires a restart of Emacs to take effect."
  3787. :group 'org-appearance
  3788. :type 'boolean)
  3789. (defcustom org-fontify-whole-heading-line nil
  3790. "Non-nil means fontify the whole line for headings.
  3791. This is useful when setting a background color for the
  3792. org-level-* faces."
  3793. :group 'org-appearance
  3794. :type 'boolean)
  3795. (defcustom org-highlight-latex-and-related nil
  3796. "Non-nil means highlight LaTeX related syntax in the buffer.
  3797. When non nil, the value should be a list containing any of the
  3798. following symbols:
  3799. `latex' Highlight LaTeX snippets and environments.
  3800. `script' Highlight subscript and superscript.
  3801. `entities' Highlight entities."
  3802. :group 'org-appearance
  3803. :version "24.4"
  3804. :package-version '(Org . "8.0")
  3805. :type '(choice
  3806. (const :tag "No highlighting" nil)
  3807. (set :greedy t :tag "Highlight"
  3808. (const :tag "LaTeX snippets and environments" latex)
  3809. (const :tag "Subscript and superscript" script)
  3810. (const :tag "Entities" entities))))
  3811. (defcustom org-hide-emphasis-markers nil
  3812. "Non-nil mean font-lock should hide the emphasis marker characters."
  3813. :group 'org-appearance
  3814. :type 'boolean)
  3815. (defcustom org-hide-macro-markers nil
  3816. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3817. :group 'org-appearance
  3818. :type 'boolean)
  3819. (defcustom org-pretty-entities nil
  3820. "Non-nil means show entities as UTF8 characters.
  3821. When nil, the \\name form remains in the buffer."
  3822. :group 'org-appearance
  3823. :version "24.1"
  3824. :type 'boolean)
  3825. (defcustom org-pretty-entities-include-sub-superscripts t
  3826. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3827. :group 'org-appearance
  3828. :version "24.1"
  3829. :type 'boolean)
  3830. (defvar org-emph-re nil
  3831. "Regular expression for matching emphasis.
  3832. After a match, the match groups contain these elements:
  3833. 0 The match of the full regular expression, including the characters
  3834. before and after the proper match
  3835. 1 The character before the proper match, or empty at beginning of line
  3836. 2 The proper match, including the leading and trailing markers
  3837. 3 The leading marker like * or /, indicating the type of highlighting
  3838. 4 The text between the emphasis markers, not including the markers
  3839. 5 The character after the match, empty at the end of a line")
  3840. (defvar org-verbatim-re nil
  3841. "Regular expression for matching verbatim text.")
  3842. (defvar org-emphasis-regexp-components) ; defined just below
  3843. (defvar org-emphasis-alist) ; defined just below
  3844. (defun org-set-emph-re (var val)
  3845. "Set variable and compute the emphasis regular expression."
  3846. (set var val)
  3847. (when (and (boundp 'org-emphasis-alist)
  3848. (boundp 'org-emphasis-regexp-components)
  3849. org-emphasis-alist org-emphasis-regexp-components)
  3850. (let* ((e org-emphasis-regexp-components)
  3851. (pre (car e))
  3852. (post (nth 1 e))
  3853. (border (nth 2 e))
  3854. (body (nth 3 e))
  3855. (nl (nth 4 e))
  3856. (body1 (concat body "*?"))
  3857. (markers (mapconcat 'car org-emphasis-alist ""))
  3858. (vmarkers (mapconcat
  3859. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3860. org-emphasis-alist "")))
  3861. ;; make sure special characters appear at the right position in the class
  3862. (if (string-match "\\^" markers)
  3863. (setq markers (concat (replace-match "" t t markers) "^")))
  3864. (if (string-match "-" markers)
  3865. (setq markers (concat (replace-match "" t t markers) "-")))
  3866. (if (string-match "\\^" vmarkers)
  3867. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3868. (if (string-match "-" vmarkers)
  3869. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3870. (if (> nl 0)
  3871. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3872. (int-to-string nl) "\\}")))
  3873. ;; Make the regexp
  3874. (setq org-emph-re
  3875. (concat "\\([" pre "]\\|^\\)"
  3876. "\\("
  3877. "\\([" markers "]\\)"
  3878. "\\("
  3879. "[^" border "]\\|"
  3880. "[^" border "]"
  3881. body1
  3882. "[^" border "]"
  3883. "\\)"
  3884. "\\3\\)"
  3885. "\\([" post "]\\|$\\)"))
  3886. (setq org-verbatim-re
  3887. (concat "\\([" pre "]\\|^\\)"
  3888. "\\("
  3889. "\\([" vmarkers "]\\)"
  3890. "\\("
  3891. "[^" border "]\\|"
  3892. "[^" border "]"
  3893. body1
  3894. "[^" border "]"
  3895. "\\)"
  3896. "\\3\\)"
  3897. "\\([" post "]\\|$\\)")))))
  3898. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3899. ;; set this option proved cumbersome. See this message/thread:
  3900. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3901. (defvar org-emphasis-regexp-components
  3902. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3903. "Components used to build the regular expression for emphasis.
  3904. This is a list with five entries. Terminology: In an emphasis string
  3905. like \" *strong word* \", we call the initial space PREMATCH, the final
  3906. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3907. and \"trong wor\" is the body. The different components in this variable
  3908. specify what is allowed/forbidden in each part:
  3909. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3910. post Chars allowed as postmatch. End of line will be allowed too.
  3911. border The chars *forbidden* as border characters.
  3912. body-regexp A regexp like \".\" to match a body character. Don't use
  3913. non-shy groups here, and don't allow newline here.
  3914. newline The maximum number of newlines allowed in an emphasis exp.
  3915. You need to reload Org or to restart Emacs after customizing this.")
  3916. (defcustom org-emphasis-alist
  3917. '(("*" bold)
  3918. ("/" italic)
  3919. ("_" underline)
  3920. ("=" org-verbatim verbatim)
  3921. ("~" org-code verbatim)
  3922. ("+" (:strike-through t)))
  3923. "Alist of characters and faces to emphasize text.
  3924. Text starting and ending with a special character will be emphasized,
  3925. for example *bold*, _underlined_ and /italic/. This variable sets the
  3926. marker characters and the face to be used by font-lock for highlighting
  3927. in Org buffers.
  3928. You need to reload Org or to restart Emacs after customizing this."
  3929. :group 'org-appearance
  3930. :set 'org-set-emph-re
  3931. :version "24.4"
  3932. :package-version '(Org . "8.0")
  3933. :type '(repeat
  3934. (list
  3935. (string :tag "Marker character")
  3936. (choice
  3937. (face :tag "Font-lock-face")
  3938. (plist :tag "Face property list"))
  3939. (option (const verbatim)))))
  3940. (defvar org-protecting-blocks '("src" "example" "export")
  3941. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3942. This is needed for font-lock setup.")
  3943. ;;; Functions and variables from their packages
  3944. ;; Declared here to avoid compiler warnings
  3945. (defvar mark-active)
  3946. ;; Various packages
  3947. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3948. (declare-function calendar-forward-day "cal-move" (arg))
  3949. (declare-function calendar-goto-date "cal-move" (date))
  3950. (declare-function calendar-goto-today "cal-move" ())
  3951. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3952. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3953. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3954. (declare-function cdlatex-tab "ext:cdlatex" ())
  3955. (declare-function dired-get-filename
  3956. "dired"
  3957. (&optional localp no-error-if-not-filep))
  3958. (declare-function iswitchb-read-buffer
  3959. "iswitchb"
  3960. (prompt &optional
  3961. default require-match _predicate start matches-set))
  3962. (declare-function org-agenda-change-all-lines
  3963. "org-agenda"
  3964. (newhead hdmarker &optional fixface just-this))
  3965. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3966. "org-agenda"
  3967. (&optional end))
  3968. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3969. (declare-function org-agenda-format-item
  3970. "org-agenda"
  3971. (extra txt &optional level category tags dotime
  3972. remove-re habitp))
  3973. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3974. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3975. (declare-function org-agenda-save-markers-for-cut-and-paste
  3976. "org-agenda"
  3977. (beg end))
  3978. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3979. (declare-function org-agenda-skip "org-agenda" ())
  3980. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3981. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3982. (declare-function org-indent-mode "org-indent" (&optional arg))
  3983. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3984. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3985. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3986. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3987. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3988. (declare-function parse-time-string "parse-time" (string))
  3989. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3990. (defvar align-mode-rules-list)
  3991. (defvar calc-embedded-close-formula)
  3992. (defvar calc-embedded-open-formula)
  3993. (defvar calc-embedded-open-mode)
  3994. (defvar font-lock-unfontify-region-function)
  3995. (defvar iswitchb-temp-buflist)
  3996. (defvar org-agenda-tags-todo-honor-ignore-options)
  3997. (defvar remember-data-file)
  3998. (defvar texmathp-why)
  3999. ;;;###autoload
  4000. (defun turn-on-orgtbl ()
  4001. "Unconditionally turn on `orgtbl-mode'."
  4002. (require 'org-table)
  4003. (orgtbl-mode 1))
  4004. (defun org-at-table-p (&optional table-type)
  4005. "Non-nil if the cursor is inside an Org table.
  4006. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  4007. If `org-enable-table-editor' is nil, return nil unconditionally."
  4008. (and
  4009. org-enable-table-editor
  4010. (save-excursion
  4011. (beginning-of-line)
  4012. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4013. (or (not (derived-mode-p 'org-mode))
  4014. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4015. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4016. (defun org-at-table.el-p ()
  4017. "Non-nil when point is at a table.el table."
  4018. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4019. (let ((element (org-element-at-point)))
  4020. (and (eq (org-element-type element) 'table)
  4021. (eq (org-element-property :type element) 'table.el)))))
  4022. (defun org-at-table-hline-p ()
  4023. "Non-nil when point is inside a hline in a table.
  4024. Assume point is already in a table. If `org-enable-table-editor'
  4025. is nil, return nil unconditionally."
  4026. (and org-enable-table-editor
  4027. (save-excursion
  4028. (beginning-of-line)
  4029. (looking-at org-table-hline-regexp))))
  4030. (defun org-table-map-tables (function &optional quietly)
  4031. "Apply FUNCTION to the start of all tables in the buffer."
  4032. (org-with-wide-buffer
  4033. (goto-char (point-min))
  4034. (while (re-search-forward org-table-any-line-regexp nil t)
  4035. (unless quietly
  4036. (message "Mapping tables: %d%%"
  4037. (floor (* 100.0 (point)) (buffer-size))))
  4038. (beginning-of-line 1)
  4039. (when (and (looking-at org-table-line-regexp)
  4040. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4041. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4042. (save-excursion (funcall function))
  4043. (or (looking-at org-table-line-regexp)
  4044. (forward-char 1)))
  4045. (re-search-forward org-table-any-border-regexp nil 1)))
  4046. (unless quietly (message "Mapping tables: done")))
  4047. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4048. (declare-function org-clock-update-mode-line "org-clock" ())
  4049. (declare-function org-resolve-clocks "org-clock"
  4050. (&optional also-non-dangling-p prompt last-valid))
  4051. (defun org-at-TBLFM-p (&optional pos)
  4052. "Non-nil when point (or POS) is in #+TBLFM line."
  4053. (save-excursion
  4054. (goto-char (or pos (point)))
  4055. (beginning-of-line)
  4056. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4057. (eq (org-element-type (org-element-at-point)) 'table))))
  4058. (defvar org-clock-start-time)
  4059. (defvar org-clock-marker (make-marker)
  4060. "Marker recording the last clock-in.")
  4061. (defvar org-clock-hd-marker (make-marker)
  4062. "Marker recording the last clock-in, but the headline position.")
  4063. (defvar org-clock-heading ""
  4064. "The heading of the current clock entry.")
  4065. (defun org-clock-is-active ()
  4066. "Return the buffer where the clock is currently running.
  4067. Return nil if no clock is running."
  4068. (marker-buffer org-clock-marker))
  4069. (defun org-check-running-clock ()
  4070. "Check if the current buffer contains the running clock.
  4071. If yes, offer to stop it and to save the buffer with the changes."
  4072. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4073. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4074. (buffer-name))))
  4075. (org-clock-out)
  4076. (when (y-or-n-p "Save changed buffer?")
  4077. (save-buffer))))
  4078. (defun org-clocktable-try-shift (dir n)
  4079. "Check if this line starts a clock table, if yes, shift the time block."
  4080. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4081. (org-clocktable-shift dir n)))
  4082. ;;;###autoload
  4083. (defun org-clock-persistence-insinuate ()
  4084. "Set up hooks for clock persistence."
  4085. (require 'org-clock)
  4086. (add-hook 'org-mode-hook 'org-clock-load)
  4087. (add-hook 'kill-emacs-hook 'org-clock-save))
  4088. (defgroup org-archive nil
  4089. "Options concerning archiving in Org mode."
  4090. :tag "Org Archive"
  4091. :group 'org-structure)
  4092. (defcustom org-archive-location "%s_archive::"
  4093. "The location where subtrees should be archived.
  4094. The value of this variable is a string, consisting of two parts,
  4095. separated by a double-colon. The first part is a filename and
  4096. the second part is a headline.
  4097. When the filename is omitted, archiving happens in the same file.
  4098. %s in the filename will be replaced by the current file
  4099. name (without the directory part). Archiving to a different file
  4100. is useful to keep archived entries from contributing to the
  4101. Org Agenda.
  4102. The archived entries will be filed as subtrees of the specified
  4103. headline. When the headline is omitted, the subtrees are simply
  4104. filed away at the end of the file, as top-level entries. Also in
  4105. the heading you can use %s to represent the file name, this can be
  4106. useful when using the same archive for a number of different files.
  4107. Here are a few examples:
  4108. \"%s_archive::\"
  4109. If the current file is Projects.org, archive in file
  4110. Projects.org_archive, as top-level trees. This is the default.
  4111. \"::* Archived Tasks\"
  4112. Archive in the current file, under the top-level headline
  4113. \"* Archived Tasks\".
  4114. \"~/org/archive.org::\"
  4115. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4116. \"~/org/archive.org::* From %s\"
  4117. Archive in file ~/org/archive.org (absolute path), under headlines
  4118. \"From FILENAME\" where file name is the current file name.
  4119. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4120. The \"datetree/\" string is special, signifying to archive
  4121. items to the datetree. Items are placed in either the CLOSED
  4122. date of the item, or the current date if there is no CLOSED date.
  4123. The heading will be a subentry to the current date. There doesn't
  4124. need to be a heading, but there always needs to be a slash after
  4125. datetree. For example, to store archived items directly in the
  4126. datetree, use \"~/org/datetree.org::datetree/\".
  4127. \"basement::** Finished Tasks\"
  4128. Archive in file ./basement (relative path), as level 3 trees
  4129. below the level 2 heading \"** Finished Tasks\".
  4130. You may set this option on a per-file basis by adding to the buffer a
  4131. line like
  4132. #+ARCHIVE: basement::** Finished Tasks
  4133. You may also define it locally for a subtree by setting an ARCHIVE property
  4134. in the entry. If such a property is found in an entry, or anywhere up
  4135. the hierarchy, it will be used."
  4136. :group 'org-archive
  4137. :type 'string)
  4138. (defcustom org-agenda-skip-archived-trees t
  4139. "Non-nil means the agenda will skip any items located in archived trees.
  4140. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4141. variable is no longer recommended, you should leave it at the value t.
  4142. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4143. :group 'org-archive
  4144. :group 'org-agenda-skip
  4145. :type 'boolean)
  4146. (defcustom org-columns-skip-archived-trees t
  4147. "Non-nil means ignore archived trees when creating column view."
  4148. :group 'org-archive
  4149. :group 'org-properties
  4150. :type 'boolean)
  4151. (defcustom org-cycle-open-archived-trees nil
  4152. "Non-nil means `org-cycle' will open archived trees.
  4153. An archived tree is a tree marked with the tag ARCHIVE.
  4154. When nil, archived trees will stay folded. You can still open them with
  4155. normal outline commands like `show-all', but not with the cycling commands."
  4156. :group 'org-archive
  4157. :group 'org-cycle
  4158. :type 'boolean)
  4159. (defcustom org-sparse-tree-open-archived-trees nil
  4160. "Non-nil means sparse tree construction shows matches in archived trees.
  4161. When nil, matches in these trees are highlighted, but the trees are kept in
  4162. collapsed state."
  4163. :group 'org-archive
  4164. :group 'org-sparse-trees
  4165. :type 'boolean)
  4166. (defcustom org-sparse-tree-default-date-type nil
  4167. "The default date type when building a sparse tree.
  4168. When this is nil, a date is a scheduled or a deadline timestamp.
  4169. Otherwise, these types are allowed:
  4170. all: all timestamps
  4171. active: only active timestamps (<...>)
  4172. inactive: only inactive timestamps ([...])
  4173. scheduled: only scheduled timestamps
  4174. deadline: only deadline timestamps"
  4175. :type '(choice (const :tag "Scheduled or deadline" nil)
  4176. (const :tag "All timestamps" all)
  4177. (const :tag "Only active timestamps" active)
  4178. (const :tag "Only inactive timestamps" inactive)
  4179. (const :tag "Only scheduled timestamps" scheduled)
  4180. (const :tag "Only deadline timestamps" deadline)
  4181. (const :tag "Only closed timestamps" closed))
  4182. :version "26.1"
  4183. :package-version '(Org . "8.3")
  4184. :group 'org-sparse-trees)
  4185. (defun org-cycle-hide-archived-subtrees (state)
  4186. "Re-hide all archived subtrees after a visibility state change."
  4187. (when (and (not org-cycle-open-archived-trees)
  4188. (not (memq state '(overview folded))))
  4189. (save-excursion
  4190. (let* ((globalp (memq state '(contents all)))
  4191. (beg (if globalp (point-min) (point)))
  4192. (end (if globalp (point-max) (org-end-of-subtree t))))
  4193. (org-hide-archived-subtrees beg end)
  4194. (goto-char beg)
  4195. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4196. (message "%s" (substitute-command-keys
  4197. "Subtree is archived and stays closed. Use \
  4198. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4199. (defun org-force-cycle-archived ()
  4200. "Cycle subtree even if it is archived."
  4201. (interactive)
  4202. (setq this-command 'org-cycle)
  4203. (let ((org-cycle-open-archived-trees t))
  4204. (call-interactively 'org-cycle)))
  4205. (defun org-hide-archived-subtrees (beg end)
  4206. "Re-hide all archived subtrees after a visibility state change."
  4207. (org-with-wide-buffer
  4208. (let ((case-fold-search nil)
  4209. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4210. (goto-char beg)
  4211. ;; Include headline point is currently on.
  4212. (beginning-of-line)
  4213. (while (and (< (point) end) (re-search-forward re end t))
  4214. (when (member org-archive-tag (org-get-tags))
  4215. (org-flag-subtree t)
  4216. (org-end-of-subtree t))))))
  4217. (declare-function outline-end-of-heading "outline" ())
  4218. (declare-function outline-flag-region "outline" (from to flag))
  4219. (defun org-flag-subtree (flag)
  4220. (save-excursion
  4221. (org-back-to-heading t)
  4222. (outline-end-of-heading)
  4223. (outline-flag-region (point)
  4224. (progn (org-end-of-subtree t) (point))
  4225. flag)))
  4226. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4227. ;; Declare Column View Code
  4228. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4229. (declare-function org-columns-compute "org-colview" (property))
  4230. ;; Declare ID code
  4231. (declare-function org-id-store-link "org-id")
  4232. (declare-function org-id-locations-load "org-id")
  4233. (declare-function org-id-locations-save "org-id")
  4234. (defvar org-id-track-globally)
  4235. ;;; Variables for pre-computed regular expressions, all buffer local
  4236. (defvar-local org-todo-regexp nil
  4237. "Matches any of the TODO state keywords.
  4238. Since TODO keywords are case-sensitive, `case-fold-search' is
  4239. expected to be bound to nil when matching against this regexp.")
  4240. (defvar-local org-not-done-regexp nil
  4241. "Matches any of the TODO state keywords except the last one.
  4242. Since TODO keywords are case-sensitive, `case-fold-search' is
  4243. expected to be bound to nil when matching against this regexp.")
  4244. (defvar-local org-not-done-heading-regexp nil
  4245. "Matches a TODO headline that is not done.
  4246. Since TODO keywords are case-sensitive, `case-fold-search' is
  4247. expected to be bound to nil when matching against this regexp.")
  4248. (defvar-local org-todo-line-regexp nil
  4249. "Matches a headline and puts TODO state into group 2 if present.
  4250. Since TODO keywords are case-sensitive, `case-fold-search' is
  4251. expected to be bound to nil when matching against this regexp.")
  4252. (defvar-local org-complex-heading-regexp nil
  4253. "Matches a headline and puts everything into groups:
  4254. group 1: Stars
  4255. group 2: The TODO keyword, maybe
  4256. group 3: Priority cookie
  4257. group 4: True headline
  4258. group 5: Tags
  4259. Since TODO keywords are case-sensitive, `case-fold-search' is
  4260. expected to be bound to nil when matching against this regexp.")
  4261. (defvar-local org-complex-heading-regexp-format nil
  4262. "Printf format to make regexp to match an exact headline.
  4263. This regexp will match the headline of any node which has the
  4264. exact headline text that is put into the format, but may have any
  4265. TODO state, priority and tags.")
  4266. (defvar-local org-todo-line-tags-regexp nil
  4267. "Matches a headline and puts TODO state into group 2 if present.
  4268. Also put tags into group 4 if tags are present.")
  4269. (defconst org-plain-time-of-day-regexp
  4270. (concat
  4271. "\\(\\<[012]?[0-9]"
  4272. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4273. "\\(--?"
  4274. "\\(\\<[012]?[0-9]"
  4275. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4276. "\\)?")
  4277. "Regular expression to match a plain time or time range.
  4278. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4279. groups carry important information:
  4280. 0 the full match
  4281. 1 the first time, range or not
  4282. 8 the second time, if it is a range.")
  4283. (defconst org-plain-time-extension-regexp
  4284. (concat
  4285. "\\(\\<[012]?[0-9]"
  4286. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4287. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4288. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4289. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4290. groups carry important information:
  4291. 0 the full match
  4292. 7 hours of duration
  4293. 9 minutes of duration")
  4294. (defconst org-stamp-time-of-day-regexp
  4295. (concat
  4296. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4297. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4298. "\\(--?"
  4299. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4300. "Regular expression to match a timestamp time or time range.
  4301. After a match, the following groups carry important information:
  4302. 0 the full match
  4303. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4304. 2 the first time, range or not
  4305. 4 the second time, if it is a range.")
  4306. (defconst org-startup-options
  4307. '(("fold" org-startup-folded t)
  4308. ("overview" org-startup-folded t)
  4309. ("nofold" org-startup-folded nil)
  4310. ("showall" org-startup-folded nil)
  4311. ("showeverything" org-startup-folded showeverything)
  4312. ("content" org-startup-folded content)
  4313. ("indent" org-startup-indented t)
  4314. ("noindent" org-startup-indented nil)
  4315. ("hidestars" org-hide-leading-stars t)
  4316. ("showstars" org-hide-leading-stars nil)
  4317. ("odd" org-odd-levels-only t)
  4318. ("oddeven" org-odd-levels-only nil)
  4319. ("align" org-startup-align-all-tables t)
  4320. ("noalign" org-startup-align-all-tables nil)
  4321. ("inlineimages" org-startup-with-inline-images t)
  4322. ("noinlineimages" org-startup-with-inline-images nil)
  4323. ("latexpreview" org-startup-with-latex-preview t)
  4324. ("nolatexpreview" org-startup-with-latex-preview nil)
  4325. ("customtime" org-display-custom-times t)
  4326. ("logdone" org-log-done time)
  4327. ("lognotedone" org-log-done note)
  4328. ("nologdone" org-log-done nil)
  4329. ("lognoteclock-out" org-log-note-clock-out t)
  4330. ("nolognoteclock-out" org-log-note-clock-out nil)
  4331. ("logrepeat" org-log-repeat state)
  4332. ("lognoterepeat" org-log-repeat note)
  4333. ("logdrawer" org-log-into-drawer t)
  4334. ("nologdrawer" org-log-into-drawer nil)
  4335. ("logstatesreversed" org-log-states-order-reversed t)
  4336. ("nologstatesreversed" org-log-states-order-reversed nil)
  4337. ("nologrepeat" org-log-repeat nil)
  4338. ("logreschedule" org-log-reschedule time)
  4339. ("lognotereschedule" org-log-reschedule note)
  4340. ("nologreschedule" org-log-reschedule nil)
  4341. ("logredeadline" org-log-redeadline time)
  4342. ("lognoteredeadline" org-log-redeadline note)
  4343. ("nologredeadline" org-log-redeadline nil)
  4344. ("logrefile" org-log-refile time)
  4345. ("lognoterefile" org-log-refile note)
  4346. ("nologrefile" org-log-refile nil)
  4347. ("fninline" org-footnote-define-inline t)
  4348. ("nofninline" org-footnote-define-inline nil)
  4349. ("fnlocal" org-footnote-section nil)
  4350. ("fnauto" org-footnote-auto-label t)
  4351. ("fnprompt" org-footnote-auto-label nil)
  4352. ("fnconfirm" org-footnote-auto-label confirm)
  4353. ("fnplain" org-footnote-auto-label plain)
  4354. ("fnadjust" org-footnote-auto-adjust t)
  4355. ("nofnadjust" org-footnote-auto-adjust nil)
  4356. ("constcgs" constants-unit-system cgs)
  4357. ("constSI" constants-unit-system SI)
  4358. ("noptag" org-tag-persistent-alist nil)
  4359. ("hideblocks" org-hide-block-startup t)
  4360. ("nohideblocks" org-hide-block-startup nil)
  4361. ("beamer" org-startup-with-beamer-mode t)
  4362. ("entitiespretty" org-pretty-entities t)
  4363. ("entitiesplain" org-pretty-entities nil))
  4364. "Variable associated with STARTUP options for org-mode.
  4365. Each element is a list of three items: the startup options (as written
  4366. in the #+STARTUP line), the corresponding variable, and the value to set
  4367. this variable to if the option is found. An optional forth element PUSH
  4368. means to push this value onto the list in the variable.")
  4369. (defcustom org-group-tags t
  4370. "When non-nil (the default), use group tags.
  4371. This can be turned on/off through `org-toggle-tags-groups'."
  4372. :group 'org-tags
  4373. :group 'org-startup
  4374. :type 'boolean)
  4375. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4376. (defun org-toggle-tags-groups ()
  4377. "Toggle support for group tags.
  4378. Support for group tags is controlled by the option
  4379. `org-group-tags', which is non-nil by default."
  4380. (interactive)
  4381. (setq org-group-tags (not org-group-tags))
  4382. (cond ((and (derived-mode-p 'org-agenda-mode)
  4383. org-group-tags)
  4384. (org-agenda-redo))
  4385. ((derived-mode-p 'org-mode)
  4386. (let ((org-inhibit-startup t)) (org-mode))))
  4387. (message "Groups tags support has been turned %s"
  4388. (if org-group-tags "on" "off")))
  4389. (defun org-set-regexps-and-options (&optional tags-only)
  4390. "Precompute regular expressions used in the current buffer.
  4391. When optional argument TAGS-ONLY is non-nil, only compute tags
  4392. related expressions."
  4393. (when (derived-mode-p 'org-mode)
  4394. (let ((alist (org--setup-collect-keywords
  4395. (org-make-options-regexp
  4396. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4397. (and (not tags-only)
  4398. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4399. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4400. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4401. ;; Startup options. Get this early since it does change
  4402. ;; behavior for other options (e.g., tags).
  4403. (let ((startup (cdr (assq 'startup alist))))
  4404. (dolist (option startup)
  4405. (let ((entry (assoc-string option org-startup-options t)))
  4406. (when entry
  4407. (let ((var (nth 1 entry))
  4408. (val (nth 2 entry)))
  4409. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4410. (unless (listp (symbol-value var))
  4411. (set (make-local-variable var) nil))
  4412. (add-to-list var val)))))))
  4413. (setq-local org-file-tags
  4414. (mapcar #'org-add-prop-inherited
  4415. (cdr (assq 'filetags alist))))
  4416. (setq org-current-tag-alist
  4417. (append org-tag-persistent-alist
  4418. (let ((tags (cdr (assq 'tags alist))))
  4419. (if tags (org-tag-string-to-alist tags)
  4420. org-tag-alist))))
  4421. (setq org-tag-groups-alist
  4422. (org-tag-alist-to-groups org-current-tag-alist))
  4423. (unless tags-only
  4424. ;; File properties.
  4425. (setq-local org-file-properties (cdr (assq 'property alist)))
  4426. ;; Archive location.
  4427. (let ((archive (cdr (assq 'archive alist))))
  4428. (when archive (setq-local org-archive-location archive)))
  4429. ;; Category.
  4430. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4431. (when cat
  4432. (setq-local org-category (intern cat))
  4433. (setq-local org-file-properties
  4434. (org--update-property-plist
  4435. "CATEGORY" cat org-file-properties))))
  4436. ;; Columns.
  4437. (let ((column (cdr (assq 'columns alist))))
  4438. (when column (setq-local org-columns-default-format column)))
  4439. ;; Constants.
  4440. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4441. ;; Link abbreviations.
  4442. (let ((links (cdr (assq 'link alist))))
  4443. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4444. ;; Priorities.
  4445. (let ((priorities (cdr (assq 'priorities alist))))
  4446. (when priorities
  4447. (setq-local org-highest-priority (nth 0 priorities))
  4448. (setq-local org-lowest-priority (nth 1 priorities))
  4449. (setq-local org-default-priority (nth 2 priorities))))
  4450. ;; Scripts.
  4451. (let ((scripts (assq 'scripts alist)))
  4452. (when scripts
  4453. (setq-local org-use-sub-superscripts (cdr scripts))))
  4454. ;; TODO keywords.
  4455. (setq-local org-todo-kwd-alist nil)
  4456. (setq-local org-todo-key-alist nil)
  4457. (setq-local org-todo-key-trigger nil)
  4458. (setq-local org-todo-keywords-1 nil)
  4459. (setq-local org-done-keywords nil)
  4460. (setq-local org-todo-heads nil)
  4461. (setq-local org-todo-sets nil)
  4462. (setq-local org-todo-log-states nil)
  4463. (let ((todo-sequences
  4464. (or (nreverse (cdr (assq 'todo alist)))
  4465. (let ((d (default-value 'org-todo-keywords)))
  4466. (if (not (stringp (car d))) d
  4467. ;; XXX: Backward compatibility code.
  4468. (list (cons org-todo-interpretation d)))))))
  4469. (dolist (sequence todo-sequences)
  4470. (let* ((sequence (or (run-hook-with-args-until-success
  4471. 'org-todo-setup-filter-hook sequence)
  4472. sequence))
  4473. (sequence-type (car sequence))
  4474. (keywords (cdr sequence))
  4475. (sep (member "|" keywords))
  4476. names alist)
  4477. (dolist (k (remove "|" keywords))
  4478. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4479. k)
  4480. (error "Invalid TODO keyword %s" k))
  4481. (let ((name (match-string 1 k))
  4482. (key (match-string 2 k))
  4483. (log (org-extract-log-state-settings k)))
  4484. (push name names)
  4485. (push (cons name (and key (string-to-char key))) alist)
  4486. (when log (push log org-todo-log-states))))
  4487. (let* ((names (nreverse names))
  4488. (done (if sep (org-remove-keyword-keys (cdr sep))
  4489. (last names)))
  4490. (head (car names))
  4491. (tail (list sequence-type head (car done) (org-last done))))
  4492. (add-to-list 'org-todo-heads head 'append)
  4493. (push names org-todo-sets)
  4494. (setq org-done-keywords (append org-done-keywords done nil))
  4495. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4496. (setq org-todo-key-alist
  4497. (append org-todo-key-alist
  4498. (and alist
  4499. (append '((:startgroup))
  4500. (nreverse alist)
  4501. '((:endgroup))))))
  4502. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4503. (setq org-todo-sets (nreverse org-todo-sets)
  4504. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4505. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4506. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4507. ;; Compute the regular expressions and other local variables.
  4508. ;; Using `org-outline-regexp-bol' would complicate them much,
  4509. ;; because of the fixed white space at the end of that string.
  4510. (unless org-done-keywords
  4511. (setq org-done-keywords
  4512. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4513. (setq org-not-done-keywords
  4514. (org-delete-all org-done-keywords
  4515. (copy-sequence org-todo-keywords-1))
  4516. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4517. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4518. org-not-done-heading-regexp
  4519. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4520. org-todo-line-regexp
  4521. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4522. org-complex-heading-regexp
  4523. (concat "^\\(\\*+\\)"
  4524. "\\(?: +" org-todo-regexp "\\)?"
  4525. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4526. "\\(?: +\\(.*?\\)\\)??"
  4527. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4528. "[ \t]*$")
  4529. org-complex-heading-regexp-format
  4530. (concat "^\\(\\*+\\)"
  4531. "\\(?: +" org-todo-regexp "\\)?"
  4532. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4533. "\\(?: +"
  4534. ;; Stats cookies can be stuck to body.
  4535. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4536. "\\(%s\\)"
  4537. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4538. "\\)"
  4539. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4540. "[ \t]*$")
  4541. org-todo-line-tags-regexp
  4542. (concat "^\\(\\*+\\)"
  4543. "\\(?: +" org-todo-regexp "\\)?"
  4544. "\\(?: +\\(.*?\\)\\)??"
  4545. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4546. "[ \t]*$"))
  4547. (org-compute-latex-and-related-regexp)))))
  4548. (defun org--setup-collect-keywords (regexp &optional files alist)
  4549. "Return setup keywords values as an alist.
  4550. REGEXP matches a subset of setup keywords. FILES is a list of
  4551. file names already visited. It is used to avoid circular setup
  4552. files. ALIST, when non-nil, is the alist computed so far.
  4553. Return value contains the following keys: `archive', `category',
  4554. `columns', `constants', `filetags', `link', `priorities',
  4555. `property', `scripts', `startup', `tags' and `todo'."
  4556. (org-with-wide-buffer
  4557. (goto-char (point-min))
  4558. (let ((case-fold-search t))
  4559. (while (re-search-forward regexp nil t)
  4560. (let ((element (org-element-at-point)))
  4561. (when (eq (org-element-type element) 'keyword)
  4562. (let ((key (org-element-property :key element))
  4563. (value (org-element-property :value element)))
  4564. (cond
  4565. ((equal key "ARCHIVE")
  4566. (when (org-string-nw-p value)
  4567. (push (cons 'archive value) alist)))
  4568. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4569. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4570. ((equal key "CONSTANTS")
  4571. (let* ((constants (assq 'constants alist))
  4572. (store (cdr constants)))
  4573. (dolist (pair (org-split-string value))
  4574. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4575. pair)
  4576. (let* ((name (match-string 1 pair))
  4577. (value (match-string 2 pair))
  4578. (old (assoc name store)))
  4579. (if old (setcdr old value)
  4580. (push (cons name value) store)))))
  4581. (if constants (setcdr constants store)
  4582. (push (cons 'constants store) alist))))
  4583. ((equal key "FILETAGS")
  4584. (when (org-string-nw-p value)
  4585. (let ((old (assq 'filetags alist))
  4586. (new (apply #'nconc
  4587. (mapcar (lambda (x) (org-split-string x ":"))
  4588. (org-split-string value)))))
  4589. (if old (setcdr old (append new (cdr old)))
  4590. (push (cons 'filetags new) alist)))))
  4591. ((equal key "LINK")
  4592. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4593. (let ((links (assq 'link alist))
  4594. (pair (cons (match-string-no-properties 1 value)
  4595. (match-string-no-properties 2 value))))
  4596. (if links (push pair (cdr links))
  4597. (push (list 'link pair) alist)))))
  4598. ((equal key "OPTIONS")
  4599. (when (and (org-string-nw-p value)
  4600. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4601. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4602. ((equal key "PRIORITIES")
  4603. (push (cons 'priorities
  4604. (let ((prio (org-split-string value)))
  4605. (if (< (length prio) 3) '(?A ?C ?B)
  4606. (mapcar #'string-to-char prio))))
  4607. alist))
  4608. ((equal key "PROPERTY")
  4609. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4610. (let* ((property (assq 'property alist))
  4611. (value (org--update-property-plist
  4612. (match-string-no-properties 1 value)
  4613. (match-string-no-properties 2 value)
  4614. (cdr property))))
  4615. (if property (setcdr property value)
  4616. (push (cons 'property value) alist)))))
  4617. ((equal key "STARTUP")
  4618. (let ((startup (assq 'startup alist)))
  4619. (if startup
  4620. (setcdr startup
  4621. (append (cdr startup) (org-split-string value)))
  4622. (push (cons 'startup (org-split-string value)) alist))))
  4623. ((equal key "TAGS")
  4624. (let ((tag-cell (assq 'tags alist)))
  4625. (if tag-cell
  4626. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4627. (push (cons 'tags value) alist))))
  4628. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4629. (let ((todo (assq 'todo alist))
  4630. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4631. (org-split-string value))))
  4632. (if todo (push value (cdr todo))
  4633. (push (list 'todo value) alist))))
  4634. ((equal key "SETUPFILE")
  4635. (unless buffer-read-only ; Do not check in Gnus messages.
  4636. (let ((f (and (org-string-nw-p value)
  4637. (expand-file-name
  4638. (org-unbracket-string "\"" "\"" value)))))
  4639. (when (and f (file-readable-p f) (not (member f files)))
  4640. (with-temp-buffer
  4641. (setq default-directory (file-name-directory f))
  4642. (insert-file-contents f)
  4643. (setq alist
  4644. ;; Fake Org mode to benefit from cache
  4645. ;; without recurring needlessly.
  4646. (let ((major-mode 'org-mode))
  4647. (org--setup-collect-keywords
  4648. regexp (cons f files) alist)))))))))))))))
  4649. alist)
  4650. (defun org-tag-string-to-alist (s)
  4651. "Return tag alist associated to string S.
  4652. S is a value for TAGS keyword or produced with
  4653. `org-tag-alist-to-string'. Return value is an alist suitable for
  4654. `org-tag-alist' or `org-tag-persistent-alist'."
  4655. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4656. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4657. "\\|{.+?}\\)" ; regular expression
  4658. "\\(?:(\\(.\\))\\)?\\'"))
  4659. alist group-flag)
  4660. (dolist (tokens lines (cdr (nreverse alist)))
  4661. (push '(:newline) alist)
  4662. (while tokens
  4663. (let ((token (pop tokens)))
  4664. (pcase token
  4665. ("{"
  4666. (push '(:startgroup) alist)
  4667. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4668. ("}"
  4669. (push '(:endgroup) alist)
  4670. (setq group-flag nil))
  4671. ("["
  4672. (push '(:startgrouptag) alist)
  4673. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4674. ("]"
  4675. (push '(:endgrouptag) alist)
  4676. (setq group-flag nil))
  4677. (":"
  4678. (push '(:grouptags) alist))
  4679. ((guard (string-match tag-re token))
  4680. (let ((tag (match-string 1 token))
  4681. (key (and (match-beginning 2)
  4682. (string-to-char (match-string 2 token)))))
  4683. ;; Push all tags in groups, no matter if they already
  4684. ;; appear somewhere else in the list.
  4685. (when (or group-flag (not (assoc tag alist)))
  4686. (push (cons tag key) alist))))))))))
  4687. (defun org-tag-alist-to-string (alist &optional skip-key)
  4688. "Return tag string associated to ALIST.
  4689. ALIST is an alist, as defined in `org-tag-alist' or
  4690. `org-tag-persistent-alist', or produced with
  4691. `org-tag-string-to-alist'.
  4692. Return value is a string suitable as a value for \"TAGS\"
  4693. keyword.
  4694. When optional argument SKIP-KEY is non-nil, skip selection keys
  4695. next to tags."
  4696. (mapconcat (lambda (token)
  4697. (pcase token
  4698. (`(:startgroup) "{")
  4699. (`(:endgroup) "}")
  4700. (`(:startgrouptag) "[")
  4701. (`(:endgrouptag) "]")
  4702. (`(:grouptags) ":")
  4703. (`(:newline) "\\n")
  4704. ((and
  4705. (guard (not skip-key))
  4706. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4707. (format "%s(%c)" tag key))
  4708. (`(,(and tag (pred stringp)) . ,_) tag)
  4709. (_ (user-error "Invalid tag token: %S" token))))
  4710. alist
  4711. " "))
  4712. (defun org-tag-alist-to-groups (alist)
  4713. "Return group alist from tag ALIST.
  4714. ALIST is an alist, as defined in `org-tag-alist' or
  4715. `org-tag-persistent-alist', or produced with
  4716. `org-tag-string-to-alist'. Return value is an alist following
  4717. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4718. a string, summarizing TAGS, as a list of strings."
  4719. (let (groups group-status current-group)
  4720. (dolist (token alist (nreverse groups))
  4721. (pcase token
  4722. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4723. (`(,(or :endgroup :endgrouptag))
  4724. (when (eq group-status 'append)
  4725. (push (nreverse current-group) groups))
  4726. (setq group-status nil))
  4727. (`(:grouptags) (setq group-status 'append))
  4728. ((and `(,tag . ,_) (guard group-status))
  4729. (if (eq group-status 'append) (push tag current-group)
  4730. (setq current-group (list tag))))
  4731. (_ nil)))))
  4732. (defun org-file-contents (file &optional noerror)
  4733. "Return the contents of FILE, as a string."
  4734. (if (and file (file-readable-p file))
  4735. (with-temp-buffer
  4736. (insert-file-contents file)
  4737. (buffer-string))
  4738. (funcall (if noerror 'message 'error)
  4739. "Cannot read file \"%s\"%s"
  4740. file
  4741. (let ((from (buffer-file-name (buffer-base-buffer))))
  4742. (if from (concat " (referenced in file \"" from "\")") "")))))
  4743. (defun org-extract-log-state-settings (x)
  4744. "Extract the log state setting from a TODO keyword string.
  4745. This will extract info from a string like \"WAIT(w@/!)\"."
  4746. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4747. (let ((kw (match-string 1 x))
  4748. (log1 (and (match-end 3) (match-string 3 x)))
  4749. (log2 (and (match-end 4) (match-string 4 x))))
  4750. (and (or log1 log2)
  4751. (list kw
  4752. (and log1 (if (equal log1 "!") 'time 'note))
  4753. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4754. (defun org-remove-keyword-keys (list)
  4755. "Remove a pair of parenthesis at the end of each string in LIST."
  4756. (mapcar (lambda (x)
  4757. (if (string-match "(.*)$" x)
  4758. (substring x 0 (match-beginning 0))
  4759. x))
  4760. list))
  4761. (defun org-assign-fast-keys (alist)
  4762. "Assign fast keys to a keyword-key alist.
  4763. Respect keys that are already there."
  4764. (let (new e (alt ?0))
  4765. (while (setq e (pop alist))
  4766. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4767. (cdr e)) ;; Key already assigned.
  4768. (push e new)
  4769. (let ((clist (string-to-list (downcase (car e))))
  4770. (used (append new alist)))
  4771. (when (= (car clist) ?@)
  4772. (pop clist))
  4773. (while (and clist (rassoc (car clist) used))
  4774. (pop clist))
  4775. (unless clist
  4776. (while (rassoc alt used)
  4777. (cl-incf alt)))
  4778. (push (cons (car e) (or (car clist) alt)) new))))
  4779. (nreverse new)))
  4780. ;;; Some variables used in various places
  4781. (defvar org-window-configuration nil
  4782. "Used in various places to store a window configuration.")
  4783. (defvar org-selected-window nil
  4784. "Used in various places to store a window configuration.")
  4785. (defvar org-finish-function nil
  4786. "Function to be called when `C-c C-c' is used.
  4787. This is for getting out of special buffers like capture.")
  4788. (defvar org-last-state)
  4789. ;; Defined somewhere in this file, but used before definition.
  4790. (defvar org-entities) ;; defined in org-entities.el
  4791. (defvar org-struct-menu)
  4792. (defvar org-org-menu)
  4793. (defvar org-tbl-menu)
  4794. ;;;; Define the Org mode
  4795. ;; We use a before-change function to check if a table might need
  4796. ;; an update.
  4797. (defvar org-table-may-need-update t
  4798. "Indicates that a table might need an update.
  4799. This variable is set by `org-before-change-function'.
  4800. `org-table-align' sets it back to nil.")
  4801. (defun org-before-change-function (_beg _end)
  4802. "Every change indicates that a table might need an update."
  4803. (setq org-table-may-need-update t))
  4804. (defvar org-mode-map)
  4805. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4806. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4807. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4808. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4809. (defvar org-table-buffer-is-an nil)
  4810. (defvar bidi-paragraph-direction)
  4811. (defvar buffer-face-mode-face)
  4812. (require 'outline)
  4813. ;; Other stuff we need.
  4814. (require 'time-date)
  4815. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4816. (require 'easymenu)
  4817. (autoload 'easy-menu-add "easymenu")
  4818. (require 'overlay)
  4819. ;; (require 'org-macs) moved higher up in the file before it is first used
  4820. (require 'org-entities)
  4821. ;; (require 'org-compat) moved higher up in the file before it is first used
  4822. (require 'org-faces)
  4823. (require 'org-list)
  4824. (require 'org-pcomplete)
  4825. (require 'org-src)
  4826. (require 'org-footnote)
  4827. (require 'org-macro)
  4828. ;; babel
  4829. (require 'ob)
  4830. ;;;###autoload
  4831. (define-derived-mode org-mode outline-mode "Org"
  4832. "Outline-based notes management and organizer, alias
  4833. \"Carsten's outline-mode for keeping track of everything.\"
  4834. Org mode develops organizational tasks around a NOTES file which
  4835. contains information about projects as plain text. Org mode is
  4836. implemented on top of Outline mode, which is ideal to keep the content
  4837. of large files well structured. It supports ToDo items, deadlines and
  4838. time stamps, which magically appear in the diary listing of the Emacs
  4839. calendar. Tables are easily created with a built-in table editor.
  4840. Plain text URL-like links connect to websites, emails (VM), Usenet
  4841. messages (Gnus), BBDB entries, and any files related to the project.
  4842. For printing and sharing of notes, an Org file (or a part of it)
  4843. can be exported as a structured ASCII or HTML file.
  4844. The following commands are available:
  4845. \\{org-mode-map}"
  4846. ;; Get rid of Outline menus, they are not needed
  4847. ;; Need to do this here because define-derived-mode sets up
  4848. ;; the keymap so late. Still, it is a waste to call this each time
  4849. ;; we switch another buffer into Org mode.
  4850. (define-key org-mode-map [menu-bar headings] 'undefined)
  4851. (define-key org-mode-map [menu-bar hide] 'undefined)
  4852. (define-key org-mode-map [menu-bar show] 'undefined)
  4853. (org-load-modules-maybe)
  4854. (org-install-agenda-files-menu)
  4855. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4856. (add-to-invisibility-spec '(org-cwidth))
  4857. (add-to-invisibility-spec '(org-hide-block . t))
  4858. (setq-local outline-regexp org-outline-regexp)
  4859. (setq-local outline-level 'org-outline-level)
  4860. (setq bidi-paragraph-direction 'left-to-right)
  4861. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4862. (unless org-display-table
  4863. (setq org-display-table (make-display-table)))
  4864. (set-display-table-slot
  4865. org-display-table 4
  4866. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4867. org-ellipsis)))
  4868. (setq buffer-display-table org-display-table))
  4869. (org-set-regexps-and-options)
  4870. (org-set-font-lock-defaults)
  4871. (when (and org-tag-faces (not org-tags-special-faces-re))
  4872. ;; tag faces set outside customize.... force initialization.
  4873. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4874. ;; Calc embedded
  4875. (setq-local calc-embedded-open-mode "# ")
  4876. ;; Modify a few syntax entries
  4877. (modify-syntax-entry ?@ "w")
  4878. (modify-syntax-entry ?\" "\"")
  4879. (modify-syntax-entry ?\\ "_")
  4880. (modify-syntax-entry ?~ "_")
  4881. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4882. ;; Activate before-change-function
  4883. (setq-local org-table-may-need-update t)
  4884. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4885. ;; Check for running clock before killing a buffer
  4886. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4887. ;; Initialize macros templates.
  4888. (org-macro-initialize-templates)
  4889. ;; Initialize radio targets.
  4890. (org-update-radio-target-regexp)
  4891. ;; Indentation.
  4892. (setq-local indent-line-function 'org-indent-line)
  4893. (setq-local indent-region-function 'org-indent-region)
  4894. ;; Filling and auto-filling.
  4895. (org-setup-filling)
  4896. ;; Comments.
  4897. (org-setup-comments-handling)
  4898. ;; Initialize cache.
  4899. (org-element-cache-reset)
  4900. ;; Beginning/end of defun
  4901. (setq-local beginning-of-defun-function 'org-backward-element)
  4902. (setq-local end-of-defun-function
  4903. (lambda ()
  4904. (if (not (org-at-heading-p))
  4905. (org-forward-element)
  4906. (org-forward-element)
  4907. (forward-char -1))))
  4908. ;; Next error for sparse trees
  4909. (setq-local next-error-function 'org-occur-next-match)
  4910. ;; Make sure dependence stuff works reliably, even for users who set it
  4911. ;; too late :-(
  4912. (if org-enforce-todo-dependencies
  4913. (add-hook 'org-blocker-hook
  4914. 'org-block-todo-from-children-or-siblings-or-parent)
  4915. (remove-hook 'org-blocker-hook
  4916. 'org-block-todo-from-children-or-siblings-or-parent))
  4917. (if org-enforce-todo-checkbox-dependencies
  4918. (add-hook 'org-blocker-hook
  4919. 'org-block-todo-from-checkboxes)
  4920. (remove-hook 'org-blocker-hook
  4921. 'org-block-todo-from-checkboxes))
  4922. ;; Align options lines
  4923. (setq-local
  4924. align-mode-rules-list
  4925. '((org-in-buffer-settings
  4926. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4927. (modes . '(org-mode)))))
  4928. ;; Imenu
  4929. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4930. ;; Make isearch reveal context
  4931. (setq-local outline-isearch-open-invisible-function
  4932. (lambda (&rest _) (org-show-context 'isearch)))
  4933. ;; Setup the pcomplete hooks
  4934. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4935. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4936. (setq-local pcomplete-default-completion-function 'ignore)
  4937. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4938. (setq-local pcomplete-termination-string "")
  4939. (setq-local buffer-face-mode-face 'org-default)
  4940. ;; If empty file that did not turn on Org mode automatically, make
  4941. ;; it to.
  4942. (when (and org-insert-mode-line-in-empty-file
  4943. (called-interactively-p 'any)
  4944. (= (point-min) (point-max)))
  4945. (insert "# -*- mode: org -*-\n\n"))
  4946. (unless org-inhibit-startup
  4947. (org-unmodified
  4948. (when org-startup-with-beamer-mode (org-beamer-mode))
  4949. (when org-startup-align-all-tables
  4950. (org-table-map-tables #'org-table-align t))
  4951. (when org-startup-with-inline-images (org-display-inline-images))
  4952. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4953. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4954. (when org-startup-truncated (setq truncate-lines t))
  4955. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4956. (org-refresh-effort-properties)))
  4957. ;; Try to set `org-hide' face correctly.
  4958. (let ((foreground (org-find-invisible-foreground)))
  4959. (when foreground
  4960. (set-face-foreground 'org-hide foreground))))
  4961. ;; Update `customize-package-emacs-version-alist'
  4962. (add-to-list 'customize-package-emacs-version-alist
  4963. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4964. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4965. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4966. ("9.0" . "26.1")))
  4967. (defvar org-mode-transpose-word-syntax-table
  4968. (let ((st (make-syntax-table text-mode-syntax-table)))
  4969. (dolist (c org-emphasis-alist st)
  4970. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4971. (when (fboundp 'abbrev-table-put)
  4972. (abbrev-table-put org-mode-abbrev-table
  4973. :parents (list text-mode-abbrev-table)))
  4974. (defun org-find-invisible-foreground ()
  4975. (let ((candidates (remove
  4976. "unspecified-bg"
  4977. (nconc
  4978. (list (face-background 'default)
  4979. (face-background 'org-default))
  4980. (mapcar
  4981. (lambda (alist)
  4982. (when (boundp alist)
  4983. (cdr (assq 'background-color (symbol-value alist)))))
  4984. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4985. (list (face-foreground 'org-hide))))))
  4986. (car (remove nil candidates))))
  4987. (defun org-current-time (&optional rounding-minutes past)
  4988. "Current time, possibly rounded to ROUNDING-MINUTES.
  4989. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4990. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4991. the rounding returns a past time."
  4992. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4993. (car org-time-stamp-rounding-minutes)))
  4994. (time (decode-time)) res)
  4995. (if (< r 1)
  4996. (current-time)
  4997. (setq res
  4998. (apply 'encode-time
  4999. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  5000. (nthcdr 2 time))))
  5001. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  5002. (seconds-to-time (- (float-time res) (* r 60)))
  5003. res))))
  5004. (defun org-today ()
  5005. "Return today date, considering `org-extend-today-until'."
  5006. (time-to-days
  5007. (time-subtract (current-time)
  5008. (list 0 (* 3600 org-extend-today-until) 0))))
  5009. ;;;; Font-Lock stuff, including the activators
  5010. (defvar org-mouse-map (make-sparse-keymap))
  5011. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5012. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5013. (when org-mouse-1-follows-link
  5014. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5015. (when org-tab-follows-link
  5016. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5017. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5018. (require 'font-lock)
  5019. (defconst org-non-link-chars "]\t\n\r<>")
  5020. (defvar org-link-types-re nil
  5021. "Matches a link that has a url-like prefix like \"http:\"")
  5022. (defvar org-link-re-with-space nil
  5023. "Matches a link with spaces, optional angular brackets around it.")
  5024. (defvar org-link-re-with-space2 nil
  5025. "Matches a link with spaces, optional angular brackets around it.")
  5026. (defvar org-link-re-with-space3 nil
  5027. "Matches a link with spaces, only for internal part in bracket links.")
  5028. (defvar org-angle-link-re nil
  5029. "Matches link with angular brackets, spaces are allowed.")
  5030. (defvar org-plain-link-re nil
  5031. "Matches plain link, without spaces.")
  5032. (defvar org-bracket-link-regexp nil
  5033. "Matches a link in double brackets.")
  5034. (defvar org-bracket-link-analytic-regexp nil
  5035. "Regular expression used to analyze links.
  5036. Here is what the match groups contain after a match:
  5037. 1: http:
  5038. 2: http
  5039. 3: path
  5040. 4: [desc]
  5041. 5: desc")
  5042. (defvar org-bracket-link-analytic-regexp++ nil
  5043. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5044. (defvar org-any-link-re nil
  5045. "Regular expression matching any link.")
  5046. (defconst org-match-sexp-depth 3
  5047. "Number of stacked braces for sub/superscript matching.")
  5048. (defun org-create-multibrace-regexp (left right n)
  5049. "Create a regular expression which will match a balanced sexp.
  5050. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5051. as single character strings.
  5052. The regexp returned will match the entire expression including the
  5053. delimiters. It will also define a single group which contains the
  5054. match except for the outermost delimiters. The maximum depth of
  5055. stacked delimiters is N. Escaping delimiters is not possible."
  5056. (let* ((nothing (concat "[^" left right "]*?"))
  5057. (or "\\|")
  5058. (re nothing)
  5059. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5060. (while (> n 1)
  5061. (setq n (1- n)
  5062. re (concat re or next)
  5063. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5064. (concat left "\\(" re "\\)" right)))
  5065. (defconst org-match-substring-regexp
  5066. (concat
  5067. "\\(\\S-\\)\\([_^]\\)\\("
  5068. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5069. "\\|"
  5070. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5071. "\\|"
  5072. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5073. "The regular expression matching a sub- or superscript.")
  5074. (defconst org-match-substring-with-braces-regexp
  5075. (concat
  5076. "\\(\\S-\\)\\([_^]\\)"
  5077. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5078. "The regular expression matching a sub- or superscript, forcing braces.")
  5079. (defun org-make-link-regexps ()
  5080. "Update the link regular expressions.
  5081. This should be called after the variable `org-link-parameters' has changed."
  5082. (let ((types-re (regexp-opt (org-link-types) t)))
  5083. (setq org-link-types-re
  5084. (concat "\\`" types-re ":")
  5085. org-link-re-with-space
  5086. (concat "<?" types-re ":"
  5087. "\\([^" org-non-link-chars " ]"
  5088. "[^" org-non-link-chars "]*"
  5089. "[^" org-non-link-chars " ]\\)>?")
  5090. org-link-re-with-space2
  5091. (concat "<?" types-re ":"
  5092. "\\([^" org-non-link-chars " ]"
  5093. "[^\t\n\r]*"
  5094. "[^" org-non-link-chars " ]\\)>?")
  5095. org-link-re-with-space3
  5096. (concat "<?" types-re ":"
  5097. "\\([^" org-non-link-chars " ]"
  5098. "[^\t\n\r]*\\)")
  5099. org-angle-link-re
  5100. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5101. types-re)
  5102. org-plain-link-re
  5103. (concat
  5104. "\\<" types-re ":"
  5105. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5106. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5107. org-bracket-link-regexp
  5108. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5109. org-bracket-link-analytic-regexp
  5110. (concat
  5111. "\\[\\["
  5112. "\\(" types-re ":\\)?"
  5113. "\\([^]]+\\)"
  5114. "\\]"
  5115. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5116. "\\]")
  5117. org-bracket-link-analytic-regexp++
  5118. (concat
  5119. "\\[\\["
  5120. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5121. "\\([^]]+\\)"
  5122. "\\]"
  5123. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5124. "\\]")
  5125. org-any-link-re
  5126. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5127. org-angle-link-re "\\)\\|\\("
  5128. org-plain-link-re "\\)"))))
  5129. (org-make-link-regexps)
  5130. (defvar org-emph-face nil)
  5131. (defun org-do-emphasis-faces (limit)
  5132. "Run through the buffer and emphasize strings."
  5133. (let (rtn a)
  5134. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5135. (let* ((border (char-after (match-beginning 3)))
  5136. (bre (regexp-quote (char-to-string border))))
  5137. (when (and (not (= border (char-after (match-beginning 4))))
  5138. (not (string-match-p (concat bre ".*" bre)
  5139. (replace-regexp-in-string
  5140. "\n" " "
  5141. (substring (match-string 2) 1 -1)))))
  5142. (setq rtn t)
  5143. (setq a (assoc (match-string 3) org-emphasis-alist))
  5144. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5145. 'face
  5146. (nth 1 a))
  5147. (and (nth 2 a)
  5148. (org-remove-flyspell-overlays-in
  5149. (match-beginning 0) (match-end 0)))
  5150. (add-text-properties (match-beginning 2) (match-end 2)
  5151. '(font-lock-multiline t org-emphasis t))
  5152. (when org-hide-emphasis-markers
  5153. (add-text-properties (match-end 4) (match-beginning 5)
  5154. '(invisible org-link))
  5155. (add-text-properties (match-beginning 3) (match-end 3)
  5156. '(invisible org-link)))))
  5157. (goto-char (1+ (match-beginning 0))))
  5158. rtn))
  5159. (defun org-emphasize (&optional char)
  5160. "Insert or change an emphasis, i.e. a font like bold or italic.
  5161. If there is an active region, change that region to a new emphasis.
  5162. If there is no region, just insert the marker characters and position
  5163. the cursor between them.
  5164. CHAR should be the marker character. If it is a space, it means to
  5165. remove the emphasis of the selected region.
  5166. If CHAR is not given (for example in an interactive call) it will be
  5167. prompted for."
  5168. (interactive)
  5169. (let ((erc org-emphasis-regexp-components)
  5170. (string "") beg end move s)
  5171. (if (org-region-active-p)
  5172. (setq beg (region-beginning)
  5173. end (region-end)
  5174. string (buffer-substring beg end))
  5175. (setq move t))
  5176. (unless char
  5177. (message "Emphasis marker or tag: [%s]"
  5178. (mapconcat #'car org-emphasis-alist ""))
  5179. (setq char (read-char-exclusive)))
  5180. (if (equal char ?\s)
  5181. (setq s ""
  5182. move nil)
  5183. (unless (assoc (char-to-string char) org-emphasis-alist)
  5184. (user-error "No such emphasis marker: \"%c\"" char))
  5185. (setq s (char-to-string char)))
  5186. (while (and (> (length string) 1)
  5187. (equal (substring string 0 1) (substring string -1))
  5188. (assoc (substring string 0 1) org-emphasis-alist))
  5189. (setq string (substring string 1 -1)))
  5190. (setq string (concat s string s))
  5191. (when beg (delete-region beg end))
  5192. (unless (or (bolp)
  5193. (string-match (concat "[" (nth 0 erc) "\n]")
  5194. (char-to-string (char-before (point)))))
  5195. (insert " "))
  5196. (unless (or (eobp)
  5197. (string-match (concat "[" (nth 1 erc) "\n]")
  5198. (char-to-string (char-after (point)))))
  5199. (insert " ") (backward-char 1))
  5200. (insert string)
  5201. (and move (backward-char 1))))
  5202. (defconst org-nonsticky-props
  5203. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5204. (defsubst org-rear-nonsticky-at (pos)
  5205. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5206. (defun org-activate-links (limit)
  5207. "Add link properties to links.
  5208. This includes angle, plain, and bracket links."
  5209. (catch :exit
  5210. (while (re-search-forward org-any-link-re limit t)
  5211. (let* ((start (match-beginning 0))
  5212. (end (match-end 0))
  5213. (style (cond ((eq ?< (char-after start)) 'angle)
  5214. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5215. (t 'plain))))
  5216. (when (and (memq style org-highlight-links)
  5217. ;; Do not confuse plain links with tags.
  5218. (not (and (eq style 'plain)
  5219. (let ((face (get-text-property
  5220. (max (1- start) (point-min)) 'face)))
  5221. (if (consp face) (memq 'org-tag face)
  5222. (eq 'org-tag face))))))
  5223. (let* ((link-object (save-excursion
  5224. (goto-char start)
  5225. (save-match-data (org-element-link-parser))))
  5226. (link (org-element-property :raw-link link-object))
  5227. (type (org-element-property :type link-object))
  5228. (path (org-element-property :path link-object))
  5229. (properties ;for link's visible part
  5230. (list
  5231. 'face (pcase (org-link-get-parameter type :face)
  5232. ((and (pred functionp) face) (funcall face path))
  5233. ((and (pred facep) face) face)
  5234. ((and (pred consp) face) face) ;anonymous
  5235. (_ 'org-link))
  5236. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5237. 'highlight)
  5238. 'keymap (or (org-link-get-parameter type :keymap)
  5239. org-mouse-map)
  5240. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5241. ((and (pred stringp) echo) echo)
  5242. ((and (pred functionp) echo) echo)
  5243. (_ (concat "LINK: " link)))
  5244. 'htmlize-link (pcase (org-link-get-parameter type
  5245. :htmlize-link)
  5246. ((and (pred functionp) f) (funcall f))
  5247. (_ `(:uri ,link)))
  5248. 'font-lock-multiline t)))
  5249. (org-remove-flyspell-overlays-in start end)
  5250. (org-rear-nonsticky-at end)
  5251. (if (not (eq 'bracket style))
  5252. (add-text-properties start end properties)
  5253. ;; Handle invisible parts in bracket links.
  5254. (remove-text-properties start end '(invisible nil))
  5255. (let ((hidden
  5256. (append `(invisible
  5257. ,(or (org-link-get-parameter type :display)
  5258. 'org-link))
  5259. properties))
  5260. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5261. (visible-end (or (match-end 4) (match-end 2))))
  5262. (add-text-properties start visible-start hidden)
  5263. (add-text-properties visible-start visible-end properties)
  5264. (add-text-properties visible-end end hidden)
  5265. (org-rear-nonsticky-at visible-start)
  5266. (org-rear-nonsticky-at visible-end)))
  5267. (let ((f (org-link-get-parameter type :activate-func)))
  5268. (when (functionp f)
  5269. (funcall f start end path (eq style 'bracket))))
  5270. (throw :exit t))))) ;signal success
  5271. nil))
  5272. (defun org-activate-code (limit)
  5273. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5274. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5275. (remove-text-properties (match-beginning 0) (match-end 0)
  5276. '(display t invisible t intangible t))
  5277. t))
  5278. (defcustom org-src-fontify-natively t
  5279. "When non-nil, fontify code in code blocks.
  5280. See also the `org-block' face."
  5281. :type 'boolean
  5282. :version "24.4"
  5283. :package-version '(Org . "8.3")
  5284. :group 'org-appearance
  5285. :group 'org-babel)
  5286. (defcustom org-allow-promoting-top-level-subtree nil
  5287. "When non-nil, allow promoting a top level subtree.
  5288. The leading star of the top level headline will be replaced
  5289. by a #."
  5290. :type 'boolean
  5291. :version "24.1"
  5292. :group 'org-appearance)
  5293. (defun org-fontify-meta-lines-and-blocks (limit)
  5294. (condition-case nil
  5295. (org-fontify-meta-lines-and-blocks-1 limit)
  5296. (error (message "org-mode fontification error in %S at %d"
  5297. (current-buffer)
  5298. (line-number-at-pos)))))
  5299. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5300. "Fontify #+ lines and blocks."
  5301. (let ((case-fold-search t))
  5302. (when (re-search-forward
  5303. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5304. limit t)
  5305. (let ((beg (match-beginning 0))
  5306. (block-start (match-end 0))
  5307. (block-end nil)
  5308. (lang (match-string 7))
  5309. (beg1 (line-beginning-position 2))
  5310. (dc1 (downcase (match-string 2)))
  5311. (dc3 (downcase (match-string 3)))
  5312. end end1 quoting block-type)
  5313. (cond
  5314. ((and (match-end 4) (equal dc3 "+begin"))
  5315. ;; Truly a block
  5316. (setq block-type (downcase (match-string 5))
  5317. quoting (member block-type org-protecting-blocks))
  5318. (when (re-search-forward
  5319. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5320. nil t) ;; on purpose, we look further than LIMIT
  5321. (setq end (min (point-max) (match-end 0))
  5322. end1 (min (point-max) (1- (match-beginning 0))))
  5323. (setq block-end (match-beginning 0))
  5324. (when quoting
  5325. (org-remove-flyspell-overlays-in beg1 end1)
  5326. (remove-text-properties beg end
  5327. '(display t invisible t intangible t)))
  5328. (add-text-properties
  5329. beg end '(font-lock-fontified t font-lock-multiline t))
  5330. (add-text-properties beg beg1 '(face org-meta-line))
  5331. (org-remove-flyspell-overlays-in beg beg1)
  5332. (add-text-properties ; For end_src
  5333. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5334. (org-remove-flyspell-overlays-in end1 end)
  5335. (cond
  5336. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5337. (org-src-font-lock-fontify-block lang block-start block-end)
  5338. (add-text-properties beg1 block-end '(src-block t)))
  5339. (quoting
  5340. (add-text-properties beg1 (min (point-max) (1+ end1))
  5341. (list 'face
  5342. (list :inherit
  5343. (let ((face-name
  5344. (intern (format "org-block-%s" lang))))
  5345. (append (and (facep face-name) (list face-name))
  5346. '(org-block))))))) ; end of source block
  5347. ((not org-fontify-quote-and-verse-blocks))
  5348. ((string= block-type "quote")
  5349. (add-face-text-property
  5350. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5351. ((string= block-type "verse")
  5352. (add-face-text-property
  5353. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5354. (add-text-properties beg beg1 '(face org-block-begin-line))
  5355. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5356. '(face org-block-end-line))
  5357. t))
  5358. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5359. (org-remove-flyspell-overlays-in
  5360. (match-beginning 0)
  5361. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5362. (add-text-properties
  5363. beg (match-end 3)
  5364. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5365. '(font-lock-fontified t invisible t)
  5366. '(font-lock-fontified t face org-document-info-keyword)))
  5367. (add-text-properties
  5368. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5369. (if (string-equal dc1 "+title:")
  5370. '(font-lock-fontified t face org-document-title)
  5371. '(font-lock-fontified t face org-document-info))))
  5372. ((string-prefix-p "+caption" dc1)
  5373. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5374. (remove-text-properties (match-beginning 0) (match-end 0)
  5375. '(display t invisible t intangible t))
  5376. ;; Handle short captions.
  5377. (save-excursion
  5378. (beginning-of-line)
  5379. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5380. (add-text-properties (line-beginning-position) (match-end 1)
  5381. '(font-lock-fontified t face org-meta-line))
  5382. (add-text-properties (match-end 0) (line-end-position)
  5383. '(font-lock-fontified t face org-block))
  5384. t)
  5385. ((member dc3 '(" " ""))
  5386. (org-remove-flyspell-overlays-in beg (match-end 0))
  5387. (add-text-properties
  5388. beg (match-end 0)
  5389. '(font-lock-fontified t face font-lock-comment-face)))
  5390. (t ;; just any other in-buffer setting, but not indented
  5391. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5392. (remove-text-properties (match-beginning 0) (match-end 0)
  5393. '(display t invisible t intangible t))
  5394. (add-text-properties beg (match-end 0)
  5395. '(font-lock-fontified t face org-meta-line))
  5396. t))))))
  5397. (defun org-fontify-drawers (limit)
  5398. "Fontify drawers."
  5399. (when (re-search-forward org-drawer-regexp limit t)
  5400. (add-text-properties
  5401. (match-beginning 0) (match-end 0)
  5402. '(font-lock-fontified t face org-special-keyword))
  5403. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5404. t))
  5405. (defun org-fontify-macros (limit)
  5406. "Fontify macros."
  5407. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5408. (add-text-properties
  5409. (match-beginning 0) (match-end 0)
  5410. '(font-lock-fontified t face org-macro))
  5411. (when org-hide-macro-markers
  5412. (add-text-properties (match-end 2) (match-beginning 2)
  5413. '(invisible t))
  5414. (add-text-properties (match-beginning 1) (match-end 1)
  5415. '(invisible t)))
  5416. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5417. t))
  5418. (defun org-activate-footnote-links (limit)
  5419. "Add text properties for footnotes."
  5420. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5421. (when fn
  5422. (let* ((beg (nth 1 fn))
  5423. (end (nth 2 fn))
  5424. (label (car fn))
  5425. (referencep (/= (line-beginning-position) beg)))
  5426. (when (and referencep (nth 3 fn))
  5427. (save-excursion
  5428. (goto-char beg)
  5429. (search-forward (or label "fn:"))
  5430. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5431. (add-text-properties beg end
  5432. (list 'mouse-face 'highlight
  5433. 'keymap org-mouse-map
  5434. 'help-echo
  5435. (if referencep "Footnote reference"
  5436. "Footnote definition")
  5437. 'font-lock-fontified t
  5438. 'font-lock-multiline t
  5439. 'face 'org-footnote))))))
  5440. (defun org-activate-dates (limit)
  5441. "Add text properties for dates."
  5442. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5443. (not (equal (char-before (match-beginning 0)) 91)))
  5444. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5445. (add-text-properties (match-beginning 0) (match-end 0)
  5446. (list 'mouse-face 'highlight
  5447. 'keymap org-mouse-map))
  5448. (org-rear-nonsticky-at (match-end 0))
  5449. (when org-display-custom-times
  5450. ;; If it's a date range, activate custom time for second date.
  5451. (when (match-end 3)
  5452. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5453. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5454. t))
  5455. (defvar-local org-target-link-regexp nil
  5456. "Regular expression matching radio targets in plain text.")
  5457. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5458. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5459. border border border))
  5460. "Regular expression matching a link target.")
  5461. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5462. "Regular expression matching a radio target.")
  5463. (defconst org-any-target-regexp
  5464. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5465. "Regular expression matching any target.")
  5466. (defun org-activate-target-links (limit)
  5467. "Add text properties for target matches."
  5468. (when org-target-link-regexp
  5469. (let ((case-fold-search t))
  5470. (when (re-search-forward org-target-link-regexp limit t)
  5471. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5472. (add-text-properties (match-beginning 1) (match-end 1)
  5473. (list 'mouse-face 'highlight
  5474. 'keymap org-mouse-map
  5475. 'help-echo "Radio target link"
  5476. 'org-linked-text t))
  5477. (org-rear-nonsticky-at (match-end 1))
  5478. t))))
  5479. (defun org-update-radio-target-regexp ()
  5480. "Find all radio targets in this file and update the regular expression.
  5481. Also refresh fontification if needed."
  5482. (interactive)
  5483. (let ((old-regexp org-target-link-regexp)
  5484. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5485. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5486. (targets
  5487. (org-with-wide-buffer
  5488. (goto-char (point-min))
  5489. (let (rtn)
  5490. (while (re-search-forward org-radio-target-regexp nil t)
  5491. ;; Make sure point is really within the object.
  5492. (backward-char)
  5493. (let ((obj (org-element-context)))
  5494. (when (eq (org-element-type obj) 'radio-target)
  5495. (cl-pushnew (org-element-property :value obj) rtn
  5496. :test #'equal))))
  5497. rtn))))
  5498. (setq org-target-link-regexp
  5499. (and targets
  5500. (concat before-re
  5501. (mapconcat
  5502. (lambda (x)
  5503. (replace-regexp-in-string
  5504. " +" "\\s-+" (regexp-quote x) t t))
  5505. targets
  5506. "\\|")
  5507. after-re)))
  5508. (unless (equal old-regexp org-target-link-regexp)
  5509. ;; Clean-up cache.
  5510. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5511. ((not org-target-link-regexp) old-regexp)
  5512. (t
  5513. (concat before-re
  5514. (mapconcat
  5515. (lambda (re)
  5516. (substring re (length before-re)
  5517. (- (length after-re))))
  5518. (list old-regexp org-target-link-regexp)
  5519. "\\|")
  5520. after-re)))))
  5521. (org-with-wide-buffer
  5522. (goto-char (point-min))
  5523. (while (re-search-forward regexp nil t)
  5524. (org-element-cache-refresh (match-beginning 1)))))
  5525. ;; Re fontify buffer.
  5526. (when (memq 'radio org-highlight-links)
  5527. (org-restart-font-lock)))))
  5528. (defun org-hide-wide-columns (limit)
  5529. (let (s e)
  5530. (setq s (text-property-any (point) (or limit (point-max))
  5531. 'org-cwidth t))
  5532. (when s
  5533. (setq e (next-single-property-change s 'org-cwidth))
  5534. (add-text-properties s e '(invisible org-cwidth))
  5535. (goto-char e)
  5536. t)))
  5537. (defvar org-latex-and-related-regexp nil
  5538. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5539. (defun org-compute-latex-and-related-regexp ()
  5540. "Compute regular expression for LaTeX, entities and sub/superscript.
  5541. Result depends on variable `org-highlight-latex-and-related'."
  5542. (setq-local
  5543. org-latex-and-related-regexp
  5544. (let* ((re-sub
  5545. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5546. ((eq org-use-sub-superscripts '{})
  5547. (list org-match-substring-with-braces-regexp))
  5548. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5549. (re-latex
  5550. (when (memq 'latex org-highlight-latex-and-related)
  5551. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5552. (delq nil
  5553. (mapcar (lambda (x)
  5554. (and (member (car x) matchers) (nth 1 x)))
  5555. org-latex-regexps)))))
  5556. (re-entities
  5557. (when (memq 'entities org-highlight-latex-and-related)
  5558. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5559. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5560. (defun org-do-latex-and-related (limit)
  5561. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5562. LIMIT bounds the search for syntax to highlight. Stop at first
  5563. highlighted object, if any. Return t if some highlighting was
  5564. done, nil otherwise."
  5565. (when (org-string-nw-p org-latex-and-related-regexp)
  5566. (catch 'found
  5567. (while (re-search-forward org-latex-and-related-regexp limit t)
  5568. (unless
  5569. (cl-some
  5570. (lambda (f)
  5571. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5572. (save-excursion
  5573. (goto-char (1+ (match-beginning 0)))
  5574. (face-at-point nil t)))
  5575. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5576. '(?_ ?^))
  5577. 1
  5578. 0)))
  5579. (font-lock-prepend-text-property
  5580. (+ offset (match-beginning 0)) (match-end 0)
  5581. 'face 'org-latex-and-related)
  5582. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5583. '(font-lock-multiline t)))
  5584. (throw 'found t)))
  5585. nil)))
  5586. (defun org-restart-font-lock ()
  5587. "Restart `font-lock-mode', to force refontification."
  5588. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5589. (font-lock-mode -1)
  5590. (font-lock-mode 1)))
  5591. (defun org-activate-tags (limit)
  5592. (when (re-search-forward
  5593. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5594. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5595. (add-text-properties (match-beginning 1) (match-end 1)
  5596. (list 'mouse-face 'highlight
  5597. 'keymap org-mouse-map))
  5598. (org-rear-nonsticky-at (match-end 1))
  5599. t))
  5600. (defun org-outline-level ()
  5601. "Compute the outline level of the heading at point.
  5602. If this is called at a normal headline, the level is the number
  5603. of stars. Use `org-reduced-level' to remove the effect of
  5604. `org-odd-levels'. Unlike to `org-current-level', this function
  5605. takes into consideration inlinetasks."
  5606. (org-with-wide-buffer
  5607. (end-of-line)
  5608. (if (re-search-backward org-outline-regexp-bol nil t)
  5609. (1- (- (match-end 0) (match-beginning 0)))
  5610. 0)))
  5611. (defvar org-font-lock-keywords nil)
  5612. (defsubst org-re-property (property &optional literal allow-null value)
  5613. "Return a regexp matching a PROPERTY line.
  5614. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5615. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5616. non-nil, match properties even without a value.
  5617. Match group 3 is set to the value when it exists. If there is no
  5618. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5619. With optional argument VALUE, match only property lines with
  5620. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5621. unless LITERAL is non-nil."
  5622. (concat
  5623. "^\\(?4:[ \t]*\\)"
  5624. (format "\\(?1::\\(?2:%s\\):\\)"
  5625. (if literal property (regexp-quote property)))
  5626. (cond (value
  5627. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5628. (if literal value (regexp-quote value))))
  5629. (allow-null
  5630. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5631. (t
  5632. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5633. (defconst org-property-re
  5634. (org-re-property "\\S-+" 'literal t)
  5635. "Regular expression matching a property line.
  5636. There are four matching groups:
  5637. 1: :PROPKEY: including the leading and trailing colon,
  5638. 2: PROPKEY without the leading and trailing colon,
  5639. 3: PROPVAL without leading or trailing spaces,
  5640. 4: the indentation of the current line,
  5641. 5: trailing whitespace.")
  5642. (defvar org-font-lock-hook nil
  5643. "Functions to be called for special font lock stuff.")
  5644. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5645. (defvar org-font-lock-set-keywords-hook nil
  5646. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5647. This is called after `org-font-lock-extra-keywords' is defined, but before
  5648. it is installed to be used by font lock. This can be useful if something
  5649. needs to be inserted at a specific position in the font-lock sequence.")
  5650. (defun org-font-lock-hook (limit)
  5651. "Run `org-font-lock-hook' within LIMIT."
  5652. (run-hook-with-args 'org-font-lock-hook limit))
  5653. (defun org-set-font-lock-defaults ()
  5654. "Set font lock defaults for the current buffer."
  5655. (let* ((em org-fontify-emphasized-text)
  5656. (lk org-highlight-links)
  5657. (org-font-lock-extra-keywords
  5658. (list
  5659. ;; Call the hook
  5660. '(org-font-lock-hook)
  5661. ;; Headlines
  5662. `(,(if org-fontify-whole-heading-line
  5663. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5664. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5665. (1 (org-get-level-face 1))
  5666. (2 (org-get-level-face 2))
  5667. (3 (org-get-level-face 3)))
  5668. ;; Table lines
  5669. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5670. (1 'org-table t))
  5671. ;; Table internals
  5672. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5673. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5674. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5675. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5676. ;; Drawers
  5677. '(org-fontify-drawers)
  5678. ;; Properties
  5679. (list org-property-re
  5680. '(1 'org-special-keyword t)
  5681. '(3 'org-property-value t))
  5682. ;; Link related fontification.
  5683. '(org-activate-links)
  5684. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5685. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5686. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5687. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5688. ;; Targets.
  5689. (list org-any-target-regexp '(0 'org-target t))
  5690. ;; Diary sexps.
  5691. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5692. ;; Macro
  5693. '(org-fontify-macros)
  5694. '(org-hide-wide-columns (0 nil append))
  5695. ;; TODO keyword
  5696. (list (format org-heading-keyword-regexp-format
  5697. org-todo-regexp)
  5698. '(2 (org-get-todo-face 2) t))
  5699. ;; DONE
  5700. (if org-fontify-done-headline
  5701. (list (format org-heading-keyword-regexp-format
  5702. (concat
  5703. "\\(?:"
  5704. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5705. "\\)"))
  5706. '(2 'org-headline-done t))
  5707. nil)
  5708. ;; Priorities
  5709. '(org-font-lock-add-priority-faces)
  5710. ;; Tags
  5711. '(org-font-lock-add-tag-faces)
  5712. ;; Tags groups
  5713. (when (and org-group-tags org-tag-groups-alist)
  5714. (list (concat org-outline-regexp-bol ".+\\(:"
  5715. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5716. ":\\).*$")
  5717. '(1 'org-tag-group prepend)))
  5718. ;; Special keywords
  5719. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5720. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5721. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5722. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5723. ;; Emphasis
  5724. (when em '(org-do-emphasis-faces))
  5725. ;; Checkboxes
  5726. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5727. 1 'org-checkbox prepend)
  5728. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5729. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5730. (0 (org-get-checkbox-statistics-face) t)))
  5731. ;; Description list items
  5732. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5733. 1 'org-list-dt prepend)
  5734. ;; ARCHIVEd headings
  5735. (list (concat
  5736. org-outline-regexp-bol
  5737. "\\(.*:" org-archive-tag ":.*\\)")
  5738. '(1 'org-archived prepend))
  5739. ;; Specials
  5740. '(org-do-latex-and-related)
  5741. '(org-fontify-entities)
  5742. '(org-raise-scripts)
  5743. ;; Code
  5744. '(org-activate-code (1 'org-code t))
  5745. ;; COMMENT
  5746. (list (format
  5747. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5748. org-todo-regexp
  5749. org-comment-string)
  5750. '(9 'org-special-keyword t))
  5751. ;; Blocks and meta lines
  5752. '(org-fontify-meta-lines-and-blocks))))
  5753. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5754. (run-hooks 'org-font-lock-set-keywords-hook)
  5755. ;; Now set the full font-lock-keywords
  5756. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5757. (setq-local font-lock-defaults
  5758. '(org-font-lock-keywords t nil nil backward-paragraph))
  5759. (kill-local-variable 'font-lock-keywords)
  5760. nil))
  5761. (defun org-toggle-pretty-entities ()
  5762. "Toggle the composition display of entities as UTF8 characters."
  5763. (interactive)
  5764. (setq-local org-pretty-entities (not org-pretty-entities))
  5765. (org-restart-font-lock)
  5766. (if org-pretty-entities
  5767. (message "Entities are now displayed as UTF8 characters")
  5768. (save-restriction
  5769. (widen)
  5770. (decompose-region (point-min) (point-max))
  5771. (message "Entities are now displayed as plain text"))))
  5772. (defvar-local org-custom-properties-overlays nil
  5773. "List of overlays used for custom properties.")
  5774. (defun org-toggle-custom-properties-visibility ()
  5775. "Display or hide properties in `org-custom-properties'."
  5776. (interactive)
  5777. (if org-custom-properties-overlays
  5778. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5779. (setq org-custom-properties-overlays nil))
  5780. (when org-custom-properties
  5781. (org-with-wide-buffer
  5782. (goto-char (point-min))
  5783. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5784. (while (re-search-forward regexp nil t)
  5785. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5786. (when (and end (< (point) end))
  5787. ;; Hide first custom property in current drawer.
  5788. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5789. (overlay-put o 'invisible t)
  5790. (overlay-put o 'org-custom-property t)
  5791. (push o org-custom-properties-overlays))
  5792. ;; Hide additional custom properties in the same drawer.
  5793. (while (re-search-forward regexp end t)
  5794. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5795. (overlay-put o 'invisible t)
  5796. (overlay-put o 'org-custom-property t)
  5797. (push o org-custom-properties-overlays)))))
  5798. ;; Each entry is limited to a single property drawer.
  5799. (outline-next-heading)))))))
  5800. (defun org-fontify-entities (limit)
  5801. "Find an entity to fontify."
  5802. (let (ee)
  5803. (when org-pretty-entities
  5804. (catch 'match
  5805. ;; "\_ "-family is left out on purpose. Only the first one,
  5806. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5807. ;; confusing when adding a second white space character.
  5808. (while (re-search-forward
  5809. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5810. limit t)
  5811. (when (and (not (org-at-comment-p))
  5812. (setq ee (org-entity-get (match-string 1)))
  5813. (= (length (nth 6 ee)) 1))
  5814. (let* ((end (if (equal (match-string 2) "{}")
  5815. (match-end 2)
  5816. (match-end 1))))
  5817. (add-text-properties
  5818. (match-beginning 0) end
  5819. (list 'font-lock-fontified t))
  5820. (compose-region (match-beginning 0) end
  5821. (nth 6 ee) nil)
  5822. (backward-char 1)
  5823. (throw 'match t))))
  5824. nil))))
  5825. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5826. "Fontify string S like in Org mode."
  5827. (with-temp-buffer
  5828. (insert s)
  5829. (let ((org-odd-levels-only odd-levels))
  5830. (org-mode)
  5831. (org-font-lock-ensure)
  5832. (buffer-string))))
  5833. (defvar org-m nil)
  5834. (defvar org-l nil)
  5835. (defvar org-f nil)
  5836. (defun org-get-level-face (n)
  5837. "Get the right face for match N in font-lock matching of headlines."
  5838. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5839. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5840. (if org-cycle-level-faces
  5841. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5842. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5843. (cond
  5844. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5845. ((eq n 2) org-f)
  5846. (t (unless org-level-color-stars-only org-f))))
  5847. (defun org-face-from-face-or-color (context inherit face-or-color)
  5848. "Create a face list that inherits INHERIT, but sets the foreground color.
  5849. When FACE-OR-COLOR is not a string, just return it."
  5850. (if (stringp face-or-color)
  5851. (list :inherit inherit
  5852. (cdr (assoc context org-faces-easy-properties))
  5853. face-or-color)
  5854. face-or-color))
  5855. (defun org-get-todo-face (kwd)
  5856. "Get the right face for a TODO keyword KWD.
  5857. If KWD is a number, get the corresponding match group."
  5858. (when (numberp kwd) (setq kwd (match-string kwd)))
  5859. (or (org-face-from-face-or-color
  5860. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5861. (and (member kwd org-done-keywords) 'org-done)
  5862. 'org-todo))
  5863. (defun org-get-priority-face (priority)
  5864. "Get the right face for PRIORITY.
  5865. PRIORITY is a character."
  5866. (or (org-face-from-face-or-color
  5867. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5868. 'org-priority))
  5869. (defun org-get-tag-face (tag)
  5870. "Get the right face for TAG.
  5871. If TAG is a number, get the corresponding match group."
  5872. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5873. (or (org-face-from-face-or-color
  5874. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5875. 'org-tag)))
  5876. (defun org-font-lock-add-priority-faces (limit)
  5877. "Add the special priority faces."
  5878. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5879. (add-text-properties
  5880. (match-beginning 1) (match-end 1)
  5881. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5882. 'font-lock-fontified t))))
  5883. (defun org-font-lock-add-tag-faces (limit)
  5884. "Add the special tag faces."
  5885. (when (and org-tag-faces org-tags-special-faces-re)
  5886. (while (re-search-forward org-tags-special-faces-re limit t)
  5887. (add-text-properties (match-beginning 1) (match-end 1)
  5888. (list 'face (org-get-tag-face 1)
  5889. 'font-lock-fontified t))
  5890. (backward-char 1))))
  5891. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5892. "Remove fontification and activation overlays from links."
  5893. (font-lock-default-unfontify-region beg end)
  5894. (let* ((buffer-undo-list t)
  5895. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5896. (inhibit-modification-hooks t)
  5897. deactivate-mark buffer-file-name buffer-file-truename)
  5898. (decompose-region beg end)
  5899. (remove-text-properties beg end
  5900. '(mouse-face t keymap t org-linked-text t
  5901. invisible t intangible t
  5902. org-emphasis t))
  5903. (org-remove-font-lock-display-properties beg end)))
  5904. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5905. ((raise 0.3) (height 0.7))
  5906. ((raise -0.5))
  5907. ((raise 0.5)))
  5908. "Display properties for showing superscripts and subscripts.")
  5909. (defun org-remove-font-lock-display-properties (beg end)
  5910. "Remove specific display properties that have been added by font lock.
  5911. The will remove the raise properties that are used to show superscripts
  5912. and subscripts."
  5913. (let (next prop)
  5914. (while (< beg end)
  5915. (setq next (next-single-property-change beg 'display nil end)
  5916. prop (get-text-property beg 'display))
  5917. (when (member prop org-script-display)
  5918. (put-text-property beg next 'display nil))
  5919. (setq beg next))))
  5920. (defun org-raise-scripts (limit)
  5921. "Add raise properties to sub/superscripts."
  5922. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5923. (re-search-forward
  5924. (if (eq org-use-sub-superscripts t)
  5925. org-match-substring-regexp
  5926. org-match-substring-with-braces-regexp)
  5927. limit t))
  5928. (let* ((pos (point)) table-p comment-p
  5929. (mpos (match-beginning 3))
  5930. (emph-p (get-text-property mpos 'org-emphasis))
  5931. (link-p (get-text-property mpos 'mouse-face))
  5932. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5933. (goto-char (point-at-bol))
  5934. (setq table-p (looking-at-p org-table-dataline-regexp)
  5935. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5936. (goto-char pos)
  5937. ;; Handle a_b^c
  5938. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5939. (unless (or comment-p emph-p link-p keyw-p)
  5940. (put-text-property (match-beginning 3) (match-end 0)
  5941. 'display
  5942. (if (equal (char-after (match-beginning 2)) ?^)
  5943. (nth (if table-p 3 1) org-script-display)
  5944. (nth (if table-p 2 0) org-script-display)))
  5945. (add-text-properties (match-beginning 2) (match-end 2)
  5946. (list 'invisible t
  5947. 'org-dwidth t 'org-dwidth-n 1))
  5948. (if (and (eq (char-after (match-beginning 3)) ?{)
  5949. (eq (char-before (match-end 3)) ?}))
  5950. (progn
  5951. (add-text-properties
  5952. (match-beginning 3) (1+ (match-beginning 3))
  5953. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5954. (add-text-properties
  5955. (1- (match-end 3)) (match-end 3)
  5956. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5957. t)))
  5958. ;;;; Visibility cycling, including org-goto and indirect buffer
  5959. ;;; Cycling
  5960. (defvar-local org-cycle-global-status nil)
  5961. (put 'org-cycle-global-status 'org-state t)
  5962. (defvar-local org-cycle-subtree-status nil)
  5963. (put 'org-cycle-subtree-status 'org-state t)
  5964. (defvar org-inlinetask-min-level)
  5965. (defun org-unlogged-message (&rest args)
  5966. "Display a message, but avoid logging it in the *Messages* buffer."
  5967. (let ((message-log-max nil))
  5968. (apply 'message args)))
  5969. ;;;###autoload
  5970. (defun org-cycle (&optional arg)
  5971. "TAB-action and visibility cycling for Org mode.
  5972. This is the command invoked in Org mode by the `TAB' key. Its main
  5973. purpose is outline visibility cycling, but it also invokes other actions
  5974. in special contexts.
  5975. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5976. the entire
  5977. buffer through 3 states (global cycling)
  5978. 1. OVERVIEW: Show only top-level headlines.
  5979. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5980. 3. SHOW ALL: Show everything.
  5981. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5982. switch to the startup visibility,
  5983. determined by the variable `org-startup-folded', and by any VISIBILITY
  5984. properties in the buffer.
  5985. With a `\\[universal-argument] \\[universal-argument] \
  5986. \\[universal-argument]' prefix argument, show the entire buffer, including
  5987. any drawers.
  5988. When inside a table, re-align the table and move to the next field.
  5989. When point is at the beginning of a headline, rotate the subtree started
  5990. by this line through 3 different states (local cycling)
  5991. 1. FOLDED: Only the main headline is shown.
  5992. 2. CHILDREN: The main headline and the direct children are shown.
  5993. From this state, you can move to one of the children
  5994. and zoom in further.
  5995. 3. SUBTREE: Show the entire subtree, including body text.
  5996. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5997. When point is at the beginning of an empty headline and the variable
  5998. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5999. of the headline by demoting and promoting it to likely levels. This
  6000. speeds up creation document structure by pressing `TAB' once or several
  6001. times right after creating a new headline.
  6002. When there is a numeric prefix, go up to a heading with level ARG, do
  6003. a `show-subtree' and return to the previous cursor position. If ARG
  6004. is negative, go up that many levels.
  6005. When point is not at the beginning of a headline, execute the global
  6006. binding for `TAB', which is re-indenting the line. See the option
  6007. `org-cycle-emulate-tab' for details.
  6008. As a special case, if point is at the beginning of the buffer and there is
  6009. no headline in line 1, this function will act as if called with prefix arg
  6010. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6011. prefix arg, but only
  6012. if the variable `org-cycle-global-at-bob' is t."
  6013. (interactive "P")
  6014. (org-load-modules-maybe)
  6015. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6016. (and org-cycle-level-after-item/entry-creation
  6017. (or (org-cycle-level)
  6018. (org-cycle-item-indentation))))
  6019. (let* ((limit-level
  6020. (or org-cycle-max-level
  6021. (and (boundp 'org-inlinetask-min-level)
  6022. org-inlinetask-min-level
  6023. (1- org-inlinetask-min-level))))
  6024. (nstars (and limit-level
  6025. (if org-odd-levels-only
  6026. (and limit-level (1- (* limit-level 2)))
  6027. limit-level)))
  6028. (org-outline-regexp
  6029. (if (not (derived-mode-p 'org-mode))
  6030. outline-regexp
  6031. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6032. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6033. (not (looking-at org-outline-regexp))))
  6034. (org-cycle-hook
  6035. (if bob-special
  6036. (delq 'org-optimize-window-after-visibility-change
  6037. (copy-sequence org-cycle-hook))
  6038. org-cycle-hook))
  6039. (pos (point)))
  6040. (cond
  6041. ((equal arg '(16))
  6042. (setq last-command 'dummy)
  6043. (org-set-startup-visibility)
  6044. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6045. ((equal arg '(64))
  6046. (outline-show-all)
  6047. (org-unlogged-message "Entire buffer visible, including drawers"))
  6048. ((equal arg '(4)) (org-cycle-internal-global))
  6049. ;; Try hiding block at point.
  6050. ((org-hide-block-toggle-maybe))
  6051. ;; Try cdlatex TAB completion
  6052. ((org-try-cdlatex-tab))
  6053. ;; Table: enter it or move to the next field.
  6054. ((org-at-table-p 'any)
  6055. (if (org-at-table.el-p)
  6056. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6057. Use `\\[org-edit-special]' to edit table.el tables"))
  6058. (if arg (org-table-edit-field t)
  6059. (org-table-justify-field-maybe)
  6060. (call-interactively 'org-table-next-field))))
  6061. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6062. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6063. (bob-special (org-cycle-internal-global))
  6064. ;; Drawers: delegate to `org-flag-drawer'.
  6065. ((save-excursion
  6066. (beginning-of-line 1)
  6067. (looking-at org-drawer-regexp))
  6068. (org-flag-drawer ; toggle block visibility
  6069. (not (get-char-property (match-end 0) 'invisible))))
  6070. ;; Show-subtree, ARG levels up from here.
  6071. ((integerp arg)
  6072. (save-excursion
  6073. (org-back-to-heading)
  6074. (outline-up-heading (if (< arg 0) (- arg)
  6075. (- (funcall outline-level) arg)))
  6076. (org-show-subtree)))
  6077. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6078. ((and (featurep 'org-inlinetask)
  6079. (org-inlinetask-at-task-p)
  6080. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6081. (org-inlinetask-toggle-visibility))
  6082. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6083. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6084. (save-excursion (move-beginning-of-line 1)
  6085. (looking-at org-outline-regexp)))
  6086. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6087. (org-cycle-internal-local))
  6088. ;; From there: TAB emulation and template completion.
  6089. (buffer-read-only (org-back-to-heading))
  6090. ((run-hook-with-args-until-success
  6091. 'org-tab-after-check-for-cycling-hook))
  6092. ((org-try-structure-completion))
  6093. ((run-hook-with-args-until-success
  6094. 'org-tab-before-tab-emulation-hook))
  6095. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6096. (or (not (bolp))
  6097. (not (looking-at org-outline-regexp))))
  6098. (call-interactively (global-key-binding "\t")))
  6099. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6100. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6101. (or (and (eq org-cycle-emulate-tab 'white)
  6102. (= (match-end 0) (point-at-eol)))
  6103. (and (eq org-cycle-emulate-tab 'whitestart)
  6104. (>= (match-end 0) pos))))
  6105. t
  6106. (eq org-cycle-emulate-tab t))
  6107. (call-interactively (global-key-binding "\t")))
  6108. (t (save-excursion
  6109. (org-back-to-heading)
  6110. (org-cycle)))))))
  6111. (defun org-cycle-internal-global ()
  6112. "Do the global cycling action."
  6113. ;; Hack to avoid display of messages for .org attachments in Gnus
  6114. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6115. (cond
  6116. ((and (eq last-command this-command)
  6117. (eq org-cycle-global-status 'overview))
  6118. ;; We just created the overview - now do table of contents
  6119. ;; This can be slow in very large buffers, so indicate action
  6120. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6121. (unless ga (org-unlogged-message "CONTENTS..."))
  6122. (org-content)
  6123. (unless ga (org-unlogged-message "CONTENTS...done"))
  6124. (setq org-cycle-global-status 'contents)
  6125. (run-hook-with-args 'org-cycle-hook 'contents))
  6126. ((and (eq last-command this-command)
  6127. (eq org-cycle-global-status 'contents))
  6128. ;; We just showed the table of contents - now show everything
  6129. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6130. (outline-show-all)
  6131. (unless ga (org-unlogged-message "SHOW ALL"))
  6132. (setq org-cycle-global-status 'all)
  6133. (run-hook-with-args 'org-cycle-hook 'all))
  6134. (t
  6135. ;; Default action: go to overview
  6136. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6137. (org-overview)
  6138. (unless ga (org-unlogged-message "OVERVIEW"))
  6139. (setq org-cycle-global-status 'overview)
  6140. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6141. (defvar org-called-with-limited-levels nil
  6142. "Non-nil when `org-with-limited-levels' is currently active.")
  6143. (defun org-invisible-p (&optional pos)
  6144. "Non-nil if the character after POS is invisible.
  6145. If POS is nil, use `point' instead."
  6146. (get-char-property (or pos (point)) 'invisible))
  6147. (defun org-cycle-internal-local ()
  6148. "Do the local cycling action."
  6149. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6150. ;; First, determine end of headline (EOH), end of subtree or item
  6151. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6152. (save-excursion
  6153. (if (org-at-item-p)
  6154. (progn
  6155. (beginning-of-line)
  6156. (setq struct (org-list-struct))
  6157. (setq eoh (point-at-eol))
  6158. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6159. (setq has-children (org-list-has-child-p (point) struct)))
  6160. (org-back-to-heading)
  6161. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6162. (setq eos (save-excursion (org-end-of-subtree t t)
  6163. (when (bolp) (backward-char)) (point)))
  6164. (setq has-children
  6165. (or (save-excursion
  6166. (let ((level (funcall outline-level)))
  6167. (outline-next-heading)
  6168. (and (org-at-heading-p t)
  6169. (> (funcall outline-level) level))))
  6170. (save-excursion
  6171. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6172. ;; Determine end invisible part of buffer (EOL)
  6173. (beginning-of-line 2)
  6174. (while (and (not (eobp)) ;This is like `next-line'.
  6175. (get-char-property (1- (point)) 'invisible))
  6176. (goto-char (next-single-char-property-change (point) 'invisible))
  6177. (and (eolp) (beginning-of-line 2)))
  6178. (setq eol (point)))
  6179. ;; Find out what to do next and set `this-command'
  6180. (cond
  6181. ((= eos eoh)
  6182. ;; Nothing is hidden behind this heading
  6183. (unless (org-before-first-heading-p)
  6184. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6185. (org-unlogged-message "EMPTY ENTRY")
  6186. (setq org-cycle-subtree-status nil)
  6187. (save-excursion
  6188. (goto-char eos)
  6189. (outline-next-heading)
  6190. (when (org-invisible-p) (org-flag-heading nil))))
  6191. ((and (or (>= eol eos)
  6192. (not (string-match "\\S-" (buffer-substring eol eos))))
  6193. (or has-children
  6194. (not (setq children-skipped
  6195. org-cycle-skip-children-state-if-no-children))))
  6196. ;; Entire subtree is hidden in one line: children view
  6197. (unless (org-before-first-heading-p)
  6198. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6199. (if (org-at-item-p)
  6200. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6201. (org-show-entry)
  6202. (org-with-limited-levels (org-show-children))
  6203. ;; FIXME: This slows down the func way too much.
  6204. ;; How keep drawers hidden in subtree anyway?
  6205. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6206. ;; (org-cycle-hide-drawers 'subtree))
  6207. ;; Fold every list in subtree to top-level items.
  6208. (when (eq org-cycle-include-plain-lists 'integrate)
  6209. (save-excursion
  6210. (org-back-to-heading)
  6211. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6212. (beginning-of-line 1)
  6213. (let* ((struct (org-list-struct))
  6214. (prevs (org-list-prevs-alist struct))
  6215. (end (org-list-get-bottom-point struct)))
  6216. (dolist (e (org-list-get-all-items (point) struct prevs))
  6217. (org-list-set-item-visibility e struct 'folded))
  6218. (goto-char (if (< end eos) end eos)))))))
  6219. (org-unlogged-message "CHILDREN")
  6220. (save-excursion
  6221. (goto-char eos)
  6222. (outline-next-heading)
  6223. (when (org-invisible-p) (org-flag-heading nil)))
  6224. (setq org-cycle-subtree-status 'children)
  6225. (unless (org-before-first-heading-p)
  6226. (run-hook-with-args 'org-cycle-hook 'children)))
  6227. ((or children-skipped
  6228. (and (eq last-command this-command)
  6229. (eq org-cycle-subtree-status 'children)))
  6230. ;; We just showed the children, or no children are there,
  6231. ;; now show everything.
  6232. (unless (org-before-first-heading-p)
  6233. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6234. (outline-flag-region eoh eos nil)
  6235. (org-unlogged-message
  6236. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6237. (setq org-cycle-subtree-status 'subtree)
  6238. (unless (org-before-first-heading-p)
  6239. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6240. (t
  6241. ;; Default action: hide the subtree.
  6242. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6243. (outline-flag-region eoh eos t)
  6244. (org-unlogged-message "FOLDED")
  6245. (setq org-cycle-subtree-status 'folded)
  6246. (unless (org-before-first-heading-p)
  6247. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6248. ;;;###autoload
  6249. (defun org-global-cycle (&optional arg)
  6250. "Cycle the global visibility. For details see `org-cycle'.
  6251. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6252. With a numeric prefix, show all headlines up to that level."
  6253. (interactive "P")
  6254. (let ((org-cycle-include-plain-lists
  6255. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6256. (cond
  6257. ((integerp arg)
  6258. (outline-show-all)
  6259. (outline-hide-sublevels arg)
  6260. (setq org-cycle-global-status 'contents))
  6261. ((equal arg '(4))
  6262. (org-set-startup-visibility)
  6263. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6264. (t
  6265. (org-cycle '(4))))))
  6266. (defun org-set-startup-visibility ()
  6267. "Set the visibility required by startup options and properties."
  6268. (cond
  6269. ((eq org-startup-folded t)
  6270. (org-overview))
  6271. ((eq org-startup-folded 'content)
  6272. (org-content))
  6273. ((or (eq org-startup-folded 'showeverything)
  6274. (eq org-startup-folded nil))
  6275. (outline-show-all)))
  6276. (unless (eq org-startup-folded 'showeverything)
  6277. (when org-hide-block-startup (org-hide-block-all))
  6278. (org-set-visibility-according-to-property 'no-cleanup)
  6279. (org-cycle-hide-archived-subtrees 'all)
  6280. (org-cycle-hide-drawers 'all)
  6281. (org-cycle-show-empty-lines t)))
  6282. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6283. "Switch subtree visibilities according to :VISIBILITY: property."
  6284. (interactive)
  6285. (org-with-wide-buffer
  6286. (goto-char (point-min))
  6287. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6288. (if (not (org-at-property-p)) (outline-next-heading)
  6289. (let ((state (match-string 3)))
  6290. (save-excursion
  6291. (org-back-to-heading t)
  6292. (outline-hide-subtree)
  6293. (org-reveal)
  6294. (cond
  6295. ((equal state "folded")
  6296. (outline-hide-subtree))
  6297. ((equal state "children")
  6298. (org-show-hidden-entry)
  6299. (org-show-children))
  6300. ((equal state "content")
  6301. (save-excursion
  6302. (save-restriction
  6303. (org-narrow-to-subtree)
  6304. (org-content))))
  6305. ((member state '("all" "showall"))
  6306. (outline-show-subtree)))))))
  6307. (unless no-cleanup
  6308. (org-cycle-hide-archived-subtrees 'all)
  6309. (org-cycle-hide-drawers 'all)
  6310. (org-cycle-show-empty-lines 'all))))
  6311. ;; This function uses outline-regexp instead of the more fundamental
  6312. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6313. ;; buffers, where outline-regexp is needed.
  6314. (defun org-overview ()
  6315. "Switch to overview mode, showing only top-level headlines.
  6316. This shows all headlines with a level equal or greater than the level
  6317. of the first headline in the buffer. This is important, because if the
  6318. first headline is not level one, then (hide-sublevels 1) gives confusing
  6319. results."
  6320. (interactive)
  6321. (save-excursion
  6322. (let ((level
  6323. (save-excursion
  6324. (goto-char (point-min))
  6325. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6326. (goto-char (match-beginning 0))
  6327. (funcall outline-level)))))
  6328. (and level (outline-hide-sublevels level)))))
  6329. (defun org-content (&optional arg)
  6330. "Show all headlines in the buffer, like a table of contents.
  6331. With numerical argument N, show content up to level N."
  6332. (interactive "P")
  6333. (org-overview)
  6334. (save-excursion
  6335. ;; Visit all headings and show their offspring
  6336. (and (integerp arg) (org-overview))
  6337. (goto-char (point-max))
  6338. (catch 'exit
  6339. (while (and (progn (condition-case nil
  6340. (outline-previous-visible-heading 1)
  6341. (error (goto-char (point-min))))
  6342. t)
  6343. (looking-at org-outline-regexp))
  6344. (if (integerp arg)
  6345. (org-show-children (1- arg))
  6346. (outline-show-branches))
  6347. (when (bobp) (throw 'exit nil))))))
  6348. (defun org-optimize-window-after-visibility-change (state)
  6349. "Adjust the window after a change in outline visibility.
  6350. This function is the default value of the hook `org-cycle-hook'."
  6351. (when (get-buffer-window (current-buffer))
  6352. (cond
  6353. ((eq state 'content) nil)
  6354. ((eq state 'all) nil)
  6355. ((eq state 'folded) nil)
  6356. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6357. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6358. (defun org-remove-empty-overlays-at (pos)
  6359. "Remove outline overlays that do not contain non-white stuff."
  6360. (dolist (o (overlays-at pos))
  6361. (and (eq 'outline (overlay-get o 'invisible))
  6362. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6363. (overlay-end o))))
  6364. (delete-overlay o))))
  6365. (defun org-clean-visibility-after-subtree-move ()
  6366. "Fix visibility issues after moving a subtree."
  6367. ;; First, find a reasonable region to look at:
  6368. ;; Start two siblings above, end three below
  6369. (let* ((beg (save-excursion
  6370. (and (org-get-last-sibling)
  6371. (org-get-last-sibling))
  6372. (point)))
  6373. (end (save-excursion
  6374. (and (org-get-next-sibling)
  6375. (org-get-next-sibling)
  6376. (org-get-next-sibling))
  6377. (if (org-at-heading-p)
  6378. (point-at-eol)
  6379. (point))))
  6380. (level (looking-at "\\*+"))
  6381. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6382. (save-excursion
  6383. (save-restriction
  6384. (narrow-to-region beg end)
  6385. (when re
  6386. ;; Properly fold already folded siblings
  6387. (goto-char (point-min))
  6388. (while (re-search-forward re nil t)
  6389. (when (and (not (org-invisible-p))
  6390. (save-excursion
  6391. (goto-char (point-at-eol)) (org-invisible-p)))
  6392. (outline-hide-entry))))
  6393. (org-cycle-show-empty-lines 'overview)
  6394. (org-cycle-hide-drawers 'overview)))))
  6395. (defun org-cycle-show-empty-lines (state)
  6396. "Show empty lines above all visible headlines.
  6397. The region to be covered depends on STATE when called through
  6398. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6399. entire buffer covered. Note that an empty line is only shown if there
  6400. are at least `org-cycle-separator-lines' empty lines before the headline."
  6401. (when (/= org-cycle-separator-lines 0)
  6402. (save-excursion
  6403. (let* ((n (abs org-cycle-separator-lines))
  6404. (re (cond
  6405. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6406. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6407. (t (let ((ns (number-to-string (- n 2))))
  6408. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6409. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6410. beg end)
  6411. (cond
  6412. ((memq state '(overview contents t))
  6413. (setq beg (point-min) end (point-max)))
  6414. ((memq state '(children folded))
  6415. (setq beg (point)
  6416. end (progn (org-end-of-subtree t t)
  6417. (line-beginning-position 2)))))
  6418. (when beg
  6419. (goto-char beg)
  6420. (while (re-search-forward re end t)
  6421. (unless (get-char-property (match-end 1) 'invisible)
  6422. (let ((e (match-end 1))
  6423. (b (if (>= org-cycle-separator-lines 0)
  6424. (match-beginning 1)
  6425. (save-excursion
  6426. (goto-char (match-beginning 0))
  6427. (skip-chars-backward " \t\n")
  6428. (line-end-position)))))
  6429. (outline-flag-region b e nil))))))))
  6430. ;; Never hide empty lines at the end of the file.
  6431. (save-excursion
  6432. (goto-char (point-max))
  6433. (outline-previous-heading)
  6434. (outline-end-of-heading)
  6435. (when (and (looking-at "[ \t\n]+")
  6436. (= (match-end 0) (point-max)))
  6437. (outline-flag-region (point) (match-end 0) nil))))
  6438. (defun org-show-empty-lines-in-parent ()
  6439. "Move to the parent and re-show empty lines before visible headlines."
  6440. (save-excursion
  6441. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6442. (org-cycle-show-empty-lines context))))
  6443. (defun org-files-list ()
  6444. "Return `org-agenda-files' list, plus all open Org files.
  6445. This is useful for operations that need to scan all of a user's
  6446. open and agenda-wise Org files."
  6447. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6448. (dolist (buf (buffer-list))
  6449. (with-current-buffer buf
  6450. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6451. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6452. files))
  6453. (defsubst org-entry-beginning-position ()
  6454. "Return the beginning position of the current entry."
  6455. (save-excursion (org-back-to-heading t) (point)))
  6456. (defsubst org-entry-end-position ()
  6457. "Return the end position of the current entry."
  6458. (save-excursion (outline-next-heading) (point)))
  6459. (defun org-cycle-hide-drawers (state &optional exceptions)
  6460. "Re-hide all drawers after a visibility state change.
  6461. When non-nil, optional argument EXCEPTIONS is a list of strings
  6462. specifying which drawers should not be hidden."
  6463. (when (and (derived-mode-p 'org-mode)
  6464. (not (memq state '(overview folded contents))))
  6465. (save-excursion
  6466. (let* ((globalp (memq state '(contents all)))
  6467. (beg (if globalp (point-min) (point)))
  6468. (end (if globalp (point-max)
  6469. (if (eq state 'children)
  6470. (save-excursion (outline-next-heading) (point))
  6471. (org-end-of-subtree t)))))
  6472. (goto-char beg)
  6473. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6474. (unless (member-ignore-case (match-string 1) exceptions)
  6475. (let ((drawer (org-element-at-point)))
  6476. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6477. (org-flag-drawer t drawer)
  6478. ;; Make sure to skip drawer entirely or we might flag
  6479. ;; it another time when matching its ending line with
  6480. ;; `org-drawer-regexp'.
  6481. (goto-char (org-element-property :end drawer))))))))))
  6482. (defun org-flag-drawer (flag &optional element)
  6483. "When FLAG is non-nil, hide the drawer we are at.
  6484. Otherwise make it visible. When optional argument ELEMENT is
  6485. a parsed drawer, as returned by `org-element-at-point', hide or
  6486. show that drawer instead."
  6487. (let ((drawer (or element
  6488. (and (save-excursion
  6489. (beginning-of-line)
  6490. (looking-at-p org-drawer-regexp))
  6491. (org-element-at-point)))))
  6492. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6493. (let ((post (org-element-property :post-affiliated drawer)))
  6494. (save-excursion
  6495. (outline-flag-region
  6496. (progn (goto-char post) (line-end-position))
  6497. (progn (goto-char (org-element-property :end drawer))
  6498. (skip-chars-backward " \r\t\n")
  6499. (line-end-position))
  6500. flag))
  6501. ;; When the drawer is hidden away, make sure point lies in
  6502. ;; a visible part of the buffer.
  6503. (when (and flag (> (line-beginning-position) post))
  6504. (goto-char post))))))
  6505. (defun org-subtree-end-visible-p ()
  6506. "Is the end of the current subtree visible?"
  6507. (pos-visible-in-window-p
  6508. (save-excursion (org-end-of-subtree t) (point))))
  6509. (defun org-first-headline-recenter ()
  6510. "Move cursor to the first headline and recenter the headline."
  6511. (let ((window (get-buffer-window)))
  6512. (when window
  6513. (goto-char (point-min))
  6514. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6515. (set-window-start window (line-beginning-position))))))
  6516. ;;; Saving and restoring visibility
  6517. (defun org-outline-overlay-data (&optional use-markers)
  6518. "Return a list of the locations of all outline overlays.
  6519. These are overlays with the `invisible' property value `outline'.
  6520. The return value is a list of cons cells, with start and stop
  6521. positions for each overlay.
  6522. If USE-MARKERS is set, return the positions as markers."
  6523. (let (beg end)
  6524. (org-with-wide-buffer
  6525. (delq nil
  6526. (mapcar (lambda (o)
  6527. (when (eq (overlay-get o 'invisible) 'outline)
  6528. (setq beg (overlay-start o)
  6529. end (overlay-end o))
  6530. (and beg end (> end beg)
  6531. (if use-markers
  6532. (cons (copy-marker beg)
  6533. (copy-marker end t))
  6534. (cons beg end)))))
  6535. (overlays-in (point-min) (point-max)))))))
  6536. (defun org-set-outline-overlay-data (data)
  6537. "Create visibility overlays for all positions in DATA.
  6538. DATA should have been made by `org-outline-overlay-data'."
  6539. (org-with-wide-buffer
  6540. (outline-show-all)
  6541. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6542. ;;; Folding of blocks
  6543. (defvar-local org-hide-block-overlays nil
  6544. "Overlays hiding blocks.")
  6545. (defun org-block-map (function &optional start end)
  6546. "Call FUNCTION at the head of all source blocks in the current buffer.
  6547. Optional arguments START and END can be used to limit the range."
  6548. (let ((start (or start (point-min)))
  6549. (end (or end (point-max))))
  6550. (save-excursion
  6551. (goto-char start)
  6552. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6553. (save-excursion
  6554. (save-match-data
  6555. (goto-char (match-beginning 0))
  6556. (funcall function)))))))
  6557. (defun org-hide-block-toggle-all ()
  6558. "Toggle the visibility of all blocks in the current buffer."
  6559. (org-block-map 'org-hide-block-toggle))
  6560. (defun org-hide-block-all ()
  6561. "Fold all blocks in the current buffer."
  6562. (interactive)
  6563. (org-show-block-all)
  6564. (org-block-map 'org-hide-block-toggle-maybe))
  6565. (defun org-show-block-all ()
  6566. "Unfold all blocks in the current buffer."
  6567. (interactive)
  6568. (mapc #'delete-overlay org-hide-block-overlays)
  6569. (setq org-hide-block-overlays nil))
  6570. (defun org-hide-block-toggle-maybe ()
  6571. "Toggle visibility of block at point.
  6572. Unlike to `org-hide-block-toggle', this function does not throw
  6573. an error. Return a non-nil value when toggling is successful."
  6574. (interactive)
  6575. (ignore-errors (org-hide-block-toggle)))
  6576. (defun org-hide-block-toggle (&optional force)
  6577. "Toggle the visibility of the current block.
  6578. When optional argument FORCE is `off', make block visible. If it
  6579. is non-nil, hide it unconditionally. Throw an error when not at
  6580. a block. Return a non-nil value when toggling is successful."
  6581. (interactive)
  6582. (let ((element (org-element-at-point)))
  6583. (unless (memq (org-element-type element)
  6584. '(center-block comment-block dynamic-block example-block
  6585. export-block quote-block special-block
  6586. src-block verse-block))
  6587. (user-error "Not at a block"))
  6588. (let* ((start (save-excursion
  6589. (goto-char (org-element-property :post-affiliated element))
  6590. (line-end-position)))
  6591. (end (save-excursion
  6592. (goto-char (org-element-property :end element))
  6593. (skip-chars-backward " \r\t\n")
  6594. (line-end-position)))
  6595. (overlays (overlays-at start)))
  6596. (cond
  6597. ;; Do nothing when not before or at the block opening line or
  6598. ;; at the block closing line.
  6599. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6600. ((and (not (eq force 'off))
  6601. (not (memq t (mapcar
  6602. (lambda (o)
  6603. (eq (overlay-get o 'invisible) 'org-hide-block))
  6604. overlays))))
  6605. (let ((ov (make-overlay start end)))
  6606. (overlay-put ov 'invisible 'org-hide-block)
  6607. ;; Make the block accessible to `isearch'.
  6608. (overlay-put
  6609. ov 'isearch-open-invisible
  6610. (lambda (ov)
  6611. (when (memq ov org-hide-block-overlays)
  6612. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6613. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6614. (delete-overlay ov))))
  6615. (push ov org-hide-block-overlays)
  6616. ;; When the block is hidden away, make sure point is left in
  6617. ;; a visible part of the buffer.
  6618. (when (> (line-beginning-position) start)
  6619. (goto-char start)
  6620. (beginning-of-line))
  6621. ;; Signal successful toggling.
  6622. t))
  6623. ((or (not force) (eq force 'off))
  6624. (dolist (ov overlays t)
  6625. (when (memq ov org-hide-block-overlays)
  6626. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6627. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6628. (delete-overlay ov))))))))
  6629. ;; Remove overlays when changing major mode
  6630. (add-hook 'org-mode-hook
  6631. (lambda () (add-hook 'change-major-mode-hook
  6632. 'org-show-block-all 'append 'local)))
  6633. ;;; Org-goto
  6634. (defvar org-goto-window-configuration nil)
  6635. (defvar org-goto-marker nil)
  6636. (defvar org-goto-map)
  6637. (defun org-goto-map ()
  6638. "Set the keymap `org-goto'."
  6639. (setq org-goto-map
  6640. (let ((map (make-sparse-keymap)))
  6641. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6642. mouse-drag-region universal-argument org-occur)))
  6643. (dolist (cmd cmds)
  6644. (substitute-key-definition cmd cmd map global-map)))
  6645. (suppress-keymap map)
  6646. (org-defkey map "\C-m" 'org-goto-ret)
  6647. (org-defkey map [(return)] 'org-goto-ret)
  6648. (org-defkey map [(left)] 'org-goto-left)
  6649. (org-defkey map [(right)] 'org-goto-right)
  6650. (org-defkey map [(control ?g)] 'org-goto-quit)
  6651. (org-defkey map "\C-i" 'org-cycle)
  6652. (org-defkey map [(tab)] 'org-cycle)
  6653. (org-defkey map [(down)] 'outline-next-visible-heading)
  6654. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6655. (if org-goto-auto-isearch
  6656. (if (fboundp 'define-key-after)
  6657. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6658. nil)
  6659. (org-defkey map "q" 'org-goto-quit)
  6660. (org-defkey map "n" 'outline-next-visible-heading)
  6661. (org-defkey map "p" 'outline-previous-visible-heading)
  6662. (org-defkey map "f" 'outline-forward-same-level)
  6663. (org-defkey map "b" 'outline-backward-same-level)
  6664. (org-defkey map "u" 'outline-up-heading))
  6665. (org-defkey map "/" 'org-occur)
  6666. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6667. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6668. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6669. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6670. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6671. map)))
  6672. (defconst org-goto-help
  6673. "Browse buffer copy, to find location or copy text.%s
  6674. RET=jump to location C-g=quit and return to previous location
  6675. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6676. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6677. (defun org-goto (&optional alternative-interface)
  6678. "Look up a different location in the current file, keeping current visibility.
  6679. When you want look-up or go to a different location in a
  6680. document, the fastest way is often to fold the entire buffer and
  6681. then dive into the tree. This method has the disadvantage, that
  6682. the previous location will be folded, which may not be what you
  6683. want.
  6684. This command works around this by showing a copy of the current
  6685. buffer in an indirect buffer, in overview mode. You can dive
  6686. into the tree in that copy, use org-occur and incremental search
  6687. to find a location. When pressing RET or `Q', the command
  6688. returns to the original buffer in which the visibility is still
  6689. unchanged. After RET it will also jump to the location selected
  6690. in the indirect buffer and expose the headline hierarchy above.
  6691. With a prefix argument, use the alternative interface: e.g., if
  6692. `org-goto-interface' is `outline' use `outline-path-completion'."
  6693. (interactive "P")
  6694. (org-goto-map)
  6695. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6696. (org-refile-use-outline-path t)
  6697. (org-refile-target-verify-function nil)
  6698. (interface
  6699. (if (not alternative-interface)
  6700. org-goto-interface
  6701. (if (eq org-goto-interface 'outline)
  6702. 'outline-path-completion
  6703. 'outline)))
  6704. (org-goto-start-pos (point))
  6705. (selected-point
  6706. (if (eq interface 'outline)
  6707. (car (org-get-location (current-buffer) org-goto-help))
  6708. (let ((pa (org-refile-get-location "Goto")))
  6709. (org-refile-check-position pa)
  6710. (nth 3 pa)))))
  6711. (if selected-point
  6712. (progn
  6713. (org-mark-ring-push org-goto-start-pos)
  6714. (goto-char selected-point)
  6715. (when (or (org-invisible-p) (org-invisible-p2))
  6716. (org-show-context 'org-goto)))
  6717. (message "Quit"))))
  6718. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6719. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6720. (defvar org-goto-local-auto-isearch-map) ; defined below
  6721. (defun org-get-location (_buf help)
  6722. "Let the user select a location in current buffer.
  6723. This function uses a recursive edit. It returns the selected position
  6724. or nil."
  6725. (org-no-popups
  6726. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6727. (isearch-hide-immediately nil)
  6728. (isearch-search-fun-function
  6729. (lambda () 'org-goto-local-search-headings))
  6730. (org-goto-selected-point org-goto-exit-command))
  6731. (save-excursion
  6732. (save-window-excursion
  6733. (delete-other-windows)
  6734. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6735. (pop-to-buffer-same-window
  6736. (condition-case nil
  6737. (make-indirect-buffer (current-buffer) "*org-goto*")
  6738. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6739. (with-output-to-temp-buffer "*Org Help*"
  6740. (princ (format help (if org-goto-auto-isearch
  6741. " Just type for auto-isearch."
  6742. " n/p/f/b/u to navigate, q to quit."))))
  6743. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6744. (setq buffer-read-only nil)
  6745. (let ((org-startup-truncated t)
  6746. (org-startup-folded nil)
  6747. (org-startup-align-all-tables nil))
  6748. (org-mode)
  6749. (org-overview))
  6750. (setq buffer-read-only t)
  6751. (if (and (boundp 'org-goto-start-pos)
  6752. (integer-or-marker-p org-goto-start-pos))
  6753. (progn (goto-char org-goto-start-pos)
  6754. (when (org-invisible-p)
  6755. (org-show-set-visibility 'lineage)))
  6756. (goto-char (point-min)))
  6757. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6758. (message "Select location and press RET")
  6759. (use-local-map org-goto-map)
  6760. (recursive-edit)))
  6761. (kill-buffer "*org-goto*")
  6762. (cons org-goto-selected-point org-goto-exit-command))))
  6763. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6764. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6765. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6766. (if (fboundp 'isearch-other-control-char)
  6767. (progn
  6768. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6769. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6770. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6771. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6772. (define-key org-goto-local-auto-isearch-map [return] nil))
  6773. (defun org-goto-local-search-headings (string bound noerror)
  6774. "Search and make sure that any matches are in headlines."
  6775. (catch 'return
  6776. (while (if isearch-forward
  6777. (search-forward string bound noerror)
  6778. (search-backward string bound noerror))
  6779. (when (save-match-data
  6780. (and (save-excursion
  6781. (beginning-of-line)
  6782. (looking-at org-complex-heading-regexp))
  6783. (or (not (match-beginning 5))
  6784. (< (point) (match-beginning 5)))))
  6785. (throw 'return (point))))))
  6786. (defun org-goto-local-auto-isearch ()
  6787. "Start isearch."
  6788. (interactive)
  6789. (goto-char (point-min))
  6790. (let ((keys (this-command-keys)))
  6791. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6792. (isearch-mode t)
  6793. (isearch-process-search-char (string-to-char keys)))))
  6794. (defun org-goto-ret (&optional _arg)
  6795. "Finish `org-goto' by going to the new location."
  6796. (interactive "P")
  6797. (setq org-goto-selected-point (point))
  6798. (setq org-goto-exit-command 'return)
  6799. (throw 'exit nil))
  6800. (defun org-goto-left ()
  6801. "Finish `org-goto' by going to the new location."
  6802. (interactive)
  6803. (if (org-at-heading-p)
  6804. (progn
  6805. (beginning-of-line 1)
  6806. (setq org-goto-selected-point (point)
  6807. org-goto-exit-command 'left)
  6808. (throw 'exit nil))
  6809. (user-error "Not on a heading")))
  6810. (defun org-goto-right ()
  6811. "Finish `org-goto' by going to the new location."
  6812. (interactive)
  6813. (if (org-at-heading-p)
  6814. (progn
  6815. (setq org-goto-selected-point (point)
  6816. org-goto-exit-command 'right)
  6817. (throw 'exit nil))
  6818. (user-error "Not on a heading")))
  6819. (defun org-goto-quit ()
  6820. "Finish `org-goto' without cursor motion."
  6821. (interactive)
  6822. (setq org-goto-selected-point nil)
  6823. (setq org-goto-exit-command 'quit)
  6824. (throw 'exit nil))
  6825. ;;; Indirect buffer display of subtrees
  6826. (defvar org-indirect-dedicated-frame nil
  6827. "This is the frame being used for indirect tree display.")
  6828. (defvar org-last-indirect-buffer nil)
  6829. (defun org-tree-to-indirect-buffer (&optional arg)
  6830. "Create indirect buffer and narrow it to current subtree.
  6831. With a numerical prefix ARG, go up to this level and then take that tree.
  6832. If ARG is negative, go up that many levels.
  6833. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6834. indirect buffer previously made with this command, to avoid proliferation of
  6835. indirect buffers. However, when you call the command with a \
  6836. `\\[universal-argument]' prefix, or
  6837. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6838. so that you can work with several indirect buffers at the same time. If
  6839. `org-indirect-buffer-display' is `dedicated-frame', the \
  6840. `\\[universal-argument]' prefix also
  6841. requests that a new frame be made for the new buffer, so that the dedicated
  6842. frame is not changed."
  6843. (interactive "P")
  6844. (let ((cbuf (current-buffer))
  6845. (cwin (selected-window))
  6846. (pos (point))
  6847. beg end level heading ibuf)
  6848. (save-excursion
  6849. (org-back-to-heading t)
  6850. (when (numberp arg)
  6851. (setq level (org-outline-level))
  6852. (when (< arg 0) (setq arg (+ level arg)))
  6853. (while (> (setq level (org-outline-level)) arg)
  6854. (org-up-heading-safe)))
  6855. (setq beg (point)
  6856. heading (org-get-heading 'no-tags))
  6857. (org-end-of-subtree t t)
  6858. (when (org-at-heading-p) (backward-char 1))
  6859. (setq end (point)))
  6860. (when (and (buffer-live-p org-last-indirect-buffer)
  6861. (not (eq org-indirect-buffer-display 'new-frame))
  6862. (not arg))
  6863. (kill-buffer org-last-indirect-buffer))
  6864. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6865. org-last-indirect-buffer ibuf)
  6866. (cond
  6867. ((or (eq org-indirect-buffer-display 'new-frame)
  6868. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6869. (select-frame (make-frame))
  6870. (delete-other-windows)
  6871. (pop-to-buffer-same-window ibuf)
  6872. (org-set-frame-title heading))
  6873. ((eq org-indirect-buffer-display 'dedicated-frame)
  6874. (raise-frame
  6875. (select-frame (or (and org-indirect-dedicated-frame
  6876. (frame-live-p org-indirect-dedicated-frame)
  6877. org-indirect-dedicated-frame)
  6878. (setq org-indirect-dedicated-frame (make-frame)))))
  6879. (delete-other-windows)
  6880. (pop-to-buffer-same-window ibuf)
  6881. (org-set-frame-title (concat "Indirect: " heading)))
  6882. ((eq org-indirect-buffer-display 'current-window)
  6883. (pop-to-buffer-same-window ibuf))
  6884. ((eq org-indirect-buffer-display 'other-window)
  6885. (pop-to-buffer ibuf))
  6886. (t (error "Invalid value")))
  6887. (narrow-to-region beg end)
  6888. (outline-show-all)
  6889. (goto-char pos)
  6890. (run-hook-with-args 'org-cycle-hook 'all)
  6891. (and (window-live-p cwin) (select-window cwin))))
  6892. (defun org-get-indirect-buffer (&optional buffer heading)
  6893. (setq buffer (or buffer (current-buffer)))
  6894. (let ((n 1) (base (buffer-name buffer)) bname)
  6895. (while (buffer-live-p
  6896. (get-buffer
  6897. (setq bname
  6898. (concat base "-"
  6899. (if heading (concat heading "-" (number-to-string n))
  6900. (number-to-string n))))))
  6901. (setq n (1+ n)))
  6902. (condition-case nil
  6903. (make-indirect-buffer buffer bname 'clone)
  6904. (error (make-indirect-buffer buffer bname)))))
  6905. (defun org-set-frame-title (title)
  6906. "Set the title of the current frame to the string TITLE."
  6907. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6908. ;;;; Structure editing
  6909. ;;; Inserting headlines
  6910. (defun org--line-empty-p (n)
  6911. "Is the Nth next line empty?
  6912. Counts the current line as N = 1 and the previous line as N = 0;
  6913. see `beginning-of-line'."
  6914. (save-excursion
  6915. (and (not (bobp))
  6916. (or (beginning-of-line n) t)
  6917. (save-match-data
  6918. (looking-at "[ \t]*$")))))
  6919. (defun org-previous-line-empty-p ()
  6920. "Is the previous line a blank line?
  6921. When NEXT is non-nil, check the next line instead."
  6922. (org--line-empty-p 0))
  6923. (defun org-next-line-empty-p ()
  6924. "Is the previous line a blank line?
  6925. When NEXT is non-nil, check the next line instead."
  6926. (org--line-empty-p 2))
  6927. (defun org-insert-heading (&optional arg invisible-ok top)
  6928. "Insert a new heading or an item with the same depth at point.
  6929. If point is at the beginning of a heading or a list item, insert
  6930. a new heading or a new item above the current one. When at the
  6931. beginning of a regular line of text, turn it into a heading.
  6932. If point is in the middle of a line, split it and create a new
  6933. headline/item with the text in the current line after point (see
  6934. `org-M-RET-may-split-line' on how to modify this behavior). As
  6935. a special case, on a headline, splitting can only happen on the
  6936. title itself. E.g., this excludes breaking stars or tags.
  6937. With a `\\[universal-argument]' prefix, set \
  6938. `org-insert-heading-respect-content' to
  6939. a non-nil value for the duration of the command. This forces the
  6940. insertion of a heading after the current subtree, independently
  6941. on the location of point.
  6942. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6943. insert the heading at the end of the tree
  6944. above the current heading. For example, if point is within a
  6945. 2nd-level heading, then it will insert a 2nd-level heading at
  6946. the end of the 1st-level parent subtree.
  6947. When INVISIBLE-OK is set, stop at invisible headlines when going
  6948. back. This is important for non-interactive uses of the
  6949. command.
  6950. When optional argument TOP is non-nil, insert a level 1 heading,
  6951. unconditionally."
  6952. (interactive "P")
  6953. (let ((itemp (and (not top) (org-in-item-p)))
  6954. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  6955. (respect-content (or org-insert-heading-respect-content
  6956. (equal arg '(4))))
  6957. (initial-content ""))
  6958. (cond
  6959. ((or (= (buffer-size) 0)
  6960. (and (not (save-excursion
  6961. (and (ignore-errors (org-back-to-heading invisible-ok))
  6962. (org-at-heading-p))))
  6963. (or arg (not itemp))))
  6964. ;; At beginning of buffer or so high up that only a heading
  6965. ;; makes sense.
  6966. (cond ((and (bolp) (not respect-content)) (insert "* "))
  6967. ((not respect-content)
  6968. (unless may-split (end-of-line))
  6969. (insert "\n* "))
  6970. ((re-search-forward org-outline-regexp-bol nil t)
  6971. (beginning-of-line)
  6972. (insert "* \n")
  6973. (backward-char))
  6974. (t (goto-char (point-max))
  6975. (insert "\n* ")))
  6976. (run-hooks 'org-insert-heading-hook))
  6977. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  6978. (t
  6979. ;; Maybe move at the end of the subtree
  6980. (when (equal arg '(16))
  6981. (org-up-heading-safe)
  6982. (org-end-of-subtree t))
  6983. ;; Insert a heading
  6984. (save-restriction
  6985. (widen)
  6986. (let* ((level nil)
  6987. (on-heading (org-at-heading-p))
  6988. (empty-line-p (if on-heading
  6989. (org-previous-line-empty-p)
  6990. ;; We will decide later
  6991. nil))
  6992. ;; Get a level string to fall back on.
  6993. (fix-level
  6994. (if (org-before-first-heading-p) "*"
  6995. (save-excursion
  6996. (org-back-to-heading t)
  6997. (when (org-previous-line-empty-p) (setq empty-line-p t))
  6998. (looking-at org-outline-regexp)
  6999. (make-string (1- (length (match-string 0))) ?*))))
  7000. (stars
  7001. (save-excursion
  7002. (condition-case nil
  7003. (if top "* "
  7004. (org-back-to-heading invisible-ok)
  7005. (when (and (not on-heading)
  7006. (featurep 'org-inlinetask)
  7007. (integerp org-inlinetask-min-level)
  7008. (>= (length (match-string 0))
  7009. org-inlinetask-min-level))
  7010. ;; Find a heading level before the inline
  7011. ;; task.
  7012. (while (and (setq level (org-up-heading-safe))
  7013. (>= level org-inlinetask-min-level)))
  7014. (if (org-at-heading-p)
  7015. (org-back-to-heading invisible-ok)
  7016. (error "This should not happen")))
  7017. (unless (and (save-excursion
  7018. (save-match-data
  7019. (org-backward-heading-same-level
  7020. 1 invisible-ok))
  7021. (= (point) (match-beginning 0)))
  7022. (not (org-next-line-empty-p)))
  7023. (setq empty-line-p (or empty-line-p
  7024. (org-previous-line-empty-p))))
  7025. (match-string 0))
  7026. (error (or fix-level "* ")))))
  7027. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7028. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7029. ;; If we insert after content, move there and clean up
  7030. ;; whitespace.
  7031. (when respect-content
  7032. (if (not (org-before-first-heading-p))
  7033. (org-end-of-subtree nil t)
  7034. (re-search-forward org-outline-regexp-bol)
  7035. (beginning-of-line 0))
  7036. (skip-chars-backward " \r\t\n")
  7037. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7038. (looking-at "[ \t]+") (replace-match ""))
  7039. (unless (eobp) (forward-char 1))
  7040. (when (looking-at "^\\*")
  7041. (unless (bobp) (backward-char 1))
  7042. (insert "\n")))
  7043. ;; If we are splitting, grab the text that should be moved
  7044. ;; to the new headline.
  7045. (when may-split
  7046. (if (org-at-heading-p)
  7047. ;; This is a heading: split intelligently (keeping
  7048. ;; tags).
  7049. (let ((pos (point)))
  7050. (beginning-of-line)
  7051. (let ((case-fold-search nil))
  7052. (unless (looking-at org-complex-heading-regexp)
  7053. (error "This should not happen")))
  7054. (when (and (match-beginning 4)
  7055. (> pos (match-beginning 4))
  7056. (< pos (match-end 4)))
  7057. (setq initial-content (buffer-substring pos (match-end 4)))
  7058. (goto-char pos)
  7059. (delete-region (point) (match-end 4))
  7060. (if (looking-at "[ \t]*$")
  7061. (replace-match "")
  7062. (insert (make-string (length initial-content) ?\s)))
  7063. (setq initial-content (org-trim initial-content)))
  7064. (goto-char pos))
  7065. ;; A normal line.
  7066. (setq initial-content
  7067. (org-trim
  7068. (delete-and-extract-region (point) (line-end-position))))))
  7069. ;; If we are at the beginning of the line, insert before it.
  7070. ;; Otherwise, after it.
  7071. (cond
  7072. ((and (bolp) (looking-at "[ \t]*$")))
  7073. ((bolp) (save-excursion (insert "\n")))
  7074. (t (end-of-line)
  7075. (insert "\n")))
  7076. ;; Insert the new heading
  7077. (insert stars)
  7078. (just-one-space)
  7079. (insert initial-content)
  7080. (unless (and blank (org-previous-line-empty-p))
  7081. (org-N-empty-lines-before-current (if blank 1 0)))
  7082. ;; Adjust visibility, which may be messed up if we removed
  7083. ;; blank lines while previous entry was hidden.
  7084. (let ((bol (line-beginning-position)))
  7085. (dolist (o (overlays-at (1- bol)))
  7086. (when (and (eq (overlay-get o 'invisible) 'outline)
  7087. (eq (overlay-end o) bol))
  7088. (move-overlay o (overlay-start o) (1- bol)))))
  7089. (run-hooks 'org-insert-heading-hook)))))))
  7090. (defun org-N-empty-lines-before-current (N)
  7091. "Make the number of empty lines before current exactly N.
  7092. So this will delete or add empty lines."
  7093. (save-excursion
  7094. (beginning-of-line)
  7095. (let ((p (point)))
  7096. (skip-chars-backward " \r\t\n")
  7097. (unless (bolp) (forward-line))
  7098. (delete-region (point) p))
  7099. (when (> N 0) (insert (make-string N ?\n)))))
  7100. (defun org-get-heading (&optional no-tags no-todo)
  7101. "Return the heading of the current entry, without the stars.
  7102. When NO-TAGS is non-nil, don't include tags.
  7103. When NO-TODO is non-nil, don't include TODO keywords."
  7104. (save-excursion
  7105. (org-back-to-heading t)
  7106. (let ((case-fold-search nil))
  7107. (cond
  7108. ((and no-tags no-todo)
  7109. (looking-at org-complex-heading-regexp)
  7110. ;; Return value has to be a string, but match group 4 is
  7111. ;; optional.
  7112. (or (match-string 4) ""))
  7113. (no-tags
  7114. (looking-at (concat org-outline-regexp
  7115. "\\(.*?\\)"
  7116. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7117. (match-string 1))
  7118. (no-todo
  7119. (looking-at org-todo-line-regexp)
  7120. (match-string 3))
  7121. (t (looking-at org-heading-regexp)
  7122. (match-string 2))))))
  7123. (defvar orgstruct-mode) ; defined below
  7124. (defun org-heading-components ()
  7125. "Return the components of the current heading.
  7126. This is a list with the following elements:
  7127. - the level as an integer
  7128. - the reduced level, different if `org-odd-levels-only' is set.
  7129. - the TODO keyword, or nil
  7130. - the priority character, like ?A, or nil if no priority is given
  7131. - the headline text itself, or the tags string if no headline text
  7132. - the tags string, or nil."
  7133. (save-excursion
  7134. (org-back-to-heading t)
  7135. (when (let (case-fold-search)
  7136. (looking-at
  7137. (if orgstruct-mode
  7138. org-heading-regexp
  7139. org-complex-heading-regexp)))
  7140. (if orgstruct-mode
  7141. (list (length (match-string 1))
  7142. (org-reduced-level (length (match-string 1)))
  7143. nil
  7144. nil
  7145. (match-string 2)
  7146. nil)
  7147. (list (length (match-string 1))
  7148. (org-reduced-level (length (match-string 1)))
  7149. (match-string-no-properties 2)
  7150. (and (match-end 3) (aref (match-string 3) 2))
  7151. (match-string-no-properties 4)
  7152. (match-string-no-properties 5))))))
  7153. (defun org-get-entry ()
  7154. "Get the entry text, after heading, entire subtree."
  7155. (save-excursion
  7156. (org-back-to-heading t)
  7157. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7158. (defun org-edit-headline (&optional heading)
  7159. "Edit the current headline.
  7160. Set it to HEADING when provided."
  7161. (interactive)
  7162. (org-with-wide-buffer
  7163. (org-back-to-heading t)
  7164. (let ((case-fold-search nil))
  7165. (when (looking-at org-complex-heading-regexp)
  7166. (let* ((old (match-string-no-properties 4))
  7167. (new (save-match-data
  7168. (org-trim (or heading (read-string "Edit: " old))))))
  7169. (unless (equal old new)
  7170. (if old (replace-match new t t nil 4)
  7171. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7172. (insert " " new))
  7173. (org-set-tags nil t)
  7174. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7175. (defun org-insert-heading-after-current ()
  7176. "Insert a new heading with same level as current, after current subtree."
  7177. (interactive)
  7178. (org-back-to-heading)
  7179. (org-insert-heading)
  7180. (org-move-subtree-down)
  7181. (end-of-line 1))
  7182. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7183. "Insert heading with `org-insert-heading-respect-content' set to t."
  7184. (interactive)
  7185. (org-insert-heading '(4) invisible-ok))
  7186. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7187. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7188. (interactive)
  7189. (org-insert-todo-heading force-state '(4)))
  7190. (defun org-insert-todo-heading (arg &optional force-heading)
  7191. "Insert a new heading with the same level and TODO state as current heading.
  7192. If the heading has no TODO state, or if the state is DONE, use
  7193. the first state (TODO by default). Also with one prefix arg,
  7194. force first state. With two prefix args, force inserting at the
  7195. end of the parent subtree.
  7196. When called at a plain list item, insert a new item with an
  7197. unchecked check box."
  7198. (interactive "P")
  7199. (when (or force-heading (not (org-insert-item 'checkbox)))
  7200. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7201. force-heading))
  7202. (save-excursion
  7203. (org-back-to-heading)
  7204. (outline-previous-heading)
  7205. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7206. (let* ((new-mark-x
  7207. (if (or (equal arg '(4))
  7208. (not (match-beginning 2))
  7209. (member (match-string 2) org-done-keywords))
  7210. (car org-todo-keywords-1)
  7211. (match-string 2)))
  7212. (new-mark
  7213. (or
  7214. (run-hook-with-args-until-success
  7215. 'org-todo-get-default-hook new-mark-x nil)
  7216. new-mark-x)))
  7217. (beginning-of-line 1)
  7218. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7219. (if org-treat-insert-todo-heading-as-state-change
  7220. (org-todo new-mark)
  7221. (insert new-mark " "))))
  7222. (when org-provide-todo-statistics
  7223. (org-update-parent-todo-statistics))))
  7224. (defun org-insert-subheading (arg)
  7225. "Insert a new subheading and demote it.
  7226. Works for outline headings and for plain lists alike."
  7227. (interactive "P")
  7228. (org-insert-heading arg)
  7229. (cond
  7230. ((org-at-heading-p) (org-do-demote))
  7231. ((org-at-item-p) (org-indent-item))))
  7232. (defun org-insert-todo-subheading (arg)
  7233. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7234. Works for outline headings and for plain lists alike."
  7235. (interactive "P")
  7236. (org-insert-todo-heading arg)
  7237. (cond
  7238. ((org-at-heading-p) (org-do-demote))
  7239. ((org-at-item-p) (org-indent-item))))
  7240. ;;; Promotion and Demotion
  7241. (defvar org-after-demote-entry-hook nil
  7242. "Hook run after an entry has been demoted.
  7243. The cursor will be at the beginning of the entry.
  7244. When a subtree is being demoted, the hook will be called for each node.")
  7245. (defvar org-after-promote-entry-hook nil
  7246. "Hook run after an entry has been promoted.
  7247. The cursor will be at the beginning of the entry.
  7248. When a subtree is being promoted, the hook will be called for each node.")
  7249. (defun org-promote-subtree ()
  7250. "Promote the entire subtree.
  7251. See also `org-promote'."
  7252. (interactive)
  7253. (save-excursion
  7254. (org-with-limited-levels (org-map-tree 'org-promote)))
  7255. (org-fix-position-after-promote))
  7256. (defun org-demote-subtree ()
  7257. "Demote the entire subtree.
  7258. See `org-demote' and `org-promote'."
  7259. (interactive)
  7260. (save-excursion
  7261. (org-with-limited-levels (org-map-tree 'org-demote)))
  7262. (org-fix-position-after-promote))
  7263. (defun org-do-promote ()
  7264. "Promote the current heading higher up the tree.
  7265. If the region is active in `transient-mark-mode', promote all
  7266. headings in the region."
  7267. (interactive)
  7268. (save-excursion
  7269. (if (org-region-active-p)
  7270. (org-map-region 'org-promote (region-beginning) (region-end))
  7271. (org-promote)))
  7272. (org-fix-position-after-promote))
  7273. (defun org-do-demote ()
  7274. "Demote the current heading lower down the tree.
  7275. If the region is active in `transient-mark-mode', demote all
  7276. headings in the region."
  7277. (interactive)
  7278. (save-excursion
  7279. (if (org-region-active-p)
  7280. (org-map-region 'org-demote (region-beginning) (region-end))
  7281. (org-demote)))
  7282. (org-fix-position-after-promote))
  7283. (defun org-fix-position-after-promote ()
  7284. "Fix cursor position and indentation after demoting/promoting."
  7285. (let ((pos (point)))
  7286. (when (save-excursion
  7287. (beginning-of-line)
  7288. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7289. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7290. (cond ((eobp) (insert " "))
  7291. ((eolp) (insert " "))
  7292. ((equal (char-after) ?\s) (forward-char 1))))))
  7293. (defun org-current-level ()
  7294. "Return the level of the current entry, or nil if before the first headline.
  7295. The level is the number of stars at the beginning of the
  7296. headline. Use `org-reduced-level' to remove the effect of
  7297. `org-odd-levels'. Unlike to `org-outline-level', this function
  7298. ignores inlinetasks."
  7299. (let ((level (org-with-limited-levels (org-outline-level))))
  7300. (and (> level 0) level)))
  7301. (defun org-get-previous-line-level ()
  7302. "Return the outline depth of the last headline before the current line.
  7303. Returns 0 for the first headline in the buffer, and nil if before the
  7304. first headline."
  7305. (and (org-current-level)
  7306. (or (and (/= (line-beginning-position) (point-min))
  7307. (save-excursion (beginning-of-line 0) (org-current-level)))
  7308. 0)))
  7309. (defun org-reduced-level (l)
  7310. "Compute the effective level of a heading.
  7311. This takes into account the setting of `org-odd-levels-only'."
  7312. (cond
  7313. ((zerop l) 0)
  7314. (org-odd-levels-only (1+ (floor (/ l 2))))
  7315. (t l)))
  7316. (defun org-level-increment ()
  7317. "Return the number of stars that will be added or removed at a
  7318. time to headlines when structure editing, based on the value of
  7319. `org-odd-levels-only'."
  7320. (if org-odd-levels-only 2 1))
  7321. (defun org-get-valid-level (level &optional change)
  7322. "Rectify a level change under the influence of `org-odd-levels-only'
  7323. LEVEL is a current level, CHANGE is by how much the level should be
  7324. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7325. even level numbers will become the next higher odd number."
  7326. (if org-odd-levels-only
  7327. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7328. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7329. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7330. (max 1 (+ level (or change 0)))))
  7331. (defun org-promote ()
  7332. "Promote the current heading higher up the tree."
  7333. (org-with-wide-buffer
  7334. (org-back-to-heading t)
  7335. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7336. after-change-functions))
  7337. (level (save-match-data (funcall outline-level)))
  7338. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7339. (diff (abs (- level (length up-head) -1))))
  7340. (cond
  7341. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7342. (replace-match "# " nil t))
  7343. ((= level 1)
  7344. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7345. (t (replace-match up-head nil t)))
  7346. (unless (= level 1)
  7347. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7348. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7349. (run-hooks 'org-after-promote-entry-hook))))
  7350. (defun org-demote ()
  7351. "Demote the current heading lower down the tree."
  7352. (org-with-wide-buffer
  7353. (org-back-to-heading t)
  7354. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7355. after-change-functions))
  7356. (level (save-match-data (funcall outline-level)))
  7357. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7358. (diff (abs (- level (length down-head) -1))))
  7359. (replace-match down-head nil t)
  7360. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7361. (when org-adapt-indentation (org-fixup-indentation diff))
  7362. (run-hooks 'org-after-demote-entry-hook))))
  7363. (defun org-cycle-level ()
  7364. "Cycle the level of an empty headline through possible states.
  7365. This goes first to child, then to parent, level, then up the hierarchy.
  7366. After top level, it switches back to sibling level."
  7367. (interactive)
  7368. (let ((org-adapt-indentation nil))
  7369. (when (org-point-at-end-of-empty-headline)
  7370. (setq this-command 'org-cycle-level) ; Only needed for caching
  7371. (let ((cur-level (org-current-level))
  7372. (prev-level (org-get-previous-line-level)))
  7373. (cond
  7374. ;; If first headline in file, promote to top-level.
  7375. ((= prev-level 0)
  7376. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7377. do (org-do-promote)))
  7378. ;; If same level as prev, demote one.
  7379. ((= prev-level cur-level)
  7380. (org-do-demote))
  7381. ;; If parent is top-level, promote to top level if not already.
  7382. ((= prev-level 1)
  7383. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7384. do (org-do-promote)))
  7385. ;; If top-level, return to prev-level.
  7386. ((= cur-level 1)
  7387. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7388. do (org-do-demote)))
  7389. ;; If less than prev-level, promote one.
  7390. ((< cur-level prev-level)
  7391. (org-do-promote))
  7392. ;; If deeper than prev-level, promote until higher than
  7393. ;; prev-level.
  7394. ((> cur-level prev-level)
  7395. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7396. do (org-do-promote))))
  7397. t))))
  7398. (defun org-map-tree (fun)
  7399. "Call FUN for every heading underneath the current one."
  7400. (org-back-to-heading t)
  7401. (let ((level (funcall outline-level)))
  7402. (save-excursion
  7403. (funcall fun)
  7404. (while (and (progn
  7405. (outline-next-heading)
  7406. (> (funcall outline-level) level))
  7407. (not (eobp)))
  7408. (funcall fun)))))
  7409. (defun org-map-region (fun beg end)
  7410. "Call FUN for every heading between BEG and END."
  7411. (let ((org-ignore-region t))
  7412. (save-excursion
  7413. (setq end (copy-marker end))
  7414. (goto-char beg)
  7415. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7416. (< (point) end))
  7417. (funcall fun))
  7418. (while (and (progn
  7419. (outline-next-heading)
  7420. (< (point) end))
  7421. (not (eobp)))
  7422. (funcall fun)))))
  7423. (defun org-fixup-indentation (diff)
  7424. "Change the indentation in the current entry by DIFF.
  7425. DIFF is an integer. Indentation is done according to the
  7426. following rules:
  7427. - Planning information and property drawers are always indented
  7428. according to the new level of the headline;
  7429. - Footnote definitions and their contents are ignored;
  7430. - Inlinetasks' boundaries are not shifted;
  7431. - Empty lines are ignored;
  7432. - Other lines' indentation are shifted by DIFF columns, unless
  7433. it would introduce a structural change in the document, in
  7434. which case no shifting is done at all.
  7435. Assume point is at a heading or an inlinetask beginning."
  7436. (org-with-wide-buffer
  7437. (narrow-to-region (line-beginning-position)
  7438. (save-excursion
  7439. (if (org-with-limited-levels (org-at-heading-p))
  7440. (org-with-limited-levels (outline-next-heading))
  7441. (org-inlinetask-goto-end))
  7442. (point)))
  7443. (forward-line)
  7444. ;; Indent properly planning info and property drawer.
  7445. (when (looking-at-p org-planning-line-re)
  7446. (org-indent-line)
  7447. (forward-line))
  7448. (when (looking-at org-property-drawer-re)
  7449. (goto-char (match-end 0))
  7450. (forward-line)
  7451. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7452. (catch 'no-shift
  7453. (when (zerop diff) (throw 'no-shift nil))
  7454. ;; If DIFF is negative, first check if a shift is possible at all
  7455. ;; (e.g., it doesn't break structure). This can only happen if
  7456. ;; some contents are not properly indented.
  7457. (let ((case-fold-search t))
  7458. (when (< diff 0)
  7459. (let ((diff (- diff))
  7460. (forbidden-re (concat org-outline-regexp
  7461. "\\|"
  7462. (substring org-footnote-definition-re 1))))
  7463. (save-excursion
  7464. (while (not (eobp))
  7465. (cond
  7466. ((looking-at-p "[ \t]*$") (forward-line))
  7467. ((and (looking-at-p org-footnote-definition-re)
  7468. (let ((e (org-element-at-point)))
  7469. (and (eq (org-element-type e) 'footnote-definition)
  7470. (goto-char (org-element-property :end e))))))
  7471. ((looking-at-p org-outline-regexp) (forward-line))
  7472. ;; Give up if shifting would move before column 0 or
  7473. ;; if it would introduce a headline or a footnote
  7474. ;; definition.
  7475. (t
  7476. (skip-chars-forward " \t")
  7477. (let ((ind (current-column)))
  7478. (when (or (< ind diff)
  7479. (and (= ind diff) (looking-at-p forbidden-re)))
  7480. (throw 'no-shift nil)))
  7481. ;; Ignore contents of example blocks and source
  7482. ;; blocks if their indentation is meant to be
  7483. ;; preserved. Jump to block's closing line.
  7484. (beginning-of-line)
  7485. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7486. (let ((e (org-element-at-point)))
  7487. (and (memq (org-element-type e)
  7488. '(example-block src-block))
  7489. (or org-src-preserve-indentation
  7490. (org-element-property :preserve-indent e))
  7491. (goto-char (org-element-property :end e))
  7492. (progn (skip-chars-backward " \r\t\n")
  7493. (beginning-of-line)
  7494. t))))
  7495. (forward-line))))))))
  7496. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7497. ;; by DIFF. Also skip contents of source or example blocks
  7498. ;; when indentation is meant to be preserved.
  7499. (while (not (eobp))
  7500. (cond
  7501. ((and (looking-at-p org-footnote-definition-re)
  7502. (let ((e (org-element-at-point)))
  7503. (and (eq (org-element-type e) 'footnote-definition)
  7504. (goto-char (org-element-property :end e))))))
  7505. ((looking-at-p org-outline-regexp) (forward-line))
  7506. ((looking-at-p "[ \t]*$") (forward-line))
  7507. (t
  7508. (indent-line-to (+ (org-get-indentation) diff))
  7509. (beginning-of-line)
  7510. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7511. (let ((e (org-element-at-point)))
  7512. (and (memq (org-element-type e)
  7513. '(example-block src-block))
  7514. (or org-src-preserve-indentation
  7515. (org-element-property :preserve-indent e))
  7516. (goto-char (org-element-property :end e))
  7517. (progn (skip-chars-backward " \r\t\n")
  7518. (beginning-of-line)
  7519. t))))
  7520. (forward-line)))))))))
  7521. (defun org-convert-to-odd-levels ()
  7522. "Convert an Org file with all levels allowed to one with odd levels.
  7523. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7524. level 5 etc."
  7525. (interactive)
  7526. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7527. (let ((outline-level 'org-outline-level)
  7528. (org-odd-levels-only nil) n)
  7529. (save-excursion
  7530. (goto-char (point-min))
  7531. (while (re-search-forward "^\\*\\*+ " nil t)
  7532. (setq n (- (length (match-string 0)) 2))
  7533. (while (>= (setq n (1- n)) 0)
  7534. (org-demote))
  7535. (end-of-line 1))))))
  7536. (defun org-convert-to-oddeven-levels ()
  7537. "Convert an Org file with only odd levels to one with odd/even levels.
  7538. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7539. file contains a section with an even level, conversion would
  7540. destroy the structure of the file. An error is signaled in this
  7541. case."
  7542. (interactive)
  7543. (goto-char (point-min))
  7544. ;; First check if there are no even levels
  7545. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7546. (org-show-set-visibility 'canonical)
  7547. (error "Not all levels are odd in this file. Conversion not possible"))
  7548. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7549. (let ((outline-regexp org-outline-regexp)
  7550. (outline-level 'org-outline-level)
  7551. (org-odd-levels-only nil) n)
  7552. (save-excursion
  7553. (goto-char (point-min))
  7554. (while (re-search-forward "^\\*\\*+ " nil t)
  7555. (setq n (/ (1- (length (match-string 0))) 2))
  7556. (while (>= (setq n (1- n)) 0)
  7557. (org-promote))
  7558. (end-of-line 1))))))
  7559. (defun org-tr-level (n)
  7560. "Make N odd if required."
  7561. (if org-odd-levels-only (1+ (/ n 2)) n))
  7562. ;;; Vertical tree motion, cutting and pasting of subtrees
  7563. (defun org-move-subtree-up (&optional arg)
  7564. "Move the current subtree up past ARG headlines of the same level."
  7565. (interactive "p")
  7566. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7567. (defun org-move-subtree-down (&optional arg)
  7568. "Move the current subtree down past ARG headlines of the same level."
  7569. (interactive "p")
  7570. (setq arg (prefix-numeric-value arg))
  7571. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7572. 'org-get-last-sibling))
  7573. (ins-point (make-marker))
  7574. (cnt (abs arg))
  7575. (col (current-column))
  7576. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7577. ;; Select the tree
  7578. (org-back-to-heading)
  7579. (setq beg0 (point))
  7580. (save-excursion
  7581. (setq ne-beg (org-back-over-empty-lines))
  7582. (setq beg (point)))
  7583. (save-match-data
  7584. (save-excursion (outline-end-of-heading)
  7585. (setq folded (org-invisible-p)))
  7586. (progn (org-end-of-subtree nil t)
  7587. (unless (eobp) (backward-char))))
  7588. (outline-next-heading)
  7589. (setq ne-end (org-back-over-empty-lines))
  7590. (setq end (point))
  7591. (goto-char beg0)
  7592. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7593. ;; include less whitespace
  7594. (save-excursion
  7595. (goto-char beg)
  7596. (forward-line (- ne-beg ne-end))
  7597. (setq beg (point))))
  7598. ;; Find insertion point, with error handling
  7599. (while (> cnt 0)
  7600. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7601. (progn (goto-char beg0)
  7602. (user-error "Cannot move past superior level or buffer limit")))
  7603. (setq cnt (1- cnt)))
  7604. (when (> arg 0)
  7605. ;; Moving forward - still need to move over subtree
  7606. (org-end-of-subtree t t)
  7607. (save-excursion
  7608. (org-back-over-empty-lines)
  7609. (or (bolp) (newline))))
  7610. (setq ne-ins (org-back-over-empty-lines))
  7611. (move-marker ins-point (point))
  7612. (setq txt (buffer-substring beg end))
  7613. (org-save-markers-in-region beg end)
  7614. (delete-region beg end)
  7615. (org-remove-empty-overlays-at beg)
  7616. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7617. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7618. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7619. (let ((bbb (point)))
  7620. (insert-before-markers txt)
  7621. (org-reinstall-markers-in-region bbb)
  7622. (move-marker ins-point bbb))
  7623. (or (bolp) (insert "\n"))
  7624. (setq ins-end (point))
  7625. (goto-char ins-point)
  7626. (org-skip-whitespace)
  7627. (when (and (< arg 0)
  7628. (org-first-sibling-p)
  7629. (> ne-ins ne-beg))
  7630. ;; Move whitespace back to beginning
  7631. (save-excursion
  7632. (goto-char ins-end)
  7633. (let ((kill-whole-line t))
  7634. (kill-line (- ne-ins ne-beg)) (point)))
  7635. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7636. (move-marker ins-point nil)
  7637. (if folded
  7638. (outline-hide-subtree)
  7639. (org-show-entry)
  7640. (org-show-children)
  7641. (org-cycle-hide-drawers 'children))
  7642. (org-clean-visibility-after-subtree-move)
  7643. ;; move back to the initial column we were at
  7644. (move-to-column col)))
  7645. (defvar org-subtree-clip ""
  7646. "Clipboard for cut and paste of subtrees.
  7647. This is actually only a copy of the kill, because we use the normal kill
  7648. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7649. (defvar org-subtree-clip-folded nil
  7650. "Was the last copied subtree folded?
  7651. This is used to fold the tree back after pasting.")
  7652. (defun org-cut-subtree (&optional n)
  7653. "Cut the current subtree into the clipboard.
  7654. With prefix arg N, cut this many sequential subtrees.
  7655. This is a short-hand for marking the subtree and then cutting it."
  7656. (interactive "p")
  7657. (org-copy-subtree n 'cut))
  7658. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7659. "Copy the current subtree it in the clipboard.
  7660. With prefix arg N, copy this many sequential subtrees.
  7661. This is a short-hand for marking the subtree and then copying it.
  7662. If CUT is non-nil, actually cut the subtree.
  7663. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7664. of some markers in the region, even if CUT is non-nil. This is
  7665. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7666. (interactive "p")
  7667. (let (beg end folded (beg0 (point)))
  7668. (if (called-interactively-p 'any)
  7669. (org-back-to-heading nil) ; take what looks like a subtree
  7670. (org-back-to-heading t)) ; take what is really there
  7671. (setq beg (point))
  7672. (skip-chars-forward " \t\r\n")
  7673. (save-match-data
  7674. (if nosubtrees
  7675. (outline-next-heading)
  7676. (save-excursion (outline-end-of-heading)
  7677. (setq folded (org-invisible-p)))
  7678. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7679. (org-end-of-subtree t t)))
  7680. ;; Include the end of an inlinetask
  7681. (when (and (featurep 'org-inlinetask)
  7682. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7683. "END[ \t]*$")))
  7684. (end-of-line))
  7685. (setq end (point))
  7686. (goto-char beg0)
  7687. (when (> end beg)
  7688. (setq org-subtree-clip-folded folded)
  7689. (when (or cut force-store-markers)
  7690. (org-save-markers-in-region beg end))
  7691. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7692. (setq org-subtree-clip (current-kill 0))
  7693. (message "%s: Subtree(s) with %d characters"
  7694. (if cut "Cut" "Copied")
  7695. (length org-subtree-clip)))))
  7696. (defun org-paste-subtree (&optional level tree for-yank remove)
  7697. "Paste the clipboard as a subtree, with modification of headline level.
  7698. The entire subtree is promoted or demoted in order to match a new headline
  7699. level.
  7700. If the cursor is at the beginning of a headline, the same level as
  7701. that headline is used to paste the tree.
  7702. If not, the new level is derived from the *visible* headings
  7703. before and after the insertion point, and taken to be the inferior headline
  7704. level of the two. So if the previous visible heading is level 3 and the
  7705. next is level 4 (or vice versa), level 4 will be used for insertion.
  7706. This makes sure that the subtree remains an independent subtree and does
  7707. not swallow low level entries.
  7708. You can also force a different level, either by using a numeric prefix
  7709. argument, or by inserting the heading marker by hand. For example, if the
  7710. cursor is after \"*****\", then the tree will be shifted to level 5.
  7711. If optional TREE is given, use this text instead of the kill ring.
  7712. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7713. move back over whitespace before inserting, and move point to the end of
  7714. the inserted text when done.
  7715. When REMOVE is non-nil, remove the subtree from the clipboard."
  7716. (interactive "P")
  7717. (setq tree (or tree (and kill-ring (current-kill 0))))
  7718. (unless (org-kill-is-subtree-p tree)
  7719. (user-error "%s"
  7720. (substitute-command-keys
  7721. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7722. (org-with-limited-levels
  7723. (let* ((visp (not (org-invisible-p)))
  7724. (txt tree)
  7725. (^re_ "\\(\\*+\\)[ \t]*")
  7726. (old-level (if (string-match org-outline-regexp-bol txt)
  7727. (- (match-end 0) (match-beginning 0) 1)
  7728. -1))
  7729. (force-level (cond (level (prefix-numeric-value level))
  7730. ((and (looking-at "[ \t]*$")
  7731. (string-match
  7732. "^\\*+$" (buffer-substring
  7733. (point-at-bol) (point))))
  7734. (- (match-end 0) (match-beginning 0)))
  7735. ((and (bolp)
  7736. (looking-at org-outline-regexp))
  7737. (- (match-end 0) (point) 1))))
  7738. (previous-level (save-excursion
  7739. (condition-case nil
  7740. (progn
  7741. (outline-previous-visible-heading 1)
  7742. (if (looking-at ^re_)
  7743. (- (match-end 0) (match-beginning 0) 1)
  7744. 1))
  7745. (error 1))))
  7746. (next-level (save-excursion
  7747. (condition-case nil
  7748. (progn
  7749. (or (looking-at org-outline-regexp)
  7750. (outline-next-visible-heading 1))
  7751. (if (looking-at ^re_)
  7752. (- (match-end 0) (match-beginning 0) 1)
  7753. 1))
  7754. (error 1))))
  7755. (new-level (or force-level (max previous-level next-level)))
  7756. (shift (if (or (= old-level -1)
  7757. (= new-level -1)
  7758. (= old-level new-level))
  7759. 0
  7760. (- new-level old-level)))
  7761. (delta (if (> shift 0) -1 1))
  7762. (func (if (> shift 0) 'org-demote 'org-promote))
  7763. (org-odd-levels-only nil)
  7764. beg end newend)
  7765. ;; Remove the forced level indicator
  7766. (when force-level
  7767. (delete-region (point-at-bol) (point)))
  7768. ;; Paste
  7769. (beginning-of-line (if (bolp) 1 2))
  7770. (setq beg (point))
  7771. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7772. (insert-before-markers txt)
  7773. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7774. (setq newend (point))
  7775. (org-reinstall-markers-in-region beg)
  7776. (setq end (point))
  7777. (goto-char beg)
  7778. (skip-chars-forward " \t\n\r")
  7779. (setq beg (point))
  7780. (when (and (org-invisible-p) visp)
  7781. (save-excursion (outline-show-heading)))
  7782. ;; Shift if necessary
  7783. (unless (= shift 0)
  7784. (save-restriction
  7785. (narrow-to-region beg end)
  7786. (while (not (= shift 0))
  7787. (org-map-region func (point-min) (point-max))
  7788. (setq shift (+ delta shift)))
  7789. (goto-char (point-min))
  7790. (setq newend (point-max))))
  7791. (when (or (called-interactively-p 'interactive) for-yank)
  7792. (message "Clipboard pasted as level %d subtree" new-level))
  7793. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7794. kill-ring
  7795. (eq org-subtree-clip (current-kill 0))
  7796. org-subtree-clip-folded)
  7797. ;; The tree was folded before it was killed/copied
  7798. (outline-hide-subtree))
  7799. (and for-yank (goto-char newend))
  7800. (and remove (setq kill-ring (cdr kill-ring))))))
  7801. (defun org-kill-is-subtree-p (&optional txt)
  7802. "Check if the current kill is an outline subtree, or a set of trees.
  7803. Returns nil if kill does not start with a headline, or if the first
  7804. headline level is not the largest headline level in the tree.
  7805. So this will actually accept several entries of equal levels as well,
  7806. which is OK for `org-paste-subtree'.
  7807. If optional TXT is given, check this string instead of the current kill."
  7808. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7809. (re (org-get-limited-outline-regexp))
  7810. (^re (concat "^" re))
  7811. (start-level (and kill
  7812. (string-match
  7813. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7814. kill)
  7815. (- (match-end 2) (match-beginning 2) 1)))
  7816. (start (1+ (or (match-beginning 2) -1))))
  7817. (if (not start-level)
  7818. (progn
  7819. nil) ;; does not even start with a heading
  7820. (catch 'exit
  7821. (while (setq start (string-match ^re kill (1+ start)))
  7822. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7823. (throw 'exit nil)))
  7824. t))))
  7825. (defvar org-markers-to-move nil
  7826. "Markers that should be moved with a cut-and-paste operation.
  7827. Those markers are stored together with their positions relative to
  7828. the start of the region.")
  7829. (defun org-save-markers-in-region (beg end)
  7830. "Check markers in region.
  7831. If these markers are between BEG and END, record their position relative
  7832. to BEG, so that after moving the block of text, we can put the markers back
  7833. into place.
  7834. This function gets called just before an entry or tree gets cut from the
  7835. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7836. called immediately, to move the markers with the entries."
  7837. (setq org-markers-to-move nil)
  7838. (when (featurep 'org-clock)
  7839. (org-clock-save-markers-for-cut-and-paste beg end))
  7840. (when (featurep 'org-agenda)
  7841. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7842. (defun org-check-and-save-marker (marker beg end)
  7843. "Check if MARKER is between BEG and END.
  7844. If yes, remember the marker and the distance to BEG."
  7845. (when (and (marker-buffer marker)
  7846. (equal (marker-buffer marker) (current-buffer))
  7847. (>= marker beg) (< marker end))
  7848. (push (cons marker (- marker beg)) org-markers-to-move)))
  7849. (defun org-reinstall-markers-in-region (beg)
  7850. "Move all remembered markers to their position relative to BEG."
  7851. (dolist (x org-markers-to-move)
  7852. (move-marker (car x) (+ beg (cdr x))))
  7853. (setq org-markers-to-move nil))
  7854. (defun org-narrow-to-subtree ()
  7855. "Narrow buffer to the current subtree."
  7856. (interactive)
  7857. (save-excursion
  7858. (save-match-data
  7859. (org-with-limited-levels
  7860. (narrow-to-region
  7861. (progn (org-back-to-heading t) (point))
  7862. (progn (org-end-of-subtree t t)
  7863. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7864. (point)))))))
  7865. (defun org-narrow-to-block ()
  7866. "Narrow buffer to the current block."
  7867. (interactive)
  7868. (let* ((case-fold-search t)
  7869. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7870. "^[ \t]*#\\+end_.*")))
  7871. (if blockp
  7872. (narrow-to-region (car blockp) (cdr blockp))
  7873. (user-error "Not in a block"))))
  7874. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7875. "Clone the task (subtree) at point N times.
  7876. The clones will be inserted as siblings.
  7877. In interactive use, the user will be prompted for the number of
  7878. clones to be produced. If the entry has a timestamp, the user
  7879. will also be prompted for a time shift, which may be a repeater
  7880. as used in time stamps, for example `+3d'. To disable this,
  7881. you can call the function with a universal prefix argument.
  7882. When a valid repeater is given and the entry contains any time
  7883. stamps, the clones will become a sequence in time, with time
  7884. stamps in the subtree shifted for each clone produced. If SHIFT
  7885. is nil or the empty string, time stamps will be left alone. The
  7886. ID property of the original subtree is removed.
  7887. In each clone, all the CLOCK entries will be removed. This
  7888. prevents Org from considering that the clocked times overlap.
  7889. If the original subtree did contain time stamps with a repeater,
  7890. the following will happen:
  7891. - the repeater will be removed in each clone
  7892. - an additional clone will be produced, with the current, unshifted
  7893. date(s) in the entry.
  7894. - the original entry will be placed *after* all the clones, with
  7895. repeater intact.
  7896. - the start days in the repeater in the original entry will be shifted
  7897. to past the last clone.
  7898. In this way you can spell out a number of instances of a repeating task,
  7899. and still retain the repeater to cover future instances of the task.
  7900. As described above, N+1 clones are produced when the original
  7901. subtree has a repeater. Setting N to 0, then, can be used to
  7902. remove the repeater from a subtree and create a shifted clone
  7903. with the original repeater."
  7904. (interactive "nNumber of clones to produce: ")
  7905. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7906. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7907. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7908. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7909. (shift
  7910. (or shift
  7911. (if (and (not (equal current-prefix-arg '(4)))
  7912. (save-excursion
  7913. (goto-char beg)
  7914. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7915. (read-from-minibuffer
  7916. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7917. ""))) ;No time shift
  7918. (doshift
  7919. (and (org-string-nw-p shift)
  7920. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7921. shift)
  7922. (user-error "Invalid shift specification %s" shift)))))
  7923. (goto-char end-of-tree)
  7924. (unless (bolp) (insert "\n"))
  7925. (let* ((end (point))
  7926. (template (buffer-substring beg end))
  7927. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7928. (shift-what (pcase (and doshift (match-string 2 shift))
  7929. (`nil nil)
  7930. ("d" 'day)
  7931. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7932. ("m" 'month)
  7933. ("y" 'year)
  7934. (_ (error "Unsupported time unit"))))
  7935. (nmin 1)
  7936. (nmax n)
  7937. (n-no-remove -1)
  7938. (idprop (org-entry-get nil "ID")))
  7939. (when (and doshift
  7940. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7941. template))
  7942. (delete-region beg end)
  7943. (setq end beg)
  7944. (setq nmin 0)
  7945. (setq nmax (1+ nmax))
  7946. (setq n-no-remove nmax))
  7947. (goto-char end)
  7948. (cl-loop for n from nmin to nmax do
  7949. (insert
  7950. ;; Prepare clone.
  7951. (with-temp-buffer
  7952. (insert template)
  7953. (org-mode)
  7954. (goto-char (point-min))
  7955. (org-show-subtree)
  7956. (and idprop (if org-clone-delete-id
  7957. (org-entry-delete nil "ID")
  7958. (org-id-get-create t)))
  7959. (unless (= n 0)
  7960. (while (re-search-forward org-clock-line-re nil t)
  7961. (delete-region (line-beginning-position)
  7962. (line-beginning-position 2)))
  7963. (goto-char (point-min))
  7964. (while (re-search-forward org-drawer-regexp nil t)
  7965. (org-remove-empty-drawer-at (point))))
  7966. (goto-char (point-min))
  7967. (when doshift
  7968. (while (re-search-forward org-ts-regexp-both nil t)
  7969. (org-timestamp-change (* n shift-n) shift-what))
  7970. (unless (= n n-no-remove)
  7971. (goto-char (point-min))
  7972. (while (re-search-forward org-ts-regexp nil t)
  7973. (save-excursion
  7974. (goto-char (match-beginning 0))
  7975. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7976. (delete-region (match-beginning 1) (match-end 1)))))))
  7977. (buffer-string)))))
  7978. (goto-char beg)))
  7979. ;;; Outline Sorting
  7980. (defun org-sort (with-case)
  7981. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7982. Optional argument WITH-CASE means sort case-sensitively."
  7983. (interactive "P")
  7984. (cond
  7985. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7986. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7987. (t
  7988. (org-call-with-arg 'org-sort-entries with-case))))
  7989. (defun org-sort-remove-invisible (s)
  7990. "Remove invisible links from string S."
  7991. (remove-text-properties 0 (length s) org-rm-props s)
  7992. (while (string-match org-bracket-link-regexp s)
  7993. (setq s (replace-match (if (match-end 2)
  7994. (match-string 3 s)
  7995. (match-string 1 s))
  7996. t t s)))
  7997. (let ((st (format " %s " s)))
  7998. (while (string-match org-emph-re st)
  7999. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8000. (setq s (substring st 1 -1)))
  8001. s)
  8002. (defvar org-priority-regexp) ; defined later in the file
  8003. (defvar org-after-sorting-entries-or-items-hook nil
  8004. "Hook that is run after a bunch of entries or items have been sorted.
  8005. When children are sorted, the cursor is in the parent line when this
  8006. hook gets called. When a region or a plain list is sorted, the cursor
  8007. will be in the first entry of the sorted region/list.")
  8008. (defun org-sort-entries
  8009. (&optional with-case sorting-type getkey-func compare-func property
  8010. interactive?)
  8011. "Sort entries on a certain level of an outline tree.
  8012. If there is an active region, the entries in the region are sorted.
  8013. Else, if the cursor is before the first entry, sort the top-level items.
  8014. Else, the children of the entry at point are sorted.
  8015. Sorting can be alphabetically, numerically, by date/time as given by
  8016. a time stamp, by a property, by priority order, or by a custom function.
  8017. The command prompts for the sorting type unless it has been given to the
  8018. function through the SORTING-TYPE argument, which needs to be a character,
  8019. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8020. the precise meaning of each character:
  8021. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8022. c By creation time, which is assumed to be the first inactive time stamp
  8023. at the beginning of a line.
  8024. d By deadline date/time.
  8025. k By clocking time.
  8026. n Numerically, by converting the beginning of the entry/item to a number.
  8027. o By order of TODO keywords.
  8028. p By priority according to the cookie.
  8029. r By the value of a property.
  8030. s By scheduled date/time.
  8031. t By date/time, either the first active time stamp in the entry, or, if
  8032. none exist, by the first inactive one.
  8033. Capital letters will reverse the sort order.
  8034. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8035. called with point at the beginning of the record. It must return a
  8036. value that is compatible with COMPARE-FUNC, the function used to
  8037. compare entries.
  8038. Comparing entries ignores case by default. However, with an optional argument
  8039. WITH-CASE, the sorting considers case as well.
  8040. Sorting is done against the visible part of the headlines, it ignores hidden
  8041. links.
  8042. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  8043. A non-nil value for INTERACTIVE? is used to signal that this
  8044. function is being called interactively."
  8045. (interactive (list current-prefix-arg nil nil nil nil t))
  8046. (let ((case-func (if with-case 'identity 'downcase))
  8047. (cmstr
  8048. ;; The clock marker is lost when using `sort-subr', let's
  8049. ;; store the clocking string.
  8050. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8051. (save-excursion
  8052. (goto-char org-clock-marker)
  8053. (buffer-substring-no-properties (line-beginning-position)
  8054. (point)))))
  8055. start beg end stars re re2
  8056. txt what tmp)
  8057. ;; Find beginning and end of region to sort
  8058. (cond
  8059. ((org-region-active-p)
  8060. ;; we will sort the region
  8061. (setq end (region-end)
  8062. what "region")
  8063. (goto-char (region-beginning))
  8064. (unless (org-at-heading-p) (outline-next-heading))
  8065. (setq start (point)))
  8066. ((or (org-at-heading-p)
  8067. (ignore-errors (progn (org-back-to-heading) t)))
  8068. ;; we will sort the children of the current headline
  8069. (org-back-to-heading)
  8070. (setq start (point)
  8071. end (progn (org-end-of-subtree t t)
  8072. (or (bolp) (insert "\n"))
  8073. (when (>= (org-back-over-empty-lines) 1)
  8074. (forward-line 1))
  8075. (point))
  8076. what "children")
  8077. (goto-char start)
  8078. (outline-show-subtree)
  8079. (outline-next-heading))
  8080. (t
  8081. ;; we will sort the top-level entries in this file
  8082. (goto-char (point-min))
  8083. (or (org-at-heading-p) (outline-next-heading))
  8084. (setq start (point))
  8085. (goto-char (point-max))
  8086. (beginning-of-line 1)
  8087. (when (looking-at ".*?\\S-")
  8088. ;; File ends in a non-white line
  8089. (end-of-line 1)
  8090. (insert "\n"))
  8091. (setq end (point-max))
  8092. (setq what "top-level")
  8093. (goto-char start)
  8094. (outline-show-all)))
  8095. (setq beg (point))
  8096. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8097. (looking-at "\\(\\*+\\)")
  8098. (setq stars (match-string 1)
  8099. re (concat "^" (regexp-quote stars) " +")
  8100. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8101. txt (buffer-substring beg end))
  8102. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8103. (when (and (not (equal stars "*")) (string-match re2 txt))
  8104. (user-error "Region to sort contains a level above the first entry"))
  8105. (unless sorting-type
  8106. (message
  8107. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8108. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8109. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8110. what)
  8111. (setq sorting-type (read-char-exclusive)))
  8112. (unless getkey-func
  8113. (and (= (downcase sorting-type) ?f)
  8114. (setq getkey-func
  8115. (or (and interactive?
  8116. (org-read-function
  8117. "Function for extracting keys: "))
  8118. (error "Missing key extractor")))))
  8119. (and (= (downcase sorting-type) ?r)
  8120. (not property)
  8121. (setq property
  8122. (completing-read "Property: "
  8123. (mapcar #'list (org-buffer-property-keys t))
  8124. nil t)))
  8125. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8126. (message "Sorting entries...")
  8127. (save-restriction
  8128. (narrow-to-region start end)
  8129. (let ((dcst (downcase sorting-type))
  8130. (case-fold-search nil)
  8131. (now (current-time)))
  8132. (sort-subr
  8133. (/= dcst sorting-type)
  8134. ;; This function moves to the beginning character of the "record" to
  8135. ;; be sorted.
  8136. (lambda nil
  8137. (if (re-search-forward re nil t)
  8138. (goto-char (match-beginning 0))
  8139. (goto-char (point-max))))
  8140. ;; This function moves to the last character of the "record" being
  8141. ;; sorted.
  8142. (lambda nil
  8143. (save-match-data
  8144. (condition-case nil
  8145. (outline-forward-same-level 1)
  8146. (error
  8147. (goto-char (point-max))))))
  8148. ;; This function returns the value that gets sorted against.
  8149. (lambda nil
  8150. (cond
  8151. ((= dcst ?n)
  8152. (if (looking-at org-complex-heading-regexp)
  8153. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8154. nil))
  8155. ((= dcst ?a)
  8156. (if (looking-at org-complex-heading-regexp)
  8157. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8158. nil))
  8159. ((= dcst ?k)
  8160. (or (get-text-property (point) :org-clock-minutes) 0))
  8161. ((= dcst ?t)
  8162. (let ((end (save-excursion (outline-next-heading) (point))))
  8163. (if (or (re-search-forward org-ts-regexp end t)
  8164. (re-search-forward org-ts-regexp-both end t))
  8165. (org-time-string-to-seconds (match-string 0))
  8166. (float-time now))))
  8167. ((= dcst ?c)
  8168. (let ((end (save-excursion (outline-next-heading) (point))))
  8169. (if (re-search-forward
  8170. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8171. end t)
  8172. (org-time-string-to-seconds (match-string 0))
  8173. (float-time now))))
  8174. ((= dcst ?s)
  8175. (let ((end (save-excursion (outline-next-heading) (point))))
  8176. (if (re-search-forward org-scheduled-time-regexp end t)
  8177. (org-time-string-to-seconds (match-string 1))
  8178. (float-time now))))
  8179. ((= dcst ?d)
  8180. (let ((end (save-excursion (outline-next-heading) (point))))
  8181. (if (re-search-forward org-deadline-time-regexp end t)
  8182. (org-time-string-to-seconds (match-string 1))
  8183. (float-time now))))
  8184. ((= dcst ?p)
  8185. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8186. (string-to-char (match-string 2))
  8187. org-default-priority))
  8188. ((= dcst ?r)
  8189. (or (org-entry-get nil property) ""))
  8190. ((= dcst ?o)
  8191. (when (looking-at org-complex-heading-regexp)
  8192. (let* ((m (match-string 2))
  8193. (s (if (member m org-done-keywords) '- '+)))
  8194. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8195. ((= dcst ?f)
  8196. (if getkey-func
  8197. (progn
  8198. (setq tmp (funcall getkey-func))
  8199. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8200. tmp)
  8201. (error "Invalid key function `%s'" getkey-func)))
  8202. (t (error "Invalid sorting type `%c'" sorting-type))))
  8203. nil
  8204. (cond
  8205. ((= dcst ?a) 'string<)
  8206. ((= dcst ?f)
  8207. (or compare-func
  8208. (and interactive?
  8209. (org-read-function
  8210. (concat "Function for comparing keys "
  8211. "(empty for default `sort-subr' predicate): ")
  8212. 'allow-empty))))
  8213. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8214. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8215. ;; Reset the clock marker if needed
  8216. (when cmstr
  8217. (save-excursion
  8218. (goto-char start)
  8219. (search-forward cmstr nil t)
  8220. (move-marker org-clock-marker (point))))
  8221. (message "Sorting entries...done")))
  8222. ;;; The orgstruct minor mode
  8223. ;; Define a minor mode which can be used in other modes in order to
  8224. ;; integrate the Org mode structure editing commands.
  8225. ;; This is really a hack, because the Org mode structure commands use
  8226. ;; keys which normally belong to the major mode. Here is how it
  8227. ;; works: The minor mode defines all the keys necessary to operate the
  8228. ;; structure commands, but wraps the commands into a function which
  8229. ;; tests if the cursor is currently at a headline or a plain list
  8230. ;; item. If that is the case, the structure command is used,
  8231. ;; temporarily setting many Org mode variables like regular
  8232. ;; expressions for filling etc. However, when any of those keys is
  8233. ;; used at a different location, function uses `key-binding' to look
  8234. ;; up if the key has an associated command in another currently active
  8235. ;; keymap (minor modes, major mode, global), and executes that
  8236. ;; command. There might be problems if any of the keys is otherwise
  8237. ;; used as a prefix key.
  8238. (defcustom orgstruct-heading-prefix-regexp ""
  8239. "Regexp that matches the custom prefix of Org headlines in
  8240. orgstruct(++)-mode."
  8241. :group 'org
  8242. :version "24.4"
  8243. :package-version '(Org . "8.3")
  8244. :type 'regexp)
  8245. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8246. (defcustom orgstruct-setup-hook nil
  8247. "Hook run after orgstruct-mode-map is filled."
  8248. :group 'org
  8249. :version "24.4"
  8250. :package-version '(Org . "8.0")
  8251. :type 'hook)
  8252. (defvar orgstruct-initialized nil)
  8253. (defvar org-local-vars nil
  8254. "List of local variables, for use by `orgstruct-mode'.")
  8255. ;;;###autoload
  8256. (define-minor-mode orgstruct-mode
  8257. "Toggle the minor mode `orgstruct-mode'.
  8258. This mode is for using Org mode structure commands in other
  8259. modes. The following keys behave as if Org mode were active, if
  8260. the cursor is on a headline, or on a plain list item (both as
  8261. defined by Org mode)."
  8262. nil " OrgStruct" (make-sparse-keymap)
  8263. (funcall (if orgstruct-mode
  8264. 'add-to-invisibility-spec
  8265. 'remove-from-invisibility-spec)
  8266. '(outline . t))
  8267. (when orgstruct-mode
  8268. (org-load-modules-maybe)
  8269. (unless orgstruct-initialized
  8270. (orgstruct-setup)
  8271. (setq orgstruct-initialized t))))
  8272. ;;;###autoload
  8273. (defun turn-on-orgstruct ()
  8274. "Unconditionally turn on `orgstruct-mode'."
  8275. (orgstruct-mode 1))
  8276. (defvar-local orgstruct-is-++ nil
  8277. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8278. (defvar-local org-fb-vars nil)
  8279. (defun orgstruct++-mode (&optional arg)
  8280. "Toggle `orgstruct-mode', the enhanced version of it.
  8281. In addition to setting orgstruct-mode, this also exports all
  8282. indentation and autofilling variables from Org mode into the
  8283. buffer. It will also recognize item context in multiline items."
  8284. (interactive "P")
  8285. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8286. (if (< arg 1)
  8287. (progn (orgstruct-mode -1)
  8288. (dolist (v org-fb-vars)
  8289. (set (make-local-variable (car v))
  8290. (if (eq (car-safe (cadr v)) 'quote)
  8291. (cl-cadadr v)
  8292. (nth 1 v)))))
  8293. (orgstruct-mode 1)
  8294. (setq org-fb-vars nil)
  8295. (unless org-local-vars
  8296. (setq org-local-vars (org-get-local-variables)))
  8297. (let (var val)
  8298. (dolist (x org-local-vars)
  8299. (when (string-match
  8300. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8301. \\|fill-prefix\\|indent-\\)"
  8302. (symbol-name (car x)))
  8303. (setq var (car x) val (nth 1 x))
  8304. (push (list var `(quote ,(eval var))) org-fb-vars)
  8305. (set (make-local-variable var)
  8306. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8307. (setq-local orgstruct-is-++ t))))
  8308. ;;;###autoload
  8309. (defun turn-on-orgstruct++ ()
  8310. "Unconditionally turn on `orgstruct++-mode'."
  8311. (orgstruct++-mode 1))
  8312. (defun orgstruct-error ()
  8313. "Error when there is no default binding for a structure key."
  8314. (interactive)
  8315. (funcall (if (fboundp 'user-error)
  8316. 'user-error
  8317. 'error)
  8318. "This key has no function outside structure elements"))
  8319. (defun orgstruct-setup ()
  8320. "Setup orgstruct keymap."
  8321. (dolist (cell '((org-demote . t)
  8322. (org-metaleft . t)
  8323. (org-metaright . t)
  8324. (org-promote . t)
  8325. (org-shiftmetaleft . t)
  8326. (org-shiftmetaright . t)
  8327. org-backward-element
  8328. org-backward-heading-same-level
  8329. org-ctrl-c-ret
  8330. org-ctrl-c-minus
  8331. org-ctrl-c-star
  8332. org-cycle
  8333. org-force-cycle-archived
  8334. org-forward-heading-same-level
  8335. org-insert-heading
  8336. org-insert-heading-respect-content
  8337. org-kill-note-or-show-branches
  8338. org-mark-subtree
  8339. org-meta-return
  8340. org-metadown
  8341. org-metaup
  8342. org-narrow-to-subtree
  8343. org-promote-subtree
  8344. org-reveal
  8345. org-shiftdown
  8346. org-shiftleft
  8347. org-shiftmetadown
  8348. org-shiftmetaup
  8349. org-shiftright
  8350. org-shifttab
  8351. org-shifttab
  8352. org-shiftup
  8353. org-show-children
  8354. org-show-subtree
  8355. org-sort
  8356. org-up-element
  8357. outline-demote
  8358. outline-next-visible-heading
  8359. outline-previous-visible-heading
  8360. outline-promote
  8361. outline-up-heading))
  8362. (let ((f (or (car-safe cell) cell))
  8363. (disable-when-heading-prefix (cdr-safe cell)))
  8364. (when (fboundp f)
  8365. (let ((new-bindings))
  8366. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8367. (where-is-internal f outline-mode-map)))
  8368. (push binding new-bindings)
  8369. ;; TODO use local-function-key-map
  8370. (dolist (rep '(("<tab>" . "TAB")
  8371. ("<return>" . "RET")
  8372. ("<escape>" . "ESC")
  8373. ("<delete>" . "DEL")))
  8374. (setq binding (read-kbd-macro
  8375. (let ((case-fold-search))
  8376. (replace-regexp-in-string
  8377. (regexp-quote (cdr rep))
  8378. (car rep)
  8379. (key-description binding)))))
  8380. (cl-pushnew binding new-bindings :test 'equal)))
  8381. (dolist (binding new-bindings)
  8382. (let ((key (lookup-key orgstruct-mode-map binding)))
  8383. (when (or (not key) (numberp key))
  8384. (ignore-errors
  8385. (org-defkey orgstruct-mode-map
  8386. binding
  8387. (orgstruct-make-binding
  8388. f binding disable-when-heading-prefix))))))))))
  8389. (run-hooks 'orgstruct-setup-hook))
  8390. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8391. "Create a function for binding in the structure minor mode.
  8392. FUN is the command to call inside a table. KEY is the key that
  8393. should be checked in for a command to execute outside of tables.
  8394. Non-nil `disable-when-heading-prefix' means to disable the command
  8395. if `orgstruct-heading-prefix-regexp' is not empty."
  8396. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8397. (let ((nname name)
  8398. (i 0))
  8399. (while (fboundp (intern nname))
  8400. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8401. (setq name (intern nname)))
  8402. (eval
  8403. (let ((bindings '((org-heading-regexp
  8404. (concat "^"
  8405. orgstruct-heading-prefix-regexp
  8406. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8407. (org-outline-regexp
  8408. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8409. (org-outline-regexp-bol
  8410. (concat "^" org-outline-regexp))
  8411. (outline-regexp org-outline-regexp)
  8412. (outline-heading-end-regexp "\n")
  8413. (outline-level 'org-outline-level)
  8414. (outline-heading-alist))))
  8415. `(defun ,name (arg)
  8416. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8417. "Outside of structure, run the binding of `"
  8418. (key-description key) "'."
  8419. (when disable-when-heading-prefix
  8420. (concat
  8421. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8422. "back to the default binding due to limitations of Org's implementation of\n"
  8423. "`" (symbol-name fun) "'.")))
  8424. (interactive "p")
  8425. (let* ((disable
  8426. ,(and disable-when-heading-prefix
  8427. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8428. (fallback
  8429. (or disable
  8430. (not
  8431. (let* ,bindings
  8432. (org-context-p 'headline 'item
  8433. ,(when (memq fun
  8434. '(org-insert-heading
  8435. org-insert-heading-respect-content
  8436. org-meta-return))
  8437. '(when orgstruct-is-++
  8438. 'item-body))))))))
  8439. (if fallback
  8440. (let* ((orgstruct-mode)
  8441. (binding
  8442. (let ((key ,key))
  8443. (catch 'exit
  8444. (dolist
  8445. (rep
  8446. '(nil
  8447. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8448. ("<\\([^>]*\\)return>" . "\\1RET")
  8449. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8450. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8451. nil)
  8452. (when rep
  8453. (setq key (read-kbd-macro
  8454. (let ((case-fold-search))
  8455. (replace-regexp-in-string
  8456. (car rep)
  8457. (cdr rep)
  8458. (key-description key))))))
  8459. (when (key-binding key)
  8460. (throw 'exit (key-binding key))))))))
  8461. (if (keymapp binding)
  8462. (org-set-transient-map binding)
  8463. (let ((func (or binding
  8464. (unless disable
  8465. 'orgstruct-error))))
  8466. (when func
  8467. (call-interactively func)))))
  8468. (org-run-like-in-org-mode
  8469. (lambda ()
  8470. (interactive)
  8471. (let* ,bindings
  8472. (call-interactively ',fun)))))))))
  8473. name))
  8474. (defun org-contextualize-keys (alist contexts)
  8475. "Return valid elements in ALIST depending on CONTEXTS.
  8476. `org-agenda-custom-commands' or `org-capture-templates' are the
  8477. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8478. or `org-capture-templates-contexts' are the associated contexts
  8479. definitions."
  8480. (let ((contexts
  8481. ;; normalize contexts
  8482. (mapcar
  8483. (lambda(c) (cond ((listp (cadr c))
  8484. (list (car c) (car c) (nth 1 c)))
  8485. ((string= "" (cadr c))
  8486. (list (car c) (car c) (nth 2 c)))
  8487. (t c)))
  8488. contexts))
  8489. (a alist) r s)
  8490. ;; loop over all commands or templates
  8491. (dolist (c a)
  8492. (let (vrules repl)
  8493. (cond
  8494. ((not (assoc (car c) contexts))
  8495. (push c r))
  8496. ((and (assoc (car c) contexts)
  8497. (setq vrules (org-contextualize-validate-key
  8498. (car c) contexts)))
  8499. (mapc (lambda (vr)
  8500. (unless (equal (car vr) (cadr vr))
  8501. (setq repl vr)))
  8502. vrules)
  8503. (if (not repl) (push c r)
  8504. (push (cadr repl) s)
  8505. (push
  8506. (cons (car c)
  8507. (cdr (or (assoc (cadr repl) alist)
  8508. (error "Undefined key `%s' as contextual replacement for `%s'"
  8509. (cadr repl) (car c)))))
  8510. r))))))
  8511. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8512. (delq
  8513. nil
  8514. (delete-dups
  8515. (mapcar (lambda (x)
  8516. (let ((tpl (car x)))
  8517. (unless (delq
  8518. nil
  8519. (mapcar (lambda (y)
  8520. (equal y tpl))
  8521. s))
  8522. x)))
  8523. (reverse r))))))
  8524. (defun org-contextualize-validate-key (key contexts)
  8525. "Check CONTEXTS for agenda or capture KEY."
  8526. (let (res)
  8527. (dolist (r contexts)
  8528. (dolist (rr (car (last r)))
  8529. (when
  8530. (and (equal key (car r))
  8531. (if (functionp rr) (funcall rr)
  8532. (or (and (eq (car rr) 'in-file)
  8533. (buffer-file-name)
  8534. (string-match (cdr rr) (buffer-file-name)))
  8535. (and (eq (car rr) 'in-mode)
  8536. (string-match (cdr rr) (symbol-name major-mode)))
  8537. (and (eq (car rr) 'in-buffer)
  8538. (string-match (cdr rr) (buffer-name)))
  8539. (when (and (eq (car rr) 'not-in-file)
  8540. (buffer-file-name))
  8541. (not (string-match (cdr rr) (buffer-file-name))))
  8542. (when (eq (car rr) 'not-in-mode)
  8543. (not (string-match (cdr rr) (symbol-name major-mode))))
  8544. (when (eq (car rr) 'not-in-buffer)
  8545. (not (string-match (cdr rr) (buffer-name)))))))
  8546. (push r res))))
  8547. (delete-dups (delq nil res))))
  8548. (defun org-context-p (&rest contexts)
  8549. "Check if local context is any of CONTEXTS.
  8550. Possible values in the list of contexts are `table', `headline', and `item'."
  8551. (let ((pos (point)))
  8552. (goto-char (point-at-bol))
  8553. (prog1 (or (and (memq 'table contexts)
  8554. (looking-at "[ \t]*|"))
  8555. (and (memq 'headline contexts)
  8556. (looking-at org-outline-regexp))
  8557. (and (memq 'item contexts)
  8558. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8559. (and (memq 'item-body contexts)
  8560. (org-in-item-p)))
  8561. (goto-char pos))))
  8562. (defconst org-unique-local-variables
  8563. '(org-element--cache
  8564. org-element--cache-objects
  8565. org-element--cache-sync-keys
  8566. org-element--cache-sync-requests
  8567. org-element--cache-sync-timer)
  8568. "List of local variables that cannot be transferred to another buffer.")
  8569. (defun org-get-local-variables ()
  8570. "Return a list of all local variables in an Org mode buffer."
  8571. (delq nil
  8572. (mapcar
  8573. (lambda (x)
  8574. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8575. (name (car binding)))
  8576. (and (not (get name 'org-state))
  8577. (not (memq name org-unique-local-variables))
  8578. (string-match-p
  8579. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8580. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8581. (symbol-name name))
  8582. binding)))
  8583. (with-temp-buffer
  8584. (org-mode)
  8585. (buffer-local-variables)))))
  8586. (defun org-clone-local-variables (from-buffer &optional regexp)
  8587. "Clone local variables from FROM-BUFFER.
  8588. Optional argument REGEXP selects variables to clone."
  8589. (dolist (pair (buffer-local-variables from-buffer))
  8590. (pcase pair
  8591. (`(,name . ,value) ;ignore unbound variables
  8592. (when (and (not (memq name org-unique-local-variables))
  8593. (or (null regexp) (string-match-p regexp (symbol-name name))))
  8594. (set (make-local-variable name) value))))))
  8595. ;;;###autoload
  8596. (defun org-run-like-in-org-mode (cmd)
  8597. "Run a command, pretending that the current buffer is in Org mode.
  8598. This will temporarily bind local variables that are typically bound in
  8599. Org mode to the values they have in Org mode, and then interactively
  8600. call CMD."
  8601. (org-load-modules-maybe)
  8602. (unless org-local-vars
  8603. (setq org-local-vars (org-get-local-variables)))
  8604. (let (binds)
  8605. (dolist (var org-local-vars)
  8606. (when (or (not (boundp (car var)))
  8607. (eq (symbol-value (car var))
  8608. (default-value (car var))))
  8609. (push (list (car var) `(quote ,(cadr var))) binds)))
  8610. (eval `(let ,binds
  8611. (call-interactively (quote ,cmd))))))
  8612. (defun org-get-category (&optional pos force-refresh)
  8613. "Get the category applying to position POS."
  8614. (save-match-data
  8615. (when force-refresh (org-refresh-category-properties))
  8616. (let ((pos (or pos (point))))
  8617. (or (get-text-property pos 'org-category)
  8618. (progn (org-refresh-category-properties)
  8619. (get-text-property pos 'org-category))))))
  8620. ;;; Refresh properties
  8621. (defun org-refresh-properties (dprop tprop)
  8622. "Refresh buffer text properties.
  8623. DPROP is the drawer property and TPROP is either the
  8624. corresponding text property to set, or an alist with each element
  8625. being a text property (as a symbol) and a function to apply to
  8626. the value of the drawer property."
  8627. (let* ((case-fold-search t)
  8628. (inhibit-read-only t)
  8629. (inherit? (org-property-inherit-p dprop))
  8630. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8631. (global (and inherit? (org--property-global-value dprop nil))))
  8632. (org-with-silent-modifications
  8633. (org-with-point-at 1
  8634. ;; Set global values (e.g., values defined through
  8635. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8636. (when global (put-text-property (point-min) (point-max) tprop global))
  8637. ;; Set local values.
  8638. (while (re-search-forward property-re nil t)
  8639. (when (org-at-property-p)
  8640. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8641. (outline-next-heading))))))
  8642. (defun org-refresh-property (tprop p &optional inherit)
  8643. "Refresh the buffer text property TPROP from the drawer property P.
  8644. The refresh happens only for the current headline, or the whole
  8645. sub-tree if optional argument INHERIT is non-nil."
  8646. (unless (org-before-first-heading-p)
  8647. (save-excursion
  8648. (org-back-to-heading t)
  8649. (let ((start (point))
  8650. (end (save-excursion
  8651. (if inherit (org-end-of-subtree t t)
  8652. (or (outline-next-heading) (point-max))))))
  8653. (if (symbolp tprop)
  8654. ;; TPROP is a text property symbol.
  8655. (put-text-property start end tprop p)
  8656. ;; TPROP is an alist with (property . function) elements.
  8657. (pcase-dolist (`(,prop . ,f) tprop)
  8658. (put-text-property start end prop (funcall f p))))))))
  8659. (defun org-refresh-category-properties ()
  8660. "Refresh category text properties in the buffer."
  8661. (let ((case-fold-search t)
  8662. (inhibit-read-only t)
  8663. (default-category
  8664. (cond ((null org-category)
  8665. (if buffer-file-name
  8666. (file-name-sans-extension
  8667. (file-name-nondirectory buffer-file-name))
  8668. "???"))
  8669. ((symbolp org-category) (symbol-name org-category))
  8670. (t org-category))))
  8671. (org-with-silent-modifications
  8672. (org-with-wide-buffer
  8673. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8674. ;; This is the default category for the buffer. If none is
  8675. ;; found, fall-back to `org-category' or buffer file name.
  8676. (put-text-property
  8677. (point-min) (point-max)
  8678. 'org-category
  8679. (catch 'buffer-category
  8680. (goto-char (point-max))
  8681. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8682. (let ((element (org-element-at-point)))
  8683. (when (eq (org-element-type element) 'keyword)
  8684. (throw 'buffer-category
  8685. (org-element-property :value element)))))
  8686. default-category))
  8687. ;; Set sub-tree specific categories.
  8688. (goto-char (point-min))
  8689. (let ((regexp (org-re-property "CATEGORY")))
  8690. (while (re-search-forward regexp nil t)
  8691. (let ((value (match-string-no-properties 3)))
  8692. (when (org-at-property-p)
  8693. (put-text-property
  8694. (save-excursion (org-back-to-heading t) (point))
  8695. (save-excursion (org-end-of-subtree t t) (point))
  8696. 'org-category
  8697. value)))))))))
  8698. (defun org-refresh-stats-properties ()
  8699. "Refresh stats text properties in the buffer."
  8700. (org-with-silent-modifications
  8701. (org-with-point-at 1
  8702. (let ((regexp (concat org-outline-regexp-bol
  8703. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8704. (while (re-search-forward regexp nil t)
  8705. (let* ((numerator (string-to-number (match-string 1)))
  8706. (denominator (and (match-end 2)
  8707. (string-to-number (match-string 2))))
  8708. (stats (cond ((not denominator) numerator) ;percent
  8709. ((= denominator 0) 0)
  8710. (t (/ (* numerator 100) denominator)))))
  8711. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8712. 'org-stats stats)))))))
  8713. (defun org-refresh-effort-properties ()
  8714. "Refresh effort properties"
  8715. (org-refresh-properties
  8716. org-effort-property
  8717. '((effort . identity)
  8718. (effort-minutes . org-duration-string-to-minutes))))
  8719. ;;;; Link Stuff
  8720. ;;; Link abbreviations
  8721. (defun org-link-expand-abbrev (link)
  8722. "Apply replacements as defined in `org-link-abbrev-alist'."
  8723. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8724. (let* ((key (match-string 1 link))
  8725. (as (or (assoc key org-link-abbrev-alist-local)
  8726. (assoc key org-link-abbrev-alist)))
  8727. (tag (and (match-end 2) (match-string 3 link)))
  8728. rpl)
  8729. (if (not as)
  8730. link
  8731. (setq rpl (cdr as))
  8732. (cond
  8733. ((symbolp rpl) (funcall rpl tag))
  8734. ((string-match "%(\\([^)]+\\))" rpl)
  8735. (replace-match
  8736. (save-match-data
  8737. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8738. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8739. ((string-match "%h" rpl)
  8740. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8741. (t (concat rpl tag)))))
  8742. link))
  8743. ;;; Storing and inserting links
  8744. (defvar org-insert-link-history nil
  8745. "Minibuffer history for links inserted with `org-insert-link'.")
  8746. (defvar org-stored-links nil
  8747. "Contains the links stored with `org-store-link'.")
  8748. (defvar org-store-link-plist nil
  8749. "Plist with info about the most recently link created with `org-store-link'.")
  8750. (defun org-store-link-functions ()
  8751. "Return a list of functions that are called to create and store a link.
  8752. The functions defined in the :store property of
  8753. `org-link-parameters'.
  8754. Each function will be called in turn until one returns a non-nil
  8755. value. Each function should check if it is responsible for
  8756. creating this link (for example by looking at the major mode).
  8757. If not, it must exit and return nil. If yes, it should return
  8758. a non-nil value after calling `org-store-link-props' with a list
  8759. of properties and values. Special properties are:
  8760. :type The link prefix, like \"http\". This must be given.
  8761. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8762. This is obligatory as well.
  8763. :description Optional default description for the second pair
  8764. of brackets in an Org mode link. The user can still change
  8765. this when inserting this link into an Org mode buffer.
  8766. In addition to these, any additional properties can be specified
  8767. and then used in capture templates."
  8768. (cl-loop for link in org-link-parameters
  8769. with store-func
  8770. do (setq store-func (org-link-get-parameter (car link) :store))
  8771. if store-func
  8772. collect store-func))
  8773. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8774. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8775. ;;;###autoload
  8776. (defun org-store-link (arg)
  8777. "Store an org-link to the current location.
  8778. \\<org-mode-map>
  8779. This link is added to `org-stored-links' and can later be inserted
  8780. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8781. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8782. A single
  8783. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8784. `org-gnus-prefer-web-links' for links to Usenet articles.
  8785. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8786. skipping storing functions that are not
  8787. part of Org core.
  8788. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8789. prefix ARG forces storing a link for each line in the
  8790. active region."
  8791. (interactive "P")
  8792. (org-load-modules-maybe)
  8793. (if (and (equal arg '(64)) (org-region-active-p))
  8794. (save-excursion
  8795. (let ((end (region-end)))
  8796. (goto-char (region-beginning))
  8797. (set-mark (point))
  8798. (while (< (point-at-eol) end)
  8799. (move-end-of-line 1) (activate-mark)
  8800. (let (current-prefix-arg)
  8801. (call-interactively 'org-store-link))
  8802. (move-beginning-of-line 2)
  8803. (set-mark (point)))))
  8804. (setq org-store-link-plist nil)
  8805. (let (link cpltxt desc description search
  8806. txt custom-id agenda-link sfuns sfunsn)
  8807. (cond
  8808. ;; Store a link using an external link type
  8809. ((and (not (equal arg '(16)))
  8810. (setq sfuns
  8811. (delq
  8812. nil (mapcar (lambda (f)
  8813. (let (fs) (if (funcall f) (push f fs))))
  8814. (org-store-link-functions)))
  8815. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8816. (or (and (cdr sfuns)
  8817. (funcall (intern
  8818. (completing-read
  8819. "Which function for creating the link? "
  8820. sfunsn nil t (car sfunsn)))))
  8821. (funcall (caar sfuns)))
  8822. (setq link (plist-get org-store-link-plist :link)
  8823. desc (or (plist-get org-store-link-plist
  8824. :description)
  8825. link))))
  8826. ;; Store a link from a source code buffer.
  8827. ((org-src-edit-buffer-p)
  8828. (let ((coderef-format (org-src-coderef-format)))
  8829. (cond ((save-excursion
  8830. (beginning-of-line)
  8831. (looking-at (org-src-coderef-regexp coderef-format)))
  8832. (setq link (format "(%s)" (match-string-no-properties 3))))
  8833. ((called-interactively-p 'any)
  8834. (let ((label (read-string "Code line label: ")))
  8835. (end-of-line)
  8836. (setq link (format coderef-format label))
  8837. (let ((gc (- 79 (length link))))
  8838. (if (< (current-column) gc)
  8839. (org-move-to-column gc t)
  8840. (insert " ")))
  8841. (insert link)
  8842. (setq link (concat "(" label ")"))
  8843. (setq desc nil)))
  8844. (t (setq link nil)))))
  8845. ;; We are in the agenda, link to referenced location
  8846. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8847. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8848. (get-text-property (point) 'org-marker))))
  8849. (when m
  8850. (org-with-point-at m
  8851. (setq agenda-link
  8852. (if (called-interactively-p 'any)
  8853. (call-interactively 'org-store-link)
  8854. (org-store-link nil)))))))
  8855. ((eq major-mode 'calendar-mode)
  8856. (let ((cd (calendar-cursor-to-date)))
  8857. (setq link
  8858. (format-time-string
  8859. (car org-time-stamp-formats)
  8860. (apply 'encode-time
  8861. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8862. nil nil nil))))
  8863. (org-store-link-props :type "calendar" :date cd)))
  8864. ((eq major-mode 'help-mode)
  8865. (setq link (concat "help:" (save-excursion
  8866. (goto-char (point-min))
  8867. (looking-at "^[^ ]+")
  8868. (match-string 0))))
  8869. (org-store-link-props :type "help"))
  8870. ((eq major-mode 'w3-mode)
  8871. (setq cpltxt (if (and (buffer-name)
  8872. (not (string-match "Untitled" (buffer-name))))
  8873. (buffer-name)
  8874. (url-view-url t))
  8875. link (url-view-url t))
  8876. (org-store-link-props :type "w3" :url (url-view-url t)))
  8877. ((eq major-mode 'image-mode)
  8878. (setq cpltxt (concat "file:"
  8879. (abbreviate-file-name buffer-file-name))
  8880. link cpltxt)
  8881. (org-store-link-props :type "image" :file buffer-file-name))
  8882. ;; In dired, store a link to the file of the current line
  8883. ((derived-mode-p 'dired-mode)
  8884. (let ((file (dired-get-filename nil t)))
  8885. (setq file (if file
  8886. (abbreviate-file-name
  8887. (expand-file-name (dired-get-filename nil t)))
  8888. ;; otherwise, no file so use current directory.
  8889. default-directory))
  8890. (setq cpltxt (concat "file:" file)
  8891. link cpltxt)))
  8892. ((setq search (run-hook-with-args-until-success
  8893. 'org-create-file-search-functions))
  8894. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8895. "::" search))
  8896. (setq cpltxt (or description link)))
  8897. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8898. (org-with-limited-levels
  8899. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8900. (cond
  8901. ;; Store a link using the target at point
  8902. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8903. (setq cpltxt
  8904. (concat "file:"
  8905. (abbreviate-file-name
  8906. (buffer-file-name (buffer-base-buffer)))
  8907. "::" (match-string 1))
  8908. link cpltxt))
  8909. ((and (featurep 'org-id)
  8910. (or (eq org-id-link-to-org-use-id t)
  8911. (and (called-interactively-p 'any)
  8912. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8913. (and (eq org-id-link-to-org-use-id
  8914. 'create-if-interactive-and-no-custom-id)
  8915. (not custom-id))))
  8916. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8917. ;; Store a link using the ID at point
  8918. (setq link (condition-case nil
  8919. (prog1 (org-id-store-link)
  8920. (setq desc (or (plist-get org-store-link-plist
  8921. :description)
  8922. "")))
  8923. (error
  8924. ;; Probably before first headline, link only to file
  8925. (concat "file:"
  8926. (abbreviate-file-name
  8927. (buffer-file-name (buffer-base-buffer))))))))
  8928. (t
  8929. ;; Just link to current headline
  8930. (setq cpltxt (concat "file:"
  8931. (abbreviate-file-name
  8932. (buffer-file-name (buffer-base-buffer)))))
  8933. ;; Add a context search string
  8934. (when (org-xor org-context-in-file-links
  8935. (equal arg '(4)))
  8936. (let* ((element (org-element-at-point))
  8937. (name (org-element-property :name element)))
  8938. (setq txt (cond
  8939. ((org-at-heading-p) nil)
  8940. (name)
  8941. ((org-region-active-p)
  8942. (buffer-substring (region-beginning) (region-end)))))
  8943. (when (or (null txt) (string-match "\\S-" txt))
  8944. (setq cpltxt
  8945. (concat cpltxt "::"
  8946. (condition-case nil
  8947. (org-make-org-heading-search-string txt)
  8948. (error "")))
  8949. desc (or name
  8950. (nth 4 (ignore-errors (org-heading-components)))
  8951. "NONE")))))
  8952. (when (string-match "::\\'" cpltxt)
  8953. (setq cpltxt (substring cpltxt 0 -2)))
  8954. (setq link cpltxt)))))
  8955. ((buffer-file-name (buffer-base-buffer))
  8956. ;; Just link to this file here.
  8957. (setq cpltxt (concat "file:"
  8958. (abbreviate-file-name
  8959. (buffer-file-name (buffer-base-buffer)))))
  8960. ;; Add a context string.
  8961. (when (org-xor org-context-in-file-links
  8962. (equal arg '(4)))
  8963. (setq txt (if (org-region-active-p)
  8964. (buffer-substring (region-beginning) (region-end))
  8965. (buffer-substring (point-at-bol) (point-at-eol))))
  8966. ;; Only use search option if there is some text.
  8967. (when (string-match "\\S-" txt)
  8968. (setq cpltxt
  8969. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8970. desc "NONE")))
  8971. (setq link cpltxt))
  8972. ((called-interactively-p 'interactive)
  8973. (user-error "No method for storing a link from this buffer"))
  8974. (t (setq link nil)))
  8975. ;; We're done setting link and desc, clean up
  8976. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8977. (setq link (or link cpltxt)
  8978. desc (or desc cpltxt))
  8979. (cond ((not desc))
  8980. ((equal desc "NONE") (setq desc nil))
  8981. (t (setq desc
  8982. (replace-regexp-in-string
  8983. org-bracket-link-analytic-regexp
  8984. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8985. desc))))
  8986. ;; Return the link
  8987. (if (not (and (or (called-interactively-p 'any)
  8988. executing-kbd-macro)
  8989. link))
  8990. (or agenda-link (and link (org-make-link-string link desc)))
  8991. (push (list link desc) org-stored-links)
  8992. (message "Stored: %s" (or desc link))
  8993. (when custom-id
  8994. (setq link (concat "file:" (abbreviate-file-name
  8995. (buffer-file-name)) "::#" custom-id))
  8996. (push (list link desc) org-stored-links))
  8997. (car org-stored-links)))))
  8998. (defun org-store-link-props (&rest plist)
  8999. "Store link properties, extract names, addresses and dates."
  9000. (let ((x (plist-get plist :from)))
  9001. (when x
  9002. (let ((adr (mail-extract-address-components x)))
  9003. (setq plist (plist-put plist :fromname (car adr)))
  9004. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9005. (let ((x (plist-get plist :to)))
  9006. (when x
  9007. (let ((adr (mail-extract-address-components x)))
  9008. (setq plist (plist-put plist :toname (car adr)))
  9009. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9010. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9011. (when x
  9012. (setq plist (plist-put plist :date-timestamp
  9013. (format-time-string
  9014. (org-time-stamp-format t) x)))
  9015. (setq plist (plist-put plist :date-timestamp-inactive
  9016. (format-time-string
  9017. (org-time-stamp-format t t) x)))))
  9018. (let ((from (plist-get plist :from))
  9019. (to (plist-get plist :to)))
  9020. (when (and from to org-from-is-user-regexp)
  9021. (setq plist
  9022. (plist-put plist :fromto
  9023. (if (string-match org-from-is-user-regexp from)
  9024. (concat "to %t")
  9025. (concat "from %f"))))))
  9026. (setq org-store-link-plist plist))
  9027. (defun org-add-link-props (&rest plist)
  9028. "Add these properties to the link property list."
  9029. (let (key value)
  9030. (while plist
  9031. (setq key (pop plist) value (pop plist))
  9032. (setq org-store-link-plist
  9033. (plist-put org-store-link-plist key value)))))
  9034. (defun org-email-link-description (&optional fmt)
  9035. "Return the description part of an email link.
  9036. This takes information from `org-store-link-plist' and formats it
  9037. according to FMT (default from `org-email-link-description-format')."
  9038. (setq fmt (or fmt org-email-link-description-format))
  9039. (let* ((p org-store-link-plist)
  9040. (to (plist-get p :toaddress))
  9041. (from (plist-get p :fromaddress))
  9042. (table
  9043. (list
  9044. (cons "%c" (plist-get p :fromto))
  9045. (cons "%F" (plist-get p :from))
  9046. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9047. (cons "%T" (plist-get p :to))
  9048. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9049. (cons "%s" (plist-get p :subject))
  9050. (cons "%d" (plist-get p :date))
  9051. (cons "%m" (plist-get p :message-id)))))
  9052. (when (string-match "%c" fmt)
  9053. ;; Check if the user wrote this message
  9054. (if (and org-from-is-user-regexp from to
  9055. (save-match-data (string-match org-from-is-user-regexp from)))
  9056. (setq fmt (replace-match "to %t" t t fmt))
  9057. (setq fmt (replace-match "from %f" t t fmt))))
  9058. (org-replace-escapes fmt table)))
  9059. (defun org-make-org-heading-search-string (&optional string)
  9060. "Make search string for the current headline or STRING."
  9061. (let ((s (or string
  9062. (and (derived-mode-p 'org-mode)
  9063. (save-excursion
  9064. (org-back-to-heading t)
  9065. (org-element-property :raw-value (org-element-at-point))))))
  9066. (lines org-context-in-file-links))
  9067. (or string (setq s (concat "*" s))) ; Add * for headlines
  9068. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9069. (when (and string (integerp lines) (> lines 0))
  9070. (let ((slines (org-split-string s "\n")))
  9071. (when (< lines (length slines))
  9072. (setq s (mapconcat
  9073. 'identity
  9074. (reverse (nthcdr (- (length slines) lines)
  9075. (reverse slines))) "\n")))))
  9076. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9077. (defun org-make-link-string (link &optional description)
  9078. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9079. (unless (org-string-nw-p link) (error "Empty link"))
  9080. (let ((uri (cond ((string-match org-link-types-re link)
  9081. (concat (match-string 1 link)
  9082. (org-link-escape (substring link (match-end 1)))))
  9083. ;; For readability, url-encode internal links only
  9084. ;; when absolutely needed (i.e, when they contain
  9085. ;; square brackets). File links however, are
  9086. ;; encoded since, e.g., spaces are significant.
  9087. ((or (file-name-absolute-p link)
  9088. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9089. (org-link-escape link))
  9090. (t link)))
  9091. (description
  9092. (and (org-string-nw-p description)
  9093. ;; Remove brackets from description, as they are fatal.
  9094. (replace-regexp-in-string
  9095. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9096. (org-trim description)))))
  9097. (format "[[%s]%s]"
  9098. uri
  9099. (if description (format "[%s]" description) ""))))
  9100. (defconst org-link-escape-chars
  9101. ;;%20 %5B %5D %25
  9102. '(?\s ?\[ ?\] ?%)
  9103. "List of characters that should be escaped in a link when stored to Org.
  9104. This is the list that is used for internal purposes.")
  9105. (defun org-link-escape (text &optional table merge)
  9106. "Return percent escaped representation of TEXT.
  9107. TEXT is a string with the text to escape.
  9108. Optional argument TABLE is a list with characters that should be
  9109. escaped. When nil, `org-link-escape-chars' is used.
  9110. If optional argument MERGE is set, merge TABLE into
  9111. `org-link-escape-chars'."
  9112. (let ((characters-to-encode
  9113. (cond ((null table) org-link-escape-chars)
  9114. (merge (append org-link-escape-chars table))
  9115. (t table))))
  9116. (mapconcat
  9117. (lambda (c)
  9118. (if (or (memq c characters-to-encode)
  9119. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9120. (mapconcat (lambda (e) (format "%%%.2X" e))
  9121. (or (encode-coding-char c 'utf-8)
  9122. (error "Unable to percent escape character: %c" c))
  9123. "")
  9124. (char-to-string c)))
  9125. text "")))
  9126. (defun org-link-unescape (str)
  9127. "Unhex hexified Unicode parts in string STR.
  9128. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9129. reciprocal of `org-link-escape', which see."
  9130. (if (org-string-nw-p str)
  9131. (replace-regexp-in-string
  9132. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9133. str))
  9134. (defun org-link-unescape-compound (hex)
  9135. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9136. Note: this function also decodes single byte encodings like
  9137. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9138. (save-match-data
  9139. (let* ((bytes (cdr (split-string hex "%")))
  9140. (ret "")
  9141. (eat 0)
  9142. (sum 0))
  9143. (while bytes
  9144. (let* ((val (string-to-number (pop bytes) 16))
  9145. (shift-xor
  9146. (if (= 0 eat)
  9147. (cond
  9148. ((>= val 252) (cons 6 252))
  9149. ((>= val 248) (cons 5 248))
  9150. ((>= val 240) (cons 4 240))
  9151. ((>= val 224) (cons 3 224))
  9152. ((>= val 192) (cons 2 192))
  9153. (t (cons 0 0)))
  9154. (cons 6 128))))
  9155. (when (>= val 192) (setq eat (car shift-xor)))
  9156. (setq val (logxor val (cdr shift-xor)))
  9157. (setq sum (+ (lsh sum (car shift-xor)) val))
  9158. (when (> eat 0) (setq eat (- eat 1)))
  9159. (cond
  9160. ((= 0 eat) ;multi byte
  9161. (setq ret (concat ret (char-to-string sum)))
  9162. (setq sum 0))
  9163. ((not bytes) ; single byte(s)
  9164. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9165. ret)))
  9166. (defun org-link-unescape-single-byte-sequence (hex)
  9167. "Unhexify hex-encoded single byte character sequences."
  9168. (mapconcat (lambda (byte)
  9169. (char-to-string (string-to-number byte 16)))
  9170. (cdr (split-string hex "%")) ""))
  9171. (defun org-xor (a b)
  9172. "Exclusive or."
  9173. (if a (not b) b))
  9174. (defun org-fixup-message-id-for-http (s)
  9175. "Replace special characters in a message id, so it can be used in an http query."
  9176. (when (string-match "%" s)
  9177. (setq s (mapconcat (lambda (c)
  9178. (if (eq c ?%)
  9179. "%25"
  9180. (char-to-string c)))
  9181. s "")))
  9182. (while (string-match "<" s)
  9183. (setq s (replace-match "%3C" t t s)))
  9184. (while (string-match ">" s)
  9185. (setq s (replace-match "%3E" t t s)))
  9186. (while (string-match "@" s)
  9187. (setq s (replace-match "%40" t t s)))
  9188. s)
  9189. (defun org-link-prettify (link)
  9190. "Return a human-readable representation of LINK.
  9191. The car of LINK must be a raw link.
  9192. The cdr of LINK must be either a link description or nil."
  9193. (let ((desc (or (cadr link) "<no description>")))
  9194. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9195. "<" (car link) ">")))
  9196. ;;;###autoload
  9197. (defun org-insert-link-global ()
  9198. "Insert a link like Org mode does.
  9199. This command can be called in any mode to insert a link in Org syntax."
  9200. (interactive)
  9201. (org-load-modules-maybe)
  9202. (org-run-like-in-org-mode 'org-insert-link))
  9203. (defun org-insert-all-links (arg &optional pre post)
  9204. "Insert all links in `org-stored-links'.
  9205. When a universal prefix, do not delete the links from `org-stored-links'.
  9206. When `ARG' is a number, insert the last N link(s).
  9207. `PRE' and `POST' are optional arguments to define a string to
  9208. prepend or to append."
  9209. (interactive "P")
  9210. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9211. (links (copy-sequence org-stored-links))
  9212. (pr (or pre "- "))
  9213. (po (or post "\n"))
  9214. (cnt 1) l)
  9215. (if (null org-stored-links)
  9216. (message "No link to insert")
  9217. (while (and (or (listp arg) (>= arg cnt))
  9218. (setq l (if (listp arg)
  9219. (pop links)
  9220. (pop org-stored-links))))
  9221. (setq cnt (1+ cnt))
  9222. (insert pr)
  9223. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9224. (insert po)))))
  9225. (defun org-insert-last-stored-link (arg)
  9226. "Insert the last link stored in `org-stored-links'."
  9227. (interactive "p")
  9228. (org-insert-all-links arg "" "\n"))
  9229. (defun org-link-fontify-links-to-this-file ()
  9230. "Fontify links to the current file in `org-stored-links'."
  9231. (let ((f (buffer-file-name)) a b)
  9232. (setq a (mapcar (lambda(l)
  9233. (let ((ll (car l)))
  9234. (when (and (string-match "^file:\\(.+\\)::" ll)
  9235. (equal f (expand-file-name (match-string 1 ll))))
  9236. ll)))
  9237. org-stored-links))
  9238. (when (featurep 'org-id)
  9239. (setq b (mapcar (lambda(l)
  9240. (let ((ll (car l)))
  9241. (when (and (string-match "^id:\\(.+\\)$" ll)
  9242. (equal f (expand-file-name
  9243. (or (org-id-find-id-file
  9244. (match-string 1 ll)) ""))))
  9245. ll)))
  9246. org-stored-links)))
  9247. (mapcar (lambda(l)
  9248. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9249. (delq nil (append a b)))))
  9250. (defvar org--links-history nil)
  9251. (defun org-insert-link (&optional complete-file link-location default-description)
  9252. "Insert a link. At the prompt, enter the link.
  9253. Completion can be used to insert any of the link protocol prefixes in use.
  9254. The history can be used to select a link previously stored with
  9255. `org-store-link'. When the empty string is entered (i.e. if you just
  9256. press `RET' at the prompt), the link defaults to the most recently
  9257. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9258. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9259. You will also be prompted for a description, and if one is given, it will
  9260. be displayed in the buffer instead of the link.
  9261. If there is already a link at point, this command will allow you to edit
  9262. link and description parts.
  9263. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9264. file name can be
  9265. selected using completion. The path to the file will be relative to the
  9266. current directory if the file is in the current directory or a subdirectory.
  9267. Otherwise, the link will be the absolute path as completed in the minibuffer
  9268. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9269. option `org-link-file-path-type'.
  9270. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9271. absolute path even if the file is in
  9272. the current directory or below.
  9273. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9274. prefix negates `org-keep-stored-link-after-insertion'.
  9275. If `org-make-link-description-function' is non-nil, this function will be
  9276. called with the link target, and the result will be the default
  9277. link description.
  9278. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9279. the link location instead of reading one interactively.
  9280. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9281. as the default description."
  9282. (interactive "P")
  9283. (let* ((wcf (current-window-configuration))
  9284. (origbuf (current-buffer))
  9285. (region (when (org-region-active-p)
  9286. (buffer-substring (region-beginning) (region-end))))
  9287. (remove (and region (list (region-beginning) (region-end))))
  9288. (desc region)
  9289. (link link-location)
  9290. (abbrevs org-link-abbrev-alist-local)
  9291. entry all-prefixes auto-desc)
  9292. (cond
  9293. (link-location) ; specified by arg, just use it.
  9294. ((org-in-regexp org-bracket-link-regexp 1)
  9295. ;; We do have a link at point, and we are going to edit it.
  9296. (setq remove (list (match-beginning 0) (match-end 0)))
  9297. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9298. (setq link (read-string "Link: "
  9299. (org-link-unescape
  9300. (match-string-no-properties 1)))))
  9301. ((or (org-in-regexp org-angle-link-re)
  9302. (org-in-regexp org-plain-link-re))
  9303. ;; Convert to bracket link
  9304. (setq remove (list (match-beginning 0) (match-end 0))
  9305. link (read-string "Link: "
  9306. (org-unbracket-string "<" ">" (match-string 0)))))
  9307. ((member complete-file '((4) (16)))
  9308. ;; Completing read for file names.
  9309. (setq link (org-file-complete-link complete-file)))
  9310. (t
  9311. ;; Read link, with completion for stored links.
  9312. (org-link-fontify-links-to-this-file)
  9313. (org-switch-to-buffer-other-window "*Org Links*")
  9314. (with-current-buffer "*Org Links*"
  9315. (erase-buffer)
  9316. (insert "Insert a link.
  9317. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9318. (when org-stored-links
  9319. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9320. (insert (mapconcat 'org-link-prettify
  9321. (reverse org-stored-links) "\n")))
  9322. (goto-char (point-min)))
  9323. (let ((cw (selected-window)))
  9324. (select-window (get-buffer-window "*Org Links*" 'visible))
  9325. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9326. (unless (pos-visible-in-window-p (point-max))
  9327. (org-fit-window-to-buffer))
  9328. (and (window-live-p cw) (select-window cw)))
  9329. (setq all-prefixes (append (mapcar 'car abbrevs)
  9330. (mapcar 'car org-link-abbrev-alist)
  9331. (org-link-types)))
  9332. (unwind-protect
  9333. ;; Fake a link history, containing the stored links.
  9334. (let ((org--links-history
  9335. (append (mapcar #'car org-stored-links)
  9336. org-insert-link-history)))
  9337. (setq link
  9338. (org-completing-read
  9339. "Link: "
  9340. (append
  9341. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9342. (mapcar #'car org-stored-links))
  9343. nil nil nil
  9344. 'org--links-history
  9345. (caar org-stored-links)))
  9346. (unless (org-string-nw-p link) (user-error "No link selected"))
  9347. (dolist (l org-stored-links)
  9348. (when (equal link (cadr l))
  9349. (setq link (car l))
  9350. (setq auto-desc t)))
  9351. (when (or (member link all-prefixes)
  9352. (and (equal ":" (substring link -1))
  9353. (member (substring link 0 -1) all-prefixes)
  9354. (setq link (substring link 0 -1))))
  9355. (setq link (with-current-buffer origbuf
  9356. (org-link-try-special-completion link)))))
  9357. (set-window-configuration wcf)
  9358. (kill-buffer "*Org Links*"))
  9359. (setq entry (assoc link org-stored-links))
  9360. (or entry (push link org-insert-link-history))
  9361. (setq desc (or desc (nth 1 entry)))))
  9362. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9363. (not org-keep-stored-link-after-insertion))
  9364. (setq org-stored-links (delq (assoc link org-stored-links)
  9365. org-stored-links)))
  9366. (when (and (string-match org-plain-link-re link)
  9367. (not (string-match org-ts-regexp link)))
  9368. ;; URL-like link, normalize the use of angular brackets.
  9369. (setq link (org-unbracket-string "<" ">" link)))
  9370. ;; Check if we are linking to the current file with a search
  9371. ;; option If yes, simplify the link by using only the search
  9372. ;; option.
  9373. (when (and buffer-file-name
  9374. (let ((case-fold-search nil))
  9375. (string-match "\\`file:\\(.+?\\)::" link)))
  9376. (let ((path (match-string-no-properties 1 link))
  9377. (search (substring-no-properties link (match-end 0))))
  9378. (save-match-data
  9379. (when (equal (file-truename buffer-file-name) (file-truename path))
  9380. ;; We are linking to this same file, with a search option
  9381. (setq link search)))))
  9382. ;; Check if we can/should use a relative path. If yes, simplify the link
  9383. (let ((case-fold-search nil))
  9384. (when (string-match "\\`\\(file\\|docview\\):" link)
  9385. (let* ((type (match-string-no-properties 0 link))
  9386. (path (substring-no-properties link (match-end 0)))
  9387. (origpath path))
  9388. (cond
  9389. ((or (eq org-link-file-path-type 'absolute)
  9390. (equal complete-file '(16)))
  9391. (setq path (abbreviate-file-name (expand-file-name path))))
  9392. ((eq org-link-file-path-type 'noabbrev)
  9393. (setq path (expand-file-name path)))
  9394. ((eq org-link-file-path-type 'relative)
  9395. (setq path (file-relative-name path)))
  9396. (t
  9397. (save-match-data
  9398. (if (string-match (concat "^" (regexp-quote
  9399. (expand-file-name
  9400. (file-name-as-directory
  9401. default-directory))))
  9402. (expand-file-name path))
  9403. ;; We are linking a file with relative path name.
  9404. (setq path (substring (expand-file-name path)
  9405. (match-end 0)))
  9406. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9407. (setq link (concat type path))
  9408. (when (equal desc origpath)
  9409. (setq desc path)))))
  9410. (if org-make-link-description-function
  9411. (setq desc
  9412. (or (condition-case nil
  9413. (funcall org-make-link-description-function link desc)
  9414. (error (progn (message "Can't get link description from `%s'"
  9415. (symbol-name org-make-link-description-function))
  9416. (sit-for 2) nil)))
  9417. (read-string "Description: " default-description)))
  9418. (if default-description (setq desc default-description)
  9419. (setq desc (or (and auto-desc desc)
  9420. (read-string "Description: " desc)))))
  9421. (unless (string-match "\\S-" desc) (setq desc nil))
  9422. (when remove (apply 'delete-region remove))
  9423. (insert (org-make-link-string link desc))
  9424. ;; Redisplay so as the new link has proper invisible characters.
  9425. (sit-for 0)))
  9426. (defun org-link-try-special-completion (type)
  9427. "If there is completion support for link type TYPE, offer it."
  9428. (let ((fun (org-link-get-parameter type :complete)))
  9429. (if (functionp fun)
  9430. (funcall fun)
  9431. (read-string "Link (no completion support): " (concat type ":")))))
  9432. (defun org-file-complete-link (&optional arg)
  9433. "Create a file link using completion."
  9434. (let ((file (read-file-name "File: "))
  9435. (pwd (file-name-as-directory (expand-file-name ".")))
  9436. (pwd1 (file-name-as-directory (abbreviate-file-name
  9437. (expand-file-name ".")))))
  9438. (cond ((equal arg '(16))
  9439. (concat "file:"
  9440. (abbreviate-file-name (expand-file-name file))))
  9441. ((string-match
  9442. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9443. (concat "file:" (match-string 1 file)))
  9444. ((string-match
  9445. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9446. (expand-file-name file))
  9447. (concat "file:"
  9448. (match-string 1 (expand-file-name file))))
  9449. (t (concat "file:" file)))))
  9450. (defun org-completing-read (&rest args)
  9451. "Completing-read with SPACE being a normal character."
  9452. (let ((enable-recursive-minibuffers t)
  9453. (minibuffer-local-completion-map
  9454. (copy-keymap minibuffer-local-completion-map)))
  9455. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9456. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9457. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9458. 'org-time-stamp-inactive)
  9459. (apply #'completing-read args)))
  9460. ;;; Opening/following a link
  9461. (defvar org-link-search-failed nil)
  9462. (defvar org-open-link-functions nil
  9463. "Hook for functions finding a plain text link.
  9464. These functions must take a single argument, the link content.
  9465. They will be called for links that look like [[link text][description]]
  9466. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9467. like a filename (e.g. \"./blue.png\").
  9468. These functions will be called *before* Org attempts to resolve the
  9469. link by doing text searches in the current buffer - so if you want a
  9470. link \"[[target]]\" to still find \"<<target>>\", your function should
  9471. handle this as a special case.
  9472. When the function does handle the link, it must return a non-nil value.
  9473. If it decides that it is not responsible for this link, it must return
  9474. nil to indicate that that Org can continue with other options like
  9475. exact and fuzzy text search.")
  9476. (defun org-next-link (&optional search-backward)
  9477. "Move forward to the next link.
  9478. If the link is in hidden text, expose it."
  9479. (interactive "P")
  9480. (when (and org-link-search-failed (eq this-command last-command))
  9481. (goto-char (point-min))
  9482. (message "Link search wrapped back to beginning of buffer"))
  9483. (setq org-link-search-failed nil)
  9484. (let* ((pos (point))
  9485. (ct (org-context))
  9486. (a (assq :link ct))
  9487. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9488. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9489. ((looking-at org-any-link-re)
  9490. ;; Don't stay stuck at link without an org-link face
  9491. (forward-char (if search-backward -1 1))))
  9492. (if (funcall srch-fun org-any-link-re nil t)
  9493. (progn
  9494. (goto-char (match-beginning 0))
  9495. (when (org-invisible-p) (org-show-context)))
  9496. (goto-char pos)
  9497. (setq org-link-search-failed t)
  9498. (message "No further link found"))))
  9499. (defun org-previous-link ()
  9500. "Move backward to the previous link.
  9501. If the link is in hidden text, expose it."
  9502. (interactive)
  9503. (funcall 'org-next-link t))
  9504. (defun org-translate-link (s)
  9505. "Translate a link string if a translation function has been defined."
  9506. (with-temp-buffer
  9507. (insert (org-trim s))
  9508. (org-trim (org-element-interpret-data (org-element-context)))))
  9509. (defun org-translate-link-from-planner (type path)
  9510. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9511. This is still an experimental function, your mileage may vary."
  9512. (cond
  9513. ((member type '("http" "https" "news" "ftp"))
  9514. ;; standard Internet links are the same.
  9515. nil)
  9516. ((and (equal type "irc") (string-match "^//" path))
  9517. ;; Planner has two / at the beginning of an irc link, we have 1.
  9518. ;; We should have zero, actually....
  9519. (setq path (substring path 1)))
  9520. ((and (equal type "lisp") (string-match "^/" path))
  9521. ;; Planner has a slash, we do not.
  9522. (setq type "elisp" path (substring path 1)))
  9523. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9524. ;; A typical message link. Planner has the id after the final slash,
  9525. ;; we separate it with a hash mark
  9526. (setq path (concat (match-string 1 path) "#"
  9527. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9528. (cons type path))
  9529. (defun org-find-file-at-mouse (ev)
  9530. "Open file link or URL at mouse."
  9531. (interactive "e")
  9532. (mouse-set-point ev)
  9533. (org-open-at-point 'in-emacs))
  9534. (defun org-open-at-mouse (ev)
  9535. "Open file link or URL at mouse.
  9536. See the docstring of `org-open-file' for details."
  9537. (interactive "e")
  9538. (mouse-set-point ev)
  9539. (when (eq major-mode 'org-agenda-mode)
  9540. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9541. (org-open-at-point))
  9542. (defvar org-window-config-before-follow-link nil
  9543. "The window configuration before following a link.
  9544. This is saved in case the need arises to restore it.")
  9545. ;;;###autoload
  9546. (defun org-open-at-point-global ()
  9547. "Follow a link or time-stamp like Org mode does.
  9548. This command can be called in any mode to follow an external link
  9549. or a time-stamp that has Org mode syntax. Its behavior is
  9550. undefined when called on internal links (e.g., fuzzy links).
  9551. Raise an error when there is nothing to follow. "
  9552. (interactive)
  9553. (cond ((org-in-regexp org-any-link-re)
  9554. (org-open-link-from-string (match-string-no-properties 0)))
  9555. ((or (org-in-regexp org-ts-regexp-both nil t)
  9556. (org-in-regexp org-tsr-regexp-both nil t))
  9557. (org-follow-timestamp-link))
  9558. (t (user-error "No link found"))))
  9559. ;;;###autoload
  9560. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9561. "Open a link in the string S, as if it was in Org mode."
  9562. (interactive "sLink: \nP")
  9563. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9564. (with-temp-buffer
  9565. (let ((org-inhibit-startup (not reference-buffer)))
  9566. (org-mode)
  9567. (insert s)
  9568. (goto-char (point-min))
  9569. (when reference-buffer
  9570. (setq org-link-abbrev-alist-local
  9571. (with-current-buffer reference-buffer
  9572. org-link-abbrev-alist-local)))
  9573. (org-open-at-point arg reference-buffer)))))
  9574. (defvar org-open-at-point-functions nil
  9575. "Hook that is run when following a link at point.
  9576. Functions in this hook must return t if they identify and follow
  9577. a link at point. If they don't find anything interesting at point,
  9578. they must return nil.")
  9579. (defvar org-link-search-inhibit-query nil)
  9580. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9581. (defun org--open-doi-link (path)
  9582. "Open a \"doi\" type link.
  9583. PATH is a the path to search for, as a string."
  9584. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9585. (defun org--open-elisp-link (path)
  9586. "Open a \"elisp\" type link.
  9587. PATH is the sexp to evaluate, as a string."
  9588. (let ((cmd path))
  9589. (if (or (and (org-string-nw-p
  9590. org-confirm-elisp-link-not-regexp)
  9591. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9592. (not org-confirm-elisp-link-function)
  9593. (funcall org-confirm-elisp-link-function
  9594. (format "Execute \"%s\" as elisp? "
  9595. (org-add-props cmd nil 'face 'org-warning))))
  9596. (message "%s => %s" cmd
  9597. (if (eq (string-to-char cmd) ?\()
  9598. (eval (read cmd))
  9599. (call-interactively (read cmd))))
  9600. (user-error "Abort"))))
  9601. (defun org--open-help-link (path)
  9602. "Open a \"help\" type link.
  9603. PATH is a symbol name, as a string."
  9604. (pcase (intern path)
  9605. ((and (pred fboundp) variable) (describe-function variable))
  9606. ((and (pred boundp) function) (describe-variable function))
  9607. (name (user-error "Unknown function or variable: %s" name))))
  9608. (defun org--open-shell-link (path)
  9609. "Open a \"shell\" type link.
  9610. PATH is the command to execute, as a string."
  9611. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9612. (cmd path))
  9613. (if (or (and (org-string-nw-p
  9614. org-confirm-shell-link-not-regexp)
  9615. (string-match
  9616. org-confirm-shell-link-not-regexp cmd))
  9617. (not org-confirm-shell-link-function)
  9618. (funcall org-confirm-shell-link-function
  9619. (format "Execute \"%s\" in shell? "
  9620. (org-add-props cmd nil
  9621. 'face 'org-warning))))
  9622. (progn
  9623. (message "Executing %s" cmd)
  9624. (shell-command cmd buf)
  9625. (when (featurep 'midnight)
  9626. (setq clean-buffer-list-kill-buffer-names
  9627. (cons (buffer-name buf)
  9628. clean-buffer-list-kill-buffer-names))))
  9629. (user-error "Abort"))))
  9630. (defun org-open-at-point (&optional arg reference-buffer)
  9631. "Open link, timestamp, footnote or tags at point.
  9632. When point is on a link, follow it. Normally, files will be
  9633. opened by an appropriate application. If the optional prefix
  9634. argument ARG is non-nil, Emacs will visit the file. With
  9635. a double prefix argument, try to open outside of Emacs, in the
  9636. application the system uses for this file type.
  9637. When point is on a timestamp, open the agenda at the day
  9638. specified.
  9639. When point is a footnote definition, move to the first reference
  9640. found. If it is on a reference, move to the associated
  9641. definition.
  9642. When point is on a headline, display a list of every link in the
  9643. entry, so it is possible to pick one, or all, of them. If point
  9644. is on a tag, call `org-tags-view' instead.
  9645. When optional argument REFERENCE-BUFFER is non-nil, it should
  9646. specify a buffer from where the link search should happen. This
  9647. is used internally by `org-open-link-from-string'.
  9648. On top of syntactically correct links, this function will also
  9649. try to open links and time-stamps in comments, example
  9650. blocks... i.e., whenever point is on something looking like
  9651. a timestamp or a link."
  9652. (interactive "P")
  9653. ;; On a code block, open block's results.
  9654. (unless (call-interactively 'org-babel-open-src-block-result)
  9655. (org-load-modules-maybe)
  9656. (setq org-window-config-before-follow-link (current-window-configuration))
  9657. (org-remove-occur-highlights nil nil t)
  9658. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9659. (let* ((context
  9660. ;; Only consider supported types, even if they are not
  9661. ;; the closest one.
  9662. (org-element-lineage
  9663. (org-element-context)
  9664. '(clock footnote-definition footnote-reference headline
  9665. inlinetask link timestamp)
  9666. t))
  9667. (type (org-element-type context))
  9668. (value (org-element-property :value context)))
  9669. (cond
  9670. ;; On a headline or an inlinetask, but not on a timestamp,
  9671. ;; a link, a footnote reference or on tags.
  9672. ((and (memq type '(headline inlinetask))
  9673. ;; Not on tags.
  9674. (let ((case-fold-search nil))
  9675. (and (org-match-line org-complex-heading-regexp)
  9676. (or (not (match-beginning 5))
  9677. (< (point) (match-beginning 5))))))
  9678. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9679. (links (car data))
  9680. (links-end (cdr data)))
  9681. (if links
  9682. (dolist (link (if (stringp links) (list links) links))
  9683. (search-forward link nil links-end)
  9684. (goto-char (match-beginning 0))
  9685. (org-open-at-point))
  9686. (require 'org-attach)
  9687. (org-attach-reveal 'if-exists))))
  9688. ;; On a footnote reference or at definition's label.
  9689. ((or (eq type 'footnote-reference)
  9690. (and (eq type 'footnote-definition)
  9691. (save-excursion
  9692. ;; Do not validate action when point is on the
  9693. ;; spaces right after the footnote label, in
  9694. ;; order to be on par with behaviour on links.
  9695. (skip-chars-forward " \t")
  9696. (let ((begin
  9697. (org-element-property :contents-begin context)))
  9698. (if begin (< (point) begin)
  9699. (= (org-element-property :post-affiliated context)
  9700. (line-beginning-position)))))))
  9701. (org-footnote-action))
  9702. ;; No valid context. Ignore catch-all types like `headline'.
  9703. ;; If point is on something looking like a link or
  9704. ;; a time-stamp, try opening it. It may be useful in
  9705. ;; comments, example blocks...
  9706. ((memq type '(footnote-definition headline inlinetask nil))
  9707. (call-interactively #'org-open-at-point-global))
  9708. ;; On a clock line, make sure point is on the timestamp
  9709. ;; before opening it.
  9710. ((and (eq type 'clock)
  9711. value
  9712. (>= (point) (org-element-property :begin value))
  9713. (<= (point) (org-element-property :end value)))
  9714. (org-follow-timestamp-link))
  9715. ;; Do nothing on white spaces after an object.
  9716. ((>= (point)
  9717. (save-excursion
  9718. (goto-char (org-element-property :end context))
  9719. (skip-chars-backward " \t")
  9720. (point)))
  9721. (user-error "No link found"))
  9722. ((eq type 'timestamp) (org-follow-timestamp-link))
  9723. ;; On tags within a headline or an inlinetask.
  9724. ((and (memq type '(headline inlinetask))
  9725. (let ((case-fold-search nil))
  9726. (save-excursion (beginning-of-line)
  9727. (looking-at org-complex-heading-regexp))
  9728. (and (match-beginning 5)
  9729. (>= (point) (match-beginning 5)))))
  9730. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9731. ((eq type 'link)
  9732. ;; When link is located within the description of another
  9733. ;; link (e.g., an inline image), always open the parent
  9734. ;; link.
  9735. (let* ((link (let ((up (org-element-property :parent context)))
  9736. (if (eq (org-element-type up) 'link) up context)))
  9737. (type (org-element-property :type link))
  9738. (path (org-link-unescape (org-element-property :path link))))
  9739. ;; Switch back to REFERENCE-BUFFER needed when called in
  9740. ;; a temporary buffer through `org-open-link-from-string'.
  9741. (with-current-buffer (or reference-buffer (current-buffer))
  9742. (cond
  9743. ((equal type "file")
  9744. (if (string-match "[*?{]" (file-name-nondirectory path))
  9745. (dired path)
  9746. ;; Look into `org-link-parameters' in order to find
  9747. ;; a DEDICATED-FUNCTION to open file. The function
  9748. ;; will be applied on raw link instead of parsed
  9749. ;; link due to the limitation in `org-add-link-type'
  9750. ;; ("open" function called with a single argument).
  9751. ;; If no such function is found, fallback to
  9752. ;; `org-open-file'.
  9753. (let* ((option (org-element-property :search-option link))
  9754. (app (org-element-property :application link))
  9755. (dedicated-function
  9756. (org-link-get-parameter
  9757. (if app (concat type "+" app) type)
  9758. :follow)))
  9759. (if dedicated-function
  9760. (funcall dedicated-function
  9761. (concat path
  9762. (and option (concat "::" option))))
  9763. (apply #'org-open-file
  9764. path
  9765. (cond (arg)
  9766. ((equal app "emacs") 'emacs)
  9767. ((equal app "sys") 'system))
  9768. (cond ((not option) nil)
  9769. ((string-match-p "\\`[0-9]+\\'" option)
  9770. (list (string-to-number option)))
  9771. (t (list nil
  9772. (org-link-unescape option)))))))))
  9773. ((functionp (org-link-get-parameter type :follow))
  9774. (funcall (org-link-get-parameter type :follow) path))
  9775. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9776. (unless (run-hook-with-args-until-success
  9777. 'org-open-link-functions path)
  9778. (if (not arg) (org-mark-ring-push)
  9779. (switch-to-buffer-other-window
  9780. (org-get-buffer-for-internal-link (current-buffer))))
  9781. (let ((destination
  9782. (org-with-wide-buffer
  9783. (if (equal type "radio")
  9784. (org-search-radio-target
  9785. (org-element-property :path link))
  9786. (org-link-search
  9787. (if (member type '("custom-id" "coderef"))
  9788. (org-element-property :raw-link link)
  9789. path)
  9790. ;; Prevent fuzzy links from matching
  9791. ;; themselves.
  9792. (and (equal type "fuzzy")
  9793. (+ 2 (org-element-property :begin link)))))
  9794. (point))))
  9795. (unless (and (<= (point-min) destination)
  9796. (>= (point-max) destination))
  9797. (widen))
  9798. (goto-char destination))))
  9799. (t (browse-url-at-point))))))
  9800. (t (user-error "No link found")))))
  9801. (run-hook-with-args 'org-follow-link-hook)))
  9802. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9803. "Offer links in the current entry and return the selected link.
  9804. If there is only one link, return it.
  9805. If NTH is an integer, return the NTH link found.
  9806. If ZERO is a string, check also this string for a link, and if
  9807. there is one, return it."
  9808. (with-current-buffer buffer
  9809. (org-with-wide-buffer
  9810. (goto-char marker)
  9811. (let ((cnt ?0)
  9812. have-zero end links link c)
  9813. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9814. (push (match-string 0 zero) links)
  9815. (setq cnt (1- cnt) have-zero t))
  9816. (save-excursion
  9817. (org-back-to-heading t)
  9818. (setq end (save-excursion (outline-next-heading) (point)))
  9819. (while (re-search-forward org-any-link-re end t)
  9820. (push (match-string 0) links))
  9821. (setq links (org-uniquify (reverse links))))
  9822. (cond
  9823. ((null links)
  9824. (message "No links"))
  9825. ((equal (length links) 1)
  9826. (setq link (car links)))
  9827. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9828. (setq link (nth (if have-zero nth (1- nth)) links)))
  9829. (t ; we have to select a link
  9830. (save-excursion
  9831. (save-window-excursion
  9832. (delete-other-windows)
  9833. (with-output-to-temp-buffer "*Select Link*"
  9834. (dolist (l links)
  9835. (cond
  9836. ((not (string-match org-bracket-link-regexp l))
  9837. (princ (format "[%c] %s\n" (cl-incf cnt)
  9838. (org-unbracket-string "<" ">" l))))
  9839. ((match-end 3)
  9840. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9841. (match-string 3 l) (match-string 1 l))))
  9842. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9843. (match-string 1 l)))))))
  9844. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9845. (message "Select link to open, RET to open all:")
  9846. (setq c (read-char-exclusive))
  9847. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9848. (when (equal c ?q) (user-error "Abort"))
  9849. (if (equal c ?\C-m)
  9850. (setq link links)
  9851. (setq nth (- c ?0))
  9852. (when have-zero (setq nth (1+ nth)))
  9853. (unless (and (integerp nth) (>= (length links) nth))
  9854. (user-error "Invalid link selection"))
  9855. (setq link (nth (1- nth) links)))))
  9856. (cons link end)))))
  9857. ;; TODO: These functions are deprecated since `org-open-at-point'
  9858. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9859. (defun org-open-file-with-system (path)
  9860. "Open file at PATH using the system way of opening it."
  9861. (org-open-file path 'system))
  9862. (defun org-open-file-with-emacs (path)
  9863. "Open file at PATH in Emacs."
  9864. (org-open-file path 'emacs))
  9865. ;;; File search
  9866. (defvar org-create-file-search-functions nil
  9867. "List of functions to construct the right search string for a file link.
  9868. These functions are called in turn with point at the location to
  9869. which the link should point.
  9870. A function in the hook should first test if it would like to
  9871. handle this file type, for example by checking the `major-mode'
  9872. or the file extension. If it decides not to handle this file, it
  9873. should just return nil to give other functions a chance. If it
  9874. does handle the file, it must return the search string to be used
  9875. when following the link. The search string will be part of the
  9876. file link, given after a double colon, and `org-open-at-point'
  9877. will automatically search for it. If special measures must be
  9878. taken to make the search successful, another function should be
  9879. added to the companion hook `org-execute-file-search-functions',
  9880. which see.
  9881. A function in this hook may also use `setq' to set the variable
  9882. `description' to provide a suggestion for the descriptive text to
  9883. be used for this link when it gets inserted into an Org buffer
  9884. with \\[org-insert-link].")
  9885. (defvar org-execute-file-search-functions nil
  9886. "List of functions to execute a file search triggered by a link.
  9887. Functions added to this hook must accept a single argument, the
  9888. search string that was part of the file link, the part after the
  9889. double colon. The function must first check if it would like to
  9890. handle this search, for example by checking the `major-mode' or
  9891. the file extension. If it decides not to handle this search, it
  9892. should just return nil to give other functions a chance. If it
  9893. does handle the search, it must return a non-nil value to keep
  9894. other functions from trying.
  9895. Each function can access the current prefix argument through the
  9896. variable `current-prefix-arg'. Note that a single prefix is used
  9897. to force opening a link in Emacs, so it may be good to only use a
  9898. numeric or double prefix to guide the search function.
  9899. In case this is needed, a function in this hook can also restore
  9900. the window configuration before `org-open-at-point' was called using:
  9901. (set-window-configuration org-window-config-before-follow-link)")
  9902. (defun org-search-radio-target (target)
  9903. "Search a radio target matching TARGET in current buffer.
  9904. White spaces are not significant."
  9905. (let ((re (format "<<<%s>>>"
  9906. (mapconcat #'regexp-quote
  9907. (org-split-string target "[ \t\n]+")
  9908. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9909. (origin (point)))
  9910. (goto-char (point-min))
  9911. (catch :radio-match
  9912. (while (re-search-forward re nil t)
  9913. (backward-char)
  9914. (let ((object (org-element-context)))
  9915. (when (eq (org-element-type object) 'radio-target)
  9916. (goto-char (org-element-property :begin object))
  9917. (org-show-context 'link-search)
  9918. (throw :radio-match nil))))
  9919. (goto-char origin)
  9920. (user-error "No match for radio target: %s" target))))
  9921. (defun org-link-search (s &optional avoid-pos stealth)
  9922. "Search for a search string S.
  9923. If S starts with \"#\", it triggers a custom ID search.
  9924. If S is enclosed within parenthesis, it initiates a coderef
  9925. search.
  9926. If S is surrounded by forward slashes, it is interpreted as
  9927. a regular expression. In Org mode files, this will create an
  9928. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9929. to list matches. If the current buffer is in `dired-mode', grep
  9930. will be used to search in all files.
  9931. When AVOID-POS is given, ignore matches near that position.
  9932. When optional argument STEALTH is non-nil, do not modify
  9933. visibility around point, thus ignoring `org-show-context-detail'
  9934. variable.
  9935. Search is case-insensitive and ignores white spaces. Return type
  9936. of matched result, which is either `dedicated' or `fuzzy'."
  9937. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9938. (let* ((case-fold-search t)
  9939. (origin (point))
  9940. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9941. (starred (eq (string-to-char normalized) ?*))
  9942. (words (split-string (if starred (substring s 1) s)))
  9943. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9944. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9945. type)
  9946. (cond
  9947. ;; Check if there are any special search functions.
  9948. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9949. ((eq (string-to-char s) ?#)
  9950. ;; Look for a custom ID S if S starts with "#".
  9951. (let* ((id (substring normalized 1))
  9952. (match (org-find-property "CUSTOM_ID" id)))
  9953. (if match (progn (goto-char match) (setf type 'dedicated))
  9954. (error "No match for custom ID: %s" id))))
  9955. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9956. ;; Look for coderef targets if S is enclosed within parenthesis.
  9957. (let ((coderef (match-string-no-properties 1 normalized))
  9958. (re (substring s-single-re 1 -1)))
  9959. (goto-char (point-min))
  9960. (catch :coderef-match
  9961. (while (re-search-forward re nil t)
  9962. (let ((element (org-element-at-point)))
  9963. (when (and (memq (org-element-type element)
  9964. '(example-block src-block))
  9965. ;; Build proper regexp according to current
  9966. ;; block's label format.
  9967. (let ((label-fmt
  9968. (regexp-quote
  9969. (or (org-element-property :label-fmt element)
  9970. org-coderef-label-format))))
  9971. (save-excursion
  9972. (beginning-of-line)
  9973. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9974. (format label-fmt coderef))))))
  9975. (setq type 'dedicated)
  9976. (goto-char (match-beginning 1))
  9977. (throw :coderef-match nil))))
  9978. (goto-char origin)
  9979. (error "No match for coderef: %s" coderef))))
  9980. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9981. ;; Look for a regular expression.
  9982. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9983. (match-string 1 s)))
  9984. ;; From here, we handle fuzzy links.
  9985. ;;
  9986. ;; Look for targets, only if not in a headline search.
  9987. ((and (not starred)
  9988. (let ((target (format "<<%s>>" s-multi-re)))
  9989. (catch :target-match
  9990. (goto-char (point-min))
  9991. (while (re-search-forward target nil t)
  9992. (backward-char)
  9993. (let ((context (org-element-context)))
  9994. (when (eq (org-element-type context) 'target)
  9995. (setq type 'dedicated)
  9996. (goto-char (org-element-property :begin context))
  9997. (throw :target-match t))))
  9998. nil))))
  9999. ;; Look for elements named after S, only if not in a headline
  10000. ;; search.
  10001. ((and (not starred)
  10002. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10003. (catch :name-match
  10004. (goto-char (point-min))
  10005. (while (re-search-forward name nil t)
  10006. (let ((element (org-element-at-point)))
  10007. (when (equal words
  10008. (split-string
  10009. (org-element-property :name element)))
  10010. (setq type 'dedicated)
  10011. (beginning-of-line)
  10012. (throw :name-match t))))
  10013. nil))))
  10014. ;; Regular text search. Prefer headlines in Org mode buffers.
  10015. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  10016. ;; statistics cookies and tags.
  10017. ((and (derived-mode-p 'org-mode)
  10018. (let ((title-re
  10019. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  10020. org-outline-regexp-bol
  10021. org-comment-string
  10022. (mapconcat #'regexp-quote words ".+")))
  10023. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  10024. (comment-re (format "\\`%s[ \t]+" org-comment-string)))
  10025. (goto-char (point-min))
  10026. (catch :found
  10027. (while (re-search-forward title-re nil t)
  10028. (when (equal words
  10029. (split-string
  10030. (replace-regexp-in-string
  10031. cookie-re ""
  10032. (replace-regexp-in-string
  10033. comment-re "" (org-get-heading t t)))))
  10034. (throw :found t)))
  10035. nil)))
  10036. (beginning-of-line)
  10037. (setq type 'dedicated))
  10038. ;; Offer to create non-existent headline depending on
  10039. ;; `org-link-search-must-match-exact-headline'.
  10040. ((and (derived-mode-p 'org-mode)
  10041. (not org-link-search-inhibit-query)
  10042. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10043. (yes-or-no-p "No match - create this as a new heading? "))
  10044. (goto-char (point-max))
  10045. (unless (bolp) (newline))
  10046. (org-insert-heading nil t t)
  10047. (insert s "\n")
  10048. (beginning-of-line 0))
  10049. ;; Only headlines are looked after. No need to process
  10050. ;; further: throw an error.
  10051. ((and (derived-mode-p 'org-mode)
  10052. (or starred org-link-search-must-match-exact-headline))
  10053. (goto-char origin)
  10054. (error "No match for fuzzy expression: %s" normalized))
  10055. ;; Regular text search.
  10056. ((catch :fuzzy-match
  10057. (goto-char (point-min))
  10058. (while (re-search-forward s-multi-re nil t)
  10059. ;; Skip match if it contains AVOID-POS or it is included in
  10060. ;; a link with a description but outside the description.
  10061. (unless (or (and avoid-pos
  10062. (<= (match-beginning 0) avoid-pos)
  10063. (> (match-end 0) avoid-pos))
  10064. (and (save-match-data
  10065. (org-in-regexp org-bracket-link-regexp))
  10066. (match-beginning 3)
  10067. (or (> (match-beginning 3) (point))
  10068. (<= (match-end 3) (point)))
  10069. (org-element-lineage
  10070. (save-match-data (org-element-context))
  10071. '(link) t)))
  10072. (goto-char (match-beginning 0))
  10073. (setq type 'fuzzy)
  10074. (throw :fuzzy-match t)))
  10075. nil))
  10076. ;; All failed. Throw an error.
  10077. (t (goto-char origin)
  10078. (error "No match for fuzzy expression: %s" normalized)))
  10079. ;; Disclose surroundings of match, if appropriate.
  10080. (when (and (derived-mode-p 'org-mode) (not stealth))
  10081. (org-show-context 'link-search))
  10082. type))
  10083. (defun org-get-buffer-for-internal-link (buffer)
  10084. "Return a buffer to be used for displaying the link target of internal links."
  10085. (cond
  10086. ((not org-display-internal-link-with-indirect-buffer)
  10087. buffer)
  10088. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10089. (message "Buffer is already a clone, not making another one")
  10090. ;; we also do not modify visibility in this case
  10091. buffer)
  10092. (t ; make a new indirect buffer for displaying the link
  10093. (let* ((bn (buffer-name buffer))
  10094. (ibn (concat bn "(Clone)"))
  10095. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10096. (with-current-buffer ib (org-overview))
  10097. ib))))
  10098. (defun org-do-occur (regexp &optional cleanup)
  10099. "Call the Emacs command `occur'.
  10100. If CLEANUP is non-nil, remove the printout of the regular expression
  10101. in the *Occur* buffer. This is useful if the regex is long and not useful
  10102. to read."
  10103. (occur regexp)
  10104. (when cleanup
  10105. (let ((cwin (selected-window)) win beg end)
  10106. (when (setq win (get-buffer-window "*Occur*"))
  10107. (select-window win))
  10108. (goto-char (point-min))
  10109. (when (re-search-forward "match[a-z]+" nil t)
  10110. (setq beg (match-end 0))
  10111. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10112. (setq end (1- (match-beginning 0)))))
  10113. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10114. (goto-char (point-min))
  10115. (select-window cwin))))
  10116. ;;; The mark ring for links jumps
  10117. (defvar org-mark-ring nil
  10118. "Mark ring for positions before jumps in Org mode.")
  10119. (defvar org-mark-ring-last-goto nil
  10120. "Last position in the mark ring used to go back.")
  10121. ;; Fill and close the ring
  10122. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10123. (dotimes (_ org-mark-ring-length)
  10124. (push (make-marker) org-mark-ring))
  10125. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10126. org-mark-ring)
  10127. (defun org-mark-ring-push (&optional pos buffer)
  10128. "Put the current position or POS into the mark ring and rotate it."
  10129. (interactive)
  10130. (setq pos (or pos (point)))
  10131. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10132. (move-marker (car org-mark-ring)
  10133. (or pos (point))
  10134. (or buffer (current-buffer)))
  10135. (message "%s"
  10136. (substitute-command-keys
  10137. "Position saved to mark ring, go back with \
  10138. `\\[org-mark-ring-goto]'.")))
  10139. (defun org-mark-ring-goto (&optional n)
  10140. "Jump to the previous position in the mark ring.
  10141. With prefix arg N, jump back that many stored positions. When
  10142. called several times in succession, walk through the entire ring.
  10143. Org mode commands jumping to a different position in the current file,
  10144. or to another Org file, automatically push the old position onto the ring."
  10145. (interactive "p")
  10146. (let (p m)
  10147. (if (eq last-command this-command)
  10148. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10149. (setq p org-mark-ring))
  10150. (setq org-mark-ring-last-goto p)
  10151. (setq m (car p))
  10152. (pop-to-buffer-same-window (marker-buffer m))
  10153. (goto-char m)
  10154. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10155. (defun org-add-angle-brackets (s)
  10156. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10157. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10158. s)
  10159. ;;; Following specific links
  10160. (defvar org-agenda-buffer-tmp-name)
  10161. (defvar org-agenda-start-on-weekday)
  10162. (defun org-follow-timestamp-link ()
  10163. "Open an agenda view for the time-stamp date/range at point."
  10164. (cond
  10165. ((org-at-date-range-p t)
  10166. (let ((org-agenda-start-on-weekday)
  10167. (t1 (match-string 1))
  10168. (t2 (match-string 2)) tt1 tt2)
  10169. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10170. tt2 (time-to-days (org-time-string-to-time t2)))
  10171. (let ((org-agenda-buffer-tmp-name
  10172. (format "*Org Agenda(a:%s)"
  10173. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10174. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10175. ((org-at-timestamp-p t)
  10176. (let ((org-agenda-buffer-tmp-name
  10177. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10178. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10179. (substring (match-string 1) 0 10)))
  10180. 1)))
  10181. (t (error "This should not happen"))))
  10182. ;;; Following file links
  10183. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10184. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10185. (declare-function mailcap-mime-info
  10186. "mailcap" (string &optional request no-decode))
  10187. (defvar org-wait nil)
  10188. (defun org-open-file (path &optional in-emacs line search)
  10189. "Open the file at PATH.
  10190. First, this expands any special file name abbreviations. Then the
  10191. configuration variable `org-file-apps' is checked if it contains an
  10192. entry for this file type, and if yes, the corresponding command is launched.
  10193. If no application is found, Emacs simply visits the file.
  10194. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10195. With a double \\[universal-argument] \\[universal-argument] \
  10196. prefix arg, Org tries to avoid opening in Emacs
  10197. and to use an external application to visit the file.
  10198. Optional LINE specifies a line to go to, optional SEARCH a string
  10199. to search for. If LINE or SEARCH is given, the file will be
  10200. opened in Emacs, unless an entry from org-file-apps that makes
  10201. use of groups in a regexp matches.
  10202. If you want to change the way frames are used when following a
  10203. link, please customize `org-link-frame-setup'.
  10204. If the file does not exist, an error is thrown."
  10205. (let* ((file (if (equal path "")
  10206. buffer-file-name
  10207. (substitute-in-file-name (expand-file-name path))))
  10208. (file-apps (append org-file-apps (org-default-apps)))
  10209. (apps (cl-remove-if
  10210. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10211. (apps-dlink (cl-remove-if-not
  10212. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10213. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10214. (dirp (unless remp (file-directory-p file)))
  10215. (file (if (and dirp org-open-directory-means-index-dot-org)
  10216. (concat (file-name-as-directory file) "index.org")
  10217. file))
  10218. (a-m-a-p (assq 'auto-mode apps))
  10219. (dfile (downcase file))
  10220. ;; Reconstruct the original link from the PATH, LINE and
  10221. ;; SEARCH args.
  10222. (link (cond (line (concat file "::" (number-to-string line)))
  10223. (search (concat file "::" search))
  10224. (t file)))
  10225. (dlink (downcase link))
  10226. (old-buffer (current-buffer))
  10227. (old-pos (point))
  10228. (old-mode major-mode)
  10229. (ext
  10230. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10231. (match-string 1 dfile)))
  10232. cmd link-match-data)
  10233. (cond
  10234. ((member in-emacs '((16) system))
  10235. (setq cmd (cdr (assq 'system apps))))
  10236. (in-emacs (setq cmd 'emacs))
  10237. (t
  10238. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10239. (and dirp (cdr (assq 'directory apps)))
  10240. ;; First, try matching against apps-dlink if we
  10241. ;; get a match here, store the match data for
  10242. ;; later.
  10243. (let ((match (assoc-default dlink apps-dlink
  10244. 'string-match)))
  10245. (if match
  10246. (progn (setq link-match-data (match-data))
  10247. match)
  10248. (progn (setq in-emacs (or in-emacs line search))
  10249. nil))) ; if we have no match in apps-dlink,
  10250. ; always open the file in emacs if line or search
  10251. ; is given (for backwards compatibility)
  10252. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10253. 'string-match)
  10254. (cdr (assoc ext apps))
  10255. (cdr (assq t apps))))))
  10256. (when (eq cmd 'system)
  10257. (setq cmd (cdr (assq 'system apps))))
  10258. (when (eq cmd 'default)
  10259. (setq cmd (cdr (assoc t apps))))
  10260. (when (eq cmd 'mailcap)
  10261. (require 'mailcap)
  10262. (mailcap-parse-mailcaps)
  10263. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10264. (command (mailcap-mime-info mime-type)))
  10265. (if (stringp command)
  10266. (setq cmd command)
  10267. (setq cmd 'emacs))))
  10268. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10269. (not (file-exists-p file))
  10270. (not org-open-non-existing-files))
  10271. (user-error "No such file: %s" file))
  10272. (cond
  10273. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10274. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10275. (while (string-match "['\"]%s['\"]" cmd)
  10276. (setq cmd (replace-match "%s" t t cmd)))
  10277. (setq cmd (replace-regexp-in-string
  10278. "%s"
  10279. (shell-quote-argument (convert-standard-filename file))
  10280. cmd
  10281. nil t))
  10282. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10283. (save-match-data
  10284. (let ((match-index 1)
  10285. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10286. (set-match-data link-match-data)
  10287. (while (<= match-index number-of-groups)
  10288. (let ((regex (concat "%" (number-to-string match-index)))
  10289. (replace-with (match-string match-index dlink)))
  10290. (while (string-match regex cmd)
  10291. (setq cmd (replace-match replace-with t t cmd))))
  10292. (setq match-index (+ match-index 1)))))
  10293. (save-window-excursion
  10294. (message "Running %s...done" cmd)
  10295. (start-process-shell-command cmd nil cmd)
  10296. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10297. ((or (stringp cmd)
  10298. (eq cmd 'emacs))
  10299. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10300. (widen)
  10301. (cond (line (org-goto-line line)
  10302. (when (derived-mode-p 'org-mode) (org-reveal)))
  10303. (search (org-link-search search))))
  10304. ((functionp cmd)
  10305. (save-match-data
  10306. (set-match-data link-match-data)
  10307. (condition-case nil
  10308. (funcall cmd file link)
  10309. ;; FIXME: Remove this check when most default installations
  10310. ;; of Emacs have at least Org 9.0.
  10311. ((debug wrong-number-of-arguments wrong-type-argument
  10312. invalid-function)
  10313. (user-error "Please see Org News for version 9.0 about \
  10314. `org-file-apps'--Lisp error: %S" cmd)))))
  10315. ((consp cmd)
  10316. ;; FIXME: Remove this check when most default installations of
  10317. ;; Emacs have at least Org 9.0.
  10318. ;; Heads-up instead of silently fall back to
  10319. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10320. ;; with sexp instead of a function for `cmd'.
  10321. (user-error "Please see Org News for version 9.0 about \
  10322. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10323. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10324. (and (derived-mode-p 'org-mode)
  10325. (eq old-mode 'org-mode)
  10326. (or (not (eq old-buffer (current-buffer)))
  10327. (not (eq old-pos (point))))
  10328. (org-mark-ring-push old-pos old-buffer))))
  10329. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10330. "This function returns non-nil if `entry' uses a regular
  10331. expression which should be matched against the whole link by
  10332. org-open-file.
  10333. It assumes that is the case when the entry uses a regular
  10334. expression which has at least one grouping construct and the
  10335. action is either a lisp form or a command string containing
  10336. `%1', i.e. using at least one subexpression match as a
  10337. parameter."
  10338. (let ((selector (car entry))
  10339. (action (cdr entry)))
  10340. (if (stringp selector)
  10341. (and (> (regexp-opt-depth selector) 0)
  10342. (or (and (stringp action)
  10343. (string-match "%[0-9]" action))
  10344. (consp action)))
  10345. nil)))
  10346. (defun org-default-apps ()
  10347. "Return the default applications for this operating system."
  10348. (cond
  10349. ((eq system-type 'darwin)
  10350. org-file-apps-defaults-macosx)
  10351. ((eq system-type 'windows-nt)
  10352. org-file-apps-defaults-windowsnt)
  10353. (t org-file-apps-defaults-gnu)))
  10354. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10355. "Convert extensions to regular expressions in the cars of LIST.
  10356. Also, weed out any non-string entries, because the return value is used
  10357. only for regexp matching.
  10358. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10359. point to the symbol `emacs', indicating that the file should
  10360. be opened in Emacs."
  10361. (append
  10362. (delq nil
  10363. (mapcar (lambda (x)
  10364. (unless (not (stringp (car x)))
  10365. (if (string-match "\\W" (car x))
  10366. x
  10367. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10368. list))
  10369. (when add-auto-mode
  10370. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10371. (defvar ange-ftp-name-format)
  10372. (defun org-file-remote-p (file)
  10373. "Test whether FILE specifies a location on a remote system.
  10374. Return non-nil if the location is indeed remote.
  10375. For example, the filename \"/user@host:/foo\" specifies a location
  10376. on the system \"/user@host:\"."
  10377. (cond ((fboundp 'file-remote-p)
  10378. (file-remote-p file))
  10379. ((fboundp 'tramp-handle-file-remote-p)
  10380. (tramp-handle-file-remote-p file))
  10381. ((and (boundp 'ange-ftp-name-format)
  10382. (string-match (car ange-ftp-name-format) file))
  10383. t)))
  10384. ;;;; Refiling
  10385. (defun org-get-org-file ()
  10386. "Read a filename, with default directory `org-directory'."
  10387. (let ((default (or org-default-notes-file remember-data-file)))
  10388. (read-file-name (format "File name [%s]: " default)
  10389. (file-name-as-directory org-directory)
  10390. default)))
  10391. (defun org-notes-order-reversed-p ()
  10392. "Check if the current file should receive notes in reversed order."
  10393. (cond
  10394. ((not org-reverse-note-order) nil)
  10395. ((eq t org-reverse-note-order) t)
  10396. ((not (listp org-reverse-note-order)) nil)
  10397. (t (catch 'exit
  10398. (dolist (entry org-reverse-note-order)
  10399. (when (string-match (car entry) buffer-file-name)
  10400. (throw 'exit (cdr entry))))))))
  10401. (defvar org-refile-target-table nil
  10402. "The list of refile targets, created by `org-refile'.")
  10403. (defvar org-agenda-new-buffers nil
  10404. "Buffers created to visit agenda files.")
  10405. (defvar org-refile-cache nil
  10406. "Cache for refile targets.")
  10407. (defvar org-refile-markers nil
  10408. "All the markers used for caching refile locations.")
  10409. (defun org-refile-marker (pos)
  10410. "Get a new refile marker, but only if caching is in use."
  10411. (if (not org-refile-use-cache)
  10412. pos
  10413. (let ((m (make-marker)))
  10414. (move-marker m pos)
  10415. (push m org-refile-markers)
  10416. m)))
  10417. (defun org-refile-cache-clear ()
  10418. "Clear the refile cache and disable all the markers."
  10419. (dolist (m org-refile-markers) (move-marker m nil))
  10420. (setq org-refile-markers nil)
  10421. (setq org-refile-cache nil)
  10422. (message "Refile cache has been cleared"))
  10423. (defun org-refile-cache-check-set (set)
  10424. "Check if all the markers in the cache still have live buffers."
  10425. (let (marker)
  10426. (catch 'exit
  10427. (while (and set (setq marker (nth 3 (pop set))))
  10428. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10429. (when (and marker (null (marker-buffer marker)))
  10430. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10431. (sit-for 3)
  10432. (throw 'exit nil)))
  10433. t)))
  10434. (defun org-refile-cache-put (set &rest identifiers)
  10435. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10436. (let* ((key (sha1 (prin1-to-string identifiers)))
  10437. (entry (assoc key org-refile-cache)))
  10438. (if entry
  10439. (setcdr entry set)
  10440. (push (cons key set) org-refile-cache))))
  10441. (defun org-refile-cache-get (&rest identifiers)
  10442. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10443. (cond
  10444. ((not org-refile-cache) nil)
  10445. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10446. (t
  10447. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10448. org-refile-cache))))
  10449. (and set (org-refile-cache-check-set set) set)))))
  10450. (defvar org-outline-path-cache nil
  10451. "Alist between buffer positions and outline paths.
  10452. It value is an alist (POSITION . PATH) where POSITION is the
  10453. buffer position at the beginning of an entry and PATH is a list
  10454. of strings describing the outline path for that entry, in reverse
  10455. order.")
  10456. (defun org-refile-get-targets (&optional default-buffer)
  10457. "Produce a table with refile targets."
  10458. (let ((case-fold-search nil)
  10459. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10460. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10461. targets tgs files desc descre)
  10462. (message "Getting targets...")
  10463. (with-current-buffer (or default-buffer (current-buffer))
  10464. (dolist (entry entries)
  10465. (setq files (car entry) desc (cdr entry))
  10466. (cond
  10467. ((null files) (setq files (list (current-buffer))))
  10468. ((eq files 'org-agenda-files)
  10469. (setq files (org-agenda-files 'unrestricted)))
  10470. ((and (symbolp files) (fboundp files))
  10471. (setq files (funcall files)))
  10472. ((and (symbolp files) (boundp files))
  10473. (setq files (symbol-value files))))
  10474. (when (stringp files) (setq files (list files)))
  10475. (cond
  10476. ((eq (car desc) :tag)
  10477. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10478. ((eq (car desc) :todo)
  10479. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10480. ((eq (car desc) :regexp)
  10481. (setq descre (cdr desc)))
  10482. ((eq (car desc) :level)
  10483. (setq descre (concat "^\\*\\{" (number-to-string
  10484. (if org-odd-levels-only
  10485. (1- (* 2 (cdr desc)))
  10486. (cdr desc)))
  10487. "\\}[ \t]")))
  10488. ((eq (car desc) :maxlevel)
  10489. (setq descre (concat "^\\*\\{1," (number-to-string
  10490. (if org-odd-levels-only
  10491. (1- (* 2 (cdr desc)))
  10492. (cdr desc)))
  10493. "\\}[ \t]")))
  10494. (t (error "Bad refiling target description %s" desc)))
  10495. (dolist (f files)
  10496. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10497. (or
  10498. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10499. (progn
  10500. (when (bufferp f)
  10501. (setq f (buffer-file-name (buffer-base-buffer f))))
  10502. (setq f (and f (expand-file-name f)))
  10503. (when (eq org-refile-use-outline-path 'file)
  10504. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10505. (org-with-wide-buffer
  10506. (goto-char (point-min))
  10507. (setq org-outline-path-cache nil)
  10508. (while (re-search-forward descre nil t)
  10509. (beginning-of-line)
  10510. (let ((case-fold-search nil))
  10511. (looking-at org-complex-heading-regexp))
  10512. (let ((begin (point))
  10513. (heading (match-string-no-properties 4)))
  10514. (unless (or (and
  10515. org-refile-target-verify-function
  10516. (not
  10517. (funcall org-refile-target-verify-function)))
  10518. (not heading))
  10519. (let ((re (format org-complex-heading-regexp-format
  10520. (regexp-quote heading)))
  10521. (target
  10522. (if (not org-refile-use-outline-path) heading
  10523. (mapconcat
  10524. #'org-protect-slash
  10525. (append
  10526. (pcase org-refile-use-outline-path
  10527. (`file (list (file-name-nondirectory
  10528. (buffer-file-name
  10529. (buffer-base-buffer)))))
  10530. (`full-file-path
  10531. (list (buffer-file-name
  10532. (buffer-base-buffer))))
  10533. (_ nil))
  10534. (org-get-outline-path t t))
  10535. "/"))))
  10536. (push (list target f re (org-refile-marker (point)))
  10537. tgs)))
  10538. (when (= (point) begin)
  10539. ;; Verification function has not moved point.
  10540. (end-of-line)))))))
  10541. (when org-refile-use-cache
  10542. (org-refile-cache-put tgs (buffer-file-name) descre))
  10543. (setq targets (append tgs targets))))))
  10544. (message "Getting targets...done")
  10545. (delete-dups (nreverse targets))))
  10546. (defun org-protect-slash (s)
  10547. (replace-regexp-in-string "/" "\\/" s nil t))
  10548. (defun org--get-outline-path-1 (&optional use-cache)
  10549. "Return outline path to current headline.
  10550. Outline path is a list of strings, in reverse order. When
  10551. optional argument USE-CACHE is non-nil, make use of a cache. See
  10552. `org-get-outline-path' for details.
  10553. Assume buffer is widened and point is on a headline."
  10554. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10555. (let ((p (point))
  10556. (heading (let ((case-fold-search nil))
  10557. (looking-at org-complex-heading-regexp)
  10558. (if (not (match-end 4)) ""
  10559. ;; Remove statistics cookies.
  10560. (org-trim
  10561. (org-link-display-format
  10562. (replace-regexp-in-string
  10563. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10564. (match-string-no-properties 4))))))))
  10565. (if (org-up-heading-safe)
  10566. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10567. (when use-cache
  10568. (push (cons p path) org-outline-path-cache))
  10569. path)
  10570. ;; This is a new root node. Since we assume we are moving
  10571. ;; forward, we can drop previous cache so as to limit number
  10572. ;; of associations there.
  10573. (let ((path (list heading)))
  10574. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10575. path)))))
  10576. (defun org-get-outline-path (&optional with-self use-cache)
  10577. "Return the outline path to the current entry.
  10578. An outline path is a list of ancestors for current headline, as
  10579. a list of strings. Statistics cookies are removed and links are
  10580. replaced with their description, if any, or their path otherwise.
  10581. When optional argument WITH-SELF is non-nil, the path also
  10582. includes the current headline.
  10583. When optional argument USE-CACHE is non-nil, cache outline paths
  10584. between calls to this function so as to avoid backtracking. This
  10585. argument is useful when planning to find more than one outline
  10586. path in the same document. In that case, there are two
  10587. conditions to satisfy:
  10588. - `org-outline-path-cache' is set to nil before starting the
  10589. process;
  10590. - outline paths are computed by increasing buffer positions."
  10591. (org-with-wide-buffer
  10592. (and (or (and with-self (org-back-to-heading t))
  10593. (org-up-heading-safe))
  10594. (reverse (org--get-outline-path-1 use-cache)))))
  10595. (defun org-format-outline-path (path &optional width prefix separator)
  10596. "Format the outline path PATH for display.
  10597. WIDTH is the maximum number of characters that is available.
  10598. PREFIX is a prefix to be included in the returned string,
  10599. such as the file name.
  10600. SEPARATOR is inserted between the different parts of the path,
  10601. the default is \"/\"."
  10602. (setq width (or width 79))
  10603. (setq path (delq nil path))
  10604. (unless (> width 0)
  10605. (user-error "Argument `width' must be positive"))
  10606. (setq separator (or separator "/"))
  10607. (let* ((org-odd-levels-only nil)
  10608. (fpath (concat
  10609. prefix (and prefix path separator)
  10610. (mapconcat
  10611. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10612. (cl-loop for head in path
  10613. for n from 0
  10614. collect (org-add-props
  10615. head nil 'face
  10616. (nth (% n org-n-level-faces) org-level-faces)))
  10617. separator))))
  10618. (when (> (length fpath) width)
  10619. (if (< width 7)
  10620. ;; It's unlikely that `width' will be this small, but don't
  10621. ;; waste characters by adding ".." if it is.
  10622. (setq fpath (substring fpath 0 width))
  10623. (setf (substring fpath (- width 2)) "..")))
  10624. fpath))
  10625. (defun org-display-outline-path (&optional file current separator just-return-string)
  10626. "Display the current outline path in the echo area.
  10627. If FILE is non-nil, prepend the output with the file name.
  10628. If CURRENT is non-nil, append the current heading to the output.
  10629. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10630. the different parts of the path and defaults to \"/\".
  10631. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10632. (interactive "P")
  10633. (let* (case-fold-search
  10634. (bfn (buffer-file-name (buffer-base-buffer)))
  10635. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10636. res)
  10637. (when current (setq path (append path
  10638. (save-excursion
  10639. (org-back-to-heading t)
  10640. (when (looking-at org-complex-heading-regexp)
  10641. (list (match-string 4)))))))
  10642. (setq res
  10643. (org-format-outline-path
  10644. path
  10645. (1- (frame-width))
  10646. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10647. separator))
  10648. (if just-return-string
  10649. (org-no-properties res)
  10650. (org-unlogged-message "%s" res))))
  10651. (defvar org-refile-history nil
  10652. "History for refiling operations.")
  10653. (defvar org-after-refile-insert-hook nil
  10654. "Hook run after `org-refile' has inserted its stuff at the new location.
  10655. Note that this is still *before* the stuff will be removed from
  10656. the *old* location.")
  10657. (defvar org-capture-last-stored-marker)
  10658. (defvar org-refile-keep nil
  10659. "Non-nil means `org-refile' will copy instead of refile.")
  10660. (defun org-copy ()
  10661. "Like `org-refile', but copy."
  10662. (interactive)
  10663. (let ((org-refile-keep t))
  10664. (funcall 'org-refile nil nil nil "Copy")))
  10665. (defun org-refile (&optional arg default-buffer rfloc msg)
  10666. "Move the entry or entries at point to another heading.
  10667. The list of target headings is compiled using the information in
  10668. `org-refile-targets', which see.
  10669. At the target location, the entry is filed as a subitem of the
  10670. target heading. Depending on `org-reverse-note-order', the new
  10671. subitem will either be the first or the last subitem.
  10672. If there is an active region, all entries in that region will be
  10673. refiled. However, the region must fulfill the requirement that
  10674. the first heading sets the top-level of the moved text.
  10675. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10676. location
  10677. and not actually move anything.
  10678. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10679. location where the last
  10680. refiling operation has put the subtree.
  10681. With a numeric prefix argument of `2', refile to the running clock.
  10682. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10683. being set to t and copy to the target location, don't move it.
  10684. Beware that keeping refiled entries may result in duplicated ID
  10685. properties.
  10686. RFLOC can be a refile location obtained in a different way.
  10687. MSG is a string to replace \"Refile\" in the default prompt with
  10688. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10689. See also `org-refile-use-outline-path'.
  10690. If you are using target caching (see `org-refile-use-cache'), you
  10691. have to clear the target cache in order to find new targets.
  10692. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10693. prefix argument (`C-u C-u C-u C-c C-w')."
  10694. (interactive "P")
  10695. (if (member arg '(0 (64)))
  10696. (org-refile-cache-clear)
  10697. (let* ((actionmsg (cond (msg msg)
  10698. ((equal arg 3) "Refile (and keep)")
  10699. (t "Refile")))
  10700. (regionp (org-region-active-p))
  10701. (region-start (and regionp (region-beginning)))
  10702. (region-end (and regionp (region-end)))
  10703. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10704. pos it nbuf file level reversed)
  10705. (setq last-command nil)
  10706. (when regionp
  10707. (goto-char region-start)
  10708. (or (bolp) (goto-char (point-at-bol)))
  10709. (setq region-start (point))
  10710. (unless (or (org-kill-is-subtree-p
  10711. (buffer-substring region-start region-end))
  10712. (prog1 org-refile-active-region-within-subtree
  10713. (let ((s (point-at-eol)))
  10714. (org-toggle-heading)
  10715. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10716. (user-error "The region is not a (sequence of) subtree(s)")))
  10717. (if (equal arg '(16))
  10718. (org-refile-goto-last-stored)
  10719. (when (or
  10720. (and (equal arg 2)
  10721. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10722. (prog1
  10723. (setq it (list (or org-clock-heading "running clock")
  10724. (buffer-file-name
  10725. (marker-buffer org-clock-hd-marker))
  10726. ""
  10727. (marker-position org-clock-hd-marker)))
  10728. (setq arg nil)))
  10729. (setq it
  10730. (or rfloc
  10731. (let (heading-text)
  10732. (save-excursion
  10733. (unless (and arg (listp arg))
  10734. (org-back-to-heading t)
  10735. (setq heading-text
  10736. (replace-regexp-in-string
  10737. org-bracket-link-regexp
  10738. "\\3"
  10739. (or (nth 4 (org-heading-components))
  10740. ""))))
  10741. (org-refile-get-location
  10742. (cond ((and arg (listp arg)) "Goto")
  10743. (regionp (concat actionmsg " region to"))
  10744. (t (concat actionmsg " subtree \""
  10745. heading-text "\" to")))
  10746. default-buffer
  10747. (and (not (equal '(4) arg))
  10748. org-refile-allow-creating-parent-nodes)))))))
  10749. (setq file (nth 1 it)
  10750. pos (nth 3 it))
  10751. (when (and (not arg)
  10752. pos
  10753. (equal (buffer-file-name) file)
  10754. (if regionp
  10755. (and (>= pos region-start)
  10756. (<= pos region-end))
  10757. (and (>= pos (point))
  10758. (< pos (save-excursion
  10759. (org-end-of-subtree t t))))))
  10760. (error "Cannot refile to position inside the tree or region"))
  10761. (setq nbuf (or (find-buffer-visiting file)
  10762. (find-file-noselect file)))
  10763. (if (and arg (not (equal arg 3)))
  10764. (progn
  10765. (pop-to-buffer-same-window nbuf)
  10766. (goto-char pos)
  10767. (org-show-context 'org-goto))
  10768. (if regionp
  10769. (progn
  10770. (org-kill-new (buffer-substring region-start region-end))
  10771. (org-save-markers-in-region region-start region-end))
  10772. (org-copy-subtree 1 nil t))
  10773. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10774. (find-file-noselect file)))
  10775. (setq reversed (org-notes-order-reversed-p))
  10776. (org-with-wide-buffer
  10777. (if pos
  10778. (progn
  10779. (goto-char pos)
  10780. (looking-at org-outline-regexp)
  10781. (setq level (org-get-valid-level (funcall outline-level) 1))
  10782. (goto-char
  10783. (if reversed
  10784. (or (outline-next-heading) (point-max))
  10785. (or (save-excursion (org-get-next-sibling))
  10786. (org-end-of-subtree t t)
  10787. (point-max)))))
  10788. (setq level 1)
  10789. (if (not reversed)
  10790. (goto-char (point-max))
  10791. (goto-char (point-min))
  10792. (or (outline-next-heading) (goto-char (point-max)))))
  10793. (unless (bolp) (newline))
  10794. (org-paste-subtree level nil nil t)
  10795. (when org-log-refile
  10796. (org-add-log-setup 'refile nil nil org-log-refile)
  10797. (unless (eq org-log-refile 'note)
  10798. (save-excursion (org-add-log-note))))
  10799. (and org-auto-align-tags
  10800. (let ((org-loop-over-headlines-in-active-region nil))
  10801. (org-set-tags nil t)))
  10802. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10803. :last-refile)))
  10804. (when bookmark-name
  10805. (with-demoted-errors
  10806. (bookmark-set bookmark-name))))
  10807. ;; If we are refiling for capture, make sure that the
  10808. ;; last-capture pointers point here
  10809. (when (bound-and-true-p org-capture-is-refiling)
  10810. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10811. :last-capture-marker)))
  10812. (when bookmark-name
  10813. (with-demoted-errors
  10814. (bookmark-set bookmark-name))))
  10815. (move-marker org-capture-last-stored-marker (point)))
  10816. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10817. (run-hooks 'org-after-refile-insert-hook)))
  10818. (unless org-refile-keep
  10819. (if regionp
  10820. (delete-region (point) (+ (point) (- region-end region-start)))
  10821. (delete-region
  10822. (and (org-back-to-heading t) (point))
  10823. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10824. (when (featurep 'org-inlinetask)
  10825. (org-inlinetask-remove-END-maybe))
  10826. (setq org-markers-to-move nil)
  10827. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10828. (defun org-refile-goto-last-stored ()
  10829. "Go to the location where the last refile was stored."
  10830. (interactive)
  10831. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10832. (message "This is the location of the last refile"))
  10833. (defun org-refile--get-location (refloc tbl)
  10834. "When user refile to REFLOC, find the associated target in TBL.
  10835. Also check `org-refile-target-table'."
  10836. (car (delq
  10837. nil
  10838. (mapcar
  10839. (lambda (r) (or (assoc r tbl)
  10840. (assoc r org-refile-target-table)))
  10841. (list (replace-regexp-in-string "/$" "" refloc)
  10842. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10843. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10844. "Prompt the user for a refile location, using PROMPT.
  10845. PROMPT should not be suffixed with a colon and a space, because
  10846. this function appends the default value from
  10847. `org-refile-history' automatically, if that is not empty."
  10848. (let ((org-refile-targets org-refile-targets)
  10849. (org-refile-use-outline-path org-refile-use-outline-path))
  10850. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10851. (unless org-refile-target-table
  10852. (user-error "No refile targets"))
  10853. (let* ((cbuf (current-buffer))
  10854. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10855. (cfunc (if (and org-refile-use-outline-path
  10856. org-outline-path-complete-in-steps)
  10857. #'org-olpath-completing-read
  10858. #'completing-read))
  10859. (extra (if org-refile-use-outline-path "/" ""))
  10860. (cbnex (concat (buffer-name) extra))
  10861. (filename (and cfn (expand-file-name cfn)))
  10862. (tbl (mapcar
  10863. (lambda (x)
  10864. (if (and (not (member org-refile-use-outline-path
  10865. '(file full-file-path)))
  10866. (not (equal filename (nth 1 x))))
  10867. (cons (concat (car x) extra " ("
  10868. (file-name-nondirectory (nth 1 x)) ")")
  10869. (cdr x))
  10870. (cons (concat (car x) extra) (cdr x))))
  10871. org-refile-target-table))
  10872. (completion-ignore-case t)
  10873. cdef
  10874. (prompt (concat prompt
  10875. (or (and (car org-refile-history)
  10876. (concat " (default " (car org-refile-history) ")"))
  10877. (and (assoc cbnex tbl) (setq cdef cbnex)
  10878. (concat " (default " cbnex ")"))) ": "))
  10879. pa answ parent-target child parent old-hist)
  10880. (setq old-hist org-refile-history)
  10881. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10882. nil 'org-refile-history (or cdef (car org-refile-history))))
  10883. (if (setq pa (org-refile--get-location answ tbl))
  10884. (progn
  10885. (org-refile-check-position pa)
  10886. (when (or (not org-refile-history)
  10887. (not (eq old-hist org-refile-history))
  10888. (not (equal (car pa) (car org-refile-history))))
  10889. (setq org-refile-history
  10890. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10891. org-refile-history
  10892. (cdr org-refile-history))))
  10893. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10894. (pop org-refile-history)))
  10895. pa)
  10896. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10897. (progn
  10898. (setq parent (match-string 1 answ)
  10899. child (match-string 2 answ))
  10900. (setq parent-target (org-refile--get-location parent tbl))
  10901. (when (and parent-target
  10902. (or (eq new-nodes t)
  10903. (and (eq new-nodes 'confirm)
  10904. (y-or-n-p (format "Create new node \"%s\"? "
  10905. child)))))
  10906. (org-refile-new-child parent-target child)))
  10907. (user-error "Invalid target location")))))
  10908. (declare-function org-string-nw-p "org-macs" (s))
  10909. (defun org-refile-check-position (refile-pointer)
  10910. "Check if the refile pointer matches the headline to which it points."
  10911. (let* ((file (nth 1 refile-pointer))
  10912. (re (nth 2 refile-pointer))
  10913. (pos (nth 3 refile-pointer))
  10914. buffer)
  10915. (if (and (not (markerp pos)) (not file))
  10916. (user-error "Please indicate a target file in the refile path")
  10917. (when (org-string-nw-p re)
  10918. (setq buffer (if (markerp pos)
  10919. (marker-buffer pos)
  10920. (or (find-buffer-visiting file)
  10921. (find-file-noselect file))))
  10922. (with-current-buffer buffer
  10923. (org-with-wide-buffer
  10924. (goto-char pos)
  10925. (beginning-of-line 1)
  10926. (unless (looking-at-p re)
  10927. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10928. (defun org-refile-new-child (parent-target child)
  10929. "Use refile target PARENT-TARGET to add new CHILD below it."
  10930. (unless parent-target
  10931. (error "Cannot find parent for new node"))
  10932. (let ((file (nth 1 parent-target))
  10933. (pos (nth 3 parent-target))
  10934. level)
  10935. (with-current-buffer (or (find-buffer-visiting file)
  10936. (find-file-noselect file))
  10937. (org-with-wide-buffer
  10938. (if pos
  10939. (goto-char pos)
  10940. (goto-char (point-max))
  10941. (unless (bolp) (newline)))
  10942. (when (looking-at org-outline-regexp)
  10943. (setq level (funcall outline-level))
  10944. (org-end-of-subtree t t))
  10945. (org-back-over-empty-lines)
  10946. (insert "\n" (make-string
  10947. (if pos (org-get-valid-level level 1) 1) ?*)
  10948. " " child "\n")
  10949. (beginning-of-line 0)
  10950. (list (concat (car parent-target) "/" child) file "" (point))))))
  10951. (defun org-olpath-completing-read (prompt collection &rest args)
  10952. "Read an outline path like a file name."
  10953. (let ((thetable collection))
  10954. (apply #'completing-read
  10955. prompt
  10956. (lambda (string predicate &optional flag)
  10957. (cond
  10958. ((eq flag nil) (try-completion string thetable))
  10959. ((eq flag t)
  10960. (let ((l (length string)))
  10961. (mapcar (lambda (x)
  10962. (let ((r (substring x l))
  10963. (f (if (string-match " ([^)]*)$" x)
  10964. (match-string 0 x)
  10965. "")))
  10966. (if (string-match "/" r)
  10967. (concat string (substring r 0 (match-end 0)) f)
  10968. x)))
  10969. (all-completions string thetable predicate))))
  10970. ;; Exact match?
  10971. ((eq flag 'lambda) (assoc string thetable))))
  10972. args)))
  10973. ;;;; Dynamic blocks
  10974. (defun org-find-dblock (name)
  10975. "Find the first dynamic block with name NAME in the buffer.
  10976. If not found, stay at current position and return nil."
  10977. (let ((case-fold-search t) pos)
  10978. (save-excursion
  10979. (goto-char (point-min))
  10980. (setq pos (and (re-search-forward
  10981. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10982. (match-beginning 0))))
  10983. (when pos (goto-char pos))
  10984. pos))
  10985. (defun org-create-dblock (plist)
  10986. "Create a dynamic block section, with parameters taken from PLIST.
  10987. PLIST must contain a :name entry which is used as the name of the block."
  10988. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10989. (end-of-line 1)
  10990. (newline))
  10991. (let ((col (current-column))
  10992. (name (plist-get plist :name)))
  10993. (insert "#+BEGIN: " name)
  10994. (while plist
  10995. (if (eq (car plist) :name)
  10996. (setq plist (cddr plist))
  10997. (insert " " (prin1-to-string (pop plist)))))
  10998. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10999. (beginning-of-line -2)))
  11000. (defun org-prepare-dblock ()
  11001. "Prepare dynamic block for refresh.
  11002. This empties the block, puts the cursor at the insert position and returns
  11003. the property list including an extra property :name with the block name."
  11004. (unless (looking-at org-dblock-start-re)
  11005. (user-error "Not at a dynamic block"))
  11006. (let* ((begdel (1+ (match-end 0)))
  11007. (name (org-no-properties (match-string 1)))
  11008. (params (append (list :name name)
  11009. (read (concat "(" (match-string 3) ")")))))
  11010. (save-excursion
  11011. (beginning-of-line 1)
  11012. (skip-chars-forward " \t")
  11013. (setq params (plist-put params :indentation-column (current-column))))
  11014. (unless (re-search-forward org-dblock-end-re nil t)
  11015. (error "Dynamic block not terminated"))
  11016. (setq params
  11017. (append params
  11018. (list :content (buffer-substring
  11019. begdel (match-beginning 0)))))
  11020. (delete-region begdel (match-beginning 0))
  11021. (goto-char begdel)
  11022. (open-line 1)
  11023. params))
  11024. (defun org-map-dblocks (&optional command)
  11025. "Apply COMMAND to all dynamic blocks in the current buffer.
  11026. If COMMAND is not given, use `org-update-dblock'."
  11027. (let ((cmd (or command 'org-update-dblock)))
  11028. (save-excursion
  11029. (goto-char (point-min))
  11030. (while (re-search-forward org-dblock-start-re nil t)
  11031. (goto-char (match-beginning 0))
  11032. (save-excursion
  11033. (condition-case nil
  11034. (funcall cmd)
  11035. (error (message "Error during update of dynamic block"))))
  11036. (unless (re-search-forward org-dblock-end-re nil t)
  11037. (error "Dynamic block not terminated"))))))
  11038. (defun org-dblock-update (&optional arg)
  11039. "User command for updating dynamic blocks.
  11040. Update the dynamic block at point. With prefix ARG, update all dynamic
  11041. blocks in the buffer."
  11042. (interactive "P")
  11043. (if arg
  11044. (org-update-all-dblocks)
  11045. (or (looking-at org-dblock-start-re)
  11046. (org-beginning-of-dblock))
  11047. (org-update-dblock)))
  11048. (defun org-update-dblock ()
  11049. "Update the dynamic block at point.
  11050. This means to empty the block, parse for parameters and then call
  11051. the correct writing function."
  11052. (interactive)
  11053. (save-excursion
  11054. (let* ((win (selected-window))
  11055. (pos (point))
  11056. (line (org-current-line))
  11057. (params (org-prepare-dblock))
  11058. (name (plist-get params :name))
  11059. (indent (plist-get params :indentation-column))
  11060. (cmd (intern (concat "org-dblock-write:" name))))
  11061. (message "Updating dynamic block `%s' at line %d..." name line)
  11062. (funcall cmd params)
  11063. (message "Updating dynamic block `%s' at line %d...done" name line)
  11064. (goto-char pos)
  11065. (when (and indent (> indent 0))
  11066. (setq indent (make-string indent ?\ ))
  11067. (save-excursion
  11068. (select-window win)
  11069. (org-beginning-of-dblock)
  11070. (forward-line 1)
  11071. (while (not (looking-at org-dblock-end-re))
  11072. (insert indent)
  11073. (beginning-of-line 2))
  11074. (when (looking-at org-dblock-end-re)
  11075. (and (looking-at "[ \t]+")
  11076. (replace-match ""))
  11077. (insert indent)))))))
  11078. (defun org-beginning-of-dblock ()
  11079. "Find the beginning of the dynamic block at point.
  11080. Error if there is no such block at point."
  11081. (let ((pos (point))
  11082. beg)
  11083. (end-of-line 1)
  11084. (if (and (re-search-backward org-dblock-start-re nil t)
  11085. (setq beg (match-beginning 0))
  11086. (re-search-forward org-dblock-end-re nil t)
  11087. (> (match-end 0) pos))
  11088. (goto-char beg)
  11089. (goto-char pos)
  11090. (error "Not in a dynamic block"))))
  11091. (defun org-update-all-dblocks ()
  11092. "Update all dynamic blocks in the buffer.
  11093. This function can be used in a hook."
  11094. (interactive)
  11095. (when (derived-mode-p 'org-mode)
  11096. (org-map-dblocks 'org-update-dblock)))
  11097. ;;;; Completion
  11098. (declare-function org-export-backend-options "ox" (cl-x) t)
  11099. (defun org-get-export-keywords ()
  11100. "Return a list of all currently understood export keywords.
  11101. Export keywords include options, block names, attributes and
  11102. keywords relative to each registered export back-end."
  11103. (let (keywords)
  11104. (dolist (backend
  11105. (bound-and-true-p org-export-registered-backends)
  11106. (delq nil keywords))
  11107. ;; Back-end name (for keywords, like #+LATEX:)
  11108. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11109. (dolist (option-entry (org-export-backend-options backend))
  11110. ;; Back-end options.
  11111. (push (nth 1 option-entry) keywords)))))
  11112. (defconst org-options-keywords
  11113. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11114. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11115. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11116. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11117. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11118. (defcustom org-structure-template-alist
  11119. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11120. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11121. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11122. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11123. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11124. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11125. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11126. ("L" "#+LaTeX: ")
  11127. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11128. ("H" "#+HTML: ")
  11129. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11130. ("A" "#+ASCII: ")
  11131. ("i" "#+INDEX: ?")
  11132. ("I" "#+INCLUDE: %file ?"))
  11133. "Structure completion elements.
  11134. This is a list of abbreviation keys and values. The value gets inserted
  11135. if you type `<' followed by the key and then press the completion key,
  11136. usually `TAB'. %file will be replaced by a file name after prompting
  11137. for the file using completion. The cursor will be placed at the position
  11138. of the `?' in the template.
  11139. There are two templates for each key, the first uses the original Org syntax,
  11140. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11141. the default when the /org-mtags.el/ module has been loaded. See also the
  11142. variable `org-mtags-prefer-muse-templates'."
  11143. :group 'org-completion
  11144. :type '(repeat
  11145. (list
  11146. (string :tag "Key")
  11147. (string :tag "Template")))
  11148. :version "26.1"
  11149. :package-version '(Org . "8.3"))
  11150. (defun org-try-structure-completion ()
  11151. "Try to complete a structure template before point.
  11152. This looks for strings like \"<e\" on an otherwise empty line and
  11153. expands them."
  11154. (let ((l (buffer-substring (point-at-bol) (point)))
  11155. a)
  11156. (when (and (looking-at "[ \t]*$")
  11157. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11158. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11159. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11160. (match-beginning 1)) a)
  11161. t)))
  11162. (defun org-complete-expand-structure-template (start cell)
  11163. "Expand a structure template."
  11164. (let ((rpl (nth 1 cell))
  11165. (ind ""))
  11166. (delete-region start (point))
  11167. (when (string-match "\\`[ \t]*#\\+" rpl)
  11168. (cond
  11169. ((bolp))
  11170. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11171. (setq ind (buffer-substring (point-at-bol) (point))))
  11172. (t (newline))))
  11173. (setq start (point))
  11174. (when (string-match "%file" rpl)
  11175. (setq rpl (replace-match
  11176. (concat
  11177. "\""
  11178. (save-match-data
  11179. (abbreviate-file-name (read-file-name "Include file: ")))
  11180. "\"")
  11181. t t rpl)))
  11182. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11183. (concat "\n" ind)))
  11184. (insert rpl)
  11185. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11186. ;;;; TODO, DEADLINE, Comments
  11187. (defun org-toggle-comment ()
  11188. "Change the COMMENT state of an entry."
  11189. (interactive)
  11190. (save-excursion
  11191. (org-back-to-heading)
  11192. (let ((case-fold-search nil))
  11193. (looking-at org-complex-heading-regexp))
  11194. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11195. (skip-chars-forward " \t")
  11196. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11197. (if (org-in-commented-heading-p t)
  11198. (delete-region (point)
  11199. (progn (search-forward " " (line-end-position) 'move)
  11200. (skip-chars-forward " \t")
  11201. (point)))
  11202. (insert org-comment-string)
  11203. (unless (eolp) (insert " ")))))
  11204. (defvar org-last-todo-state-is-todo nil
  11205. "This is non-nil when the last TODO state change led to a TODO state.
  11206. If the last change removed the TODO tag or switched to DONE, then
  11207. this is nil.")
  11208. (defvar org-setting-tags nil) ; dynamically skipped
  11209. (defvar org-todo-setup-filter-hook nil
  11210. "Hook for functions that pre-filter todo specs.
  11211. Each function takes a todo spec and returns either nil or the spec
  11212. transformed into canonical form." )
  11213. (defvar org-todo-get-default-hook nil
  11214. "Hook for functions that get a default item for todo.
  11215. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11216. nil or a string to be used for the todo mark." )
  11217. (defvar org-agenda-headline-snapshot-before-repeat)
  11218. (defun org-current-effective-time ()
  11219. "Return current time adjusted for `org-extend-today-until' variable."
  11220. (let* ((ct (org-current-time))
  11221. (dct (decode-time ct))
  11222. (ct1
  11223. (cond
  11224. (org-use-last-clock-out-time-as-effective-time
  11225. (or (org-clock-get-last-clock-out-time) ct))
  11226. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11227. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11228. (t ct))))
  11229. ct1))
  11230. (defun org-todo-yesterday (&optional arg)
  11231. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11232. (interactive "P")
  11233. (if (eq major-mode 'org-agenda-mode)
  11234. (apply 'org-agenda-todo-yesterday arg)
  11235. (let* ((org-use-effective-time t)
  11236. (hour (nth 2 (decode-time (org-current-time))))
  11237. (org-extend-today-until (1+ hour)))
  11238. (org-todo arg))))
  11239. (defvar org-block-entry-blocking ""
  11240. "First entry preventing the TODO state change.")
  11241. (defun org-cancel-repeater ()
  11242. "Cancel a repeater by setting its numeric value to zero."
  11243. (interactive)
  11244. (save-excursion
  11245. (org-back-to-heading t)
  11246. (let ((bound1 (point))
  11247. (bound0 (save-excursion (outline-next-heading) (point))))
  11248. (when (and (re-search-forward
  11249. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11250. org-deadline-time-regexp "\\)\\|\\("
  11251. org-ts-regexp "\\)")
  11252. bound0 t)
  11253. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11254. bound1 t))
  11255. (replace-match "0" t nil nil 1)))))
  11256. (defvar org-state)
  11257. (defvar org-blocked-by-checkboxes)
  11258. (defun org-todo (&optional arg)
  11259. "Change the TODO state of an item.
  11260. The state of an item is given by a keyword at the start of the heading,
  11261. like
  11262. *** TODO Write paper
  11263. *** DONE Call mom
  11264. The different keywords are specified in the variable `org-todo-keywords'.
  11265. By default the available states are \"TODO\" and \"DONE\". So, for this
  11266. example: when the item starts with TODO, it is changed to DONE.
  11267. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11268. DONE are present, add TODO at the beginning of the heading.
  11269. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11270. state.
  11271. With numeric prefix ARG, switch to that state.
  11272. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11273. next set of TODO \
  11274. keywords (nextset).
  11275. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11276. prefix, circumvent any state blocking.
  11277. With a numeric prefix arg of 0, inhibit note taking for the change.
  11278. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11279. When called through ELisp, arg is also interpreted in the following way:
  11280. `none' -> empty state
  11281. \"\" -> switch to empty state
  11282. `done' -> switch to DONE
  11283. `nextset' -> switch to the next set of keywords
  11284. `previousset' -> switch to the previous set of keywords
  11285. \"WAITING\" -> switch to the specified keyword, but only if it
  11286. really is a member of `org-todo-keywords'."
  11287. (interactive "P")
  11288. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11289. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11290. 'region-start-level 'region))
  11291. org-loop-over-headlines-in-active-region)
  11292. (org-map-entries
  11293. `(org-todo ,arg)
  11294. org-loop-over-headlines-in-active-region
  11295. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11296. (when (equal arg '(16)) (setq arg 'nextset))
  11297. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11298. (let ((org-blocker-hook org-blocker-hook)
  11299. commentp
  11300. case-fold-search)
  11301. (when (equal arg '(64))
  11302. (setq arg nil org-blocker-hook nil))
  11303. (when (and org-blocker-hook
  11304. (or org-inhibit-blocking
  11305. (org-entry-get nil "NOBLOCKING")))
  11306. (setq org-blocker-hook nil))
  11307. (save-excursion
  11308. (catch 'exit
  11309. (org-back-to-heading t)
  11310. (when (org-in-commented-heading-p t)
  11311. (org-toggle-comment)
  11312. (setq commentp t))
  11313. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11314. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11315. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11316. (let* ((match-data (match-data))
  11317. (startpos (point-at-bol))
  11318. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11319. (org-log-done org-log-done)
  11320. (org-log-repeat org-log-repeat)
  11321. (org-todo-log-states org-todo-log-states)
  11322. (org-inhibit-logging
  11323. (if (equal arg 0)
  11324. (progn (setq arg nil) 'note) org-inhibit-logging))
  11325. (this (match-string 1))
  11326. (hl-pos (match-beginning 0))
  11327. (head (org-get-todo-sequence-head this))
  11328. (ass (assoc head org-todo-kwd-alist))
  11329. (interpret (nth 1 ass))
  11330. (done-word (nth 3 ass))
  11331. (final-done-word (nth 4 ass))
  11332. (org-last-state (or this ""))
  11333. (completion-ignore-case t)
  11334. (member (member this org-todo-keywords-1))
  11335. (tail (cdr member))
  11336. (org-state (cond
  11337. ((and org-todo-key-trigger
  11338. (or (and (equal arg '(4))
  11339. (eq org-use-fast-todo-selection 'prefix))
  11340. (and (not arg) org-use-fast-todo-selection
  11341. (not (eq org-use-fast-todo-selection
  11342. 'prefix)))))
  11343. ;; Use fast selection.
  11344. (org-fast-todo-selection))
  11345. ((and (equal arg '(4))
  11346. (or (not org-use-fast-todo-selection)
  11347. (not org-todo-key-trigger)))
  11348. ;; Read a state with completion.
  11349. (completing-read
  11350. "State: " (mapcar #'list org-todo-keywords-1)
  11351. nil t))
  11352. ((eq arg 'right)
  11353. (if this
  11354. (if tail (car tail) nil)
  11355. (car org-todo-keywords-1)))
  11356. ((eq arg 'left)
  11357. (unless (equal member org-todo-keywords-1)
  11358. (if this
  11359. (nth (- (length org-todo-keywords-1)
  11360. (length tail) 2)
  11361. org-todo-keywords-1)
  11362. (org-last org-todo-keywords-1))))
  11363. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11364. (setq arg nil))) ;hack to fall back to cycling
  11365. (arg
  11366. ;; User or caller requests a specific state.
  11367. (cond
  11368. ((equal arg "") nil)
  11369. ((eq arg 'none) nil)
  11370. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11371. ((eq arg 'nextset)
  11372. (or (car (cdr (member head org-todo-heads)))
  11373. (car org-todo-heads)))
  11374. ((eq arg 'previousset)
  11375. (let ((org-todo-heads (reverse org-todo-heads)))
  11376. (or (car (cdr (member head org-todo-heads)))
  11377. (car org-todo-heads))))
  11378. ((car (member arg org-todo-keywords-1)))
  11379. ((stringp arg)
  11380. (user-error "State `%s' not valid in this file" arg))
  11381. ((nth (1- (prefix-numeric-value arg))
  11382. org-todo-keywords-1))))
  11383. ((null member) (or head (car org-todo-keywords-1)))
  11384. ((equal this final-done-word) nil) ;-> make empty
  11385. ((null tail) nil) ;-> first entry
  11386. ((memq interpret '(type priority))
  11387. (if (eq this-command last-command)
  11388. (car tail)
  11389. (if (> (length tail) 0)
  11390. (or done-word (car org-done-keywords))
  11391. nil)))
  11392. (t
  11393. (car tail))))
  11394. (org-state (or
  11395. (run-hook-with-args-until-success
  11396. 'org-todo-get-default-hook org-state org-last-state)
  11397. org-state))
  11398. (next (if org-state (concat " " org-state " ") " "))
  11399. (change-plist (list :type 'todo-state-change :from this :to org-state
  11400. :position startpos))
  11401. dolog now-done-p)
  11402. (when org-blocker-hook
  11403. (let (org-blocked-by-checkboxes block-reason)
  11404. (setq org-last-todo-state-is-todo
  11405. (not (member this org-done-keywords)))
  11406. (unless (save-excursion
  11407. (save-match-data
  11408. (org-with-wide-buffer
  11409. (run-hook-with-args-until-failure
  11410. 'org-blocker-hook change-plist))))
  11411. (setq block-reason (if org-blocked-by-checkboxes
  11412. "contained checkboxes"
  11413. (format "\"%s\"" org-block-entry-blocking)))
  11414. (if (called-interactively-p 'interactive)
  11415. (user-error "TODO state change from %s to %s blocked (by %s)"
  11416. this org-state block-reason)
  11417. ;; Fail silently.
  11418. (message "TODO state change from %s to %s blocked (by %s)"
  11419. this org-state block-reason)
  11420. (throw 'exit nil)))))
  11421. (store-match-data match-data)
  11422. (replace-match next t t)
  11423. (cond ((equal this org-state)
  11424. (message "TODO state was already %s" (org-trim next)))
  11425. ((not (pos-visible-in-window-p hl-pos))
  11426. (message "TODO state changed to %s" (org-trim next))))
  11427. (unless head
  11428. (setq head (org-get-todo-sequence-head org-state)
  11429. ass (assoc head org-todo-kwd-alist)
  11430. interpret (nth 1 ass)
  11431. done-word (nth 3 ass)
  11432. final-done-word (nth 4 ass)))
  11433. (when (memq arg '(nextset previousset))
  11434. (message "Keyword-Set %d/%d: %s"
  11435. (- (length org-todo-sets) -1
  11436. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11437. (length org-todo-sets)
  11438. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11439. (setq org-last-todo-state-is-todo
  11440. (not (member org-state org-done-keywords)))
  11441. (setq now-done-p (and (member org-state org-done-keywords)
  11442. (not (member this org-done-keywords))))
  11443. (and logging (org-local-logging logging))
  11444. (when (and (or org-todo-log-states org-log-done)
  11445. (not (eq org-inhibit-logging t))
  11446. (not (memq arg '(nextset previousset))))
  11447. ;; We need to look at recording a time and note.
  11448. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11449. (nth 2 (assoc this org-todo-log-states))))
  11450. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11451. (setq dolog 'time))
  11452. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11453. (and org-state
  11454. (member org-state org-not-done-keywords)
  11455. (not (member this org-not-done-keywords))))
  11456. ;; This is now a todo state and was not one before
  11457. ;; If there was a CLOSED time stamp, get rid of it.
  11458. (org-add-planning-info nil nil 'closed))
  11459. (when (and now-done-p org-log-done)
  11460. ;; It is now done, and it was not done before.
  11461. (org-add-planning-info 'closed (org-current-effective-time))
  11462. (when (and (not dolog) (eq 'note org-log-done))
  11463. (org-add-log-setup 'done org-state this 'note)))
  11464. (when (and org-state dolog)
  11465. ;; This is a non-nil state, and we need to log it.
  11466. (org-add-log-setup 'state org-state this dolog)))
  11467. ;; Fixup tag positioning.
  11468. (org-todo-trigger-tag-changes org-state)
  11469. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11470. (when org-provide-todo-statistics
  11471. (org-update-parent-todo-statistics))
  11472. (run-hooks 'org-after-todo-state-change-hook)
  11473. (when (and arg (not (member org-state org-done-keywords)))
  11474. (setq head (org-get-todo-sequence-head org-state)))
  11475. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11476. ;; Do we need to trigger a repeat?
  11477. (when now-done-p
  11478. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11479. ;; This is for the agenda, take a snapshot of the headline.
  11480. (save-match-data
  11481. (setq org-agenda-headline-snapshot-before-repeat
  11482. (org-get-heading))))
  11483. (org-auto-repeat-maybe org-state))
  11484. ;; Fixup cursor location if close to the keyword.
  11485. (when (and (outline-on-heading-p)
  11486. (not (bolp))
  11487. (save-excursion (beginning-of-line 1)
  11488. (looking-at org-todo-line-regexp))
  11489. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11490. (goto-char (or (match-end 2) (match-end 1)))
  11491. (and (looking-at " ") (just-one-space)))
  11492. (when org-trigger-hook
  11493. (save-excursion
  11494. (run-hook-with-args 'org-trigger-hook change-plist)))
  11495. (when commentp (org-toggle-comment))))))))
  11496. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11497. "Block turning an entry into a TODO, using the hierarchy.
  11498. This checks whether the current task should be blocked from state
  11499. changes. Such blocking occurs when:
  11500. 1. The task has children which are not all in a completed state.
  11501. 2. A task has a parent with the property :ORDERED:, and there
  11502. are siblings prior to the current task with incomplete
  11503. status.
  11504. 3. The parent of the task is blocked because it has siblings that should
  11505. be done first, or is child of a block grandparent TODO entry."
  11506. (if (not org-enforce-todo-dependencies)
  11507. t ; if locally turned off don't block
  11508. (catch 'dont-block
  11509. ;; If this is not a todo state change, or if this entry is already DONE,
  11510. ;; do not block
  11511. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11512. (member (plist-get change-plist :from)
  11513. (cons 'done org-done-keywords))
  11514. (member (plist-get change-plist :to)
  11515. (cons 'todo org-not-done-keywords))
  11516. (not (plist-get change-plist :to)))
  11517. (throw 'dont-block t))
  11518. ;; If this task has children, and any are undone, it's blocked
  11519. (save-excursion
  11520. (org-back-to-heading t)
  11521. (let ((this-level (funcall outline-level)))
  11522. (outline-next-heading)
  11523. (let ((child-level (funcall outline-level)))
  11524. (while (and (not (eobp))
  11525. (> child-level this-level))
  11526. ;; this todo has children, check whether they are all
  11527. ;; completed
  11528. (when (and (not (org-entry-is-done-p))
  11529. (org-entry-is-todo-p))
  11530. (setq org-block-entry-blocking (org-get-heading))
  11531. (throw 'dont-block nil))
  11532. (outline-next-heading)
  11533. (setq child-level (funcall outline-level))))))
  11534. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11535. ;; any previous siblings are undone, it's blocked
  11536. (save-excursion
  11537. (org-back-to-heading t)
  11538. (let* ((pos (point))
  11539. (parent-pos (and (org-up-heading-safe) (point)))
  11540. (case-fold-search nil))
  11541. (unless parent-pos (throw 'dont-block t)) ; no parent
  11542. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11543. (forward-line 1)
  11544. (re-search-forward org-not-done-heading-regexp pos t))
  11545. (setq org-block-entry-blocking (match-string 0))
  11546. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11547. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11548. (while t
  11549. (goto-char parent-pos)
  11550. (unless (looking-at org-not-done-heading-regexp)
  11551. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11552. (setq pos (point))
  11553. (setq parent-pos (and (org-up-heading-safe) (point)))
  11554. (unless parent-pos (throw 'dont-block t)) ; no parent
  11555. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11556. (forward-line 1)
  11557. (re-search-forward org-not-done-heading-regexp pos t)
  11558. (setq org-block-entry-blocking (org-get-heading)))
  11559. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11560. (defcustom org-track-ordered-property-with-tag nil
  11561. "Should the ORDERED property also be shown as a tag?
  11562. The ORDERED property decides if an entry should require subtasks to be
  11563. completed in sequence. Since a property is not very visible, setting
  11564. this option means that toggling the ORDERED property with the command
  11565. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11566. not relevant for the behavior, but it makes things more visible.
  11567. Note that toggling the tag with tags commands will not change the property
  11568. and therefore not influence behavior!
  11569. This can be t, meaning the tag ORDERED should be used, It can also be a
  11570. string to select a different tag for this task."
  11571. :group 'org-todo
  11572. :type '(choice
  11573. (const :tag "No tracking" nil)
  11574. (const :tag "Track with ORDERED tag" t)
  11575. (string :tag "Use other tag")))
  11576. (defun org-toggle-ordered-property ()
  11577. "Toggle the ORDERED property of the current entry.
  11578. For better visibility, you can track the value of this property with a tag.
  11579. See variable `org-track-ordered-property-with-tag'."
  11580. (interactive)
  11581. (let* ((t1 org-track-ordered-property-with-tag)
  11582. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11583. (save-excursion
  11584. (org-back-to-heading)
  11585. (if (org-entry-get nil "ORDERED")
  11586. (progn
  11587. (org-delete-property "ORDERED")
  11588. (and tag (org-toggle-tag tag 'off))
  11589. (message "Subtasks can be completed in arbitrary order"))
  11590. (org-entry-put nil "ORDERED" "t")
  11591. (and tag (org-toggle-tag tag 'on))
  11592. (message "Subtasks must be completed in sequence")))))
  11593. (defun org-block-todo-from-checkboxes (change-plist)
  11594. "Block turning an entry into a TODO, using checkboxes.
  11595. This checks whether the current task should be blocked from state
  11596. changes because there are unchecked boxes in this entry."
  11597. (if (not org-enforce-todo-checkbox-dependencies)
  11598. t ; if locally turned off don't block
  11599. (catch 'dont-block
  11600. ;; If this is not a todo state change, or if this entry is already DONE,
  11601. ;; do not block
  11602. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11603. (member (plist-get change-plist :from)
  11604. (cons 'done org-done-keywords))
  11605. (member (plist-get change-plist :to)
  11606. (cons 'todo org-not-done-keywords))
  11607. (not (plist-get change-plist :to)))
  11608. (throw 'dont-block t))
  11609. ;; If this task has checkboxes that are not checked, it's blocked
  11610. (save-excursion
  11611. (org-back-to-heading t)
  11612. (let ((beg (point)) end)
  11613. (outline-next-heading)
  11614. (setq end (point))
  11615. (goto-char beg)
  11616. (when (org-list-search-forward
  11617. (concat (org-item-beginning-re)
  11618. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11619. "\\[[- ]\\]")
  11620. end t)
  11621. (when (boundp 'org-blocked-by-checkboxes)
  11622. (setq org-blocked-by-checkboxes t))
  11623. (throw 'dont-block nil))))
  11624. t))) ; do not block
  11625. (defun org-entry-blocked-p ()
  11626. "Non-nil if entry at point is blocked."
  11627. (and (not (org-entry-get nil "NOBLOCKING"))
  11628. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11629. (not (run-hook-with-args-until-failure
  11630. 'org-blocker-hook
  11631. (list :type 'todo-state-change
  11632. :position (point)
  11633. :from 'todo
  11634. :to 'done)))))
  11635. (defun org-update-statistics-cookies (all)
  11636. "Update the statistics cookie, either from TODO or from checkboxes.
  11637. This should be called with the cursor in a line with a statistics
  11638. cookie. When called with a \\[universal-argument] prefix, update
  11639. all statistics cookies in the buffer."
  11640. (interactive "P")
  11641. (if all
  11642. (progn
  11643. (org-update-checkbox-count 'all)
  11644. (org-map-entries 'org-update-parent-todo-statistics))
  11645. (if (not (org-at-heading-p))
  11646. (org-update-checkbox-count)
  11647. (let ((pos (point-marker))
  11648. end l1 l2)
  11649. (ignore-errors (org-back-to-heading t))
  11650. (if (not (org-at-heading-p))
  11651. (org-update-checkbox-count)
  11652. (setq l1 (org-outline-level))
  11653. (setq end (save-excursion
  11654. (outline-next-heading)
  11655. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11656. (point)))
  11657. (if (and (save-excursion
  11658. (re-search-forward
  11659. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11660. (not (save-excursion (re-search-forward
  11661. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11662. (org-update-checkbox-count)
  11663. (if (and l2 (> l2 l1))
  11664. (progn
  11665. (goto-char end)
  11666. (org-update-parent-todo-statistics))
  11667. (goto-char pos)
  11668. (beginning-of-line 1)
  11669. (while (re-search-forward
  11670. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11671. (point-at-eol) t)
  11672. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11673. (goto-char pos)
  11674. (move-marker pos nil)))))
  11675. (defvar org-entry-property-inherited-from) ;; defined below
  11676. (defun org-update-parent-todo-statistics ()
  11677. "Update any statistics cookie in the parent of the current headline.
  11678. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11679. the entire subtree and this will travel up the hierarchy and update
  11680. statistics everywhere."
  11681. (let* ((prop (save-excursion (org-up-heading-safe)
  11682. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11683. (recursive (or (not org-hierarchical-todo-statistics)
  11684. (and prop (string-match "\\<recursive\\>" prop))))
  11685. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11686. 0))
  11687. (first t)
  11688. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11689. level ltoggle l1 new ndel
  11690. (cnt-all 0) (cnt-done 0) is-percent kwd
  11691. checkbox-beg cookie-present)
  11692. (catch 'exit
  11693. (save-excursion
  11694. (beginning-of-line 1)
  11695. (setq ltoggle (funcall outline-level))
  11696. ;; Three situations are to consider:
  11697. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11698. ;; to the top-level ancestor on the headline;
  11699. ;; 2. If parent has "recursive" property, repeat up to the
  11700. ;; headline setting that property, taking inheritance into
  11701. ;; account;
  11702. ;; 3. Else, move up to direct parent and proceed only once.
  11703. (while (and (setq level (org-up-heading-safe))
  11704. (or recursive first)
  11705. (>= (point) lim))
  11706. (setq first nil cookie-present nil)
  11707. (unless (and level
  11708. (not (string-match
  11709. "\\<checkbox\\>"
  11710. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11711. "")))))
  11712. (throw 'exit nil))
  11713. (while (re-search-forward box-re (point-at-eol) t)
  11714. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11715. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11716. (save-match-data
  11717. (unless (outline-next-heading) (throw 'exit nil))
  11718. (while (and (looking-at org-complex-heading-regexp)
  11719. (> (setq l1 (length (match-string 1))) level))
  11720. (setq kwd (and (or recursive (= l1 ltoggle))
  11721. (match-string 2)))
  11722. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11723. (and (eq org-provide-todo-statistics t)
  11724. (or (member kwd org-done-keywords)))
  11725. (and (listp org-provide-todo-statistics)
  11726. (stringp (car org-provide-todo-statistics))
  11727. (or (member kwd org-provide-todo-statistics)
  11728. (member kwd org-done-keywords)))
  11729. (and (listp org-provide-todo-statistics)
  11730. (listp (car org-provide-todo-statistics))
  11731. (or (member kwd (car org-provide-todo-statistics))
  11732. (and (member kwd org-done-keywords)
  11733. (member kwd (cadr org-provide-todo-statistics))))))
  11734. (setq cnt-all (1+ cnt-all))
  11735. (and (eq org-provide-todo-statistics t)
  11736. kwd
  11737. (setq cnt-all (1+ cnt-all))))
  11738. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11739. (member kwd org-done-keywords))
  11740. (and (listp org-provide-todo-statistics)
  11741. (listp (car org-provide-todo-statistics))
  11742. (member kwd org-done-keywords)
  11743. (member kwd (cadr org-provide-todo-statistics)))
  11744. (and (listp org-provide-todo-statistics)
  11745. (stringp (car org-provide-todo-statistics))
  11746. (member kwd org-done-keywords)))
  11747. (setq cnt-done (1+ cnt-done)))
  11748. (outline-next-heading)))
  11749. (setq new
  11750. (if is-percent
  11751. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11752. (max 1 cnt-all)))
  11753. (format "[%d/%d]" cnt-done cnt-all))
  11754. ndel (- (match-end 0) checkbox-beg))
  11755. (goto-char checkbox-beg)
  11756. (insert new)
  11757. (delete-region (point) (+ (point) ndel))
  11758. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11759. (when cookie-present
  11760. (run-hook-with-args 'org-after-todo-statistics-hook
  11761. cnt-done (- cnt-all cnt-done))))))
  11762. (run-hooks 'org-todo-statistics-hook)))
  11763. (defvar org-after-todo-statistics-hook nil
  11764. "Hook that is called after a TODO statistics cookie has been updated.
  11765. Each function is called with two arguments: the number of not-done entries
  11766. and the number of done entries.
  11767. For example, the following function, when added to this hook, will switch
  11768. an entry to DONE when all children are done, and back to TODO when new
  11769. entries are set to a TODO status. Note that this hook is only called
  11770. when there is a statistics cookie in the headline!
  11771. (defun org-summary-todo (n-done n-not-done)
  11772. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11773. (let (org-log-done org-log-states) ; turn off logging
  11774. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11775. ")
  11776. (defvar org-todo-statistics-hook nil
  11777. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11778. This hook runs even if there is no statistics cookie present, in which case
  11779. `org-after-todo-statistics-hook' would not run.")
  11780. (defun org-todo-trigger-tag-changes (state)
  11781. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11782. (let ((l org-todo-state-tags-triggers)
  11783. changes)
  11784. (when (or (not state) (equal state ""))
  11785. (setq changes (append changes (cdr (assoc "" l)))))
  11786. (when (and (stringp state) (> (length state) 0))
  11787. (setq changes (append changes (cdr (assoc state l)))))
  11788. (when (member state org-not-done-keywords)
  11789. (setq changes (append changes (cdr (assq 'todo l)))))
  11790. (when (member state org-done-keywords)
  11791. (setq changes (append changes (cdr (assq 'done l)))))
  11792. (dolist (c changes)
  11793. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11794. (defun org-local-logging (value)
  11795. "Get logging settings from a property VALUE."
  11796. ;; Directly set the variables, they are already local.
  11797. (setq org-log-done nil
  11798. org-log-repeat nil
  11799. org-todo-log-states nil)
  11800. (dolist (w (org-split-string value))
  11801. (let (a)
  11802. (cond
  11803. ((setq a (assoc w org-startup-options))
  11804. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11805. (set (nth 1 a) (nth 2 a))))
  11806. ((setq a (org-extract-log-state-settings w))
  11807. (and (member (car a) org-todo-keywords-1)
  11808. (push a org-todo-log-states)))))))
  11809. (defun org-get-todo-sequence-head (kwd)
  11810. "Return the head of the TODO sequence to which KWD belongs.
  11811. If KWD is not set, check if there is a text property remembering the
  11812. right sequence."
  11813. (let (p)
  11814. (cond
  11815. ((not kwd)
  11816. (or (get-text-property (point-at-bol) 'org-todo-head)
  11817. (progn
  11818. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11819. nil (point-at-eol)))
  11820. (get-text-property p 'org-todo-head))))
  11821. ((not (member kwd org-todo-keywords-1))
  11822. (car org-todo-keywords-1))
  11823. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11824. (defun org-fast-todo-selection ()
  11825. "Fast TODO keyword selection with single keys.
  11826. Returns the new TODO keyword, or nil if no state change should occur."
  11827. (let* ((fulltable org-todo-key-alist)
  11828. (done-keywords org-done-keywords) ;; needed for the faces.
  11829. (maxlen (apply 'max (mapcar
  11830. (lambda (x)
  11831. (if (stringp (car x)) (string-width (car x)) 0))
  11832. fulltable)))
  11833. (expert nil)
  11834. (fwidth (+ maxlen 3 1 3))
  11835. (ncol (/ (- (window-width) 4) fwidth))
  11836. tg cnt e c tbl
  11837. groups ingroup)
  11838. (save-excursion
  11839. (save-window-excursion
  11840. (if expert
  11841. (set-buffer (get-buffer-create " *Org todo*"))
  11842. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11843. (erase-buffer)
  11844. (setq-local org-done-keywords done-keywords)
  11845. (setq tbl fulltable cnt 0)
  11846. (while (setq e (pop tbl))
  11847. (cond
  11848. ((equal e '(:startgroup))
  11849. (push '() groups) (setq ingroup t)
  11850. (unless (= cnt 0)
  11851. (setq cnt 0)
  11852. (insert "\n"))
  11853. (insert "{ "))
  11854. ((equal e '(:endgroup))
  11855. (setq ingroup nil cnt 0)
  11856. (insert "}\n"))
  11857. ((equal e '(:newline))
  11858. (unless (= cnt 0)
  11859. (setq cnt 0)
  11860. (insert "\n")
  11861. (setq e (car tbl))
  11862. (while (equal (car tbl) '(:newline))
  11863. (insert "\n")
  11864. (setq tbl (cdr tbl)))))
  11865. (t
  11866. (setq tg (car e) c (cdr e))
  11867. (when ingroup (push tg (car groups)))
  11868. (setq tg (org-add-props tg nil 'face
  11869. (org-get-todo-face tg)))
  11870. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11871. (insert "[" c "] " tg (make-string
  11872. (- fwidth 4 (length tg)) ?\ ))
  11873. (when (= (setq cnt (1+ cnt)) ncol)
  11874. (insert "\n")
  11875. (when ingroup (insert " "))
  11876. (setq cnt 0)))))
  11877. (insert "\n")
  11878. (goto-char (point-min))
  11879. (unless expert (org-fit-window-to-buffer))
  11880. (message "[a-z..]:Set [SPC]:clear")
  11881. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11882. (cond
  11883. ((or (= c ?\C-g)
  11884. (and (= c ?q) (not (rassoc c fulltable))))
  11885. (setq quit-flag t))
  11886. ((= c ?\ ) nil)
  11887. ((setq e (rassoc c fulltable) tg (car e))
  11888. tg)
  11889. (t (setq quit-flag t)))))))
  11890. (defun org-entry-is-todo-p ()
  11891. (member (org-get-todo-state) org-not-done-keywords))
  11892. (defun org-entry-is-done-p ()
  11893. (member (org-get-todo-state) org-done-keywords))
  11894. (defun org-get-todo-state ()
  11895. "Return the TODO keyword of the current subtree."
  11896. (save-excursion
  11897. (org-back-to-heading t)
  11898. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11899. (match-end 2)
  11900. (match-string 2))))
  11901. (defun org-at-date-range-p (&optional inactive-ok)
  11902. "Non-nil if point is inside a date range.
  11903. When optional argument INACTIVE-OK is non-nil, also consider
  11904. inactive time ranges.
  11905. When this function returns a non-nil value, match data is set
  11906. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11907. on INACTIVE-OK."
  11908. (interactive)
  11909. (save-excursion
  11910. (catch 'exit
  11911. (let ((pos (point)))
  11912. (skip-chars-backward "^[<\r\n")
  11913. (skip-chars-backward "<[")
  11914. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11915. (>= (match-end 0) pos)
  11916. (throw 'exit t))
  11917. (skip-chars-backward "^<[\r\n")
  11918. (skip-chars-backward "<[")
  11919. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11920. (>= (match-end 0) pos)
  11921. (throw 'exit t)))
  11922. nil)))
  11923. (defun org-get-repeat (&optional tagline)
  11924. "Check if there is a deadline/schedule with repeater in this entry."
  11925. (save-match-data
  11926. (save-excursion
  11927. (org-back-to-heading t)
  11928. (and (re-search-forward (if tagline
  11929. (concat tagline "\\s-*" org-repeat-re)
  11930. org-repeat-re)
  11931. (org-entry-end-position) t)
  11932. (match-string-no-properties 1)))))
  11933. (defvar org-last-changed-timestamp)
  11934. (defvar org-last-inserted-timestamp)
  11935. (defvar org-log-post-message)
  11936. (defvar org-log-note-purpose)
  11937. (defvar org-log-note-how nil)
  11938. (defvar org-log-note-extra)
  11939. (defun org-auto-repeat-maybe (done-word)
  11940. "Check if the current headline contains a repeated time-stamp.
  11941. If yes, set TODO state back to what it was and change the base date
  11942. of repeating deadline/scheduled time stamps to new date.
  11943. This function is run automatically after each state change to a DONE state."
  11944. (let* ((repeat (org-get-repeat))
  11945. (aa (assoc org-last-state org-todo-kwd-alist))
  11946. (interpret (nth 1 aa))
  11947. (head (nth 2 aa))
  11948. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11949. (msg "Entry repeats: ")
  11950. (org-log-done nil)
  11951. (org-todo-log-states nil))
  11952. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11953. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11954. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11955. org-todo-repeat-to-state)))
  11956. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  11957. to-state)
  11958. ((eq interpret 'type) org-last-state)
  11959. (head)
  11960. (t 'none))))
  11961. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11962. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11963. (org-time-stamp-format t t))))
  11964. (when org-log-repeat
  11965. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11966. (memq 'org-add-log-note post-command-hook))
  11967. ;; We are already setup for some record.
  11968. (when (eq org-log-repeat 'note)
  11969. ;; Make sure we take a note, not only a time stamp.
  11970. (setq org-log-note-how 'note))
  11971. ;; Set up for taking a record.
  11972. (org-add-log-setup 'state
  11973. (or done-word (car org-done-keywords))
  11974. org-last-state
  11975. org-log-repeat)))
  11976. (org-back-to-heading t)
  11977. (org-add-planning-info nil nil 'closed)
  11978. (let ((end (save-excursion (outline-next-heading) (point)))
  11979. (planning-re (regexp-opt
  11980. (list org-scheduled-string org-deadline-string))))
  11981. (while (re-search-forward org-ts-regexp end t)
  11982. (let* ((ts (match-string 0))
  11983. (planning? (org-at-planning-p))
  11984. (type (if (not planning?) "Plain:"
  11985. (save-excursion
  11986. (re-search-backward
  11987. planning-re (line-beginning-position) t)
  11988. (match-string 0)))))
  11989. (cond
  11990. ;; Ignore fake time-stamps (e.g., within comments).
  11991. ((and (not planning?)
  11992. (not (org-at-property-p))
  11993. (not (eq 'timestamp
  11994. (org-element-type (save-excursion
  11995. (backward-char)
  11996. (org-element-context)))))))
  11997. ;; Time-stamps without a repeater are usually skipped.
  11998. ;; However, a SCHEDULED time-stamp without one is
  11999. ;; removed, as it is considered as no longer relevant.
  12000. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12001. (when (equal type org-scheduled-string)
  12002. (org-remove-timestamp-with-keyword type)))
  12003. (t
  12004. (let ((n (string-to-number (match-string 2 ts)))
  12005. (what (match-string 3 ts)))
  12006. (when (equal what "w") (setq n (* n 7) what "d"))
  12007. (when (and (equal what "h")
  12008. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12009. ts)))
  12010. (user-error
  12011. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12012. has been set"
  12013. n))
  12014. ;; Preparation, see if we need to modify the start
  12015. ;; date for the change.
  12016. (when (match-end 1)
  12017. (let ((time (save-match-data (org-time-string-to-time ts))))
  12018. (cond
  12019. ((equal (match-string 1 ts) ".")
  12020. ;; Shift starting date to today
  12021. (org-timestamp-change
  12022. (- (org-today) (time-to-days time))
  12023. 'day))
  12024. ((equal (match-string 1 ts) "+")
  12025. (let ((nshiftmax 10)
  12026. (nshift 0))
  12027. (while (or (= nshift 0)
  12028. (not (time-less-p (current-time) time)))
  12029. (when (= (cl-incf nshift) nshiftmax)
  12030. (or (y-or-n-p
  12031. (format "%d repeater intervals were not \
  12032. enough to shift date past today. Continue? "
  12033. nshift))
  12034. (user-error "Abort")))
  12035. (org-timestamp-change n (cdr (assoc what whata)))
  12036. (org-at-timestamp-p t)
  12037. (setq ts (match-string 1))
  12038. (setq time
  12039. (save-match-data
  12040. (org-time-string-to-time ts)))))
  12041. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12042. ;; Rematch, so that we have everything in place
  12043. ;; for the real shift.
  12044. (org-at-timestamp-p t)
  12045. (setq ts (match-string 1))
  12046. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12047. ts)))))
  12048. (save-excursion
  12049. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12050. (setq msg
  12051. (concat
  12052. msg type " " org-last-changed-timestamp " "))))))))
  12053. (setq org-log-post-message msg)
  12054. (message "%s" msg))))
  12055. (defun org-show-todo-tree (arg)
  12056. "Make a compact tree which shows all headlines marked with TODO.
  12057. The tree will show the lines where the regexp matches, and all higher
  12058. headlines above the match.
  12059. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12060. With a numeric prefix N, construct a sparse tree for the Nth element
  12061. of `org-todo-keywords-1'."
  12062. (interactive "P")
  12063. (let ((case-fold-search nil)
  12064. (kwd-re
  12065. (cond ((null arg) org-not-done-regexp)
  12066. ((equal arg '(4))
  12067. (let ((kwd
  12068. (completing-read "Keyword (or KWD1|KWD2|...): "
  12069. (mapcar #'list org-todo-keywords-1))))
  12070. (concat "\\("
  12071. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12072. "\\)\\>")))
  12073. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12074. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12075. org-todo-keywords-1)))
  12076. (t (user-error "Invalid prefix argument: %s" arg)))))
  12077. (message "%d TODO entries found"
  12078. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12079. (defun org--deadline-or-schedule (arg type time)
  12080. "Insert DEADLINE or SCHEDULE information in current entry.
  12081. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  12082. `org-schedule' for information about ARG and TIME arguments."
  12083. (let* ((deadline? (eq type 'deadline))
  12084. (keyword (if deadline? org-deadline-string org-scheduled-string))
  12085. (log (if deadline? org-log-redeadline org-log-reschedule))
  12086. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  12087. (old-date-time (and old-date (org-time-string-to-time old-date)))
  12088. ;; Save repeater cookie from either TIME or current scheduled
  12089. ;; time stamp. We are going to insert it back at the end of
  12090. ;; the process.
  12091. (repeater (or (and (org-string-nw-p time)
  12092. ;; We use `org-repeat-re' because we need
  12093. ;; to tell the difference between a real
  12094. ;; repeater and a time delta, e.g. "+2d".
  12095. (string-match org-repeat-re time)
  12096. (match-string 1 time))
  12097. (and (org-string-nw-p old-date)
  12098. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  12099. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  12100. old-date)
  12101. (match-string 1 old-date)))))
  12102. (pcase arg
  12103. (`(4)
  12104. (when (and old-date log)
  12105. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  12106. nil old-date log))
  12107. (org-remove-timestamp-with-keyword keyword)
  12108. (message (if deadline? "Item no longer has a deadline."
  12109. "Item is no longer scheduled.")))
  12110. (`(16)
  12111. (save-excursion
  12112. (org-back-to-heading t)
  12113. (let ((regexp (if deadline? org-deadline-time-regexp
  12114. org-scheduled-time-regexp)))
  12115. (if (not (re-search-forward regexp (line-end-position 2) t))
  12116. (user-error (if deadline? "No deadline information to update"
  12117. "No scheduled information to update"))
  12118. (let* ((rpl0 (match-string 1))
  12119. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  12120. (msg (if deadline? "Warn starting from" "Delay until")))
  12121. (replace-match
  12122. (concat keyword
  12123. " <" rpl
  12124. (format " -%dd"
  12125. (abs (- (time-to-days
  12126. (save-match-data
  12127. (org-read-date
  12128. nil t nil msg old-date-time)))
  12129. (time-to-days old-date-time))))
  12130. ">") t t))))))
  12131. (_
  12132. (org-add-planning-info type time 'closed)
  12133. (when (and old-date
  12134. log
  12135. (not (equal old-date org-last-inserted-timestamp)))
  12136. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  12137. org-last-inserted-timestamp
  12138. old-date
  12139. log))
  12140. (when repeater
  12141. (save-excursion
  12142. (org-back-to-heading t)
  12143. (when (re-search-forward
  12144. (concat keyword " " org-last-inserted-timestamp)
  12145. (line-end-position 2)
  12146. t)
  12147. (goto-char (1- (match-end 0)))
  12148. (insert " " repeater)
  12149. (setq org-last-inserted-timestamp
  12150. (concat (substring org-last-inserted-timestamp 0 -1)
  12151. " " repeater
  12152. (substring org-last-inserted-timestamp -1))))))
  12153. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12154. org-last-inserted-timestamp)))))
  12155. (defun org-deadline (arg &optional time)
  12156. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12157. With one universal prefix argument, remove any deadline from the item.
  12158. With two universal prefix arguments, prompt for a warning delay.
  12159. With argument TIME, set the deadline at the corresponding date. TIME
  12160. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12161. (interactive "P")
  12162. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12163. (org-map-entries
  12164. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12165. nil
  12166. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12167. 'region-start-level
  12168. 'region)
  12169. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12170. (org--deadline-or-schedule arg 'deadline time)))
  12171. (defun org-schedule (arg &optional time)
  12172. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12173. With one universal prefix argument, remove any scheduling date from the item.
  12174. With two universal prefix arguments, prompt for a delay cookie.
  12175. With argument TIME, scheduled at the corresponding date. TIME can
  12176. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12177. (interactive "P")
  12178. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12179. (org-map-entries
  12180. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12181. nil
  12182. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12183. 'region-start-level
  12184. 'region)
  12185. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12186. (org--deadline-or-schedule arg 'scheduled time)))
  12187. (defun org-get-scheduled-time (pom &optional inherit)
  12188. "Get the scheduled time as a time tuple, of a format suitable
  12189. for calling org-schedule with, or if there is no scheduling,
  12190. returns nil."
  12191. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12192. (when time
  12193. (apply 'encode-time (org-parse-time-string time)))))
  12194. (defun org-get-deadline-time (pom &optional inherit)
  12195. "Get the deadline as a time tuple, of a format suitable for
  12196. calling org-deadline with, or if there is no scheduling, returns
  12197. nil."
  12198. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12199. (when time
  12200. (apply 'encode-time (org-parse-time-string time)))))
  12201. (defun org-remove-timestamp-with-keyword (keyword)
  12202. "Remove all time stamps with KEYWORD in the current entry."
  12203. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12204. beg)
  12205. (save-excursion
  12206. (org-back-to-heading t)
  12207. (setq beg (point))
  12208. (outline-next-heading)
  12209. (while (re-search-backward re beg t)
  12210. (replace-match "")
  12211. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12212. (equal (char-before) ?\ ))
  12213. (backward-delete-char 1)
  12214. (when (string-match "^[ \t]*$" (buffer-substring
  12215. (point-at-bol) (point-at-eol)))
  12216. (delete-region (point-at-bol)
  12217. (min (point-max) (1+ (point-at-eol))))))))))
  12218. (defvar org-time-was-given) ; dynamically scoped parameter
  12219. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12220. (defun org-at-planning-p ()
  12221. "Non-nil when point is on a planning info line."
  12222. ;; This is as accurate and faster than `org-element-at-point' since
  12223. ;; planning info location is fixed in the section.
  12224. (org-with-wide-buffer
  12225. (beginning-of-line)
  12226. (and (looking-at-p org-planning-line-re)
  12227. (eq (point)
  12228. (ignore-errors
  12229. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12230. (org-back-to-heading t)
  12231. (org-with-limited-levels (org-back-to-heading t)))
  12232. (line-beginning-position 2))))))
  12233. (defun org-add-planning-info (what &optional time &rest remove)
  12234. "Insert new timestamp with keyword in the planning line.
  12235. WHAT indicates what kind of time stamp to add. It is a symbol
  12236. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12237. the time to use. If none is given, the user is prompted for
  12238. a date. REMOVE indicates what kind of entries to remove. An old
  12239. WHAT entry will also be removed."
  12240. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12241. (catch 'exit
  12242. (when (and (memq what '(scheduled deadline))
  12243. (or (not time)
  12244. (and (stringp time)
  12245. (string-match "^[-+]+[0-9]" time))))
  12246. ;; Try to get a default date/time from existing timestamp
  12247. (save-excursion
  12248. (org-back-to-heading t)
  12249. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12250. (when (re-search-forward (if (eq what 'scheduled)
  12251. org-scheduled-time-regexp
  12252. org-deadline-time-regexp)
  12253. end t)
  12254. (setq ts (match-string 1)
  12255. default-time (apply 'encode-time (org-parse-time-string ts))
  12256. default-input (and ts (org-get-compact-tod ts)))))))
  12257. (when what
  12258. (setq time
  12259. (if (stringp time)
  12260. ;; This is a string (relative or absolute), set
  12261. ;; proper date.
  12262. (apply #'encode-time
  12263. (org-read-date-analyze
  12264. time default-time (decode-time default-time)))
  12265. ;; If necessary, get the time from the user
  12266. (or time (org-read-date nil 'to-time nil nil
  12267. default-time default-input)))))
  12268. (org-with-wide-buffer
  12269. (org-back-to-heading t)
  12270. (forward-line)
  12271. (unless (bolp) (insert "\n"))
  12272. (cond ((looking-at-p org-planning-line-re)
  12273. ;; Move to current indentation.
  12274. (skip-chars-forward " \t")
  12275. ;; Check if we have to remove something.
  12276. (dolist (type (if what (cons what remove) remove))
  12277. (save-excursion
  12278. (when (re-search-forward
  12279. (cl-case type
  12280. (closed org-closed-time-regexp)
  12281. (deadline org-deadline-time-regexp)
  12282. (scheduled org-scheduled-time-regexp)
  12283. (otherwise
  12284. (error "Invalid planning type: %s" type)))
  12285. (line-end-position) t)
  12286. ;; Delete until next keyword or end of line.
  12287. (delete-region
  12288. (match-beginning 0)
  12289. (if (re-search-forward org-keyword-time-not-clock-regexp
  12290. (line-end-position)
  12291. t)
  12292. (match-beginning 0)
  12293. (line-end-position))))))
  12294. ;; If there is nothing more to add and no more keyword
  12295. ;; is left, remove the line completely.
  12296. (if (and (looking-at-p "[ \t]*$") (not what))
  12297. (delete-region (line-beginning-position)
  12298. (line-beginning-position 2))
  12299. ;; If we removed last keyword, do not leave trailing
  12300. ;; white space at the end of line.
  12301. (let ((p (point)))
  12302. (save-excursion
  12303. (end-of-line)
  12304. (unless (= (skip-chars-backward " \t" p) 0)
  12305. (delete-region (point) (line-end-position)))))))
  12306. ((not what) (throw 'exit nil)) ; Nothing to do.
  12307. (t (insert-before-markers "\n")
  12308. (backward-char 1)
  12309. (when org-adapt-indentation
  12310. (indent-to-column (1+ (org-outline-level))))))
  12311. (when what
  12312. ;; Insert planning keyword.
  12313. (insert (cl-case what
  12314. (closed org-closed-string)
  12315. (deadline org-deadline-string)
  12316. (scheduled org-scheduled-string)
  12317. (otherwise (error "Invalid planning type: %s" what)))
  12318. " ")
  12319. ;; Insert associated timestamp.
  12320. (let ((ts (org-insert-time-stamp
  12321. time
  12322. (or org-time-was-given
  12323. (and (eq what 'closed) org-log-done-with-time))
  12324. (eq what 'closed)
  12325. nil nil (list org-end-time-was-given))))
  12326. (unless (eolp) (insert " "))
  12327. ts))))))
  12328. (defvar org-log-note-marker (make-marker)
  12329. "Marker pointing at the entry where the note is to be inserted.")
  12330. (defvar org-log-note-purpose nil)
  12331. (defvar org-log-note-state nil)
  12332. (defvar org-log-note-previous-state nil)
  12333. (defvar org-log-note-extra nil)
  12334. (defvar org-log-note-window-configuration nil)
  12335. (defvar org-log-note-return-to (make-marker))
  12336. (defvar org-log-note-effective-time nil
  12337. "Remembered current time so that dynamically scoped
  12338. `org-extend-today-until' affects timestamps in state change log")
  12339. (defvar org-log-post-message nil
  12340. "Message to be displayed after a log note has been stored.
  12341. The auto-repeater uses this.")
  12342. (defun org-add-note ()
  12343. "Add a note to the current entry.
  12344. This is done in the same way as adding a state change note."
  12345. (interactive)
  12346. (org-add-log-setup 'note))
  12347. (defun org-log-beginning (&optional create)
  12348. "Return expected start of log notes in current entry.
  12349. When optional argument CREATE is non-nil, the function creates
  12350. a drawer to store notes, if necessary. Returned position ignores
  12351. narrowing."
  12352. (org-with-wide-buffer
  12353. (let ((drawer (org-log-into-drawer)))
  12354. (cond
  12355. (drawer
  12356. (org-end-of-meta-data)
  12357. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12358. (end (if (org-at-heading-p) (point)
  12359. (save-excursion (outline-next-heading) (point))))
  12360. (case-fold-search t))
  12361. (catch 'exit
  12362. ;; Try to find existing drawer.
  12363. (while (re-search-forward regexp end t)
  12364. (let ((element (org-element-at-point)))
  12365. (when (eq (org-element-type element) 'drawer)
  12366. (let ((cend (org-element-property :contents-end element)))
  12367. (when (and (not org-log-states-order-reversed) cend)
  12368. (goto-char cend)))
  12369. (throw 'exit nil))))
  12370. ;; No drawer found. Create one, if permitted.
  12371. (when create
  12372. (unless (bolp) (insert "\n"))
  12373. (let ((beg (point)))
  12374. (insert ":" drawer ":\n:END:\n")
  12375. (org-indent-region beg (point)))
  12376. (end-of-line -1)))))
  12377. (t
  12378. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12379. (skip-chars-forward " \t\n")
  12380. (beginning-of-line)
  12381. (unless org-log-states-order-reversed
  12382. (org-skip-over-state-notes)
  12383. (skip-chars-backward " \t\n")
  12384. (forward-line)))))
  12385. (if (bolp) (point) (line-beginning-position 2))))
  12386. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12387. "Set up the post command hook to take a note.
  12388. If this is about to TODO state change, the new state is expected in STATE.
  12389. HOW is an indicator what kind of note should be created.
  12390. EXTRA is additional text that will be inserted into the notes buffer."
  12391. (move-marker org-log-note-marker (point))
  12392. (setq org-log-note-purpose purpose
  12393. org-log-note-state state
  12394. org-log-note-previous-state prev-state
  12395. org-log-note-how how
  12396. org-log-note-extra extra
  12397. org-log-note-effective-time (org-current-effective-time))
  12398. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12399. (defun org-skip-over-state-notes ()
  12400. "Skip past the list of State notes in an entry."
  12401. (when (ignore-errors (goto-char (org-in-item-p)))
  12402. (let* ((struct (org-list-struct))
  12403. (prevs (org-list-prevs-alist struct))
  12404. (regexp
  12405. (concat "[ \t]*- +"
  12406. (replace-regexp-in-string
  12407. " +" " +"
  12408. (org-replace-escapes
  12409. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12410. `(("%d" . ,org-ts-regexp-inactive)
  12411. ("%D" . ,org-ts-regexp)
  12412. ("%s" . "\"\\S-+\"")
  12413. ("%S" . "\"\\S-+\"")
  12414. ("%t" . ,org-ts-regexp-inactive)
  12415. ("%T" . ,org-ts-regexp)
  12416. ("%u" . ".*?")
  12417. ("%U" . ".*?")))))))
  12418. (while (looking-at-p regexp)
  12419. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12420. (org-list-get-item-end (point) struct)))))))
  12421. (defun org-add-log-note (&optional _purpose)
  12422. "Pop up a window for taking a note, and add this note later."
  12423. (remove-hook 'post-command-hook 'org-add-log-note)
  12424. (setq org-log-note-window-configuration (current-window-configuration))
  12425. (delete-other-windows)
  12426. (move-marker org-log-note-return-to (point))
  12427. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12428. (goto-char org-log-note-marker)
  12429. (org-switch-to-buffer-other-window "*Org Note*")
  12430. (erase-buffer)
  12431. (if (memq org-log-note-how '(time state))
  12432. (org-store-log-note)
  12433. (let ((org-inhibit-startup t)) (org-mode))
  12434. (insert (format "# Insert note for %s.
  12435. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12436. (cond
  12437. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12438. ((eq org-log-note-purpose 'done) "closed todo item")
  12439. ((eq org-log-note-purpose 'state)
  12440. (format "state change from \"%s\" to \"%s\""
  12441. (or org-log-note-previous-state "")
  12442. (or org-log-note-state "")))
  12443. ((eq org-log-note-purpose 'reschedule)
  12444. "rescheduling")
  12445. ((eq org-log-note-purpose 'delschedule)
  12446. "no longer scheduled")
  12447. ((eq org-log-note-purpose 'redeadline)
  12448. "changing deadline")
  12449. ((eq org-log-note-purpose 'deldeadline)
  12450. "removing deadline")
  12451. ((eq org-log-note-purpose 'refile)
  12452. "refiling")
  12453. ((eq org-log-note-purpose 'note)
  12454. "this entry")
  12455. (t (error "This should not happen")))))
  12456. (when org-log-note-extra (insert org-log-note-extra))
  12457. (setq-local org-finish-function 'org-store-log-note)
  12458. (run-hooks 'org-log-buffer-setup-hook)))
  12459. (defvar org-note-abort nil) ; dynamically scoped
  12460. (defun org-store-log-note ()
  12461. "Finish taking a log note, and insert it to where it belongs."
  12462. (let ((txt (prog1 (buffer-string)
  12463. (kill-buffer)))
  12464. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12465. lines)
  12466. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12467. (setq txt (replace-match "" t t txt)))
  12468. (when (string-match "\\s-+\\'" txt)
  12469. (setq txt (replace-match "" t t txt)))
  12470. (setq lines (org-split-string txt "\n"))
  12471. (when (org-string-nw-p note)
  12472. (setq note
  12473. (org-replace-escapes
  12474. note
  12475. (list (cons "%u" (user-login-name))
  12476. (cons "%U" user-full-name)
  12477. (cons "%t" (format-time-string
  12478. (org-time-stamp-format 'long 'inactive)
  12479. org-log-note-effective-time))
  12480. (cons "%T" (format-time-string
  12481. (org-time-stamp-format 'long nil)
  12482. org-log-note-effective-time))
  12483. (cons "%d" (format-time-string
  12484. (org-time-stamp-format nil 'inactive)
  12485. org-log-note-effective-time))
  12486. (cons "%D" (format-time-string
  12487. (org-time-stamp-format nil nil)
  12488. org-log-note-effective-time))
  12489. (cons "%s" (cond
  12490. ((not org-log-note-state) "")
  12491. ((string-match-p org-ts-regexp
  12492. org-log-note-state)
  12493. (format "\"[%s]\""
  12494. (substring org-log-note-state 1 -1)))
  12495. (t (format "\"%s\"" org-log-note-state))))
  12496. (cons "%S"
  12497. (cond
  12498. ((not org-log-note-previous-state) "")
  12499. ((string-match-p org-ts-regexp
  12500. org-log-note-previous-state)
  12501. (format "\"[%s]\""
  12502. (substring
  12503. org-log-note-previous-state 1 -1)))
  12504. (t (format "\"%s\""
  12505. org-log-note-previous-state)))))))
  12506. (when lines (setq note (concat note " \\\\")))
  12507. (push note lines))
  12508. (when (and lines (not org-note-abort))
  12509. (with-current-buffer (marker-buffer org-log-note-marker)
  12510. (org-with-wide-buffer
  12511. ;; Find location for the new note.
  12512. (goto-char org-log-note-marker)
  12513. (set-marker org-log-note-marker nil)
  12514. ;; Note associated to a clock is to be located right after
  12515. ;; the clock. Do not move point.
  12516. (unless (eq org-log-note-purpose 'clock-out)
  12517. (goto-char (org-log-beginning t)))
  12518. ;; Make sure point is at the beginning of an empty line.
  12519. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12520. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12521. ;; In an existing list, add a new item at the top level.
  12522. ;; Otherwise, indent line like a regular one.
  12523. (let ((itemp (org-in-item-p)))
  12524. (if itemp
  12525. (indent-line-to
  12526. (let ((struct (save-excursion
  12527. (goto-char itemp) (org-list-struct))))
  12528. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12529. (org-indent-line)))
  12530. (insert (org-list-bullet-string "-") (pop lines))
  12531. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12532. (dolist (line lines)
  12533. (insert "\n")
  12534. (indent-line-to ind)
  12535. (insert line)))
  12536. (message "Note stored")
  12537. (org-back-to-heading t)
  12538. (org-cycle-hide-drawers 'children))
  12539. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12540. ;; from within `org-add-log-note' because `buffer-undo-list'
  12541. ;; is then modified outside of `org-with-remote-undo'.
  12542. (when (eq this-command 'org-agenda-todo)
  12543. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12544. ;; Don't add undo information when called from `org-agenda-todo'.
  12545. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12546. (set-window-configuration org-log-note-window-configuration)
  12547. (with-current-buffer (marker-buffer org-log-note-return-to)
  12548. (goto-char org-log-note-return-to))
  12549. (move-marker org-log-note-return-to nil)
  12550. (when org-log-post-message (message "%s" org-log-post-message))))
  12551. (defun org-remove-empty-drawer-at (pos)
  12552. "Remove an empty drawer at position POS.
  12553. POS may also be a marker."
  12554. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12555. (org-with-wide-buffer
  12556. (goto-char pos)
  12557. (let ((drawer (org-element-at-point)))
  12558. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12559. (not (org-element-property :contents-begin drawer)))
  12560. (delete-region (org-element-property :begin drawer)
  12561. (progn (goto-char (org-element-property :end drawer))
  12562. (skip-chars-backward " \r\t\n")
  12563. (forward-line)
  12564. (point))))))))
  12565. (defvar org-ts-type nil)
  12566. (defun org-sparse-tree (&optional arg type)
  12567. "Create a sparse tree, prompt for the details.
  12568. This command can create sparse trees. You first need to select the type
  12569. of match used to create the tree:
  12570. t Show all TODO entries.
  12571. T Show entries with a specific TODO keyword.
  12572. m Show entries selected by a tags/property match.
  12573. p Enter a property name and its value (both with completion on existing
  12574. names/values) and show entries with that property.
  12575. r Show entries matching a regular expression (`/' can be used as well).
  12576. b Show deadlines and scheduled items before a date.
  12577. a Show deadlines and scheduled items after a date.
  12578. d Show deadlines due within `org-deadline-warning-days'.
  12579. D Show deadlines and scheduled items between a date range."
  12580. (interactive "P")
  12581. (setq type (or type org-sparse-tree-default-date-type))
  12582. (setq org-ts-type type)
  12583. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12584. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12585. \[c]ycle through date types: %s"
  12586. (cl-case type
  12587. (all "all timestamps")
  12588. (scheduled "only scheduled")
  12589. (deadline "only deadline")
  12590. (active "only active timestamps")
  12591. (inactive "only inactive timestamps")
  12592. (closed "with a closed time-stamp")
  12593. (otherwise "scheduled/deadline")))
  12594. (let ((answer (read-char-exclusive)))
  12595. (cl-case answer
  12596. (?c
  12597. (org-sparse-tree
  12598. arg
  12599. (cadr
  12600. (memq type '(nil all scheduled deadline active inactive closed)))))
  12601. (?d (call-interactively 'org-check-deadlines))
  12602. (?b (call-interactively 'org-check-before-date))
  12603. (?a (call-interactively 'org-check-after-date))
  12604. (?D (call-interactively 'org-check-dates-range))
  12605. (?t (call-interactively 'org-show-todo-tree))
  12606. (?T (org-show-todo-tree '(4)))
  12607. (?m (call-interactively 'org-match-sparse-tree))
  12608. ((?p ?P)
  12609. (let* ((kwd (completing-read
  12610. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12611. (value (completing-read
  12612. "Value: " (mapcar #'list (org-property-values kwd)))))
  12613. (unless (string-match "\\`{.*}\\'" value)
  12614. (setq value (concat "\"" value "\"")))
  12615. (org-match-sparse-tree arg (concat kwd "=" value))))
  12616. ((?r ?R ?/) (call-interactively 'org-occur))
  12617. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12618. (defvar-local org-occur-highlights nil
  12619. "List of overlays used for occur matches.")
  12620. (defvar-local org-occur-parameters nil
  12621. "Parameters of the active org-occur calls.
  12622. This is a list, each call to org-occur pushes as cons cell,
  12623. containing the regular expression and the callback, onto the list.
  12624. The list can contain several entries if `org-occur' has been called
  12625. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12626. will only contain one set of parameters. When the highlights are
  12627. removed (for example with `C-c C-c', or with the next edit (depending
  12628. on `org-remove-highlights-with-change'), this variable is emptied
  12629. as well.")
  12630. (defun org-occur (regexp &optional keep-previous callback)
  12631. "Make a compact tree which shows all matches of REGEXP.
  12632. The tree will show the lines where the regexp matches, and any other context
  12633. defined in `org-show-context-detail', which see.
  12634. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12635. done by a previous call to `org-occur' will be kept, to allow stacking of
  12636. calls to this command.
  12637. Optional argument CALLBACK can be a function of no argument. In this case,
  12638. it is called with point at the end of the match, match data being set
  12639. accordingly. Current match is shown only if the return value is non-nil.
  12640. The function must neither move point nor alter narrowing."
  12641. (interactive "sRegexp: \nP")
  12642. (when (equal regexp "")
  12643. (user-error "Regexp cannot be empty"))
  12644. (unless keep-previous
  12645. (org-remove-occur-highlights nil nil t))
  12646. (push (cons regexp callback) org-occur-parameters)
  12647. (let ((cnt 0))
  12648. (save-excursion
  12649. (goto-char (point-min))
  12650. (when (or (not keep-previous) ; do not want to keep
  12651. (not org-occur-highlights)) ; no previous matches
  12652. ;; hide everything
  12653. (org-overview))
  12654. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12655. (isearch-no-upper-case-p regexp t)
  12656. org-occur-case-fold-search)))
  12657. (while (re-search-forward regexp nil t)
  12658. (when (or (not callback)
  12659. (save-match-data (funcall callback)))
  12660. (setq cnt (1+ cnt))
  12661. (when org-highlight-sparse-tree-matches
  12662. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12663. (org-show-context 'occur-tree)))))
  12664. (when org-remove-highlights-with-change
  12665. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12666. nil 'local))
  12667. (unless org-sparse-tree-open-archived-trees
  12668. (org-hide-archived-subtrees (point-min) (point-max)))
  12669. (run-hooks 'org-occur-hook)
  12670. (when (called-interactively-p 'interactive)
  12671. (message "%d match(es) for regexp %s" cnt regexp))
  12672. cnt))
  12673. (defun org-occur-next-match (&optional n _reset)
  12674. "Function for `next-error-function' to find sparse tree matches.
  12675. N is the number of matches to move, when negative move backwards.
  12676. This function always goes back to the starting point when no
  12677. match is found."
  12678. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12679. (search-func (if (< n 0)
  12680. 'previous-single-char-property-change
  12681. 'next-single-char-property-change))
  12682. (n (abs n))
  12683. (pos (point))
  12684. p1)
  12685. (catch 'exit
  12686. (while (setq p1 (funcall search-func (point) 'org-type))
  12687. (when (equal p1 limit)
  12688. (goto-char pos)
  12689. (user-error "No more matches"))
  12690. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12691. (setq n (1- n))
  12692. (when (= n 0)
  12693. (goto-char p1)
  12694. (throw 'exit (point))))
  12695. (goto-char p1))
  12696. (goto-char p1)
  12697. (user-error "No more matches"))))
  12698. (defun org-show-context (&optional key)
  12699. "Make sure point and context are visible.
  12700. Optional argument KEY, when non-nil, is a symbol. See
  12701. `org-show-context-detail' for allowed values and how much is to
  12702. be shown."
  12703. (org-show-set-visibility
  12704. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12705. ((cdr (assq key org-show-context-detail)))
  12706. (t (cdr (assq 'default org-show-context-detail))))))
  12707. (defun org-show-set-visibility (detail)
  12708. "Set visibility around point according to DETAIL.
  12709. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12710. `tree', `canonical' or t. See `org-show-context-detail' for more
  12711. information."
  12712. ;; Show current heading and possibly its entry, following headline
  12713. ;; or all children.
  12714. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12715. (org-flag-heading nil)
  12716. (org-show-entry)
  12717. ;; If point is hidden within a drawer or a block, make sure to
  12718. ;; expose it.
  12719. (dolist (o (overlays-at (point)))
  12720. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12721. (delete-overlay o)))
  12722. (unless (org-before-first-heading-p)
  12723. (org-with-limited-levels
  12724. (cl-case detail
  12725. ((tree canonical t) (org-show-children))
  12726. ((nil minimal ancestors))
  12727. (t (save-excursion
  12728. (outline-next-heading)
  12729. (org-flag-heading nil)))))))
  12730. ;; Show all siblings.
  12731. (when (eq detail 'lineage) (org-show-siblings))
  12732. ;; Show ancestors, possibly with their children.
  12733. (when (memq detail '(ancestors lineage tree canonical t))
  12734. (save-excursion
  12735. (while (org-up-heading-safe)
  12736. (org-flag-heading nil)
  12737. (when (memq detail '(canonical t)) (org-show-entry))
  12738. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12739. (defvar org-reveal-start-hook nil
  12740. "Hook run before revealing a location.")
  12741. (defun org-reveal (&optional siblings)
  12742. "Show current entry, hierarchy above it, and the following headline.
  12743. This can be used to show a consistent set of context around
  12744. locations exposed with `org-show-context'.
  12745. With optional argument SIBLINGS, on each level of the hierarchy all
  12746. siblings are shown. This repairs the tree structure to what it would
  12747. look like when opened with hierarchical calls to `org-cycle'.
  12748. With a \\[universal-argument] \\[universal-argument] prefix, \
  12749. go to the parent and show the entire tree."
  12750. (interactive "P")
  12751. (run-hooks 'org-reveal-start-hook)
  12752. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12753. ((equal siblings '(16))
  12754. (save-excursion
  12755. (when (org-up-heading-safe)
  12756. (org-show-subtree)
  12757. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12758. (t (org-show-set-visibility 'lineage))))
  12759. (defun org-highlight-new-match (beg end)
  12760. "Highlight from BEG to END and mark the highlight is an occur headline."
  12761. (let ((ov (make-overlay beg end)))
  12762. (overlay-put ov 'face 'secondary-selection)
  12763. (overlay-put ov 'org-type 'org-occur)
  12764. (push ov org-occur-highlights)))
  12765. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12766. "Remove the occur highlights from the buffer.
  12767. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12768. from the `before-change-functions' in the current buffer."
  12769. (interactive)
  12770. (unless org-inhibit-highlight-removal
  12771. (mapc #'delete-overlay org-occur-highlights)
  12772. (setq org-occur-highlights nil)
  12773. (setq org-occur-parameters nil)
  12774. (unless noremove
  12775. (remove-hook 'before-change-functions
  12776. 'org-remove-occur-highlights 'local))))
  12777. ;;;; Priorities
  12778. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12779. "Regular expression matching the priority indicator.")
  12780. (defvar org-remove-priority-next-time nil)
  12781. (defun org-priority-up ()
  12782. "Increase the priority of the current item."
  12783. (interactive)
  12784. (org-priority 'up))
  12785. (defun org-priority-down ()
  12786. "Decrease the priority of the current item."
  12787. (interactive)
  12788. (org-priority 'down))
  12789. (defun org-priority (&optional action _show)
  12790. "Change the priority of an item.
  12791. ACTION can be `set', `up', `down', or a character."
  12792. (interactive "P")
  12793. (if (equal action '(4))
  12794. (org-show-priority)
  12795. (unless org-enable-priority-commands
  12796. (user-error "Priority commands are disabled"))
  12797. (setq action (or action 'set))
  12798. (let (current new news have remove)
  12799. (save-excursion
  12800. (org-back-to-heading t)
  12801. (when (looking-at org-priority-regexp)
  12802. (setq current (string-to-char (match-string 2))
  12803. have t))
  12804. (cond
  12805. ((eq action 'remove)
  12806. (setq remove t new ?\ ))
  12807. ((or (eq action 'set)
  12808. (integerp action))
  12809. (if (not (eq action 'set))
  12810. (setq new action)
  12811. (message "Priority %c-%c, SPC to remove: "
  12812. org-highest-priority org-lowest-priority)
  12813. (save-match-data
  12814. (setq new (read-char-exclusive))))
  12815. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12816. (= (upcase org-lowest-priority) org-lowest-priority))
  12817. (setq new (upcase new)))
  12818. (cond ((equal new ?\ ) (setq remove t))
  12819. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12820. (user-error "Priority must be between `%c' and `%c'"
  12821. org-highest-priority org-lowest-priority))))
  12822. ((eq action 'up)
  12823. (setq new (if have
  12824. (1- current) ; normal cycling
  12825. ;; last priority was empty
  12826. (if (eq last-command this-command)
  12827. org-lowest-priority ; wrap around empty to lowest
  12828. ;; default
  12829. (if org-priority-start-cycle-with-default
  12830. org-default-priority
  12831. (1- org-default-priority))))))
  12832. ((eq action 'down)
  12833. (setq new (if have
  12834. (1+ current) ; normal cycling
  12835. ;; last priority was empty
  12836. (if (eq last-command this-command)
  12837. org-highest-priority ; wrap around empty to highest
  12838. ;; default
  12839. (if org-priority-start-cycle-with-default
  12840. org-default-priority
  12841. (1+ org-default-priority))))))
  12842. (t (user-error "Invalid action")))
  12843. (when (or (< (upcase new) org-highest-priority)
  12844. (> (upcase new) org-lowest-priority))
  12845. (if (and (memq action '(up down))
  12846. (not have) (not (eq last-command this-command)))
  12847. ;; `new' is from default priority
  12848. (error
  12849. "The default can not be set, see `org-default-priority' why")
  12850. ;; normal cycling: `new' is beyond highest/lowest priority
  12851. ;; and is wrapped around to the empty priority
  12852. (setq remove t)))
  12853. (setq news (format "%c" new))
  12854. (if have
  12855. (if remove
  12856. (replace-match "" t t nil 1)
  12857. (replace-match news t t nil 2))
  12858. (if remove
  12859. (user-error "No priority cookie found in line")
  12860. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12861. (if (match-end 2)
  12862. (progn
  12863. (goto-char (match-end 2))
  12864. (insert " [#" news "]"))
  12865. (goto-char (match-beginning 3))
  12866. (insert "[#" news "] "))))
  12867. (org-set-tags nil 'align))
  12868. (if remove
  12869. (message "Priority removed")
  12870. (message "Priority of current item set to %s" news)))))
  12871. (defun org-show-priority ()
  12872. "Show the priority of the current item.
  12873. This priority is composed of the main priority given with the [#A] cookies,
  12874. and by additional input from the age of a schedules or deadline entry."
  12875. (interactive)
  12876. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12877. (org-get-at-bol 'priority)
  12878. (save-excursion
  12879. (save-match-data
  12880. (beginning-of-line)
  12881. (and (looking-at org-heading-regexp)
  12882. (org-get-priority (match-string 0))))))))
  12883. (message "Priority is %d" (if pri pri -1000))))
  12884. (defun org-get-priority (s)
  12885. "Find priority cookie and return priority."
  12886. (save-match-data
  12887. (if (functionp org-get-priority-function)
  12888. (funcall org-get-priority-function)
  12889. (if (not (string-match org-priority-regexp s))
  12890. (* 1000 (- org-lowest-priority org-default-priority))
  12891. (* 1000 (- org-lowest-priority
  12892. (string-to-char (match-string 2 s))))))))
  12893. ;;;; Tags
  12894. (defvar org-agenda-archives-mode)
  12895. (defvar org-map-continue-from nil
  12896. "Position from where mapping should continue.
  12897. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12898. (defvar org-scanner-tags nil
  12899. "The current tag list while the tags scanner is running.")
  12900. (defvar org-trust-scanner-tags nil
  12901. "Should `org-get-tags-at' use the tags for the scanner.
  12902. This is for internal dynamical scoping only.
  12903. When this is non-nil, the function `org-get-tags-at' will return the value
  12904. of `org-scanner-tags' instead of building the list by itself. This
  12905. can lead to large speed-ups when the tags scanner is used in a file with
  12906. many entries, and when the list of tags is retrieved, for example to
  12907. obtain a list of properties. Building the tags list for each entry in such
  12908. a file becomes an N^2 operation - but with this variable set, it scales
  12909. as N.")
  12910. (defvar org--matcher-tags-todo-only nil)
  12911. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12912. "Scan headline tags with inheritance and produce output ACTION.
  12913. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12914. or `agenda' to produce an entry list for an agenda view. It can also be
  12915. a Lisp form or a function that should be called at each matched headline, in
  12916. this case the return value is a list of all return values from these calls.
  12917. MATCHER is a function accepting three arguments, returning
  12918. a non-nil value whenever a given set of tags qualifies a headline
  12919. for inclusion. See `org-make-tags-matcher' for more information.
  12920. As a special case, it can also be set to t (respectively nil) in
  12921. order to match all (respectively none) headline.
  12922. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12923. keyword are included in the output.
  12924. START-LEVEL can be a string with asterisks, reducing the scope to
  12925. headlines matching this string."
  12926. (require 'org-agenda)
  12927. (let* ((re (concat "^"
  12928. (if start-level
  12929. ;; Get the correct level to match
  12930. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12931. org-outline-regexp)
  12932. " *\\(\\<\\("
  12933. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12934. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12935. (props (list 'face 'default
  12936. 'done-face 'org-agenda-done
  12937. 'undone-face 'default
  12938. 'mouse-face 'highlight
  12939. 'org-not-done-regexp org-not-done-regexp
  12940. 'org-todo-regexp org-todo-regexp
  12941. 'org-complex-heading-regexp org-complex-heading-regexp
  12942. 'help-echo
  12943. (format "mouse-2 or RET jump to org file %s"
  12944. (abbreviate-file-name
  12945. (or (buffer-file-name (buffer-base-buffer))
  12946. (buffer-name (buffer-base-buffer)))))))
  12947. (org-map-continue-from nil)
  12948. lspos tags tags-list
  12949. (tags-alist (list (cons 0 org-file-tags)))
  12950. (llast 0) rtn rtn1 level category i txt
  12951. todo marker entry priority
  12952. ts-date ts-date-type ts-date-pair)
  12953. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12954. (setq action (list 'lambda nil action)))
  12955. (save-excursion
  12956. (goto-char (point-min))
  12957. (when (eq action 'sparse-tree)
  12958. (org-overview)
  12959. (org-remove-occur-highlights))
  12960. (while (let (case-fold-search)
  12961. (re-search-forward re nil t))
  12962. (setq org-map-continue-from nil)
  12963. (catch :skip
  12964. (setq todo
  12965. ;; TODO: is the 1-2 difference a bug?
  12966. (when (match-end 1) (match-string-no-properties 2))
  12967. tags (when (match-end 4) (match-string-no-properties 4)))
  12968. (goto-char (setq lspos (match-beginning 0)))
  12969. (setq level (org-reduced-level (org-outline-level))
  12970. category (org-get-category))
  12971. (when (eq action 'agenda)
  12972. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12973. ts-date (car ts-date-pair)
  12974. ts-date-type (cdr ts-date-pair)))
  12975. (setq i llast llast level)
  12976. ;; remove tag lists from same and sublevels
  12977. (while (>= i level)
  12978. (when (setq entry (assoc i tags-alist))
  12979. (setq tags-alist (delete entry tags-alist)))
  12980. (setq i (1- i)))
  12981. ;; add the next tags
  12982. (when tags
  12983. (setq tags (org-split-string tags ":")
  12984. tags-alist
  12985. (cons (cons level tags) tags-alist)))
  12986. ;; compile tags for current headline
  12987. (setq tags-list
  12988. (if org-use-tag-inheritance
  12989. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12990. tags)
  12991. org-scanner-tags tags-list)
  12992. (when org-use-tag-inheritance
  12993. (setcdr (car tags-alist)
  12994. (mapcar (lambda (x)
  12995. (setq x (copy-sequence x))
  12996. (org-add-prop-inherited x))
  12997. (cdar tags-alist))))
  12998. (when (and tags org-use-tag-inheritance
  12999. (or (not (eq t org-use-tag-inheritance))
  13000. org-tags-exclude-from-inheritance))
  13001. ;; Selective inheritance, remove uninherited ones.
  13002. (setcdr (car tags-alist)
  13003. (org-remove-uninherited-tags (cdar tags-alist))))
  13004. (when (and
  13005. ;; eval matcher only when the todo condition is OK
  13006. (and (or (not todo-only) (member todo org-not-done-keywords))
  13007. (if (functionp matcher)
  13008. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13009. (funcall matcher todo tags-list level))
  13010. matcher))
  13011. ;; Call the skipper, but return t if it does not
  13012. ;; skip, so that the `and' form continues evaluating.
  13013. (progn
  13014. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13015. t)
  13016. ;; Check if timestamps are deselecting this entry
  13017. (or (not todo-only)
  13018. (and (member todo org-not-done-keywords)
  13019. (or (not org-agenda-tags-todo-honor-ignore-options)
  13020. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13021. ;; select this headline
  13022. (cond
  13023. ((eq action 'sparse-tree)
  13024. (and org-highlight-sparse-tree-matches
  13025. (org-get-heading) (match-end 0)
  13026. (org-highlight-new-match
  13027. (match-beginning 1) (match-end 1)))
  13028. (org-show-context 'tags-tree))
  13029. ((eq action 'agenda)
  13030. (setq txt (org-agenda-format-item
  13031. ""
  13032. (concat
  13033. (if (eq org-tags-match-list-sublevels 'indented)
  13034. (make-string (1- level) ?.) "")
  13035. (org-get-heading))
  13036. (make-string level ?\s)
  13037. category
  13038. tags-list)
  13039. priority (org-get-priority txt))
  13040. (goto-char lspos)
  13041. (setq marker (org-agenda-new-marker))
  13042. (org-add-props txt props
  13043. 'org-marker marker 'org-hd-marker marker 'org-category category
  13044. 'todo-state todo
  13045. 'ts-date ts-date
  13046. 'priority priority
  13047. 'type (concat "tagsmatch" ts-date-type))
  13048. (push txt rtn))
  13049. ((functionp action)
  13050. (setq org-map-continue-from nil)
  13051. (save-excursion
  13052. (setq rtn1 (funcall action))
  13053. (push rtn1 rtn)))
  13054. (t (user-error "Invalid action")))
  13055. ;; if we are to skip sublevels, jump to end of subtree
  13056. (unless org-tags-match-list-sublevels
  13057. (org-end-of-subtree t)
  13058. (backward-char 1))))
  13059. ;; Get the correct position from where to continue
  13060. (if org-map-continue-from
  13061. (goto-char org-map-continue-from)
  13062. (and (= (point) lspos) (end-of-line 1)))))
  13063. (when (and (eq action 'sparse-tree)
  13064. (not org-sparse-tree-open-archived-trees))
  13065. (org-hide-archived-subtrees (point-min) (point-max)))
  13066. (nreverse rtn)))
  13067. (defun org-remove-uninherited-tags (tags)
  13068. "Remove all tags that are not inherited from the list TAGS."
  13069. (cond
  13070. ((eq org-use-tag-inheritance t)
  13071. (if org-tags-exclude-from-inheritance
  13072. (org-delete-all org-tags-exclude-from-inheritance tags)
  13073. tags))
  13074. ((not org-use-tag-inheritance) nil)
  13075. ((stringp org-use-tag-inheritance)
  13076. (delq nil (mapcar
  13077. (lambda (x)
  13078. (if (and (string-match org-use-tag-inheritance x)
  13079. (not (member x org-tags-exclude-from-inheritance)))
  13080. x nil))
  13081. tags)))
  13082. ((listp org-use-tag-inheritance)
  13083. (delq nil (mapcar
  13084. (lambda (x)
  13085. (if (member x org-use-tag-inheritance) x nil))
  13086. tags)))))
  13087. (defun org-match-sparse-tree (&optional todo-only match)
  13088. "Create a sparse tree according to tags string MATCH.
  13089. MATCH is a string with match syntax. It can contain a selection
  13090. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13091. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13092. those. See the manual for details.
  13093. If optional argument TODO-ONLY is non-nil, only select lines that
  13094. are also TODO tasks."
  13095. (interactive "P")
  13096. (org-agenda-prepare-buffers (list (current-buffer)))
  13097. (let ((org--matcher-tags-todo-only todo-only))
  13098. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13099. org--matcher-tags-todo-only)))
  13100. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13101. (defvar org-cached-props nil)
  13102. (defun org-cached-entry-get (pom property)
  13103. (if (or (eq t org-use-property-inheritance)
  13104. (and (stringp org-use-property-inheritance)
  13105. (let ((case-fold-search t))
  13106. (string-match-p org-use-property-inheritance property)))
  13107. (and (listp org-use-property-inheritance)
  13108. (member-ignore-case property org-use-property-inheritance)))
  13109. ;; Caching is not possible, check it directly.
  13110. (org-entry-get pom property 'inherit)
  13111. ;; Get all properties, so we can do complicated checks easily.
  13112. (cdr (assoc-string property
  13113. (or org-cached-props
  13114. (setq org-cached-props (org-entry-properties pom)))
  13115. t))))
  13116. (defun org-global-tags-completion-table (&optional files)
  13117. "Return the list of all tags in all agenda buffer/files.
  13118. Optional FILES argument is a list of files which can be used
  13119. instead of the agenda files."
  13120. (save-excursion
  13121. (org-uniquify
  13122. (delq nil
  13123. (apply #'append
  13124. (mapcar
  13125. (lambda (file)
  13126. (set-buffer (find-file-noselect file))
  13127. (mapcar (lambda (x)
  13128. (and (stringp (car-safe x))
  13129. (list (car-safe x))))
  13130. (or org-current-tag-alist (org-get-buffer-tags))))
  13131. (if (car-safe files) files
  13132. (org-agenda-files))))))))
  13133. (defun org-make-tags-matcher (match)
  13134. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13135. Returns a cons of the selection string MATCH and a function
  13136. implementing the matcher.
  13137. The matcher is to be called at an Org entry, with point on the
  13138. headline, and returns non-nil if the entry matches the selection
  13139. string MATCH. It must be called with three arguments: the TODO
  13140. keyword at the entry (or nil if none), the list of all tags at
  13141. the entry including inherited ones and the reduced level of the
  13142. headline. Additionally, the category of the entry, if any, must
  13143. be specified as the text property `org-category' on the headline.
  13144. This function sets the variable `org--matcher-tags-todo-only' to
  13145. a non-nil value if the matcher restricts matching to TODO
  13146. entries, otherwise it is not touched.
  13147. See also `org-scan-tags'."
  13148. (unless match
  13149. ;; Get a new match request, with completion against the global
  13150. ;; tags table and the local tags in current buffer.
  13151. (let ((org-last-tags-completion-table
  13152. (org-uniquify
  13153. (delq nil (append (org-get-buffer-tags)
  13154. (org-global-tags-completion-table))))))
  13155. (setq match
  13156. (completing-read
  13157. "Match: "
  13158. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13159. (let ((match0 match)
  13160. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13161. (start 0)
  13162. tagsmatch todomatch tagsmatcher todomatcher)
  13163. ;; Expand group tags.
  13164. (setq match (org-tags-expand match))
  13165. ;; Check if there is a TODO part of this match, which would be the
  13166. ;; part after a "/". To make sure that this slash is not part of
  13167. ;; a property value to be matched against, we also check that
  13168. ;; there is no / after that slash. First, find the last slash.
  13169. (let ((s 0))
  13170. (while (string-match "/+" match s)
  13171. (setq start (match-beginning 0))
  13172. (setq s (match-end 0))))
  13173. (if (and (string-match "/+" match start)
  13174. (not (string-match-p "\"" match start)))
  13175. ;; Match contains also a TODO-matching request.
  13176. (progn
  13177. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13178. (setq todomatch (substring match (match-end 0)))
  13179. (when (string-prefix-p "!" todomatch)
  13180. (setq org--matcher-tags-todo-only t)
  13181. (setq todomatch (substring todomatch 1)))
  13182. (when (string-match "\\`\\s-*\\'" todomatch)
  13183. (setq todomatch nil)))
  13184. ;; Only matching tags.
  13185. (setq tagsmatch match)
  13186. (setq todomatch nil))
  13187. ;; Make the tags matcher.
  13188. (when (org-string-nw-p tagsmatch)
  13189. (let ((orlist nil)
  13190. (orterms (org-split-string tagsmatch "|"))
  13191. term)
  13192. (while (setq term (pop orterms))
  13193. (while (and (equal (substring term -1) "\\") orterms)
  13194. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13195. (while (string-match re term)
  13196. (let* ((rest (substring term (match-end 0)))
  13197. (minus (and (match-end 1)
  13198. (equal (match-string 1 term) "-")))
  13199. (tag (save-match-data
  13200. (replace-regexp-in-string
  13201. "\\\\-" "-" (match-string 2 term))))
  13202. (regexp (eq (string-to-char tag) ?{))
  13203. (levelp (match-end 4))
  13204. (propp (match-end 5))
  13205. (mm
  13206. (cond
  13207. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13208. (levelp
  13209. `(,(org-op-to-function (match-string 3 term))
  13210. level
  13211. ,(string-to-number (match-string 4 term))))
  13212. (propp
  13213. (let* ((gv (pcase (upcase (match-string 5 term))
  13214. ("CATEGORY"
  13215. '(get-text-property (point) 'org-category))
  13216. ("TODO" 'todo)
  13217. (p `(org-cached-entry-get nil ,p))))
  13218. (pv (match-string 7 term))
  13219. (regexp (eq (string-to-char pv) ?{))
  13220. (strp (eq (string-to-char pv) ?\"))
  13221. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13222. (po (org-op-to-function (match-string 6 term)
  13223. (if timep 'time strp))))
  13224. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13225. (when timep (setq pv (org-matcher-time pv)))
  13226. (cond ((and regexp (eq po 'org<>))
  13227. `(not (string-match ,pv (or ,gv ""))))
  13228. (regexp `(string-match ,pv (or ,gv "")))
  13229. (strp `(,po (or ,gv "") ,pv))
  13230. (t
  13231. `(,po
  13232. (string-to-number (or ,gv ""))
  13233. ,(string-to-number pv))))))
  13234. (t `(member ,tag tags-list)))))
  13235. (push (if minus `(not ,mm) mm) tagsmatcher)
  13236. (setq term rest)))
  13237. (push `(and ,@tagsmatcher) orlist)
  13238. (setq tagsmatcher nil))
  13239. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13240. ;; Make the TODO matcher.
  13241. (when (org-string-nw-p todomatch)
  13242. (let ((orlist nil))
  13243. (dolist (term (org-split-string todomatch "|"))
  13244. (while (string-match re term)
  13245. (let* ((minus (and (match-end 1)
  13246. (equal (match-string 1 term) "-")))
  13247. (kwd (match-string 2 term))
  13248. (regexp (eq (string-to-char kwd) ?{))
  13249. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13250. `(equal todo ,kwd))))
  13251. (push (if minus `(not ,mm) mm) todomatcher))
  13252. (setq term (substring term (match-end 0))))
  13253. (push (if (> (length todomatcher) 1)
  13254. (cons 'and todomatcher)
  13255. (car todomatcher))
  13256. orlist)
  13257. (setq todomatcher nil))
  13258. (setq todomatcher (cons 'or orlist))))
  13259. ;; Return the string and function of the matcher. If no
  13260. ;; tags-specific or todo-specific matcher exists, match
  13261. ;; everything.
  13262. (let ((matcher (if (and tagsmatcher todomatcher)
  13263. `(and ,tagsmatcher ,todomatcher)
  13264. (or tagsmatcher todomatcher t))))
  13265. (when org--matcher-tags-todo-only
  13266. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13267. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13268. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13269. "Expand group tags in MATCH.
  13270. This replaces every group tag in MATCH with a regexp tag search.
  13271. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13272. will be replaced like this:
  13273. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13274. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13275. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13276. Replacing by a regexp preserves the structure of the match.
  13277. E.g., this expansion
  13278. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13279. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13280. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13281. A group tag in MATCH can contain regular expressions of its own.
  13282. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13283. will be replaced like this:
  13284. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13285. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13286. assumed to be a single group tag, and the function will return
  13287. the list of tags in this group.
  13288. When DOWNCASE is non-nil, expand downcased TAGS."
  13289. (if org-group-tags
  13290. (let* ((case-fold-search t)
  13291. (stable org-mode-syntax-table)
  13292. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13293. (taggroups (if downcased
  13294. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13295. taggroups)
  13296. taggroups))
  13297. (taggroups-keys (mapcar #'car taggroups))
  13298. (return-match (if downcased (downcase match) match))
  13299. (count 0)
  13300. (work-already-expanded tags-already-expanded)
  13301. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13302. ;; @ and _ are allowed as word-components in tags.
  13303. (modify-syntax-entry ?@ "w" stable)
  13304. (modify-syntax-entry ?_ "w" stable)
  13305. ;; Temporarily replace regexp-expressions in the match-expression.
  13306. (while (string-match "{.+?}" return-match)
  13307. (cl-incf count)
  13308. (push (match-string 0 return-match) regexps-in-match)
  13309. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13310. (while (and taggroups-keys
  13311. (with-syntax-table stable
  13312. (string-match
  13313. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13314. (regexp-opt taggroups-keys) "\\>\\)")
  13315. return-match)))
  13316. (let* ((dir (match-string 1 return-match))
  13317. (tag (match-string 2 return-match))
  13318. (tag (if downcased (downcase tag) tag)))
  13319. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13320. (member tag work-already-expanded))
  13321. (setq tags-in-group (assoc tag taggroups))
  13322. (push tag work-already-expanded)
  13323. ;; Recursively expand each tag in the group, if the tag hasn't
  13324. ;; already been expanded. Restore the match-data after all recursive calls.
  13325. (save-match-data
  13326. (let (tags-expanded)
  13327. (dolist (x (cdr tags-in-group))
  13328. (if (and (member x taggroups-keys)
  13329. (not (member x work-already-expanded)))
  13330. (setq tags-expanded
  13331. (delete-dups
  13332. (append
  13333. (org-tags-expand x t downcased
  13334. work-already-expanded)
  13335. tags-expanded)))
  13336. (setq tags-expanded
  13337. (append (list x) tags-expanded)))
  13338. (setq work-already-expanded
  13339. (delete-dups
  13340. (append tags-expanded
  13341. work-already-expanded))))
  13342. (setq tags-in-group
  13343. (delete-dups (cons (car tags-in-group)
  13344. tags-expanded)))))
  13345. ;; Filter tag-regexps from tags.
  13346. (setq regexp-in-group-escaped
  13347. (delq nil (mapcar (lambda (x)
  13348. (if (stringp x)
  13349. (and (equal "{" (substring x 0 1))
  13350. (equal "}" (substring x -1))
  13351. x)
  13352. x))
  13353. tags-in-group))
  13354. regexp-in-group
  13355. (mapcar (lambda (x)
  13356. (substring x 1 -1))
  13357. regexp-in-group-escaped)
  13358. tags-in-group
  13359. (delq nil (mapcar (lambda (x)
  13360. (if (stringp x)
  13361. (and (not (equal "{" (substring x 0 1)))
  13362. (not (equal "}" (substring x -1)))
  13363. x)
  13364. x))
  13365. tags-in-group)))
  13366. ;; If single-as-list, do no more in the while-loop.
  13367. (if (not single-as-list)
  13368. (progn
  13369. (when regexp-in-group
  13370. (setq regexp-in-group
  13371. (concat "\\|"
  13372. (mapconcat 'identity regexp-in-group
  13373. "\\|"))))
  13374. (setq tags-in-group
  13375. (concat dir
  13376. "{\\<"
  13377. (regexp-opt tags-in-group)
  13378. "\\>"
  13379. regexp-in-group
  13380. "}"))
  13381. (when (stringp tags-in-group)
  13382. (org-add-props tags-in-group '(grouptag t)))
  13383. (setq return-match
  13384. (replace-match tags-in-group t t return-match)))
  13385. (setq tags-in-group
  13386. (append regexp-in-group-escaped tags-in-group))))
  13387. (setq taggroups-keys (delete tag taggroups-keys))))
  13388. ;; Add the regular expressions back into the match-expression again.
  13389. (while regexps-in-match
  13390. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13391. (pop regexps-in-match)
  13392. return-match t t))
  13393. (cl-decf count))
  13394. (if single-as-list
  13395. (if tags-in-group tags-in-group (list return-match))
  13396. return-match))
  13397. (if single-as-list
  13398. (list (if downcased (downcase match) match))
  13399. match)))
  13400. (defun org-op-to-function (op &optional stringp)
  13401. "Turn an operator into the appropriate function."
  13402. (setq op
  13403. (cond
  13404. ((equal op "<" ) '(< string< org-time<))
  13405. ((equal op ">" ) '(> org-string> org-time>))
  13406. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13407. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13408. ((member op '("=" "==")) '(= string= org-time=))
  13409. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13410. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13411. (defun org<> (a b) (not (= a b)))
  13412. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13413. (defun org-string>= (a b) (not (string< a b)))
  13414. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13415. (defun org-string<> (a b) (not (string= a b)))
  13416. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13417. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13418. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13419. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13420. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13421. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13422. (defun org-2ft (s)
  13423. "Convert S to a floating point time.
  13424. If S is already a number, just return it. If it is a string, parse
  13425. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13426. (cond
  13427. ((numberp s) s)
  13428. ((stringp s)
  13429. (condition-case nil
  13430. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13431. (error 0.)))
  13432. (t 0.)))
  13433. (defun org-time-today ()
  13434. "Time in seconds today at 0:00.
  13435. Returns the float number of seconds since the beginning of the
  13436. epoch to the beginning of today (00:00)."
  13437. (float-time (apply 'encode-time
  13438. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13439. (defun org-matcher-time (s)
  13440. "Interpret a time comparison value."
  13441. (save-match-data
  13442. (cond
  13443. ((string= s "<now>") (float-time))
  13444. ((string= s "<today>") (org-time-today))
  13445. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13446. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13447. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13448. (+ (org-time-today)
  13449. (* (string-to-number (match-string 1 s))
  13450. (cdr (assoc (match-string 2 s)
  13451. '(("d" . 86400.0) ("w" . 604800.0)
  13452. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13453. (t (org-2ft s)))))
  13454. (defun org-match-any-p (re list)
  13455. "Does re match any element of list?"
  13456. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13457. (delq nil list))
  13458. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13459. (defvar org-tags-overlay (make-overlay 1 1))
  13460. (delete-overlay org-tags-overlay)
  13461. (defun org-get-local-tags-at (&optional pos)
  13462. "Get a list of tags defined in the current headline."
  13463. (org-get-tags-at pos 'local))
  13464. (defun org-get-local-tags ()
  13465. "Get a list of tags defined in the current headline."
  13466. (org-get-tags-at nil 'local))
  13467. (defun org-get-tags-at (&optional pos local)
  13468. "Get a list of all headline tags applicable at POS.
  13469. POS defaults to point. If tags are inherited, the list contains
  13470. the targets in the same sequence as the headlines appear, i.e.
  13471. the tags of the current headline come last.
  13472. When LOCAL is non-nil, only return tags from the current headline,
  13473. ignore inherited ones."
  13474. (interactive)
  13475. (if (and org-trust-scanner-tags
  13476. (or (not pos) (equal pos (point)))
  13477. (not local))
  13478. org-scanner-tags
  13479. (let (tags ltags lastpos parent)
  13480. (save-excursion
  13481. (save-restriction
  13482. (widen)
  13483. (goto-char (or pos (point)))
  13484. (save-match-data
  13485. (catch 'done
  13486. (condition-case nil
  13487. (progn
  13488. (org-back-to-heading t)
  13489. (while (not (equal lastpos (point)))
  13490. (setq lastpos (point))
  13491. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13492. (setq ltags (org-split-string
  13493. (match-string-no-properties 1) ":"))
  13494. (when parent
  13495. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13496. (setq tags (append
  13497. (if parent
  13498. (org-remove-uninherited-tags ltags)
  13499. ltags)
  13500. tags)))
  13501. (or org-use-tag-inheritance (throw 'done t))
  13502. (when local (throw 'done t))
  13503. (or (org-up-heading-safe) (error nil))
  13504. (setq parent t)))
  13505. (error nil)))))
  13506. (if local
  13507. tags
  13508. (reverse (delete-dups
  13509. (reverse (append
  13510. (org-remove-uninherited-tags
  13511. org-file-tags)
  13512. tags)))))))))
  13513. (defun org-add-prop-inherited (s)
  13514. (add-text-properties 0 (length s) '(inherited t) s)
  13515. s)
  13516. (defun org-toggle-tag (tag &optional onoff)
  13517. "Toggle the tag TAG for the current line.
  13518. If ONOFF is `on' or `off', don't toggle but set to this state."
  13519. (let (res current)
  13520. (save-excursion
  13521. (org-back-to-heading t)
  13522. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13523. (point-at-eol) t)
  13524. (progn
  13525. (setq current (match-string 1))
  13526. (replace-match ""))
  13527. (setq current ""))
  13528. (setq current (nreverse (org-split-string current ":")))
  13529. (cond
  13530. ((eq onoff 'on)
  13531. (setq res t)
  13532. (or (member tag current) (push tag current)))
  13533. ((eq onoff 'off)
  13534. (or (not (member tag current)) (setq current (delete tag current))))
  13535. (t (if (member tag current)
  13536. (setq current (delete tag current))
  13537. (setq res t)
  13538. (push tag current))))
  13539. (end-of-line 1)
  13540. (if current
  13541. (progn
  13542. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13543. (org-set-tags nil t))
  13544. (delete-horizontal-space))
  13545. (run-hooks 'org-after-tags-change-hook))
  13546. res))
  13547. (defun org--align-tags-here (to-col)
  13548. "Align tags on the current headline to TO-COL.
  13549. Assume point is on a headline."
  13550. (let ((pos (point)))
  13551. (beginning-of-line)
  13552. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13553. (>= pos (match-beginning 2)))
  13554. ;; No tags or point within tags: do not align.
  13555. (goto-char pos)
  13556. (goto-char (match-beginning 1))
  13557. (let ((shift (max (- (if (>= to-col 0) to-col
  13558. (- (abs to-col) (string-width (match-string 2))))
  13559. (current-column))
  13560. 1)))
  13561. (replace-match (make-string shift ?\s) nil nil nil 1)
  13562. ;; Preserve initial position, if possible. In any case, stop
  13563. ;; before tags.
  13564. (when (< pos (point)) (goto-char pos))))))
  13565. (defun org-set-tags-command (&optional arg just-align)
  13566. "Call the set-tags command for the current entry."
  13567. (interactive "P")
  13568. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13569. (org-set-tags arg just-align)
  13570. (save-excursion
  13571. (unless (and (org-region-active-p)
  13572. org-loop-over-headlines-in-active-region)
  13573. (org-back-to-heading t))
  13574. (org-set-tags arg just-align))))
  13575. (defun org-set-tags-to (data)
  13576. "Set the tags of the current entry to DATA, replacing the current tags.
  13577. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13578. If DATA is nil or the empty string, any tags will be removed."
  13579. (interactive "sTags: ")
  13580. (setq data
  13581. (cond
  13582. ((eq data nil) "")
  13583. ((equal data "") "")
  13584. ((stringp data)
  13585. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13586. ":"))
  13587. ((listp data)
  13588. (concat ":" (mapconcat 'identity data ":") ":"))))
  13589. (when data
  13590. (save-excursion
  13591. (org-back-to-heading t)
  13592. (when (let ((case-fold-search nil))
  13593. (looking-at org-complex-heading-regexp))
  13594. (if (match-end 5)
  13595. (progn
  13596. (goto-char (match-beginning 5))
  13597. (insert data)
  13598. (delete-region (point) (point-at-eol))
  13599. (org-set-tags nil 'align))
  13600. (goto-char (point-at-eol))
  13601. (insert " " data)
  13602. (org-set-tags nil 'align)))
  13603. (beginning-of-line 1)
  13604. (when (looking-at ".*?\\([ \t]+\\)$")
  13605. (delete-region (match-beginning 1) (match-end 1))))))
  13606. (defun org-align-all-tags ()
  13607. "Align the tags in all headings."
  13608. (interactive)
  13609. (save-excursion
  13610. (or (ignore-errors (org-back-to-heading t))
  13611. (outline-next-heading))
  13612. (if (org-at-heading-p)
  13613. (org-set-tags t)
  13614. (message "No headings"))))
  13615. (defvar org-indent-indentation-per-level)
  13616. (defun org-set-tags (&optional arg just-align)
  13617. "Set the tags for the current headline.
  13618. With prefix ARG, realign all tags in headings in the current buffer.
  13619. When JUST-ALIGN is non-nil, only align tags."
  13620. (interactive "P")
  13621. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13622. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13623. 'region-start-level
  13624. 'region))
  13625. org-loop-over-headlines-in-active-region)
  13626. (org-map-entries
  13627. ;; We don't use ARG and JUST-ALIGN here because these args
  13628. ;; are not useful when looping over headlines.
  13629. #'org-set-tags
  13630. org-loop-over-headlines-in-active-region
  13631. cl
  13632. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13633. (let ((org-setting-tags t))
  13634. (if arg
  13635. (save-excursion
  13636. (goto-char (point-min))
  13637. (while (re-search-forward org-outline-regexp-bol nil t)
  13638. (org-set-tags nil t)
  13639. (end-of-line))
  13640. (message "All tags realigned to column %d" org-tags-column))
  13641. (let* ((current (org-get-tags-string))
  13642. (tags
  13643. (if just-align current
  13644. ;; Get a new set of tags from the user.
  13645. (save-excursion
  13646. (let* ((seen)
  13647. (table
  13648. (setq
  13649. org-last-tags-completion-table
  13650. ;; Uniquify tags in alists, yet preserve
  13651. ;; structure (i.e., keywords).
  13652. (delq nil
  13653. (mapcar
  13654. (lambda (pair)
  13655. (let ((head (car pair)))
  13656. (cond ((symbolp head) pair)
  13657. ((member head seen) nil)
  13658. (t (push head seen)
  13659. pair))))
  13660. (append
  13661. (or org-current-tag-alist
  13662. (org-get-buffer-tags))
  13663. (and
  13664. org-complete-tags-always-offer-all-agenda-tags
  13665. (org-global-tags-completion-table
  13666. (org-agenda-files))))))))
  13667. (current-tags (org-split-string current ":"))
  13668. (inherited-tags
  13669. (nreverse (nthcdr (length current-tags)
  13670. (nreverse (org-get-tags-at))))))
  13671. (replace-regexp-in-string
  13672. "\\([-+&]+\\|,\\)"
  13673. ":"
  13674. (if (or (eq t org-use-fast-tag-selection)
  13675. (and org-use-fast-tag-selection
  13676. (delq nil (mapcar #'cdr table))))
  13677. (org-fast-tag-selection
  13678. current-tags inherited-tags table
  13679. (and org-fast-tag-selection-include-todo
  13680. org-todo-key-alist))
  13681. (let ((org-add-colon-after-tag-completion
  13682. (< 1 (length table))))
  13683. (org-trim
  13684. (completing-read
  13685. "Tags: "
  13686. #'org-tags-completion-function
  13687. nil nil current 'org-tags-history))))))))))
  13688. (when org-tags-sort-function
  13689. (setq tags
  13690. (mapconcat
  13691. #'identity
  13692. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13693. org-tags-sort-function)
  13694. ":")))
  13695. (if (or (string= ":" tags)
  13696. (string= "::" tags))
  13697. (setq tags ""))
  13698. (if (not (org-string-nw-p tags)) (setq tags "")
  13699. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13700. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13701. ;; Insert new tags at the correct column.
  13702. (unless (equal current tags)
  13703. (save-excursion
  13704. (beginning-of-line)
  13705. (let ((case-fold-search nil))
  13706. (looking-at org-complex-heading-regexp))
  13707. ;; Remove current tags, if any.
  13708. (when (match-end 5) (replace-match "" nil nil nil 5))
  13709. ;; Insert new tags, if any. Otherwise, remove trailing
  13710. ;; white spaces.
  13711. (end-of-line)
  13712. (if (not (equal tags ""))
  13713. ;; When text is being inserted on an invisible
  13714. ;; region boundary, it can be inadvertently sucked
  13715. ;; into invisibility.
  13716. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13717. (skip-chars-backward " \t")
  13718. (delete-region (point) (line-end-position)))))
  13719. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13720. ;; is on.
  13721. (unless (equal tags "")
  13722. (let* ((level (save-excursion
  13723. (beginning-of-line)
  13724. (skip-chars-forward "\\*")))
  13725. (offset (if (bound-and-true-p org-indent-mode)
  13726. (* (1- org-indent-indentation-per-level)
  13727. (1- level))
  13728. 0))
  13729. (tags-column
  13730. (+ org-tags-column
  13731. (if (> org-tags-column 0) (- offset) offset))))
  13732. (org--align-tags-here tags-column))))
  13733. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13734. (defun org-change-tag-in-region (beg end tag off)
  13735. "Add or remove TAG for each entry in the region.
  13736. This works in the agenda, and also in an Org buffer."
  13737. (interactive
  13738. (list (region-beginning) (region-end)
  13739. (let ((org-last-tags-completion-table
  13740. (if (derived-mode-p 'org-mode)
  13741. (org-uniquify
  13742. (delq nil (append (org-get-buffer-tags)
  13743. (org-global-tags-completion-table))))
  13744. (org-global-tags-completion-table))))
  13745. (completing-read
  13746. "Tag: " 'org-tags-completion-function nil nil nil
  13747. 'org-tags-history))
  13748. (progn
  13749. (message "[s]et or [r]emove? ")
  13750. (equal (read-char-exclusive) ?r))))
  13751. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13752. (let ((agendap (equal major-mode 'org-agenda-mode))
  13753. l1 l2 m buf pos newhead (cnt 0))
  13754. (goto-char end)
  13755. (setq l2 (1- (org-current-line)))
  13756. (goto-char beg)
  13757. (setq l1 (org-current-line))
  13758. (cl-loop for l from l1 to l2 do
  13759. (org-goto-line l)
  13760. (setq m (get-text-property (point) 'org-hd-marker))
  13761. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13762. (and agendap m))
  13763. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13764. pos (if agendap m (point)))
  13765. (with-current-buffer buf
  13766. (save-excursion
  13767. (save-restriction
  13768. (goto-char pos)
  13769. (setq cnt (1+ cnt))
  13770. (org-toggle-tag tag (if off 'off 'on))
  13771. (setq newhead (org-get-heading)))))
  13772. (and agendap (org-agenda-change-all-lines newhead m))))
  13773. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13774. (defun org-tags-completion-function (string _predicate &optional flag)
  13775. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13776. (confirm (lambda (x) (stringp (car x)))))
  13777. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13778. (setq s1 (match-string 1 string)
  13779. s2 (match-string 2 string))
  13780. (setq s1 "" s2 string))
  13781. (cond
  13782. ((eq flag nil)
  13783. ;; try completion
  13784. (setq rtn (try-completion s2 ctable confirm))
  13785. (when (stringp rtn)
  13786. (setq rtn
  13787. (concat s1 s2 (substring rtn (length s2))
  13788. (if (and org-add-colon-after-tag-completion
  13789. (assoc rtn ctable))
  13790. ":" ""))))
  13791. rtn)
  13792. ((eq flag t)
  13793. ;; all-completions
  13794. (all-completions s2 ctable confirm))
  13795. ((eq flag 'lambda)
  13796. ;; exact match?
  13797. (assoc s2 ctable)))))
  13798. (defun org-fast-tag-insert (kwd tags face &optional end)
  13799. "Insert KDW, and the TAGS, the latter with face FACE.
  13800. Also insert END."
  13801. (insert (format "%-12s" (concat kwd ":"))
  13802. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13803. (or end "")))
  13804. (defun org-fast-tag-show-exit (flag)
  13805. (save-excursion
  13806. (org-goto-line 3)
  13807. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13808. (replace-match ""))
  13809. (when flag
  13810. (end-of-line 1)
  13811. (org-move-to-column (- (window-width) 19) t)
  13812. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13813. (defun org-set-current-tags-overlay (current prefix)
  13814. "Add an overlay to CURRENT tag with PREFIX."
  13815. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13816. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13817. (org-overlay-display org-tags-overlay (concat prefix s))))
  13818. (defvar org-last-tag-selection-key nil)
  13819. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13820. "Fast tag selection with single keys.
  13821. CURRENT is the current list of tags in the headline, INHERITED is the
  13822. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13823. possibly with grouping information. TODO-TABLE is a similar table with
  13824. TODO keywords, should these have keys assigned to them.
  13825. If the keys are nil, a-z are automatically assigned.
  13826. Returns the new tags string, or nil to not change the current settings."
  13827. (let* ((fulltable (append table todo-table))
  13828. (maxlen (apply 'max (mapcar
  13829. (lambda (x)
  13830. (if (stringp (car x)) (string-width (car x)) 0))
  13831. fulltable)))
  13832. (buf (current-buffer))
  13833. (expert (eq org-fast-tag-selection-single-key 'expert))
  13834. (buffer-tags nil)
  13835. (fwidth (+ maxlen 3 1 3))
  13836. (ncol (/ (- (window-width) 4) fwidth))
  13837. (i-face 'org-done)
  13838. (c-face 'org-todo)
  13839. tg cnt e c char c1 c2 ntable tbl rtn
  13840. ov-start ov-end ov-prefix
  13841. (exit-after-next org-fast-tag-selection-single-key)
  13842. (done-keywords org-done-keywords)
  13843. groups ingroup intaggroup)
  13844. (save-excursion
  13845. (beginning-of-line 1)
  13846. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13847. (setq ov-start (match-beginning 1)
  13848. ov-end (match-end 1)
  13849. ov-prefix "")
  13850. (setq ov-start (1- (point-at-eol))
  13851. ov-end (1+ ov-start))
  13852. (skip-chars-forward "^\n\r")
  13853. (setq ov-prefix
  13854. (concat
  13855. (buffer-substring (1- (point)) (point))
  13856. (if (> (current-column) org-tags-column)
  13857. " "
  13858. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13859. (move-overlay org-tags-overlay ov-start ov-end)
  13860. (save-window-excursion
  13861. (if expert
  13862. (set-buffer (get-buffer-create " *Org tags*"))
  13863. (delete-other-windows)
  13864. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13865. (org-switch-to-buffer-other-window " *Org tags*"))
  13866. (erase-buffer)
  13867. (setq-local org-done-keywords done-keywords)
  13868. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13869. (org-fast-tag-insert "Current" current c-face "\n\n")
  13870. (org-fast-tag-show-exit exit-after-next)
  13871. (org-set-current-tags-overlay current ov-prefix)
  13872. (setq tbl fulltable char ?a cnt 0)
  13873. (while (setq e (pop tbl))
  13874. (cond
  13875. ((eq (car e) :startgroup)
  13876. (push '() groups) (setq ingroup t)
  13877. (unless (zerop cnt)
  13878. (setq cnt 0)
  13879. (insert "\n"))
  13880. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13881. ((eq (car e) :endgroup)
  13882. (setq ingroup nil cnt 0)
  13883. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13884. ((eq (car e) :startgrouptag)
  13885. (setq intaggroup t)
  13886. (unless (zerop cnt)
  13887. (setq cnt 0)
  13888. (insert "\n"))
  13889. (insert "[ "))
  13890. ((eq (car e) :endgrouptag)
  13891. (setq intaggroup nil cnt 0)
  13892. (insert "]\n"))
  13893. ((equal e '(:newline))
  13894. (unless (zerop cnt)
  13895. (setq cnt 0)
  13896. (insert "\n")
  13897. (setq e (car tbl))
  13898. (while (equal (car tbl) '(:newline))
  13899. (insert "\n")
  13900. (setq tbl (cdr tbl)))))
  13901. ((equal e '(:grouptags)) (insert " : "))
  13902. (t
  13903. (setq tg (copy-sequence (car e)) c2 nil)
  13904. (if (cdr e)
  13905. (setq c (cdr e))
  13906. ;; automatically assign a character.
  13907. (setq c1 (string-to-char
  13908. (downcase (substring
  13909. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13910. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13911. (while (or (rassoc char ntable) (rassoc char table))
  13912. (setq char (1+ char)))
  13913. (setq c2 c1))
  13914. (setq c (or c2 char)))
  13915. (when ingroup (push tg (car groups)))
  13916. (setq tg (org-add-props tg nil 'face
  13917. (cond
  13918. ((not (assoc tg table))
  13919. (org-get-todo-face tg))
  13920. ((member tg current) c-face)
  13921. ((member tg inherited) i-face))))
  13922. (when (equal (caar tbl) :grouptags)
  13923. (org-add-props tg nil 'face 'org-tag-group))
  13924. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13925. (insert "[" c "] " tg (make-string
  13926. (- fwidth 4 (length tg)) ?\ ))
  13927. (push (cons tg c) ntable)
  13928. (when (= (cl-incf cnt) ncol)
  13929. (insert "\n")
  13930. (when (or ingroup intaggroup) (insert " "))
  13931. (setq cnt 0)))))
  13932. (setq ntable (nreverse ntable))
  13933. (insert "\n")
  13934. (goto-char (point-min))
  13935. (unless expert (org-fit-window-to-buffer))
  13936. (setq rtn
  13937. (catch 'exit
  13938. (while t
  13939. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13940. (if (not groups) "no " "")
  13941. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13942. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13943. (setq org-last-tag-selection-key c)
  13944. (cond
  13945. ((= c ?\r) (throw 'exit t))
  13946. ((= c ?!)
  13947. (setq groups (not groups))
  13948. (goto-char (point-min))
  13949. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13950. ((= c ?\C-c)
  13951. (if (not expert)
  13952. (org-fast-tag-show-exit
  13953. (setq exit-after-next (not exit-after-next)))
  13954. (setq expert nil)
  13955. (delete-other-windows)
  13956. (set-window-buffer (split-window-vertically) " *Org tags*")
  13957. (org-switch-to-buffer-other-window " *Org tags*")
  13958. (org-fit-window-to-buffer)))
  13959. ((or (= c ?\C-g)
  13960. (and (= c ?q) (not (rassoc c ntable))))
  13961. (delete-overlay org-tags-overlay)
  13962. (setq quit-flag t))
  13963. ((= c ?\ )
  13964. (setq current nil)
  13965. (when exit-after-next (setq exit-after-next 'now)))
  13966. ((= c ?\t)
  13967. (condition-case nil
  13968. (setq tg (completing-read
  13969. "Tag: "
  13970. (or buffer-tags
  13971. (with-current-buffer buf
  13972. (setq buffer-tags
  13973. (org-get-buffer-tags))))))
  13974. (quit (setq tg "")))
  13975. (when (string-match "\\S-" tg)
  13976. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13977. (if (member tg current)
  13978. (setq current (delete tg current))
  13979. (push tg current)))
  13980. (when exit-after-next (setq exit-after-next 'now)))
  13981. ((setq e (rassoc c todo-table) tg (car e))
  13982. (with-current-buffer buf
  13983. (save-excursion (org-todo tg)))
  13984. (when exit-after-next (setq exit-after-next 'now)))
  13985. ((setq e (rassoc c ntable) tg (car e))
  13986. (if (member tg current)
  13987. (setq current (delete tg current))
  13988. (cl-loop for g in groups do
  13989. (when (member tg g)
  13990. (dolist (x g) (setq current (delete x current)))))
  13991. (push tg current))
  13992. (when exit-after-next (setq exit-after-next 'now))))
  13993. ;; Create a sorted list
  13994. (setq current
  13995. (sort current
  13996. (lambda (a b)
  13997. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13998. (when (eq exit-after-next 'now) (throw 'exit t))
  13999. (goto-char (point-min))
  14000. (beginning-of-line 2)
  14001. (delete-region (point) (point-at-eol))
  14002. (org-fast-tag-insert "Current" current c-face)
  14003. (org-set-current-tags-overlay current ov-prefix)
  14004. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14005. (setq tg (match-string 1))
  14006. (add-text-properties
  14007. (match-beginning 1) (match-end 1)
  14008. (list 'face
  14009. (cond
  14010. ((member tg current) c-face)
  14011. ((member tg inherited) i-face)
  14012. (t (get-text-property (match-beginning 1) 'face))))))
  14013. (goto-char (point-min)))))
  14014. (delete-overlay org-tags-overlay)
  14015. (if rtn
  14016. (mapconcat 'identity current ":")
  14017. nil))))
  14018. (defun org-get-tags-string ()
  14019. "Get the TAGS string in the current headline."
  14020. (unless (org-at-heading-p t)
  14021. (user-error "Not on a heading"))
  14022. (save-excursion
  14023. (beginning-of-line 1)
  14024. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14025. (match-string-no-properties 1)
  14026. "")))
  14027. (defun org-get-tags ()
  14028. "Get the list of tags specified in the current headline."
  14029. (org-split-string (org-get-tags-string) ":"))
  14030. (defun org-get-buffer-tags ()
  14031. "Get a table of all tags used in the buffer, for completion."
  14032. (org-with-wide-buffer
  14033. (goto-char (point-min))
  14034. (let ((tag-re (concat org-outline-regexp-bol
  14035. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14036. tags)
  14037. (while (re-search-forward tag-re nil t)
  14038. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14039. (push tag tags)))
  14040. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14041. ;;;; The mapping API
  14042. (defvar org-agenda-skip-comment-trees)
  14043. (defvar org-agenda-skip-function)
  14044. (defun org-map-entries (func &optional match scope &rest skip)
  14045. "Call FUNC at each headline selected by MATCH in SCOPE.
  14046. FUNC is a function or a lisp form. The function will be called without
  14047. arguments, with the cursor positioned at the beginning of the headline.
  14048. The return values of all calls to the function will be collected and
  14049. returned as a list.
  14050. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14051. does not need to preserve point. After evaluation, the cursor will be
  14052. moved to the end of the line (presumably of the headline of the
  14053. processed entry) and search continues from there. Under some
  14054. circumstances, this may not produce the wanted results. For example,
  14055. if you have removed (e.g. archived) the current (sub)tree it could
  14056. mean that the next entry will be skipped entirely. In such cases, you
  14057. can specify the position from where search should continue by making
  14058. FUNC set the variable `org-map-continue-from' to the desired buffer
  14059. position.
  14060. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14061. Only headlines that are matched by this query will be considered during
  14062. the iteration. When MATCH is nil or t, all headlines will be
  14063. visited by the iteration.
  14064. SCOPE determines the scope of this command. It can be any of:
  14065. nil The current buffer, respecting the restriction if any
  14066. tree The subtree started with the entry at point
  14067. region The entries within the active region, if any
  14068. region-start-level
  14069. The entries within the active region, but only those at
  14070. the same level than the first one.
  14071. file The current buffer, without restriction
  14072. file-with-archives
  14073. The current buffer, and any archives associated with it
  14074. agenda All agenda files
  14075. agenda-with-archives
  14076. All agenda files with any archive files associated with them
  14077. \(file1 file2 ...)
  14078. If this is a list, all files in the list will be scanned
  14079. The remaining args are treated as settings for the skipping facilities of
  14080. the scanner. The following items can be given here:
  14081. archive skip trees with the archive tag
  14082. comment skip trees with the COMMENT keyword
  14083. function or Emacs Lisp form:
  14084. will be used as value for `org-agenda-skip-function', so
  14085. whenever the function returns a position, FUNC will not be
  14086. called for that entry and search will continue from the
  14087. position returned
  14088. If your function needs to retrieve the tags including inherited tags
  14089. at the *current* entry, you can use the value of the variable
  14090. `org-scanner-tags' which will be much faster than getting the value
  14091. with `org-get-tags-at'. If your function gets properties with
  14092. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14093. to t around the call to `org-entry-properties' to get the same speedup.
  14094. Note that if your function moves around to retrieve tags and properties at
  14095. a *different* entry, you cannot use these techniques."
  14096. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14097. (not (org-region-active-p)))
  14098. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14099. (org-agenda-skip-archived-trees (memq 'archive skip))
  14100. (org-agenda-skip-comment-trees (memq 'comment skip))
  14101. (org-agenda-skip-function
  14102. (car (org-delete-all '(comment archive) skip)))
  14103. (org-tags-match-list-sublevels t)
  14104. (start-level (eq scope 'region-start-level))
  14105. matcher res
  14106. org-todo-keywords-for-agenda
  14107. org-done-keywords-for-agenda
  14108. org-todo-keyword-alist-for-agenda
  14109. org-tag-alist-for-agenda
  14110. org--matcher-tags-todo-only)
  14111. (cond
  14112. ((eq match t) (setq matcher t))
  14113. ((eq match nil) (setq matcher t))
  14114. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14115. (save-excursion
  14116. (save-restriction
  14117. (cond ((eq scope 'tree)
  14118. (org-back-to-heading t)
  14119. (org-narrow-to-subtree)
  14120. (setq scope nil))
  14121. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14122. (org-region-active-p))
  14123. ;; If needed, set start-level to a string like "2"
  14124. (when start-level
  14125. (save-excursion
  14126. (goto-char (region-beginning))
  14127. (unless (org-at-heading-p) (outline-next-heading))
  14128. (setq start-level (org-current-level))))
  14129. (narrow-to-region (region-beginning)
  14130. (save-excursion
  14131. (goto-char (region-end))
  14132. (unless (and (bolp) (org-at-heading-p))
  14133. (outline-next-heading))
  14134. (point)))
  14135. (setq scope nil)))
  14136. (if (not scope)
  14137. (progn
  14138. (org-agenda-prepare-buffers
  14139. (and buffer-file-name (list buffer-file-name)))
  14140. (setq res
  14141. (org-scan-tags
  14142. func matcher org--matcher-tags-todo-only start-level)))
  14143. ;; Get the right scope
  14144. (cond
  14145. ((and scope (listp scope) (symbolp (car scope)))
  14146. (setq scope (eval scope)))
  14147. ((eq scope 'agenda)
  14148. (setq scope (org-agenda-files t)))
  14149. ((eq scope 'agenda-with-archives)
  14150. (setq scope (org-agenda-files t))
  14151. (setq scope (org-add-archive-files scope)))
  14152. ((eq scope 'file)
  14153. (setq scope (and buffer-file-name (list buffer-file-name))))
  14154. ((eq scope 'file-with-archives)
  14155. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14156. (org-agenda-prepare-buffers scope)
  14157. (dolist (file scope)
  14158. (with-current-buffer (org-find-base-buffer-visiting file)
  14159. (org-with-wide-buffer
  14160. (goto-char (point-min))
  14161. (setq res
  14162. (append
  14163. res
  14164. (org-scan-tags
  14165. func matcher org--matcher-tags-todo-only)))))))))
  14166. res)))
  14167. ;;; Properties API
  14168. (defconst org-special-properties
  14169. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14170. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14171. "The special properties valid in Org mode.
  14172. These are properties that are not defined in the property drawer,
  14173. but in some other way.")
  14174. (defconst org-default-properties
  14175. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14176. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14177. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14178. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14179. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14180. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14181. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14182. "Some properties that are used by Org mode for various purposes.
  14183. Being in this list makes sure that they are offered for completion.")
  14184. (defun org--valid-property-p (property)
  14185. "Non nil when string PROPERTY is a valid property name."
  14186. (not
  14187. (or (equal property "")
  14188. (string-match-p "\\s-" property))))
  14189. (defun org--update-property-plist (key val props)
  14190. "Associate KEY to VAL in alist PROPS.
  14191. Modifications are made by side-effect. Return new alist."
  14192. (let* ((appending (string= (substring key -1) "+"))
  14193. (key (if appending (substring key 0 -1) key))
  14194. (old (assoc-string key props t)))
  14195. (if (not old) (cons (cons key val) props)
  14196. (setcdr old (if appending (concat (cdr old) " " val) val))
  14197. props)))
  14198. (defun org-get-property-block (&optional beg force)
  14199. "Return the (beg . end) range of the body of the property drawer.
  14200. BEG is the beginning of the current subtree, or of the part
  14201. before the first headline. If it is not given, it will be found.
  14202. If the drawer does not exist, create it if FORCE is non-nil, or
  14203. return nil."
  14204. (org-with-wide-buffer
  14205. (when beg (goto-char beg))
  14206. (unless (org-before-first-heading-p)
  14207. (let ((beg (cond (beg)
  14208. ((or (not (featurep 'org-inlinetask))
  14209. (org-inlinetask-in-task-p))
  14210. (org-back-to-heading t))
  14211. (t (org-with-limited-levels (org-back-to-heading t))))))
  14212. (forward-line)
  14213. (when (looking-at-p org-planning-line-re) (forward-line))
  14214. (cond ((looking-at org-property-drawer-re)
  14215. (forward-line)
  14216. (cons (point) (progn (goto-char (match-end 0))
  14217. (line-beginning-position))))
  14218. (force
  14219. (goto-char beg)
  14220. (org-insert-property-drawer)
  14221. (let ((pos (save-excursion (search-forward ":END:")
  14222. (line-beginning-position))))
  14223. (cons pos pos))))))))
  14224. (defun org-at-property-p ()
  14225. "Non-nil when point is inside a property drawer.
  14226. See `org-property-re' for match data, if applicable."
  14227. (save-excursion
  14228. (beginning-of-line)
  14229. (and (looking-at org-property-re)
  14230. (let ((property-drawer (save-match-data (org-get-property-block))))
  14231. (and property-drawer
  14232. (>= (point) (car property-drawer))
  14233. (< (point) (cdr property-drawer)))))))
  14234. (defun org-property-action ()
  14235. "Do an action on properties."
  14236. (interactive)
  14237. (unless (org-at-property-p) (user-error "Not at a property"))
  14238. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14239. (let ((c (read-char-exclusive)))
  14240. (cl-case c
  14241. (?s (call-interactively #'org-set-property))
  14242. (?d (call-interactively #'org-delete-property))
  14243. (?D (call-interactively #'org-delete-property-globally))
  14244. (?c (call-interactively #'org-compute-property-at-point))
  14245. (otherwise (user-error "No such property action %c" c)))))
  14246. (defun org-inc-effort ()
  14247. "Increment the value of the effort property in the current entry."
  14248. (interactive)
  14249. (org-set-effort nil t))
  14250. (defvar org-clock-effort) ; Defined in org-clock.el.
  14251. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14252. (defun org-set-effort (&optional value increment)
  14253. "Set the effort property of the current entry.
  14254. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14255. 10th allowed value.
  14256. When INCREMENT is non-nil, set the property to the next allowed value."
  14257. (interactive "P")
  14258. (when (equal value 0) (setq value 10))
  14259. (let* ((completion-ignore-case t)
  14260. (prop org-effort-property)
  14261. (cur (org-entry-get nil prop))
  14262. (allowed (org-property-get-allowed-values nil prop 'table))
  14263. (existing (mapcar 'list (org-property-values prop)))
  14264. (heading (nth 4 (org-heading-components)))
  14265. rpl
  14266. (val (cond
  14267. ((stringp value) value)
  14268. ((and allowed (integerp value))
  14269. (or (car (nth (1- value) allowed))
  14270. (car (org-last allowed))))
  14271. ((and allowed increment)
  14272. (or (cl-caadr (member (list cur) allowed))
  14273. (user-error "Allowed effort values are not set")))
  14274. (allowed
  14275. (message "Select 1-9,0, [RET%s]: %s"
  14276. (if cur (concat "=" cur) "")
  14277. (mapconcat 'car allowed " "))
  14278. (setq rpl (read-char-exclusive))
  14279. (if (equal rpl ?\r)
  14280. cur
  14281. (setq rpl (- rpl ?0))
  14282. (when (equal rpl 0) (setq rpl 10))
  14283. (if (and (> rpl 0) (<= rpl (length allowed)))
  14284. (car (nth (1- rpl) allowed))
  14285. (org-completing-read "Effort: " allowed nil))))
  14286. (t
  14287. (org-completing-read
  14288. (concat "Effort" (and cur (string-match "\\S-" cur)
  14289. (concat " [" cur "]"))
  14290. ": ")
  14291. existing nil nil "" nil cur)))))
  14292. (unless (equal (org-entry-get nil prop) val)
  14293. (org-entry-put nil prop val))
  14294. (org-refresh-property
  14295. '((effort . identity)
  14296. (effort-minutes . org-duration-string-to-minutes))
  14297. val)
  14298. (when (equal heading (bound-and-true-p org-clock-current-task))
  14299. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14300. (org-clock-update-mode-line))
  14301. (message "%s is now %s" prop val)))
  14302. (defun org-entry-properties (&optional pom which)
  14303. "Get all properties of the current entry.
  14304. When POM is a buffer position, get all properties from the entry
  14305. there instead.
  14306. This includes the TODO keyword, the tags, time strings for
  14307. deadline, scheduled, and clocking, and any additional properties
  14308. defined in the entry.
  14309. If WHICH is nil or `all', get all properties. If WHICH is
  14310. `special' or `standard', only get that subclass. If WHICH is
  14311. a string, only get that property.
  14312. Return value is an alist. Keys are properties, as upcased
  14313. strings."
  14314. (org-with-point-at pom
  14315. (when (and (derived-mode-p 'org-mode)
  14316. (ignore-errors (org-back-to-heading t)))
  14317. (catch 'exit
  14318. (let* ((beg (point))
  14319. (specific (and (stringp which) (upcase which)))
  14320. (which (cond ((not specific) which)
  14321. ((member specific org-special-properties) 'special)
  14322. (t 'standard)))
  14323. props)
  14324. ;; Get the special properties, like TODO and TAGS.
  14325. (when (memq which '(nil all special))
  14326. (when (or (not specific) (string= specific "CLOCKSUM"))
  14327. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14328. (when clocksum
  14329. (push (cons "CLOCKSUM"
  14330. (org-minutes-to-clocksum-string clocksum))
  14331. props)))
  14332. (when specific (throw 'exit props)))
  14333. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14334. (let ((clocksumt (get-text-property (point)
  14335. :org-clock-minutes-today)))
  14336. (when clocksumt
  14337. (push (cons "CLOCKSUM_T"
  14338. (org-minutes-to-clocksum-string clocksumt))
  14339. props)))
  14340. (when specific (throw 'exit props)))
  14341. (when (or (not specific) (string= specific "ITEM"))
  14342. (let ((case-fold-search nil))
  14343. (when (looking-at org-complex-heading-regexp)
  14344. (push (cons "ITEM"
  14345. (let ((title (match-string-no-properties 4)))
  14346. (if (org-string-nw-p title)
  14347. (org-remove-tabs title)
  14348. "")))
  14349. props)))
  14350. (when specific (throw 'exit props)))
  14351. (when (or (not specific) (string= specific "TODO"))
  14352. (let ((case-fold-search nil))
  14353. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14354. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14355. (when specific (throw 'exit props)))
  14356. (when (or (not specific) (string= specific "PRIORITY"))
  14357. (push (cons "PRIORITY"
  14358. (if (looking-at org-priority-regexp)
  14359. (match-string-no-properties 2)
  14360. (char-to-string org-default-priority)))
  14361. props)
  14362. (when specific (throw 'exit props)))
  14363. (when (or (not specific) (string= specific "FILE"))
  14364. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14365. props)
  14366. (when specific (throw 'exit props)))
  14367. (when (or (not specific) (string= specific "TAGS"))
  14368. (let ((value (org-string-nw-p (org-get-tags-string))))
  14369. (when value (push (cons "TAGS" value) props)))
  14370. (when specific (throw 'exit props)))
  14371. (when (or (not specific) (string= specific "ALLTAGS"))
  14372. (let ((value (org-get-tags-at)))
  14373. (when value
  14374. (push (cons "ALLTAGS"
  14375. (format ":%s:" (mapconcat #'identity value ":")))
  14376. props)))
  14377. (when specific (throw 'exit props)))
  14378. (when (or (not specific) (string= specific "BLOCKED"))
  14379. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14380. (when specific (throw 'exit props)))
  14381. (when (or (not specific)
  14382. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14383. (forward-line)
  14384. (when (looking-at-p org-planning-line-re)
  14385. (end-of-line)
  14386. (let ((bol (line-beginning-position))
  14387. ;; Backward compatibility: time keywords used to
  14388. ;; be configurable (before 8.3). Make sure we
  14389. ;; get the correct keyword.
  14390. (key-assoc `(("CLOSED" . ,org-closed-string)
  14391. ("DEADLINE" . ,org-deadline-string)
  14392. ("SCHEDULED" . ,org-scheduled-string))))
  14393. (dolist (pair (if specific (list (assoc specific key-assoc))
  14394. key-assoc))
  14395. (save-excursion
  14396. (when (search-backward (cdr pair) bol t)
  14397. (goto-char (match-end 0))
  14398. (skip-chars-forward " \t")
  14399. (and (looking-at org-ts-regexp-both)
  14400. (push (cons (car pair)
  14401. (match-string-no-properties 0))
  14402. props)))))))
  14403. (when specific (throw 'exit props)))
  14404. (when (or (not specific)
  14405. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14406. (let ((find-ts
  14407. (lambda (end ts)
  14408. ;; Fix next time-stamp before END. TS is the
  14409. ;; list of time-stamps found so far.
  14410. (let ((ts ts)
  14411. (regexp (cond
  14412. ((string= specific "TIMESTAMP")
  14413. org-ts-regexp)
  14414. ((string= specific "TIMESTAMP_IA")
  14415. org-ts-regexp-inactive)
  14416. ((assoc "TIMESTAMP_IA" ts)
  14417. org-ts-regexp)
  14418. ((assoc "TIMESTAMP" ts)
  14419. org-ts-regexp-inactive)
  14420. (t org-ts-regexp-both))))
  14421. (catch 'next
  14422. (while (re-search-forward regexp end t)
  14423. (backward-char)
  14424. (let ((object (org-element-context)))
  14425. ;; Accept to match timestamps in node
  14426. ;; properties, too.
  14427. (when (memq (org-element-type object)
  14428. '(node-property timestamp))
  14429. (let ((type
  14430. (org-element-property :type object)))
  14431. (cond
  14432. ((and (memq type '(active active-range))
  14433. (not (equal specific "TIMESTAMP_IA")))
  14434. (unless (assoc "TIMESTAMP" ts)
  14435. (push (cons "TIMESTAMP"
  14436. (org-element-property
  14437. :raw-value object))
  14438. ts)
  14439. (when specific (throw 'exit ts))))
  14440. ((and (memq type '(inactive inactive-range))
  14441. (not (string= specific "TIMESTAMP")))
  14442. (unless (assoc "TIMESTAMP_IA" ts)
  14443. (push (cons "TIMESTAMP_IA"
  14444. (org-element-property
  14445. :raw-value object))
  14446. ts)
  14447. (when specific (throw 'exit ts))))))
  14448. ;; Both timestamp types are found,
  14449. ;; move to next part.
  14450. (when (= (length ts) 2) (throw 'next ts)))))
  14451. ts)))))
  14452. (goto-char beg)
  14453. ;; First look for timestamps within headline.
  14454. (let ((ts (funcall find-ts (line-end-position) nil)))
  14455. (if (= (length ts) 2) (setq props (nconc ts props))
  14456. ;; Then find timestamps in the section, skipping
  14457. ;; planning line.
  14458. (let ((end (save-excursion (outline-next-heading))))
  14459. (forward-line)
  14460. (when (looking-at-p org-planning-line-re) (forward-line))
  14461. (setq props (nconc (funcall find-ts end ts) props))))))))
  14462. ;; Get the standard properties, like :PROP:.
  14463. (when (memq which '(nil all standard))
  14464. ;; If we are looking after a specific property, delegate
  14465. ;; to `org-entry-get', which is faster. However, make an
  14466. ;; exception for "CATEGORY", since it can be also set
  14467. ;; through keywords (i.e. #+CATEGORY).
  14468. (if (and specific (not (equal specific "CATEGORY")))
  14469. (let ((value (org-entry-get beg specific nil t)))
  14470. (throw 'exit (and value (list (cons specific value)))))
  14471. (let ((range (org-get-property-block beg)))
  14472. (when range
  14473. (let ((end (cdr range)) seen-base)
  14474. (goto-char (car range))
  14475. ;; Unlike to `org--update-property-plist', we
  14476. ;; handle the case where base values is found
  14477. ;; after its extension. We also forbid standard
  14478. ;; properties to be named as special properties.
  14479. (while (re-search-forward org-property-re end t)
  14480. (let* ((key (upcase (match-string-no-properties 2)))
  14481. (extendp (string-match-p "\\+\\'" key))
  14482. (key-base (if extendp (substring key 0 -1) key))
  14483. (value (match-string-no-properties 3)))
  14484. (cond
  14485. ((member-ignore-case key-base org-special-properties))
  14486. (extendp
  14487. (setq props
  14488. (org--update-property-plist key value props)))
  14489. ((member key seen-base))
  14490. (t (push key seen-base)
  14491. (let ((p (assoc-string key props t)))
  14492. (if p (setcdr p (concat value " " (cdr p)))
  14493. (push (cons key value) props))))))))))))
  14494. (unless (assoc "CATEGORY" props)
  14495. (push (cons "CATEGORY" (org-get-category beg)) props)
  14496. (when (string= specific "CATEGORY") (throw 'exit props)))
  14497. ;; Return value.
  14498. props)))))
  14499. (defun org--property-local-values (property literal-nil)
  14500. "Return value for PROPERTY in current entry.
  14501. Value is a list whose car is the base value for PROPERTY and cdr
  14502. a list of accumulated values. Return nil if neither is found in
  14503. the entry. Also return nil when PROPERTY is set to \"nil\",
  14504. unless LITERAL-NIL is non-nil."
  14505. (let ((range (org-get-property-block)))
  14506. (when range
  14507. (goto-char (car range))
  14508. (let* ((case-fold-search t)
  14509. (end (cdr range))
  14510. (value
  14511. ;; Base value.
  14512. (save-excursion
  14513. (let ((v (and (re-search-forward
  14514. (org-re-property property nil t) end t)
  14515. (match-string-no-properties 3))))
  14516. (list (if literal-nil v (org-not-nil v)))))))
  14517. ;; Find additional values.
  14518. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14519. (while (re-search-forward property+ end t)
  14520. (push (match-string-no-properties 3) value)))
  14521. ;; Return final values.
  14522. (and (not (equal value '(nil))) (nreverse value))))))
  14523. (defun org--property-global-value (property literal-nil)
  14524. "Return value for PROPERTY in current buffer.
  14525. Return value is a string. Return nil if property is not set
  14526. globally. Also return nil when PROPERTY is set to \"nil\",
  14527. unless LITERAL-NIL is non-nil."
  14528. (let ((global
  14529. (cdr (or (assoc-string property org-file-properties t)
  14530. (assoc-string property org-global-properties t)
  14531. (assoc-string property org-global-properties-fixed t)))))
  14532. (if literal-nil global (org-not-nil global))))
  14533. (defun org-entry-get (pom property &optional inherit literal-nil)
  14534. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14535. If INHERIT is non-nil and the entry does not have the property,
  14536. then also check higher levels of the hierarchy. If INHERIT is
  14537. the symbol `selective', use inheritance only if the setting in
  14538. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14539. If the property is present but empty, the return value is the
  14540. empty string. If the property is not present at all, nil is
  14541. returned. In any other case, return the value as a string.
  14542. Search is case-insensitive.
  14543. If LITERAL-NIL is set, return the string value \"nil\" as
  14544. a string, do not interpret it as the list atom nil. This is used
  14545. for inheritance when a \"nil\" value can supersede a non-nil
  14546. value higher up the hierarchy."
  14547. (org-with-point-at pom
  14548. (cond
  14549. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14550. ;; We need a special property. Use `org-entry-properties' to
  14551. ;; retrieve it, but specify the wanted property.
  14552. (cdr (assoc-string property (org-entry-properties nil property))))
  14553. ((and inherit
  14554. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14555. (org-entry-get-with-inheritance property literal-nil))
  14556. (t
  14557. (let* ((local (org--property-local-values property literal-nil))
  14558. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14559. (if literal-nil value (org-not-nil value)))))))
  14560. (defun org-property-or-variable-value (var &optional inherit)
  14561. "Check if there is a property fixing the value of VAR.
  14562. If yes, return this value. If not, return the current value of the variable."
  14563. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14564. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14565. (read prop)
  14566. (symbol-value var))))
  14567. (defun org-entry-delete (pom property)
  14568. "Delete PROPERTY from entry at point-or-marker POM.
  14569. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14570. non-nil when a property was removed."
  14571. (org-with-point-at pom
  14572. (pcase (org-get-property-block)
  14573. (`(,begin . ,origin)
  14574. (let* ((end (copy-marker origin))
  14575. (re (org-re-property
  14576. (concat (regexp-quote property) "\\+?") t t)))
  14577. (goto-char begin)
  14578. (while (re-search-forward re end t)
  14579. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14580. ;; If drawer is empty, remove it altogether.
  14581. (when (= begin end)
  14582. (delete-region (line-beginning-position 0)
  14583. (line-beginning-position 2)))
  14584. ;; Return non-nil if some property was removed.
  14585. (prog1 (/= end origin) (set-marker end nil))))
  14586. (_ nil))))
  14587. ;; Multi-values properties are properties that contain multiple values
  14588. ;; These values are assumed to be single words, separated by whitespace.
  14589. (defun org-entry-add-to-multivalued-property (pom property value)
  14590. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14591. (let* ((old (org-entry-get pom property))
  14592. (values (and old (org-split-string old "[ \t]"))))
  14593. (setq value (org-entry-protect-space value))
  14594. (unless (member value values)
  14595. (setq values (append values (list value)))
  14596. (org-entry-put pom property
  14597. (mapconcat 'identity values " ")))))
  14598. (defun org-entry-remove-from-multivalued-property (pom property value)
  14599. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14600. (let* ((old (org-entry-get pom property))
  14601. (values (and old (org-split-string old "[ \t]"))))
  14602. (setq value (org-entry-protect-space value))
  14603. (when (member value values)
  14604. (setq values (delete value values))
  14605. (org-entry-put pom property
  14606. (mapconcat 'identity values " ")))))
  14607. (defun org-entry-member-in-multivalued-property (pom property value)
  14608. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14609. (let* ((old (org-entry-get pom property))
  14610. (values (and old (org-split-string old "[ \t]"))))
  14611. (setq value (org-entry-protect-space value))
  14612. (member value values)))
  14613. (defun org-entry-get-multivalued-property (pom property)
  14614. "Return a list of values in a multivalued property."
  14615. (let* ((value (org-entry-get pom property))
  14616. (values (and value (org-split-string value "[ \t]"))))
  14617. (mapcar 'org-entry-restore-space values)))
  14618. (defun org-entry-put-multivalued-property (pom property &rest values)
  14619. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14620. VALUES should be a list of strings. Spaces will be protected."
  14621. (org-entry-put pom property
  14622. (mapconcat 'org-entry-protect-space values " "))
  14623. (let* ((value (org-entry-get pom property))
  14624. (values (and value (org-split-string value "[ \t]"))))
  14625. (mapcar 'org-entry-restore-space values)))
  14626. (defun org-entry-protect-space (s)
  14627. "Protect spaces and newline in string S."
  14628. (while (string-match " " s)
  14629. (setq s (replace-match "%20" t t s)))
  14630. (while (string-match "\n" s)
  14631. (setq s (replace-match "%0A" t t s)))
  14632. s)
  14633. (defun org-entry-restore-space (s)
  14634. "Restore spaces and newline in string S."
  14635. (while (string-match "%20" s)
  14636. (setq s (replace-match " " t t s)))
  14637. (while (string-match "%0A" s)
  14638. (setq s (replace-match "\n" t t s)))
  14639. s)
  14640. (defvar org-entry-property-inherited-from (make-marker)
  14641. "Marker pointing to the entry from where a property was inherited.
  14642. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14643. location of the entry where the inheritance search matched. If there was
  14644. no match, the marker will point nowhere.
  14645. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14646. is set.")
  14647. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14648. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14649. The search will stop at the first ancestor which has the property defined.
  14650. If the value found is \"nil\", return nil to show that the property
  14651. should be considered as undefined (this is the meaning of nil here).
  14652. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14653. (move-marker org-entry-property-inherited-from nil)
  14654. (org-with-wide-buffer
  14655. (let (value)
  14656. (catch 'exit
  14657. (while t
  14658. (let ((v (org--property-local-values property literal-nil)))
  14659. (when v
  14660. (setq value
  14661. (concat (mapconcat #'identity (delq nil v) " ")
  14662. (and value " ")
  14663. value)))
  14664. (cond
  14665. ((car v)
  14666. (org-back-to-heading t)
  14667. (move-marker org-entry-property-inherited-from (point))
  14668. (throw 'exit nil))
  14669. ((org-up-heading-safe))
  14670. (t
  14671. (let ((global (org--property-global-value property literal-nil)))
  14672. (cond ((not global))
  14673. (value (setq value (concat global " " value)))
  14674. (t (setq value global))))
  14675. (throw 'exit nil))))))
  14676. (if literal-nil value (org-not-nil value)))))
  14677. (defvar org-property-changed-functions nil
  14678. "Hook called when the value of a property has changed.
  14679. Each hook function should accept two arguments, the name of the property
  14680. and the new value.")
  14681. (defun org-entry-put (pom property value)
  14682. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14683. If the value is nil, it is converted to the empty string. If it
  14684. is not a string, an error is raised. Also raise an error on
  14685. invalid property names.
  14686. PROPERTY can be any regular property (see
  14687. `org-special-properties'). It can also be \"TODO\",
  14688. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14689. For the last two properties, VALUE may have any of the special
  14690. values \"earlier\" and \"later\". The function then increases or
  14691. decreases scheduled or deadline date by one day."
  14692. (cond ((null value) (setq value ""))
  14693. ((not (stringp value)) (error "Properties values should be strings"))
  14694. ((not (org--valid-property-p property))
  14695. (user-error "Invalid property name: \"%s\"" property)))
  14696. (org-with-point-at pom
  14697. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14698. (org-back-to-heading t)
  14699. (org-with-limited-levels (org-back-to-heading t)))
  14700. (let ((beg (point)))
  14701. (cond
  14702. ((equal property "TODO")
  14703. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14704. ((not (member value org-todo-keywords-1))
  14705. (user-error "\"%s\" is not a valid TODO state" value)))
  14706. (org-todo value)
  14707. (org-set-tags nil 'align))
  14708. ((equal property "PRIORITY")
  14709. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14710. (org-set-tags nil 'align))
  14711. ((equal property "SCHEDULED")
  14712. (forward-line)
  14713. (if (and (looking-at-p org-planning-line-re)
  14714. (re-search-forward
  14715. org-scheduled-time-regexp (line-end-position) t))
  14716. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14717. ((string= value "later") (org-timestamp-change 1 'day))
  14718. ((string= value "") (org-schedule '(4)))
  14719. (t (org-schedule nil value)))
  14720. (if (member value '("earlier" "later" ""))
  14721. (call-interactively #'org-schedule)
  14722. (org-schedule nil value))))
  14723. ((equal property "DEADLINE")
  14724. (forward-line)
  14725. (if (and (looking-at-p org-planning-line-re)
  14726. (re-search-forward
  14727. org-deadline-time-regexp (line-end-position) t))
  14728. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14729. ((string= value "later") (org-timestamp-change 1 'day))
  14730. ((string= value "") (org-deadline '(4)))
  14731. (t (org-deadline nil value)))
  14732. (if (member value '("earlier" "later" ""))
  14733. (call-interactively #'org-deadline)
  14734. (org-deadline nil value))))
  14735. ((member property org-special-properties)
  14736. (error "The %s property cannot be set with `org-entry-put'" property))
  14737. (t
  14738. (let* ((range (org-get-property-block beg 'force))
  14739. (end (cdr range))
  14740. (case-fold-search t))
  14741. (goto-char (car range))
  14742. (if (re-search-forward (org-re-property property nil t) end t)
  14743. (progn (delete-region (match-beginning 0) (match-end 0))
  14744. (goto-char (match-beginning 0)))
  14745. (goto-char end)
  14746. (insert "\n")
  14747. (backward-char))
  14748. (insert ":" property ":")
  14749. (when value (insert " " value))
  14750. (org-indent-line)))))
  14751. (run-hook-with-args 'org-property-changed-functions property value)))
  14752. (defun org-buffer-property-keys
  14753. (&optional specials defaults columns ignore-malformed)
  14754. "Get all property keys in the current buffer.
  14755. When SPECIALS is non-nil, also list the special properties that
  14756. reflect things like tags and TODO state.
  14757. When DEFAULTS is non-nil, also include properties that has
  14758. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14759. DESCRIPTION, LOCATION, and LOGGING and others.
  14760. When COLUMNS in non-nil, also include property names given in
  14761. COLUMN formats in the current buffer.
  14762. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14763. automatically performed, such drawers will be silently ignored."
  14764. (let ((case-fold-search t)
  14765. (props (append
  14766. (and specials org-special-properties)
  14767. (and defaults (cons org-effort-property org-default-properties))
  14768. nil)))
  14769. (org-with-wide-buffer
  14770. (goto-char (point-min))
  14771. (while (re-search-forward org-property-start-re nil t)
  14772. (let ((range (org-get-property-block)))
  14773. (catch 'skip
  14774. (unless range
  14775. (when (and (not ignore-malformed)
  14776. (not (org-before-first-heading-p))
  14777. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14778. (line-beginning-position))))
  14779. (org-get-property-block nil t))
  14780. (throw 'skip nil))
  14781. (goto-char (car range))
  14782. (let ((begin (car range))
  14783. (end (cdr range)))
  14784. ;; Make sure that found property block is not located
  14785. ;; before current point, as it would generate an infloop.
  14786. ;; It can happen, for example, in the following
  14787. ;; situation:
  14788. ;;
  14789. ;; * Headline
  14790. ;; :PROPERTIES:
  14791. ;; ...
  14792. ;; :END:
  14793. ;; *************** Inlinetask
  14794. ;; #+BEGIN_EXAMPLE
  14795. ;; :PROPERTIES:
  14796. ;; #+END_EXAMPLE
  14797. ;;
  14798. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14799. (while (< (point) end)
  14800. (let ((p (progn (looking-at org-property-re)
  14801. (match-string-no-properties 2))))
  14802. ;; Only add true property name, not extension symbol.
  14803. (push (if (not (string-match-p "\\+\\'" p)) p
  14804. (substring p 0 -1))
  14805. props))
  14806. (forward-line))))
  14807. (outline-next-heading)))
  14808. (when columns
  14809. (goto-char (point-min))
  14810. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14811. (let ((element (org-element-at-point)))
  14812. (when (memq (org-element-type element) '(keyword node-property))
  14813. (let ((value (org-element-property :value element))
  14814. (start 0))
  14815. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14816. (setq start (match-end 0))
  14817. (let ((p (match-string-no-properties 1 value)))
  14818. (unless (member-ignore-case p org-special-properties)
  14819. (push p props))))))))))
  14820. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14821. (defun org-property-values (key)
  14822. "List all non-nil values of property KEY in current buffer."
  14823. (org-with-wide-buffer
  14824. (goto-char (point-min))
  14825. (let ((case-fold-search t)
  14826. (re (org-re-property key))
  14827. values)
  14828. (while (re-search-forward re nil t)
  14829. (push (org-entry-get (point) key) values))
  14830. (delete-dups values))))
  14831. (defun org-insert-property-drawer ()
  14832. "Insert a property drawer into the current entry."
  14833. (org-with-wide-buffer
  14834. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14835. (org-back-to-heading t)
  14836. (org-with-limited-levels (org-back-to-heading t)))
  14837. (forward-line)
  14838. (when (looking-at-p org-planning-line-re) (forward-line))
  14839. (unless (looking-at-p org-property-drawer-re)
  14840. ;; Make sure we start editing a line from current entry, not from
  14841. ;; next one. It prevents extending text properties or overlays
  14842. ;; belonging to the latter.
  14843. (when (bolp) (backward-char))
  14844. (let ((begin (1+ (point)))
  14845. (inhibit-read-only t))
  14846. (insert "\n:PROPERTIES:\n:END:")
  14847. (when (eobp) (insert "\n"))
  14848. (org-indent-region begin (point))))))
  14849. (defun org-insert-drawer (&optional arg drawer)
  14850. "Insert a drawer at point.
  14851. When optional argument ARG is non-nil, insert a property drawer.
  14852. Optional argument DRAWER, when non-nil, is a string representing
  14853. drawer's name. Otherwise, the user is prompted for a name.
  14854. If a region is active, insert the drawer around that region
  14855. instead.
  14856. Point is left between drawer's boundaries."
  14857. (interactive "P")
  14858. (let* ((drawer (if arg "PROPERTIES"
  14859. (or drawer (read-from-minibuffer "Drawer: ")))))
  14860. (cond
  14861. ;; With C-u, fall back on `org-insert-property-drawer'
  14862. (arg (org-insert-property-drawer))
  14863. ;; Check validity of suggested drawer's name.
  14864. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14865. (user-error "Invalid drawer name"))
  14866. ;; With an active region, insert a drawer at point.
  14867. ((not (org-region-active-p))
  14868. (progn
  14869. (unless (bolp) (insert "\n"))
  14870. (insert (format ":%s:\n\n:END:\n" drawer))
  14871. (forward-line -2)))
  14872. ;; Otherwise, insert the drawer at point
  14873. (t
  14874. (let ((rbeg (region-beginning))
  14875. (rend (copy-marker (region-end))))
  14876. (unwind-protect
  14877. (progn
  14878. (goto-char rbeg)
  14879. (beginning-of-line)
  14880. (when (save-excursion
  14881. (re-search-forward org-outline-regexp-bol rend t))
  14882. (user-error "Drawers cannot contain headlines"))
  14883. ;; Position point at the beginning of the first
  14884. ;; non-blank line in region. Insert drawer's opening
  14885. ;; there, then indent it.
  14886. (org-skip-whitespace)
  14887. (beginning-of-line)
  14888. (insert ":" drawer ":\n")
  14889. (forward-line -1)
  14890. (indent-for-tab-command)
  14891. ;; Move point to the beginning of the first blank line
  14892. ;; after the last non-blank line in region. Insert
  14893. ;; drawer's closing, then indent it.
  14894. (goto-char rend)
  14895. (skip-chars-backward " \r\t\n")
  14896. (insert "\n:END:")
  14897. (deactivate-mark t)
  14898. (indent-for-tab-command)
  14899. (unless (eolp) (insert "\n")))
  14900. ;; Clear marker, whatever the outcome of insertion is.
  14901. (set-marker rend nil)))))))
  14902. (defvar org-property-set-functions-alist nil
  14903. "Property set function alist.
  14904. Each entry should have the following format:
  14905. (PROPERTY . READ-FUNCTION)
  14906. The read function will be called with the same argument as
  14907. `org-completing-read'.")
  14908. (defun org-set-property-function (property)
  14909. "Get the function that should be used to set PROPERTY.
  14910. This is computed according to `org-property-set-functions-alist'."
  14911. (or (cdr (assoc property org-property-set-functions-alist))
  14912. 'org-completing-read))
  14913. (defun org-read-property-value (property)
  14914. "Read PROPERTY value from user."
  14915. (let* ((completion-ignore-case t)
  14916. (allowed (org-property-get-allowed-values nil property 'table))
  14917. (cur (org-entry-get nil property))
  14918. (prompt (concat property " value"
  14919. (if (and cur (string-match "\\S-" cur))
  14920. (concat " [" cur "]") "") ": "))
  14921. (set-function (org-set-property-function property))
  14922. (val (if allowed
  14923. (funcall set-function prompt allowed nil
  14924. (not (get-text-property 0 'org-unrestricted
  14925. (caar allowed))))
  14926. (funcall set-function prompt
  14927. (mapcar 'list (org-property-values property))
  14928. nil nil "" nil cur))))
  14929. (org-trim val)))
  14930. (defvar org-last-set-property nil)
  14931. (defvar org-last-set-property-value nil)
  14932. (defun org-read-property-name ()
  14933. "Read a property name."
  14934. (let ((completion-ignore-case t)
  14935. (default-prop (or (and (org-at-property-p)
  14936. (match-string-no-properties 2))
  14937. org-last-set-property)))
  14938. (org-completing-read
  14939. (concat "Property"
  14940. (if default-prop (concat " [" default-prop "]") "")
  14941. ": ")
  14942. (mapcar #'list (org-buffer-property-keys nil t t))
  14943. nil nil nil nil default-prop)))
  14944. (defun org-set-property-and-value (use-last)
  14945. "Allow to set [PROPERTY]: [value] direction from prompt.
  14946. When use-default, don't even ask, just use the last
  14947. \"[PROPERTY]: [value]\" string from the history."
  14948. (interactive "P")
  14949. (let* ((completion-ignore-case t)
  14950. (pv (or (and use-last org-last-set-property-value)
  14951. (org-completing-read
  14952. "Enter a \"[Property]: [value]\" pair: "
  14953. nil nil nil nil nil
  14954. org-last-set-property-value)))
  14955. prop val)
  14956. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14957. (setq prop (match-string 1 pv)
  14958. val (match-string 2 pv))
  14959. (org-set-property prop val))))
  14960. (defun org-set-property (property value)
  14961. "In the current entry, set PROPERTY to VALUE.
  14962. When called interactively, this will prompt for a property name, offering
  14963. completion on existing and default properties. And then it will prompt
  14964. for a value, offering completion either on allowed values (via an inherited
  14965. xxx_ALL property) or on existing values in other instances of this property
  14966. in the current file.
  14967. Throw an error when trying to set a property with an invalid name."
  14968. (interactive (list nil nil))
  14969. (let ((property (or property (org-read-property-name))))
  14970. ;; `org-entry-put' also makes the following check, but this one
  14971. ;; avoids polluting `org-last-set-property' and
  14972. ;; `org-last-set-property-value' needlessly.
  14973. (unless (org--valid-property-p property)
  14974. (user-error "Invalid property name: \"%s\"" property))
  14975. (let ((value (or value (org-read-property-value property)))
  14976. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14977. (setq org-last-set-property property)
  14978. (setq org-last-set-property-value (concat property ": " value))
  14979. ;; Possibly postprocess the inserted value:
  14980. (when fn (setq value (funcall fn value)))
  14981. (unless (equal (org-entry-get nil property) value)
  14982. (org-entry-put nil property value)))))
  14983. (defun org-find-property (property &optional value)
  14984. "Find first entry in buffer that sets PROPERTY.
  14985. When optional argument VALUE is non-nil, only consider an entry
  14986. if it contains PROPERTY set to this value. If PROPERTY should be
  14987. explicitly set to nil, use string \"nil\" for VALUE.
  14988. Return position where the entry begins, or nil if there is no
  14989. such entry. If narrowing is in effect, only search the visible
  14990. part of the buffer."
  14991. (save-excursion
  14992. (goto-char (point-min))
  14993. (let ((case-fold-search t)
  14994. (re (org-re-property property nil (not value) value)))
  14995. (catch 'exit
  14996. (while (re-search-forward re nil t)
  14997. (when (if value (org-at-property-p)
  14998. (org-entry-get (point) property nil t))
  14999. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15000. (defun org-delete-property (property)
  15001. "In the current entry, delete PROPERTY."
  15002. (interactive
  15003. (let* ((completion-ignore-case t)
  15004. (cat (org-entry-get (point) "CATEGORY"))
  15005. (props0 (org-entry-properties nil 'standard))
  15006. (props (if cat props0
  15007. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15008. (prop (if (< 1 (length props))
  15009. (completing-read "Property: " props nil t)
  15010. (caar props))))
  15011. (list prop)))
  15012. (if (not property)
  15013. (message "No property to delete in this entry")
  15014. (org-entry-delete nil property)
  15015. (message "Property \"%s\" deleted" property)))
  15016. (defun org-delete-property-globally (property)
  15017. "Remove PROPERTY globally, from all entries.
  15018. This function ignores narrowing, if any."
  15019. (interactive
  15020. (let* ((completion-ignore-case t)
  15021. (prop (completing-read
  15022. "Globally remove property: "
  15023. (mapcar #'list (org-buffer-property-keys)))))
  15024. (list prop)))
  15025. (org-with-wide-buffer
  15026. (goto-char (point-min))
  15027. (let ((count 0)
  15028. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15029. (while (re-search-forward re nil t)
  15030. (when (org-entry-delete (point) property) (cl-incf count)))
  15031. (message "Property \"%s\" removed from %d entries" property count))))
  15032. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15033. (defun org-compute-property-at-point ()
  15034. "Compute the property at point.
  15035. This looks for an enclosing column format, extracts the operator and
  15036. then applies it to the property in the column format's scope."
  15037. (interactive)
  15038. (unless (org-at-property-p)
  15039. (user-error "Not at a property"))
  15040. (let ((prop (match-string-no-properties 2)))
  15041. (org-columns-get-format-and-top-level)
  15042. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15043. (user-error "No operator defined for property %s" prop))
  15044. (org-columns-compute prop)))
  15045. (defvar org-property-allowed-value-functions nil
  15046. "Hook for functions supplying allowed values for a specific property.
  15047. The functions must take a single argument, the name of the property, and
  15048. return a flat list of allowed values. If \":ETC\" is one of
  15049. the values, this means that these values are intended as defaults for
  15050. completion, but that other values should be allowed too.
  15051. The functions must return nil if they are not responsible for this
  15052. property.")
  15053. (defun org-property-get-allowed-values (pom property &optional table)
  15054. "Get allowed values for the property PROPERTY.
  15055. When TABLE is non-nil, return an alist that can directly be used for
  15056. completion."
  15057. (let (vals)
  15058. (cond
  15059. ((equal property "TODO")
  15060. (setq vals (org-with-point-at pom
  15061. (append org-todo-keywords-1 '("")))))
  15062. ((equal property "PRIORITY")
  15063. (let ((n org-lowest-priority))
  15064. (while (>= n org-highest-priority)
  15065. (push (char-to-string n) vals)
  15066. (setq n (1- n)))))
  15067. ((equal property "CATEGORY"))
  15068. ((member property org-special-properties))
  15069. ((setq vals (run-hook-with-args-until-success
  15070. 'org-property-allowed-value-functions property)))
  15071. (t
  15072. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15073. (when (and vals (string-match "\\S-" vals))
  15074. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15075. (setq vals (mapcar (lambda (x)
  15076. (cond ((stringp x) x)
  15077. ((numberp x) (number-to-string x))
  15078. ((symbolp x) (symbol-name x))
  15079. (t "???")))
  15080. vals)))))
  15081. (when (member ":ETC" vals)
  15082. (setq vals (remove ":ETC" vals))
  15083. (org-add-props (car vals) '(org-unrestricted t)))
  15084. (if table (mapcar 'list vals) vals)))
  15085. (defun org-property-previous-allowed-value (&optional _previous)
  15086. "Switch to the next allowed value for this property."
  15087. (interactive)
  15088. (org-property-next-allowed-value t))
  15089. (defun org-property-next-allowed-value (&optional previous)
  15090. "Switch to the next allowed value for this property."
  15091. (interactive)
  15092. (unless (org-at-property-p)
  15093. (user-error "Not at a property"))
  15094. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15095. (key (match-string 2))
  15096. (value (match-string 3))
  15097. (allowed (or (org-property-get-allowed-values (point) key)
  15098. (and (member value '("[ ]" "[-]" "[X]"))
  15099. '("[ ]" "[X]"))))
  15100. (heading (save-match-data (nth 4 (org-heading-components))))
  15101. nval)
  15102. (unless allowed
  15103. (user-error "Allowed values for this property have not been defined"))
  15104. (when previous (setq allowed (reverse allowed)))
  15105. (when (member value allowed)
  15106. (setq nval (car (cdr (member value allowed)))))
  15107. (setq nval (or nval (car allowed)))
  15108. (when (equal nval value)
  15109. (user-error "Only one allowed value for this property"))
  15110. (org-at-property-p)
  15111. (replace-match (concat " :" key ": " nval) t t)
  15112. (org-indent-line)
  15113. (beginning-of-line 1)
  15114. (skip-chars-forward " \t")
  15115. (when (equal prop org-effort-property)
  15116. (org-refresh-property
  15117. '((effort . identity)
  15118. (effort-minutes . org-duration-string-to-minutes))
  15119. nval)
  15120. (when (string= org-clock-current-task heading)
  15121. (setq org-clock-effort nval)
  15122. (org-clock-update-mode-line)))
  15123. (run-hook-with-args 'org-property-changed-functions key nval)))
  15124. (defun org-find-olp (path &optional this-buffer)
  15125. "Return a marker pointing to the entry at outline path OLP.
  15126. If anything goes wrong, throw an error.
  15127. You can wrap this call to catch the error like this:
  15128. (condition-case msg
  15129. (org-mobile-locate-entry (match-string 4))
  15130. (error (nth 1 msg)))
  15131. The return value will then be either a string with the error message,
  15132. or a marker if everything is OK.
  15133. If THIS-BUFFER is set, the outline path does not contain a file,
  15134. only headings."
  15135. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15136. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15137. (level 1)
  15138. (lmin 1)
  15139. (lmax 1)
  15140. end found flevel)
  15141. (unless buffer (error "File not found :%s" file))
  15142. (with-current-buffer buffer
  15143. (org-with-wide-buffer
  15144. (goto-char (point-min))
  15145. (dolist (heading path)
  15146. (let ((re (format org-complex-heading-regexp-format
  15147. (regexp-quote heading)))
  15148. (cnt 0))
  15149. (while (re-search-forward re end t)
  15150. (setq level (- (match-end 1) (match-beginning 1)))
  15151. (when (and (>= level lmin) (<= level lmax))
  15152. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15153. (when (= cnt 0)
  15154. (error "Heading not found on level %d: %s" lmax heading))
  15155. (when (> cnt 1)
  15156. (error "Heading not unique on level %d: %s" lmax heading))
  15157. (goto-char found)
  15158. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15159. (setq end (save-excursion (org-end-of-subtree t t)))))
  15160. (when (org-at-heading-p)
  15161. (point-marker))))))
  15162. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15163. "Find node HEADING in BUFFER.
  15164. Return a marker to the heading if it was found, or nil if not.
  15165. If POS-ONLY is set, return just the position instead of a marker.
  15166. The heading text must match exact, but it may have a TODO keyword,
  15167. a priority cookie and tags in the standard locations."
  15168. (with-current-buffer (or buffer (current-buffer))
  15169. (org-with-wide-buffer
  15170. (goto-char (point-min))
  15171. (let (case-fold-search)
  15172. (when (re-search-forward
  15173. (format org-complex-heading-regexp-format
  15174. (regexp-quote heading)) nil t)
  15175. (if pos-only
  15176. (match-beginning 0)
  15177. (move-marker (make-marker) (match-beginning 0))))))))
  15178. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15179. "Find Org node headline HEADING in all .org files in directory DIR.
  15180. When the target headline is found, return a marker to this location."
  15181. (let ((files (directory-files (or dir default-directory)
  15182. t "\\`[^.#].*\\.org\\'"))
  15183. visiting m buffer)
  15184. (catch 'found
  15185. (dolist (file files)
  15186. (message "trying %s" file)
  15187. (setq visiting (org-find-base-buffer-visiting file))
  15188. (setq buffer (or visiting (find-file-noselect file)))
  15189. (setq m (org-find-exact-headline-in-buffer
  15190. heading buffer))
  15191. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15192. (and m (throw 'found m))))))
  15193. (defun org-find-entry-with-id (ident)
  15194. "Locate the entry that contains the ID property with exact value IDENT.
  15195. IDENT can be a string, a symbol or a number, this function will search for
  15196. the string representation of it.
  15197. Return the position where this entry starts, or nil if there is no such entry."
  15198. (interactive "sID: ")
  15199. (let ((id (cond
  15200. ((stringp ident) ident)
  15201. ((symbolp ident) (symbol-name ident))
  15202. ((numberp ident) (number-to-string ident))
  15203. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15204. (org-with-wide-buffer (org-find-property "ID" id))))
  15205. ;;;; Timestamps
  15206. (defvar org-last-changed-timestamp nil)
  15207. (defvar org-last-inserted-timestamp nil
  15208. "The last time stamp inserted with `org-insert-time-stamp'.")
  15209. (defvar org-ts-what) ; dynamically scoped parameter
  15210. (defun org-time-stamp (arg &optional inactive)
  15211. "Prompt for a date/time and insert a time stamp.
  15212. If the user specifies a time like HH:MM or if this command is
  15213. called with at least one prefix argument, the time stamp contains
  15214. the date and the time. Otherwise, only the date is included.
  15215. All parts of a date not specified by the user are filled in from
  15216. the timestamp at point, if any, or the current date/time
  15217. otherwise.
  15218. If there is already a timestamp at the cursor, it is replaced.
  15219. With two universal prefix arguments, insert an active timestamp
  15220. with the current time without prompting the user.
  15221. When called from lisp, the timestamp is inactive if INACTIVE is
  15222. non-nil."
  15223. (interactive "P")
  15224. (let* ((ts (cond
  15225. ((org-at-date-range-p t)
  15226. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15227. ((org-at-timestamp-p t) (match-string 0))))
  15228. ;; Default time is either the timestamp at point or today.
  15229. ;; When entering a range, only the range start is considered.
  15230. (default-time (if (not ts) (current-time)
  15231. (apply #'encode-time (org-parse-time-string ts))))
  15232. (default-input (and ts (org-get-compact-tod ts)))
  15233. (repeater (and ts
  15234. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15235. (match-string 0 ts)))
  15236. org-time-was-given
  15237. org-end-time-was-given
  15238. (time
  15239. (and (if (equal arg '(16)) (current-time)
  15240. ;; Preserve `this-command' and `last-command'.
  15241. (let ((this-command this-command)
  15242. (last-command last-command))
  15243. (org-read-date
  15244. arg 'totime nil nil default-time default-input
  15245. inactive))))))
  15246. (cond
  15247. ((and ts
  15248. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15249. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15250. (insert "--")
  15251. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15252. (ts
  15253. ;; Make sure we're on a timestamp. When in the middle of a date
  15254. ;; range, move arbitrarily to range end.
  15255. (unless (org-at-timestamp-p t)
  15256. (skip-chars-forward "-")
  15257. (org-at-timestamp-p t))
  15258. (replace-match "")
  15259. (setq org-last-changed-timestamp
  15260. (org-insert-time-stamp
  15261. time (or org-time-was-given arg)
  15262. inactive nil nil (list org-end-time-was-given)))
  15263. (when repeater
  15264. (backward-char)
  15265. (insert " " repeater)
  15266. (setq org-last-changed-timestamp
  15267. (concat (substring org-last-inserted-timestamp 0 -1)
  15268. " " repeater ">")))
  15269. (message "Timestamp updated"))
  15270. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15271. (t (org-insert-time-stamp
  15272. time (or org-time-was-given arg) inactive nil nil
  15273. (list org-end-time-was-given))))))
  15274. ;; FIXME: can we use this for something else, like computing time differences?
  15275. (defun org-get-compact-tod (s)
  15276. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15277. (let* ((t1 (match-string 1 s))
  15278. (h1 (string-to-number (match-string 2 s)))
  15279. (m1 (string-to-number (match-string 3 s)))
  15280. (t2 (and (match-end 4) (match-string 5 s)))
  15281. (h2 (and t2 (string-to-number (match-string 6 s))))
  15282. (m2 (and t2 (string-to-number (match-string 7 s))))
  15283. dh dm)
  15284. (if (not t2)
  15285. t1
  15286. (setq dh (- h2 h1) dm (- m2 m1))
  15287. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15288. (concat t1 "+" (number-to-string dh)
  15289. (and (/= 0 dm) (format ":%02d" dm)))))))
  15290. (defun org-time-stamp-inactive (&optional arg)
  15291. "Insert an inactive time stamp.
  15292. An inactive time stamp is enclosed in square brackets instead of angle
  15293. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15294. does not link to the calendar and cannot be changed with the S-cursor keys.
  15295. So these are more for recording a certain time/date."
  15296. (interactive "P")
  15297. (org-time-stamp arg 'inactive))
  15298. (defvar org-date-ovl (make-overlay 1 1))
  15299. (overlay-put org-date-ovl 'face 'org-date-selected)
  15300. (delete-overlay org-date-ovl)
  15301. (defvar org-ans1) ; dynamically scoped parameter
  15302. (defvar org-ans2) ; dynamically scoped parameter
  15303. (defvar org-plain-time-of-day-regexp) ; defined below
  15304. (defvar org-overriding-default-time nil) ; dynamically scoped
  15305. (defvar org-read-date-overlay nil)
  15306. (defvar org-dcst nil) ; dynamically scoped
  15307. (defvar org-read-date-history nil)
  15308. (defvar org-read-date-final-answer nil)
  15309. (defvar org-read-date-analyze-futurep nil)
  15310. (defvar org-read-date-analyze-forced-year nil)
  15311. (defvar org-read-date-inactive)
  15312. (defvar org-read-date-minibuffer-local-map
  15313. (let* ((map (make-sparse-keymap)))
  15314. (set-keymap-parent map minibuffer-local-map)
  15315. (org-defkey map (kbd ".")
  15316. (lambda () (interactive)
  15317. ;; Are we at the beginning of the prompt?
  15318. (if (looking-back "^[^:]+: "
  15319. (let ((inhibit-field-text-motion t))
  15320. (line-beginning-position)))
  15321. (org-eval-in-calendar '(calendar-goto-today))
  15322. (insert "."))))
  15323. (org-defkey map (kbd "C-.")
  15324. (lambda () (interactive)
  15325. (org-eval-in-calendar '(calendar-goto-today))))
  15326. (org-defkey map [(meta shift left)]
  15327. (lambda () (interactive)
  15328. (org-eval-in-calendar '(calendar-backward-month 1))))
  15329. (org-defkey map [(meta shift right)]
  15330. (lambda () (interactive)
  15331. (org-eval-in-calendar '(calendar-forward-month 1))))
  15332. (org-defkey map [(meta shift up)]
  15333. (lambda () (interactive)
  15334. (org-eval-in-calendar '(calendar-backward-year 1))))
  15335. (org-defkey map [(meta shift down)]
  15336. (lambda () (interactive)
  15337. (org-eval-in-calendar '(calendar-forward-year 1))))
  15338. (org-defkey map [?\e (shift left)]
  15339. (lambda () (interactive)
  15340. (org-eval-in-calendar '(calendar-backward-month 1))))
  15341. (org-defkey map [?\e (shift right)]
  15342. (lambda () (interactive)
  15343. (org-eval-in-calendar '(calendar-forward-month 1))))
  15344. (org-defkey map [?\e (shift up)]
  15345. (lambda () (interactive)
  15346. (org-eval-in-calendar '(calendar-backward-year 1))))
  15347. (org-defkey map [?\e (shift down)]
  15348. (lambda () (interactive)
  15349. (org-eval-in-calendar '(calendar-forward-year 1))))
  15350. (org-defkey map [(shift up)]
  15351. (lambda () (interactive)
  15352. (org-eval-in-calendar '(calendar-backward-week 1))))
  15353. (org-defkey map [(shift down)]
  15354. (lambda () (interactive)
  15355. (org-eval-in-calendar '(calendar-forward-week 1))))
  15356. (org-defkey map [(shift left)]
  15357. (lambda () (interactive)
  15358. (org-eval-in-calendar '(calendar-backward-day 1))))
  15359. (org-defkey map [(shift right)]
  15360. (lambda () (interactive)
  15361. (org-eval-in-calendar '(calendar-forward-day 1))))
  15362. (org-defkey map "!"
  15363. (lambda () (interactive)
  15364. (org-eval-in-calendar '(diary-view-entries))
  15365. (message "")))
  15366. (org-defkey map ">"
  15367. (lambda () (interactive)
  15368. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15369. (org-defkey map "<"
  15370. (lambda () (interactive)
  15371. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15372. (org-defkey map "\C-v"
  15373. (lambda () (interactive)
  15374. (org-eval-in-calendar
  15375. '(calendar-scroll-left-three-months 1))))
  15376. (org-defkey map "\M-v"
  15377. (lambda () (interactive)
  15378. (org-eval-in-calendar
  15379. '(calendar-scroll-right-three-months 1))))
  15380. map)
  15381. "Keymap for minibuffer commands when using `org-read-date'.")
  15382. (defvar org-def)
  15383. (defvar org-defdecode)
  15384. (defvar org-with-time)
  15385. (defvar calendar-setup) ; Dynamically scoped.
  15386. (defun org-read-date (&optional with-time to-time from-string prompt
  15387. default-time default-input inactive)
  15388. "Read a date, possibly a time, and make things smooth for the user.
  15389. The prompt will suggest to enter an ISO date, but you can also enter anything
  15390. which will at least partially be understood by `parse-time-string'.
  15391. Unrecognized parts of the date will default to the current day, month, year,
  15392. hour and minute. If this command is called to replace a timestamp at point,
  15393. or to enter the second timestamp of a range, the default time is taken
  15394. from the existing stamp. Furthermore, the command prefers the future,
  15395. so if you are giving a date where the year is not given, and the day-month
  15396. combination is already past in the current year, it will assume you
  15397. mean next year. For details, see the manual. A few examples:
  15398. 3-2-5 --> 2003-02-05
  15399. feb 15 --> currentyear-02-15
  15400. 2/15 --> currentyear-02-15
  15401. sep 12 9 --> 2009-09-12
  15402. 12:45 --> today 12:45
  15403. 22 sept 0:34 --> currentyear-09-22 0:34
  15404. 12 --> currentyear-currentmonth-12
  15405. Fri --> nearest Friday after today
  15406. -Tue --> last Tuesday
  15407. etc.
  15408. Furthermore you can specify a relative date by giving, as the *first* thing
  15409. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15410. change in days weeks, months, years.
  15411. With a single plus or minus, the date is relative to today. With a double
  15412. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15413. +4d --> four days from today
  15414. +4 --> same as above
  15415. +2w --> two weeks from today
  15416. ++5 --> five days from default date
  15417. The function understands only English month and weekday abbreviations.
  15418. While prompting, a calendar is popped up - you can also select the
  15419. date with the mouse (button 1). The calendar shows a period of three
  15420. months. To scroll it to other months, use the keys `>' and `<'.
  15421. If you don't like the calendar, turn it off with
  15422. (setq org-read-date-popup-calendar nil)
  15423. With optional argument TO-TIME, the date will immediately be converted
  15424. to an internal time.
  15425. With an optional argument WITH-TIME, the prompt will suggest to
  15426. also insert a time. Note that when WITH-TIME is not set, you can
  15427. still enter a time, and this function will inform the calling routine
  15428. about this change. The calling routine may then choose to change the
  15429. format used to insert the time stamp into the buffer to include the time.
  15430. With optional argument FROM-STRING, read from this string instead from
  15431. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15432. the time/date that is used for everything that is not specified by the
  15433. user."
  15434. (require 'parse-time)
  15435. (let* ((org-with-time with-time)
  15436. (org-time-stamp-rounding-minutes
  15437. (if (equal org-with-time '(16))
  15438. '(0 0)
  15439. org-time-stamp-rounding-minutes))
  15440. (org-dcst org-display-custom-times)
  15441. (ct (org-current-time))
  15442. (org-def (or org-overriding-default-time default-time ct))
  15443. (org-defdecode (decode-time org-def))
  15444. (cur-frame (selected-frame))
  15445. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15446. (calendar-setup
  15447. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15448. (calendar-move-hook nil)
  15449. (calendar-view-diary-initially-flag nil)
  15450. (calendar-view-holidays-initially-flag nil)
  15451. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15452. ;; Rationalize `org-def' and `org-defdecode', if required.
  15453. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15454. (setf (nth 2 org-defdecode) -1)
  15455. (setf (nth 1 org-defdecode) 59)
  15456. (setq org-def (apply #'encode-time org-defdecode))
  15457. (setq org-defdecode (decode-time org-def)))
  15458. (let* ((timestr (format-time-string
  15459. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15460. org-def))
  15461. (prompt (concat (if prompt (concat prompt " ") "")
  15462. (format "Date+time [%s]: " timestr))))
  15463. (cond
  15464. (from-string (setq ans from-string))
  15465. (org-read-date-popup-calendar
  15466. (save-excursion
  15467. (save-window-excursion
  15468. (calendar)
  15469. (when (eq calendar-setup 'calendar-only)
  15470. (setq cal-frame
  15471. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15472. (select-frame cal-frame))
  15473. (org-eval-in-calendar '(setq cursor-type nil) t)
  15474. (unwind-protect
  15475. (progn
  15476. (calendar-forward-day (- (time-to-days org-def)
  15477. (calendar-absolute-from-gregorian
  15478. (calendar-current-date))))
  15479. (org-eval-in-calendar nil t)
  15480. (let* ((old-map (current-local-map))
  15481. (map (copy-keymap calendar-mode-map))
  15482. (minibuffer-local-map
  15483. (copy-keymap org-read-date-minibuffer-local-map)))
  15484. (org-defkey map (kbd "RET") 'org-calendar-select)
  15485. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15486. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15487. (unwind-protect
  15488. (progn
  15489. (use-local-map map)
  15490. (setq org-read-date-inactive inactive)
  15491. (add-hook 'post-command-hook 'org-read-date-display)
  15492. (setq org-ans0
  15493. (read-string prompt
  15494. default-input
  15495. 'org-read-date-history
  15496. nil))
  15497. ;; org-ans0: from prompt
  15498. ;; org-ans1: from mouse click
  15499. ;; org-ans2: from calendar motion
  15500. (setq ans
  15501. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15502. (remove-hook 'post-command-hook 'org-read-date-display)
  15503. (use-local-map old-map)
  15504. (when org-read-date-overlay
  15505. (delete-overlay org-read-date-overlay)
  15506. (setq org-read-date-overlay nil)))))
  15507. (bury-buffer "*Calendar*")
  15508. (when cal-frame
  15509. (delete-frame cal-frame)
  15510. (select-frame-set-input-focus cur-frame))))))
  15511. (t ; Naked prompt only
  15512. (unwind-protect
  15513. (setq ans (read-string prompt default-input
  15514. 'org-read-date-history timestr))
  15515. (when org-read-date-overlay
  15516. (delete-overlay org-read-date-overlay)
  15517. (setq org-read-date-overlay nil))))))
  15518. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15519. (when org-read-date-analyze-forced-year
  15520. (message "Year was forced into %s"
  15521. (if org-read-date-force-compatible-dates
  15522. "compatible range (1970-2037)"
  15523. "range representable on this machine"))
  15524. (ding))
  15525. ;; One round trip to get rid of 34th of August and stuff like that....
  15526. (setq final (decode-time (apply 'encode-time final)))
  15527. (setq org-read-date-final-answer ans)
  15528. (if to-time
  15529. (apply 'encode-time final)
  15530. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15531. (format "%04d-%02d-%02d %02d:%02d"
  15532. (nth 5 final) (nth 4 final) (nth 3 final)
  15533. (nth 2 final) (nth 1 final))
  15534. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15535. (defun org-read-date-display ()
  15536. "Display the current date prompt interpretation in the minibuffer."
  15537. (when org-read-date-display-live
  15538. (when org-read-date-overlay
  15539. (delete-overlay org-read-date-overlay))
  15540. (when (minibufferp (current-buffer))
  15541. (save-excursion
  15542. (end-of-line 1)
  15543. (while (not (equal (buffer-substring
  15544. (max (point-min) (- (point) 4)) (point))
  15545. " "))
  15546. (insert " ")))
  15547. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15548. " " (or org-ans1 org-ans2)))
  15549. (org-end-time-was-given nil)
  15550. (f (org-read-date-analyze ans org-def org-defdecode))
  15551. (fmts (if org-dcst
  15552. org-time-stamp-custom-formats
  15553. org-time-stamp-formats))
  15554. (fmt (if (or org-with-time
  15555. (and (boundp 'org-time-was-given) org-time-was-given))
  15556. (cdr fmts)
  15557. (car fmts)))
  15558. (txt (format-time-string fmt (apply 'encode-time f)))
  15559. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15560. (txt (concat "=> " txt)))
  15561. (when (and org-end-time-was-given
  15562. (string-match org-plain-time-of-day-regexp txt))
  15563. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15564. org-end-time-was-given
  15565. (substring txt (match-end 0)))))
  15566. (when org-read-date-analyze-futurep
  15567. (setq txt (concat txt " (=>F)")))
  15568. (setq org-read-date-overlay
  15569. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15570. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15571. (defun org-read-date-analyze (ans def defdecode)
  15572. "Analyze the combined answer of the date prompt."
  15573. ;; FIXME: cleanup and comment
  15574. ;; Pass `current-time' result to `decode-time' (instead of calling
  15575. ;; without arguments) so that only `current-time' has to be
  15576. ;; overriden in tests.
  15577. (let ((org-def def)
  15578. (org-defdecode defdecode)
  15579. (nowdecode (decode-time (current-time)))
  15580. delta deltan deltaw deltadef year month day
  15581. hour minute second wday pm h2 m2 tl wday1
  15582. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15583. (setq org-read-date-analyze-futurep nil
  15584. org-read-date-analyze-forced-year nil)
  15585. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15586. (setq ans "+0"))
  15587. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15588. (setq ans (replace-match "" t t ans)
  15589. deltan (car delta)
  15590. deltaw (nth 1 delta)
  15591. deltadef (nth 2 delta)))
  15592. ;; Check if there is an iso week date in there. If yes, store the
  15593. ;; info and postpone interpreting it until the rest of the parsing
  15594. ;; is done.
  15595. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15596. (setq iso-year (when (match-end 1)
  15597. (org-small-year-to-year
  15598. (string-to-number (match-string 1 ans))))
  15599. iso-weekday (when (match-end 3)
  15600. (string-to-number (match-string 3 ans)))
  15601. iso-week (string-to-number (match-string 2 ans)))
  15602. (setq ans (replace-match "" t t ans)))
  15603. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15604. (when (string-match
  15605. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15606. (setq year (if (match-end 2)
  15607. (string-to-number (match-string 2 ans))
  15608. (progn (setq kill-year t)
  15609. (string-to-number (format-time-string "%Y"))))
  15610. month (string-to-number (match-string 3 ans))
  15611. day (string-to-number (match-string 4 ans)))
  15612. (setq year (org-small-year-to-year year))
  15613. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15614. t nil ans)))
  15615. ;; Help matching dotted european dates
  15616. (when (string-match
  15617. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15618. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15619. (setq kill-year t)
  15620. (string-to-number (format-time-string "%Y")))
  15621. day (string-to-number (match-string 1 ans))
  15622. month (string-to-number (match-string 2 ans))
  15623. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15624. t nil ans)))
  15625. ;; Help matching american dates, like 5/30 or 5/30/7
  15626. (when (string-match
  15627. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15628. (setq year (if (match-end 4)
  15629. (string-to-number (match-string 4 ans))
  15630. (progn (setq kill-year t)
  15631. (string-to-number (format-time-string "%Y"))))
  15632. month (string-to-number (match-string 1 ans))
  15633. day (string-to-number (match-string 2 ans)))
  15634. (setq year (org-small-year-to-year year))
  15635. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15636. t nil ans)))
  15637. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15638. ;; If there is a time with am/pm, and *no* time without it, we convert
  15639. ;; so that matching will be successful.
  15640. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15641. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15642. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15643. (setq hour (string-to-number (match-string 1 ans))
  15644. minute (if (match-end 3)
  15645. (string-to-number (match-string 3 ans))
  15646. 0)
  15647. pm (equal ?p
  15648. (string-to-char (downcase (match-string 4 ans)))))
  15649. (if (and (= hour 12) (not pm))
  15650. (setq hour 0)
  15651. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15652. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15653. t t ans))))
  15654. ;; Check if a time range is given as a duration
  15655. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15656. (setq hour (string-to-number (match-string 1 ans))
  15657. h2 (+ hour (string-to-number (match-string 3 ans)))
  15658. minute (string-to-number (match-string 2 ans))
  15659. m2 (+ minute (if (match-end 5) (string-to-number
  15660. (match-string 5 ans))0)))
  15661. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15662. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15663. t t ans)))
  15664. ;; Check if there is a time range
  15665. (when (boundp 'org-end-time-was-given)
  15666. (setq org-time-was-given nil)
  15667. (when (and (string-match org-plain-time-of-day-regexp ans)
  15668. (match-end 8))
  15669. (setq org-end-time-was-given (match-string 8 ans))
  15670. (setq ans (concat (substring ans 0 (match-beginning 7))
  15671. (substring ans (match-end 7))))))
  15672. (setq tl (parse-time-string ans)
  15673. day (or (nth 3 tl) (nth 3 org-defdecode))
  15674. month
  15675. (cond ((nth 4 tl))
  15676. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15677. ;; Day was specified. Make sure DAY+MONTH
  15678. ;; combination happens in the future.
  15679. ((nth 3 tl)
  15680. (setq futurep t)
  15681. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15682. (nth 4 nowdecode)))
  15683. (t (nth 4 org-defdecode)))
  15684. year
  15685. (cond ((and (not kill-year) (nth 5 tl)))
  15686. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15687. ;; Month was guessed in the future and is at least
  15688. ;; equal to NOWDECODE's. Fix year accordingly.
  15689. (futurep
  15690. (if (or (> month (nth 4 nowdecode))
  15691. (>= day (nth 3 nowdecode)))
  15692. (nth 5 nowdecode)
  15693. (1+ (nth 5 nowdecode))))
  15694. ;; Month was specified. Make sure MONTH+YEAR
  15695. ;; combination happens in the future.
  15696. ((nth 4 tl)
  15697. (setq futurep t)
  15698. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15699. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15700. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15701. (t (nth 5 nowdecode))))
  15702. (t (nth 5 org-defdecode)))
  15703. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15704. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15705. second (or (nth 0 tl) 0)
  15706. wday (nth 6 tl))
  15707. (when (and (eq org-read-date-prefer-future 'time)
  15708. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15709. (equal day (nth 3 nowdecode))
  15710. (equal month (nth 4 nowdecode))
  15711. (equal year (nth 5 nowdecode))
  15712. (nth 2 tl)
  15713. (or (< (nth 2 tl) (nth 2 nowdecode))
  15714. (and (= (nth 2 tl) (nth 2 nowdecode))
  15715. (nth 1 tl)
  15716. (< (nth 1 tl) (nth 1 nowdecode)))))
  15717. (setq day (1+ day)
  15718. futurep t))
  15719. ;; Special date definitions below
  15720. (cond
  15721. (iso-week
  15722. ;; There was an iso week
  15723. (require 'cal-iso)
  15724. (setq futurep nil)
  15725. (setq year (or iso-year year)
  15726. day (or iso-weekday wday 1)
  15727. wday nil ; to make sure that the trigger below does not match
  15728. iso-date (calendar-gregorian-from-absolute
  15729. (calendar-iso-to-absolute
  15730. (list iso-week day year))))
  15731. ; FIXME: Should we also push ISO weeks into the future?
  15732. ; (when (and org-read-date-prefer-future
  15733. ; (not iso-year)
  15734. ; (< (calendar-absolute-from-gregorian iso-date)
  15735. ; (time-to-days (current-time))))
  15736. ; (setq year (1+ year)
  15737. ; iso-date (calendar-gregorian-from-absolute
  15738. ; (calendar-iso-to-absolute
  15739. ; (list iso-week day year)))))
  15740. (setq month (car iso-date)
  15741. year (nth 2 iso-date)
  15742. day (nth 1 iso-date)))
  15743. (deltan
  15744. (setq futurep nil)
  15745. (unless deltadef
  15746. ;; Pass `current-time' result to `decode-time' (instead of
  15747. ;; calling without arguments) so that only `current-time' has
  15748. ;; to be overriden in tests.
  15749. (let ((now (decode-time (current-time))))
  15750. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15751. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15752. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15753. ((equal deltaw "m") (setq month (+ month deltan)))
  15754. ((equal deltaw "y") (setq year (+ year deltan)))))
  15755. ((and wday (not (nth 3 tl)))
  15756. ;; Weekday was given, but no day, so pick that day in the week
  15757. ;; on or after the derived date.
  15758. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15759. (unless (equal wday wday1)
  15760. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15761. (when (and (boundp 'org-time-was-given)
  15762. (nth 2 tl))
  15763. (setq org-time-was-given t))
  15764. (when (< year 100) (setq year (+ 2000 year)))
  15765. ;; Check of the date is representable
  15766. (if org-read-date-force-compatible-dates
  15767. (progn
  15768. (when (< year 1970)
  15769. (setq year 1970 org-read-date-analyze-forced-year t))
  15770. (when (> year 2037)
  15771. (setq year 2037 org-read-date-analyze-forced-year t)))
  15772. (condition-case nil
  15773. (ignore (encode-time second minute hour day month year))
  15774. (error
  15775. (setq year (nth 5 org-defdecode))
  15776. (setq org-read-date-analyze-forced-year t))))
  15777. (setq org-read-date-analyze-futurep futurep)
  15778. (list second minute hour day month year)))
  15779. (defvar parse-time-weekdays)
  15780. (defun org-read-date-get-relative (s today default)
  15781. "Check string S for special relative date string.
  15782. TODAY and DEFAULT are internal times, for today and for a default.
  15783. Return shift list (N what def-flag)
  15784. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15785. N is the number of WHATs to shift.
  15786. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15787. the DEFAULT date rather than TODAY."
  15788. (require 'parse-time)
  15789. (when (and
  15790. (string-match
  15791. (concat
  15792. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15793. "\\([0-9]+\\)?"
  15794. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15795. "\\([ \t]\\|$\\)") s)
  15796. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15797. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15798. (string-to-char (substring (match-string 1 s) -1))
  15799. ?+))
  15800. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15801. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15802. (what (if (match-end 3) (match-string 3 s) "d"))
  15803. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15804. (date (if rel default today))
  15805. (wday (nth 6 (decode-time date)))
  15806. delta)
  15807. (if wday1
  15808. (progn
  15809. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15810. (when (= delta 0) (setq delta 7))
  15811. (when (= dir ?-)
  15812. (setq delta (- delta 7))
  15813. (when (= delta 0) (setq delta -7)))
  15814. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15815. (list delta "d" rel))
  15816. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15817. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15818. "Turn a user-specified date into the internal representation.
  15819. The internal representation needed by the calendar is (month day year).
  15820. This is a wrapper to handle the brain-dead convention in calendar that
  15821. user function argument order change dependent on argument order."
  15822. (pcase calendar-date-style
  15823. (`american (list arg1 arg2 arg3))
  15824. (`european (list arg2 arg1 arg3))
  15825. (`iso (list arg2 arg3 arg1))))
  15826. (defun org-eval-in-calendar (form &optional keepdate)
  15827. "Eval FORM in the calendar window and return to current window.
  15828. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15829. (let ((sf (selected-frame))
  15830. (sw (selected-window)))
  15831. (select-window (get-buffer-window "*Calendar*" t))
  15832. (eval form)
  15833. (when (and (not keepdate) (calendar-cursor-to-date))
  15834. (let* ((date (calendar-cursor-to-date))
  15835. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15836. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15837. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15838. (select-window sw)
  15839. (select-frame-set-input-focus sf)))
  15840. (defun org-calendar-select ()
  15841. "Return to `org-read-date' with the date currently selected.
  15842. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15843. (interactive)
  15844. (when (calendar-cursor-to-date)
  15845. (let* ((date (calendar-cursor-to-date))
  15846. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15847. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15848. (when (active-minibuffer-window) (exit-minibuffer))))
  15849. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15850. "Insert a date stamp for the date given by the internal TIME.
  15851. See `format-time-string' for the format of TIME.
  15852. WITH-HM means use the stamp format that includes the time of the day.
  15853. INACTIVE means use square brackets instead of angular ones, so that the
  15854. stamp will not contribute to the agenda.
  15855. PRE and POST are optional strings to be inserted before and after the
  15856. stamp.
  15857. The command returns the inserted time stamp."
  15858. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15859. stamp)
  15860. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15861. (insert-before-markers (or pre ""))
  15862. (when (listp extra)
  15863. (setq extra (car extra))
  15864. (if (and (stringp extra)
  15865. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15866. (setq extra (format "-%02d:%02d"
  15867. (string-to-number (match-string 1 extra))
  15868. (string-to-number (match-string 2 extra))))
  15869. (setq extra nil)))
  15870. (when extra
  15871. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15872. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15873. (insert-before-markers (or post ""))
  15874. (setq org-last-inserted-timestamp stamp)))
  15875. (defun org-toggle-time-stamp-overlays ()
  15876. "Toggle the use of custom time stamp formats."
  15877. (interactive)
  15878. (setq org-display-custom-times (not org-display-custom-times))
  15879. (unless org-display-custom-times
  15880. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15881. (while (setq p (next-single-property-change p 'display))
  15882. (when (and (get-text-property p 'display)
  15883. (eq (get-text-property p 'face) 'org-date))
  15884. (remove-text-properties
  15885. p (setq p (next-single-property-change p 'display))
  15886. '(display t))))
  15887. (set-buffer-modified-p bmp)))
  15888. (org-restart-font-lock)
  15889. (setq org-table-may-need-update t)
  15890. (if org-display-custom-times
  15891. (message "Time stamps are overlaid with custom format")
  15892. (message "Time stamp overlays removed")))
  15893. (defun org-display-custom-time (beg end)
  15894. "Overlay modified time stamp format over timestamp between BEG and END."
  15895. (let* ((ts (buffer-substring beg end))
  15896. t1 w1 with-hm tf time str w2 (off 0))
  15897. (save-match-data
  15898. (setq t1 (org-parse-time-string ts t))
  15899. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15900. (setq off (- (match-end 0) (match-beginning 0)))))
  15901. (setq end (- end off))
  15902. (setq w1 (- end beg)
  15903. with-hm (and (nth 1 t1) (nth 2 t1))
  15904. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15905. time (org-fix-decoded-time t1)
  15906. str (org-add-props
  15907. (format-time-string
  15908. (substring tf 1 -1) (apply 'encode-time time))
  15909. nil 'mouse-face 'highlight)
  15910. w2 (length str))
  15911. (unless (= w2 w1)
  15912. (add-text-properties (1+ beg) (+ 2 beg)
  15913. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15914. (put-text-property beg end 'display str)))
  15915. (defun org-fix-decoded-time (time)
  15916. "Set 0 instead of nil for the first 6 elements of time.
  15917. Don't touch the rest."
  15918. (let ((n 0))
  15919. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15920. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15921. "Difference between TIMESTAMP-STRING and now in days.
  15922. If SECONDS is non-nil, return the difference in seconds."
  15923. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15924. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15925. (funcall fdiff (current-time)))))
  15926. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15927. "Is the time in TIMESTAMP-STRING close to the current date?"
  15928. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15929. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15930. (not (org-entry-is-done-p))))
  15931. (defun org-get-wdays (ts &optional delay zero-delay)
  15932. "Get the deadline lead time appropriate for timestring TS.
  15933. When DELAY is non-nil, get the delay time for scheduled items
  15934. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15935. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15936. don't try to find the delay cookie in the scheduled timestamp."
  15937. (let ((tv (if delay org-scheduled-delay-days
  15938. org-deadline-warning-days)))
  15939. (cond
  15940. ((or (and delay (< tv 0))
  15941. (and delay zero-delay (<= tv 0))
  15942. (and (not delay) (<= tv 0)))
  15943. ;; Enforce this value no matter what
  15944. (- tv))
  15945. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15946. ;; lead time is specified.
  15947. (floor (* (string-to-number (match-string 1 ts))
  15948. (cdr (assoc (match-string 2 ts)
  15949. '(("d" . 1) ("w" . 7)
  15950. ("m" . 30.4) ("y" . 365.25)
  15951. ("h" . 0.041667)))))))
  15952. ;; go for the default.
  15953. (t tv))))
  15954. (defun org-calendar-select-mouse (ev)
  15955. "Return to `org-read-date' with the date currently selected.
  15956. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15957. (interactive "e")
  15958. (mouse-set-point ev)
  15959. (when (calendar-cursor-to-date)
  15960. (let* ((date (calendar-cursor-to-date))
  15961. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15962. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15963. (when (active-minibuffer-window) (exit-minibuffer))))
  15964. (defun org-check-deadlines (ndays)
  15965. "Check if there are any deadlines due or past due.
  15966. A deadline is considered due if it happens within `org-deadline-warning-days'
  15967. days from today's date. If the deadline appears in an entry marked DONE,
  15968. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15969. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15970. are shown."
  15971. (interactive "P")
  15972. (let* ((org-warn-days
  15973. (cond
  15974. ((equal ndays '(4)) 100000)
  15975. (ndays (prefix-numeric-value ndays))
  15976. (t (abs org-deadline-warning-days))))
  15977. (case-fold-search nil)
  15978. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15979. (callback
  15980. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15981. (message "%d deadlines past-due or due within %d days"
  15982. (org-occur regexp nil callback)
  15983. org-warn-days)))
  15984. (defsubst org-re-timestamp (type)
  15985. "Return a regexp for timestamp TYPE.
  15986. Allowed values for TYPE are:
  15987. all: all timestamps
  15988. active: only active timestamps (<...>)
  15989. inactive: only inactive timestamps ([...])
  15990. scheduled: only scheduled timestamps
  15991. deadline: only deadline timestamps
  15992. closed: only closed time-stamps
  15993. When TYPE is nil, fall back on returning a regexp that matches
  15994. both scheduled and deadline timestamps."
  15995. (cl-case type
  15996. (all org-ts-regexp-both)
  15997. (active org-ts-regexp)
  15998. (inactive org-ts-regexp-inactive)
  15999. (scheduled org-scheduled-time-regexp)
  16000. (deadline org-deadline-time-regexp)
  16001. (closed org-closed-time-regexp)
  16002. (otherwise
  16003. (concat "\\<"
  16004. (regexp-opt (list org-deadline-string org-scheduled-string))
  16005. " *<\\([^>]+\\)>"))))
  16006. (defun org-check-before-date (d)
  16007. "Check if there are deadlines or scheduled entries before date D."
  16008. (interactive (list (org-read-date)))
  16009. (let* ((case-fold-search nil)
  16010. (regexp (org-re-timestamp org-ts-type))
  16011. (ts-type org-ts-type)
  16012. (callback
  16013. (lambda ()
  16014. (let ((match (match-string 1)))
  16015. (and (if (memq ts-type '(active inactive all))
  16016. (eq (org-element-type (save-excursion
  16017. (backward-char)
  16018. (org-element-context)))
  16019. 'timestamp)
  16020. (org-at-planning-p))
  16021. (time-less-p
  16022. (org-time-string-to-time match)
  16023. (org-time-string-to-time d)))))))
  16024. (message "%d entries before %s"
  16025. (org-occur regexp nil callback)
  16026. d)))
  16027. (defun org-check-after-date (d)
  16028. "Check if there are deadlines or scheduled entries after date D."
  16029. (interactive (list (org-read-date)))
  16030. (let* ((case-fold-search nil)
  16031. (regexp (org-re-timestamp org-ts-type))
  16032. (ts-type org-ts-type)
  16033. (callback
  16034. (lambda ()
  16035. (let ((match (match-string 1)))
  16036. (and (if (memq ts-type '(active inactive all))
  16037. (eq (org-element-type (save-excursion
  16038. (backward-char)
  16039. (org-element-context)))
  16040. 'timestamp)
  16041. (org-at-planning-p))
  16042. (not (time-less-p
  16043. (org-time-string-to-time match)
  16044. (org-time-string-to-time d))))))))
  16045. (message "%d entries after %s"
  16046. (org-occur regexp nil callback)
  16047. d)))
  16048. (defun org-check-dates-range (start-date end-date)
  16049. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16050. (interactive (list (org-read-date nil nil nil "Range starts")
  16051. (org-read-date nil nil nil "Range end")))
  16052. (let ((case-fold-search nil)
  16053. (regexp (org-re-timestamp org-ts-type))
  16054. (callback
  16055. (let ((type org-ts-type))
  16056. (lambda ()
  16057. (let ((match (match-string 1)))
  16058. (and
  16059. (if (memq type '(active inactive all))
  16060. (eq (org-element-type (save-excursion
  16061. (backward-char)
  16062. (org-element-context)))
  16063. 'timestamp)
  16064. (org-at-planning-p))
  16065. (not (time-less-p
  16066. (org-time-string-to-time match)
  16067. (org-time-string-to-time start-date)))
  16068. (time-less-p
  16069. (org-time-string-to-time match)
  16070. (org-time-string-to-time end-date))))))))
  16071. (message "%d entries between %s and %s"
  16072. (org-occur regexp nil callback) start-date end-date)))
  16073. (defun org-evaluate-time-range (&optional to-buffer)
  16074. "Evaluate a time range by computing the difference between start and end.
  16075. Normally the result is just printed in the echo area, but with prefix arg
  16076. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16077. If the time range is actually in a table, the result is inserted into the
  16078. next column.
  16079. For time difference computation, a year is assumed to be exactly 365
  16080. days in order to avoid rounding problems."
  16081. (interactive "P")
  16082. (or
  16083. (org-clock-update-time-maybe)
  16084. (save-excursion
  16085. (unless (org-at-date-range-p t)
  16086. (goto-char (point-at-bol))
  16087. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16088. (unless (org-at-date-range-p t)
  16089. (user-error "Not at a time-stamp range, and none found in current line")))
  16090. (let* ((ts1 (match-string 1))
  16091. (ts2 (match-string 2))
  16092. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16093. (match-end (match-end 0))
  16094. (time1 (org-time-string-to-time ts1))
  16095. (time2 (org-time-string-to-time ts2))
  16096. (t1 (float-time time1))
  16097. (t2 (float-time time2))
  16098. (diff (abs (- t2 t1)))
  16099. (negative (< (- t2 t1) 0))
  16100. ;; (ys (floor (* 365 24 60 60)))
  16101. (ds (* 24 60 60))
  16102. (hs (* 60 60))
  16103. (fy "%dy %dd %02d:%02d")
  16104. (fy1 "%dy %dd")
  16105. (fd "%dd %02d:%02d")
  16106. (fd1 "%dd")
  16107. (fh "%02d:%02d")
  16108. y d h m align)
  16109. (if havetime
  16110. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16111. y 0
  16112. d (floor (/ diff ds)) diff (mod diff ds)
  16113. h (floor (/ diff hs)) diff (mod diff hs)
  16114. m (floor (/ diff 60)))
  16115. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16116. y 0
  16117. d (floor (+ (/ diff ds) 0.5))
  16118. h 0 m 0))
  16119. (if (not to-buffer)
  16120. (message "%s" (org-make-tdiff-string y d h m))
  16121. (if (org-at-table-p)
  16122. (progn
  16123. (goto-char match-end)
  16124. (setq align t)
  16125. (and (looking-at " *|") (goto-char (match-end 0))))
  16126. (goto-char match-end))
  16127. (when (looking-at
  16128. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16129. (replace-match ""))
  16130. (when negative (insert " -"))
  16131. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16132. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16133. (insert " " (format fh h m))))
  16134. (when align (org-table-align))
  16135. (message "Time difference inserted")))))
  16136. (defun org-make-tdiff-string (y d h m)
  16137. (let ((fmt "")
  16138. (l nil))
  16139. (when (> y 0)
  16140. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16141. (push y l))
  16142. (when (> d 0)
  16143. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16144. (push d l))
  16145. (when (> h 0)
  16146. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16147. (push h l))
  16148. (when (> m 0)
  16149. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16150. (push m l))
  16151. (apply 'format fmt (nreverse l))))
  16152. (defun org-time-string-to-time (s &optional buffer pos)
  16153. "Convert a timestamp string into internal time."
  16154. (condition-case errdata
  16155. (apply 'encode-time (org-parse-time-string s))
  16156. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16157. s (if (not (and buffer pos))
  16158. ""
  16159. (format-message " at %d in buffer `%s'" pos buffer))
  16160. (cdr errdata)))))
  16161. (defun org-time-string-to-seconds (s)
  16162. "Convert a timestamp string to a number of seconds."
  16163. (float-time (org-time-string-to-time s)))
  16164. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16165. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16166. "Convert time stamp S to an absolute day number.
  16167. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16168. stamp, get the closest date to DAYNR. If PREFER is
  16169. `past' (respectively `future') return a date past (respectively
  16170. after) or equal to DAYNR.
  16171. POS is the location of time stamp S, as a buffer position in
  16172. BUFFER.
  16173. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16174. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16175. signalled."
  16176. (cond
  16177. ((string-match "\\`%%\\((.*)\\)" s)
  16178. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16179. ;; only able to match individual dates. If it fails, raise an
  16180. ;; error.
  16181. (if (and daynr
  16182. (org-diary-sexp-entry
  16183. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16184. daynr
  16185. (signal 'org-diary-sexp-no-match (list s))))
  16186. (daynr (org-closest-date s daynr prefer))
  16187. (t (time-to-days
  16188. (condition-case errdata
  16189. (apply #'encode-time (org-parse-time-string s))
  16190. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16191. s
  16192. (if (not (and buffer pos)) ""
  16193. (format-message " at %d in buffer `%s'" pos buffer))
  16194. (cdr errdata))))))))
  16195. (defun org-days-to-iso-week (days)
  16196. "Return the iso week number."
  16197. (require 'cal-iso)
  16198. (car (calendar-iso-from-absolute days)))
  16199. (defun org-small-year-to-year (year)
  16200. "Convert 2-digit years into 4-digit years.
  16201. YEAR is expanded into one of the 30 next years, if possible, or
  16202. into a past one. Any year larger than 99 is returned unchanged."
  16203. (if (>= year 100) year
  16204. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16205. (century (/ current 100))
  16206. (offset (- year (% current 100))))
  16207. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16208. ((> offset -70) (+ (* century 100) year))
  16209. (t (+ (* (1+ century) 100) year))))))
  16210. (defun org-time-from-absolute (d)
  16211. "Return the time corresponding to date D.
  16212. D may be an absolute day number, or a calendar-type list (month day year)."
  16213. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16214. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16215. (defvar org-agenda-current-date)
  16216. (defun org-calendar-holiday ()
  16217. "List of holidays, for Diary display in Org mode."
  16218. (require 'holidays)
  16219. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16220. (and hl (mapconcat #'identity hl "; "))))
  16221. (defun org-diary-sexp-entry (sexp entry d)
  16222. "Process a SEXP diary ENTRY for date D."
  16223. (require 'diary-lib)
  16224. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16225. ;; dynamically.
  16226. (let* ((sexp `(let ((entry ,entry)
  16227. (date ',d))
  16228. ,(car (read-from-string sexp))))
  16229. (result (if calendar-debug-sexp (eval sexp)
  16230. (condition-case nil
  16231. (eval sexp)
  16232. (error
  16233. (beep)
  16234. (message "Bad sexp at line %d in %s: %s"
  16235. (org-current-line)
  16236. (buffer-file-name) sexp)
  16237. (sleep-for 2))))))
  16238. (cond ((stringp result) (split-string result "; "))
  16239. ((and (consp result)
  16240. (not (consp (cdr result)))
  16241. (stringp (cdr result))) (cdr result))
  16242. ((and (consp result)
  16243. (stringp (car result))) result)
  16244. (result entry))))
  16245. (defun org-diary-to-ical-string (frombuf)
  16246. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16247. This uses the icalendar.el library."
  16248. (let* ((tmpdir temporary-file-directory)
  16249. (tmpfile (make-temp-name
  16250. (expand-file-name "orgics" tmpdir)))
  16251. buf rtn b e)
  16252. (with-current-buffer frombuf
  16253. (icalendar-export-region (point-min) (point-max) tmpfile)
  16254. (setq buf (find-buffer-visiting tmpfile))
  16255. (set-buffer buf)
  16256. (goto-char (point-min))
  16257. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16258. (setq b (match-beginning 0)))
  16259. (goto-char (point-max))
  16260. (when (re-search-backward "^END:VEVENT" nil t)
  16261. (setq e (match-end 0)))
  16262. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16263. (kill-buffer buf)
  16264. (delete-file tmpfile)
  16265. rtn))
  16266. (defun org-closest-date (start current prefer)
  16267. "Return closest date to CURRENT starting from START.
  16268. CURRENT and START are both time stamps.
  16269. When PREFER is `past', return a date that is either CURRENT or
  16270. past. When PREFER is `future', return a date that is either
  16271. CURRENT or future.
  16272. Only time stamps with a repeater are modified. Any other time
  16273. stamp stay unchanged. In any case, return value is an absolute
  16274. day number."
  16275. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16276. ;; No repeater. Do not shift time stamp.
  16277. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16278. (let ((value (string-to-number (match-string 1 start)))
  16279. (type (match-string 2 start)))
  16280. (if (= 0 value)
  16281. ;; Repeater with a 0-value is considered as void.
  16282. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16283. (let* ((base (org-date-to-gregorian start))
  16284. (target (org-date-to-gregorian current))
  16285. (sday (calendar-absolute-from-gregorian base))
  16286. (cday (calendar-absolute-from-gregorian target))
  16287. n1 n2)
  16288. ;; If START is already past CURRENT, just return START.
  16289. (if (<= cday sday) sday
  16290. ;; Compute closest date before (N1) and closest date past
  16291. ;; (N2) CURRENT.
  16292. (pcase type
  16293. ("h"
  16294. (let ((missing-hours
  16295. (mod (+ (- (* 24 (- cday sday))
  16296. (nth 2 (org-parse-time-string start)))
  16297. org-extend-today-until)
  16298. value)))
  16299. (setf n1 (if (= missing-hours 0) cday
  16300. (- cday (1+ (/ missing-hours 24)))))
  16301. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16302. ((or "d" "w")
  16303. (let ((value (if (equal type "w") (* 7 value) value)))
  16304. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16305. (setf n2 (+ n1 value))))
  16306. ("m"
  16307. (let* ((add-months
  16308. (lambda (d n)
  16309. ;; Add N months to gregorian date D, i.e.,
  16310. ;; a list (MONTH DAY YEAR). Return a valid
  16311. ;; gregorian date.
  16312. (let ((m (+ (nth 0 d) n)))
  16313. (list (mod m 12)
  16314. (nth 1 d)
  16315. (+ (/ m 12) (nth 2 d))))))
  16316. (months ; Complete months to TARGET.
  16317. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16318. (- (nth 0 target) (nth 0 base))
  16319. ;; If START's day is greater than
  16320. ;; TARGET's, remove incomplete month.
  16321. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16322. value)
  16323. value))
  16324. (before (funcall add-months base months)))
  16325. (setf n1 (calendar-absolute-from-gregorian before))
  16326. (setf n2
  16327. (calendar-absolute-from-gregorian
  16328. (funcall add-months before value)))))
  16329. (_
  16330. (let* ((d (nth 1 base))
  16331. (m (nth 0 base))
  16332. (y (nth 2 base))
  16333. (years ; Complete years to TARGET.
  16334. (* (/ (- (nth 2 target)
  16335. y
  16336. ;; If START's month and day are
  16337. ;; greater than TARGET's, remove
  16338. ;; incomplete year.
  16339. (if (or (> (nth 0 target) m)
  16340. (and (= (nth 0 target) m)
  16341. (> (nth 1 target) d)))
  16342. 0
  16343. 1))
  16344. value)
  16345. value))
  16346. (before (list m d (+ y years))))
  16347. (setf n1 (calendar-absolute-from-gregorian before))
  16348. (setf n2 (calendar-absolute-from-gregorian
  16349. (list m d (+ (nth 2 before) value)))))))
  16350. ;; Handle PREFER parameter, if any.
  16351. (cond
  16352. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16353. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16354. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16355. (defun org-date-to-gregorian (d)
  16356. "Turn any specification of date D into a Gregorian date for the calendar."
  16357. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16358. ((and (listp d) (= (length d) 3)) d)
  16359. ((stringp d)
  16360. (let ((d (org-parse-time-string d)))
  16361. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16362. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16363. (defun org-parse-time-string (s &optional nodefault zone)
  16364. "Parse the standard Org time string.
  16365. This should be a lot faster than the normal `parse-time-string'.
  16366. If time is not given, defaults to 0:00. However, with optional
  16367. NODEFAULT, hour and minute fields will be nil if not given.
  16368. The optional ZONE is omitted or nil for Emacs local time, t for
  16369. Universal Time, ‘wall’ for system wall clock time, or a string as
  16370. in the TZ environment variable."
  16371. (cond ((string-match org-ts-regexp0 s)
  16372. (list 0
  16373. (when (or (match-beginning 8) (not nodefault))
  16374. (string-to-number (or (match-string 8 s) "0")))
  16375. (when (or (match-beginning 7) (not nodefault))
  16376. (string-to-number (or (match-string 7 s) "0")))
  16377. (string-to-number (match-string 4 s))
  16378. (string-to-number (match-string 3 s))
  16379. (string-to-number (match-string 2 s))
  16380. nil nil zone))
  16381. ((string-match "^<[^>]+>$" s)
  16382. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16383. ;; second argument. However, this requires at least Emacs
  16384. ;; 25.1. We can do it when we switch to this version as our
  16385. ;; minimal requirement.
  16386. (decode-time (seconds-to-time (org-matcher-time s))))
  16387. (t (error "Not a standard Org time string: %s" s))))
  16388. (defun org-timestamp-up (&optional arg)
  16389. "Increase the date item at the cursor by one.
  16390. If the cursor is on the year, change the year. If it is on the month,
  16391. the day or the time, change that.
  16392. With prefix ARG, change by that many units."
  16393. (interactive "p")
  16394. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16395. (defun org-timestamp-down (&optional arg)
  16396. "Decrease the date item at the cursor by one.
  16397. If the cursor is on the year, change the year. If it is on the month,
  16398. the day or the time, change that.
  16399. With prefix ARG, change by that many units."
  16400. (interactive "p")
  16401. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16402. (defun org-timestamp-up-day (&optional arg)
  16403. "Increase the date in the time stamp by one day.
  16404. With prefix ARG, change that many days."
  16405. (interactive "p")
  16406. (if (and (not (org-at-timestamp-p t))
  16407. (org-at-heading-p))
  16408. (org-todo 'up)
  16409. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16410. (defun org-timestamp-down-day (&optional arg)
  16411. "Decrease the date in the time stamp by one day.
  16412. With prefix ARG, change that many days."
  16413. (interactive "p")
  16414. (if (and (not (org-at-timestamp-p t))
  16415. (org-at-heading-p))
  16416. (org-todo 'down)
  16417. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16418. (defun org-at-timestamp-p (&optional inactive-ok)
  16419. "Non-nil if point is inside a timestamp.
  16420. When optional argument INACTIVE-OK is non-nil, also consider
  16421. inactive timestamps.
  16422. When this function returns a non-nil value, match data is set
  16423. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16424. INACTIVE-OK."
  16425. (interactive)
  16426. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16427. (pos (point))
  16428. (ans (or (looking-at tsr)
  16429. (save-excursion
  16430. (skip-chars-backward "^[<\n\r\t")
  16431. (when (> (point) (point-min)) (backward-char 1))
  16432. (and (looking-at tsr)
  16433. (> (- (match-end 0) pos) -1))))))
  16434. (and ans
  16435. (boundp 'org-ts-what)
  16436. (setq org-ts-what
  16437. (cond
  16438. ((= pos (match-beginning 0)) 'bracket)
  16439. ;; Point is considered to be "on the bracket" whether
  16440. ;; it's really on it or right after it.
  16441. ((= pos (1- (match-end 0))) 'bracket)
  16442. ((= pos (match-end 0)) 'after)
  16443. ((org-pos-in-match-range pos 2) 'year)
  16444. ((org-pos-in-match-range pos 3) 'month)
  16445. ((org-pos-in-match-range pos 7) 'hour)
  16446. ((org-pos-in-match-range pos 8) 'minute)
  16447. ((or (org-pos-in-match-range pos 4)
  16448. (org-pos-in-match-range pos 5)) 'day)
  16449. ((and (> pos (or (match-end 8) (match-end 5)))
  16450. (< pos (match-end 0)))
  16451. (- pos (or (match-end 8) (match-end 5))))
  16452. (t 'day))))
  16453. ans))
  16454. (defun org-toggle-timestamp-type ()
  16455. "Toggle the type (<active> or [inactive]) of a time stamp."
  16456. (interactive)
  16457. (when (org-at-timestamp-p t)
  16458. (let ((beg (match-beginning 0)) (end (match-end 0))
  16459. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16460. (save-excursion
  16461. (goto-char beg)
  16462. (while (re-search-forward "[][<>]" end t)
  16463. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16464. t t)))
  16465. (message "Timestamp is now %sactive"
  16466. (if (equal (char-after beg) ?<) "" "in")))))
  16467. (defun org-at-clock-log-p nil
  16468. "Is the cursor on the clock log line?"
  16469. (save-excursion
  16470. (beginning-of-line)
  16471. (looking-at org-clock-line-re)))
  16472. (defvar org-clock-history) ; defined in org-clock.el
  16473. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16474. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16475. "Change the date in the time stamp at point.
  16476. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16477. `year', `minute', `second'. If WHAT is not given, the cursor position
  16478. in the timestamp determines what will be changed.
  16479. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16480. (let ((origin (point)) origin-cat
  16481. with-hm inactive
  16482. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16483. org-ts-what
  16484. extra rem
  16485. ts time time0 fixnext clrgx)
  16486. (unless (org-at-timestamp-p t)
  16487. (user-error "Not at a timestamp"))
  16488. (if (and (not what) (eq org-ts-what 'bracket))
  16489. (org-toggle-timestamp-type)
  16490. ;; Point isn't on brackets. Remember the part of the time-stamp
  16491. ;; the point was in. Indeed, size of time-stamps may change,
  16492. ;; but point must be kept in the same category nonetheless.
  16493. (setq origin-cat org-ts-what)
  16494. (when (and (not what) (not (eq org-ts-what 'day))
  16495. org-display-custom-times
  16496. (get-text-property (point) 'display)
  16497. (not (get-text-property (1- (point)) 'display)))
  16498. (setq org-ts-what 'day))
  16499. (setq org-ts-what (or what org-ts-what)
  16500. inactive (= (char-after (match-beginning 0)) ?\[)
  16501. ts (match-string 0))
  16502. (replace-match "")
  16503. (when (string-match
  16504. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16505. ts)
  16506. (setq extra (match-string 1 ts))
  16507. (when suppress-tmp-delay
  16508. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16509. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16510. (setq with-hm t))
  16511. (setq time0 (org-parse-time-string ts))
  16512. (when (and updown
  16513. (eq org-ts-what 'minute)
  16514. (not current-prefix-arg))
  16515. ;; This looks like s-up and s-down. Change by one rounding step.
  16516. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16517. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16518. (setcar (cdr time0) (+ (nth 1 time0)
  16519. (if (> n 0) (- rem) (- dm rem))))))
  16520. (setq time
  16521. (apply #'encode-time
  16522. (or (car time0) 0)
  16523. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16524. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16525. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16526. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16527. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16528. (nthcdr 6 time0)))
  16529. (when (and (member org-ts-what '(hour minute))
  16530. extra
  16531. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16532. (setq extra (org-modify-ts-extra
  16533. extra
  16534. (if (eq org-ts-what 'hour) 2 5)
  16535. n dm)))
  16536. (when (integerp org-ts-what)
  16537. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16538. (when (eq what 'calendar)
  16539. (let ((cal-date (org-get-date-from-calendar)))
  16540. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16541. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16542. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16543. (setcar time0 (or (car time0) 0))
  16544. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16545. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16546. (setq time (apply 'encode-time time0))))
  16547. ;; Insert the new time-stamp, and ensure point stays in the same
  16548. ;; category as before (i.e. not after the last position in that
  16549. ;; category).
  16550. (let ((pos (point)))
  16551. ;; Stay before inserted string. `save-excursion' is of no use.
  16552. (setq org-last-changed-timestamp
  16553. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16554. (goto-char pos))
  16555. (save-match-data
  16556. (looking-at org-ts-regexp3)
  16557. (goto-char
  16558. (pcase origin-cat
  16559. ;; `day' category ends before `hour' if any, or at the end
  16560. ;; of the day name.
  16561. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16562. (`hour (min (match-end 7) origin))
  16563. (`minute (min (1- (match-end 8)) origin))
  16564. ((pred integerp) (min (1- (match-end 0)) origin))
  16565. ;; Point was right after the time-stamp. However, the
  16566. ;; time-stamp length might have changed, so refer to
  16567. ;; (match-end 0) instead.
  16568. (`after (match-end 0))
  16569. ;; `year' and `month' have both fixed size: point couldn't
  16570. ;; have moved into another part.
  16571. (_ origin))))
  16572. ;; Update clock if on a CLOCK line.
  16573. (org-clock-update-time-maybe)
  16574. ;; Maybe adjust the closest clock in `org-clock-history'
  16575. (when org-clock-adjust-closest
  16576. (if (not (and (org-at-clock-log-p)
  16577. (< 1 (length (delq nil (mapcar 'marker-position
  16578. org-clock-history))))))
  16579. (message "No clock to adjust")
  16580. (cond ((save-excursion ; fix previous clock?
  16581. (re-search-backward org-ts-regexp0 nil t)
  16582. (looking-back (concat org-clock-string " \\[")
  16583. (line-beginning-position)))
  16584. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16585. ((save-excursion ; fix next clock?
  16586. (re-search-backward org-ts-regexp0 nil t)
  16587. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16588. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16589. (save-window-excursion
  16590. ;; Find closest clock to point, adjust the previous/next one in history
  16591. (let* ((p (save-excursion (org-back-to-heading t)))
  16592. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16593. (clfixnth
  16594. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16595. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16596. (if (not clfixpos)
  16597. (message "No clock to adjust")
  16598. (save-excursion
  16599. (org-goto-marker-or-bmk clfixpos)
  16600. (org-show-subtree)
  16601. (when (re-search-forward clrgx nil t)
  16602. (goto-char (match-beginning 1))
  16603. (let (org-clock-adjust-closest)
  16604. (org-timestamp-change n org-ts-what updown))
  16605. (message "Clock adjusted in %s for heading: %s"
  16606. (file-name-nondirectory (buffer-file-name))
  16607. (org-get-heading t t)))))))))
  16608. ;; Try to recenter the calendar window, if any.
  16609. (when (and org-calendar-follow-timestamp-change
  16610. (get-buffer-window "*Calendar*" t)
  16611. (memq org-ts-what '(day month year)))
  16612. (org-recenter-calendar (time-to-days time))))))
  16613. (defun org-modify-ts-extra (s pos n dm)
  16614. "Change the different parts of the lead-time and repeat fields in timestamp."
  16615. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16616. ng h m new rem)
  16617. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16618. (cond
  16619. ((or (org-pos-in-match-range pos 2)
  16620. (org-pos-in-match-range pos 3))
  16621. (setq m (string-to-number (match-string 3 s))
  16622. h (string-to-number (match-string 2 s)))
  16623. (if (org-pos-in-match-range pos 2)
  16624. (setq h (+ h n))
  16625. (setq n (* dm (with-no-warnings (signum n))))
  16626. (unless (= 0 (setq rem (% m dm)))
  16627. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16628. (setq m (+ m n)))
  16629. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16630. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16631. (setq h (mod h 24))
  16632. (setq ng 1 new (format "-%02d:%02d" h m)))
  16633. ((org-pos-in-match-range pos 6)
  16634. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16635. ((org-pos-in-match-range pos 5)
  16636. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16637. ((org-pos-in-match-range pos 9)
  16638. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16639. ((org-pos-in-match-range pos 8)
  16640. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16641. (when ng
  16642. (setq s (concat
  16643. (substring s 0 (match-beginning ng))
  16644. new
  16645. (substring s (match-end ng))))))
  16646. s))
  16647. (defun org-recenter-calendar (d)
  16648. "If the calendar is visible, recenter it to date D."
  16649. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16650. (when cwin
  16651. (let ((calendar-move-hook nil))
  16652. (with-selected-window cwin
  16653. (calendar-goto-date
  16654. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16655. (defun org-goto-calendar (&optional arg)
  16656. "Go to the Emacs calendar at the current date.
  16657. If there is a time stamp in the current line, go to that date.
  16658. A prefix ARG can be used to force the current date."
  16659. (interactive "P")
  16660. (let ((tsr org-ts-regexp) diff
  16661. (calendar-move-hook nil)
  16662. (calendar-view-holidays-initially-flag nil)
  16663. (calendar-view-diary-initially-flag nil))
  16664. (when (or (org-at-timestamp-p)
  16665. (save-excursion
  16666. (beginning-of-line 1)
  16667. (looking-at (concat ".*" tsr))))
  16668. (let ((d1 (time-to-days (current-time)))
  16669. (d2 (time-to-days
  16670. (org-time-string-to-time (match-string 1)))))
  16671. (setq diff (- d2 d1))))
  16672. (calendar)
  16673. (calendar-goto-today)
  16674. (when (and diff (not arg)) (calendar-forward-day diff))))
  16675. (defun org-get-date-from-calendar ()
  16676. "Return a list (month day year) of date at point in calendar."
  16677. (with-current-buffer "*Calendar*"
  16678. (save-match-data
  16679. (calendar-cursor-to-date))))
  16680. (defun org-date-from-calendar ()
  16681. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16682. If there is already a time stamp at the cursor position, update it."
  16683. (interactive)
  16684. (if (org-at-timestamp-p t)
  16685. (org-timestamp-change 0 'calendar)
  16686. (let ((cal-date (org-get-date-from-calendar)))
  16687. (org-insert-time-stamp
  16688. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16689. (defcustom org-effort-durations
  16690. `(("min" . 1)
  16691. ("h" . 60)
  16692. ("d" . ,(* 60 8))
  16693. ("w" . ,(* 60 8 5))
  16694. ("m" . ,(* 60 8 5 4))
  16695. ("y" . ,(* 60 8 5 40)))
  16696. "Conversion factor to minutes for an effort modifier.
  16697. Each entry has the form (MODIFIER . MINUTES).
  16698. In an effort string, a number followed by MODIFIER is multiplied
  16699. by the specified number of MINUTES to obtain an effort in
  16700. minutes.
  16701. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16702. effort string \"2hours\" is equivalent to 120 minutes."
  16703. :group 'org-agenda
  16704. :version "26.1"
  16705. :package-version '(Org . "8.3")
  16706. :type '(alist :key-type (string :tag "Modifier")
  16707. :value-type (number :tag "Minutes")))
  16708. (defun org-minutes-to-clocksum-string (m)
  16709. "Format number of minutes as a clocksum string.
  16710. The format is determined by `org-time-clocksum-format',
  16711. `org-time-clocksum-use-fractional' and
  16712. `org-time-clocksum-fractional-format' and
  16713. `org-time-clocksum-use-effort-durations'."
  16714. (let ((clocksum "")
  16715. (m (round m)) ; Don't allow fractions of minutes
  16716. h d w mo y fmt n)
  16717. (setq h (if org-time-clocksum-use-effort-durations
  16718. (cdr (assoc "h" org-effort-durations)) 60)
  16719. d (if org-time-clocksum-use-effort-durations
  16720. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16721. w (if org-time-clocksum-use-effort-durations
  16722. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16723. mo (if org-time-clocksum-use-effort-durations
  16724. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16725. y (if org-time-clocksum-use-effort-durations
  16726. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16727. ;; fractional format
  16728. (if org-time-clocksum-use-fractional
  16729. (cond
  16730. ;; single format string
  16731. ((stringp org-time-clocksum-fractional-format)
  16732. (format org-time-clocksum-fractional-format (/ m (float h))))
  16733. ;; choice of fractional formats for different time units
  16734. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16735. (> (/ (truncate m) (* y d h)) 0))
  16736. (format fmt (/ m (* y d (float h)))))
  16737. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16738. (> (/ (truncate m) (* mo d h)) 0))
  16739. (format fmt (/ m (* mo d (float h)))))
  16740. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16741. (> (/ (truncate m) (* w d h)) 0))
  16742. (format fmt (/ m (* w d (float h)))))
  16743. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16744. (> (/ (truncate m) (* d h)) 0))
  16745. (format fmt (/ m (* d (float h)))))
  16746. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16747. (> (/ (truncate m) h) 0))
  16748. (format fmt (/ m (float h))))
  16749. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16750. (format fmt m))
  16751. ;; fall back to smallest time unit with a format
  16752. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16753. (format fmt (/ m (float h))))
  16754. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16755. (format fmt (/ m (* d (float h)))))
  16756. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16757. (format fmt (/ m (* w d (float h)))))
  16758. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16759. (format fmt (/ m (* mo d (float h)))))
  16760. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16761. (format fmt (/ m (* y d (float h))))))
  16762. ;; standard (non-fractional) format, with single format string
  16763. (if (stringp org-time-clocksum-format)
  16764. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16765. ;; separate formats components
  16766. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16767. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16768. (plist-get org-time-clocksum-format :require-years))
  16769. (setq clocksum (concat clocksum (format fmt n))
  16770. m (- m (* n y d h))))
  16771. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16772. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16773. (plist-get org-time-clocksum-format :require-months))
  16774. (setq clocksum (concat clocksum (format fmt n))
  16775. m (- m (* n mo d h))))
  16776. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16777. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16778. (plist-get org-time-clocksum-format :require-weeks))
  16779. (setq clocksum (concat clocksum (format fmt n))
  16780. m (- m (* n w d h))))
  16781. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16782. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16783. (plist-get org-time-clocksum-format :require-days))
  16784. (setq clocksum (concat clocksum (format fmt n))
  16785. m (- m (* n d h))))
  16786. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16787. (or (> (setq n (/ (truncate m) h)) 0)
  16788. (plist-get org-time-clocksum-format :require-hours))
  16789. (setq clocksum (concat clocksum (format fmt n))
  16790. m (- m (* n h))))
  16791. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16792. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16793. (setq clocksum (concat clocksum (format fmt m))))
  16794. ;; return formatted time duration
  16795. clocksum))))
  16796. (defun org-hours-to-clocksum-string (n)
  16797. (org-minutes-to-clocksum-string (* n 60)))
  16798. (defun org-hh:mm-string-to-minutes (s)
  16799. "Convert a string H:MM to a number of minutes.
  16800. If the string is just a number, interpret it as minutes.
  16801. In fact, the first hh:mm or number in the string will be taken,
  16802. there can be extra stuff in the string.
  16803. If no number is found, the return value is 0."
  16804. (cond
  16805. ((integerp s) s)
  16806. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16807. (+ (* (string-to-number (match-string 1 s)) 60)
  16808. (string-to-number (match-string 2 s))))
  16809. ((string-match "\\([0-9]+\\)" s)
  16810. (string-to-number (match-string 1 s)))
  16811. (t 0)))
  16812. (defcustom org-image-actual-width t
  16813. "Should we use the actual width of images when inlining them?
  16814. When set to t, always use the image width.
  16815. When set to a number, use imagemagick (when available) to set
  16816. the image's width to this value.
  16817. When set to a number in a list, try to get the width from any
  16818. #+ATTR.* keyword if it matches a width specification like
  16819. #+ATTR_HTML: :width 300px
  16820. and fall back on that number if none is found.
  16821. When set to nil, try to get the width from an #+ATTR.* keyword
  16822. and fall back on the original width if none is found.
  16823. This requires Emacs >= 24.1, build with imagemagick support."
  16824. :group 'org-appearance
  16825. :version "24.4"
  16826. :package-version '(Org . "8.0")
  16827. :type '(choice
  16828. (const :tag "Use the image width" t)
  16829. (integer :tag "Use a number of pixels")
  16830. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16831. (const :tag "Use #+ATTR* or don't resize" nil)))
  16832. (defcustom org-agenda-inhibit-startup nil
  16833. "Inhibit startup when preparing agenda buffers.
  16834. When this variable is t, the initialization of the Org agenda
  16835. buffers is inhibited: e.g. the visibility state is not set, the
  16836. tables are not re-aligned, etc."
  16837. :type 'boolean
  16838. :version "24.3"
  16839. :group 'org-agenda)
  16840. (defcustom org-agenda-ignore-properties nil
  16841. "Avoid updating text properties when building the agenda.
  16842. Properties are used to prepare buffers for effort estimates,
  16843. appointments, statistics and subtree-local categories.
  16844. If you don't use these in the agenda, you can add them to this
  16845. list and agenda building will be a bit faster.
  16846. The value is a list, with zero or more of the symbols `effort', `appt',
  16847. `stats' or `category'."
  16848. :type '(set :greedy t
  16849. (const effort)
  16850. (const appt)
  16851. (const stats)
  16852. (const category))
  16853. :version "26.1"
  16854. :package-version '(Org . "8.3")
  16855. :group 'org-agenda)
  16856. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16857. "Convert a duration string S to minutes.
  16858. A bare number is interpreted as minutes, modifiers can be set by
  16859. customizing `org-effort-durations' (which see).
  16860. Entries containing a colon are interpreted as H:MM by
  16861. `org-hh:mm-string-to-minutes'."
  16862. (let ((result 0)
  16863. (re (concat "\\([0-9.]+\\) *\\("
  16864. (regexp-opt (mapcar 'car org-effort-durations))
  16865. "\\)")))
  16866. (while (string-match re s)
  16867. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16868. (string-to-number (match-string 1 s))))
  16869. (setq s (replace-match "" nil t s)))
  16870. (setq result (floor result))
  16871. (cl-incf result (org-hh:mm-string-to-minutes s))
  16872. (if output-to-string (number-to-string result) result)))
  16873. ;;;; Files
  16874. (defun org-save-all-org-buffers ()
  16875. "Save all Org buffers without user confirmation."
  16876. (interactive)
  16877. (message "Saving all Org buffers...")
  16878. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16879. (when (featurep 'org-id) (org-id-locations-save))
  16880. (message "Saving all Org buffers... done"))
  16881. (defun org-revert-all-org-buffers ()
  16882. "Revert all Org buffers.
  16883. Prompt for confirmation when there are unsaved changes.
  16884. Be sure you know what you are doing before letting this function
  16885. overwrite your changes.
  16886. This function is useful in a setup where one tracks org files
  16887. with a version control system, to revert on one machine after pulling
  16888. changes from another. I believe the procedure must be like this:
  16889. 1. M-x org-save-all-org-buffers
  16890. 2. Pull changes from the other machine, resolve conflicts
  16891. 3. M-x org-revert-all-org-buffers"
  16892. (interactive)
  16893. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16894. (user-error "Abort"))
  16895. (save-excursion
  16896. (save-window-excursion
  16897. (dolist (b (buffer-list))
  16898. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16899. (with-current-buffer b buffer-file-name))
  16900. (pop-to-buffer-same-window b)
  16901. (revert-buffer t 'no-confirm)))
  16902. (when (and (featurep 'org-id) org-id-track-globally)
  16903. (org-id-locations-load)))))
  16904. ;;;; Agenda files
  16905. ;;;###autoload
  16906. (defun org-switchb (&optional arg)
  16907. "Switch between Org buffers.
  16908. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16909. With `\\[universal-argument] \\[universal-argument]' \
  16910. prefix, restrict available buffers to agenda files."
  16911. (interactive "P")
  16912. (let ((blist (org-buffer-list
  16913. (cond ((equal arg '(4)) 'files)
  16914. ((equal arg '(16)) 'agenda)))))
  16915. (pop-to-buffer-same-window
  16916. (completing-read "Org buffer: "
  16917. (mapcar #'list (mapcar #'buffer-name blist))
  16918. nil t))))
  16919. (defun org-buffer-list (&optional predicate exclude-tmp)
  16920. "Return a list of Org buffers.
  16921. PREDICATE can be `export', `files' or `agenda'.
  16922. export restrict the list to Export buffers.
  16923. files restrict the list to buffers visiting Org files.
  16924. agenda restrict the list to buffers visiting agenda files.
  16925. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16926. (let* ((bfn nil)
  16927. (agenda-files (and (eq predicate 'agenda)
  16928. (mapcar 'file-truename (org-agenda-files t))))
  16929. (filter
  16930. (cond
  16931. ((eq predicate 'files)
  16932. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16933. ((eq predicate 'export)
  16934. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16935. ((eq predicate 'agenda)
  16936. (lambda (b)
  16937. (with-current-buffer b
  16938. (and (derived-mode-p 'org-mode)
  16939. (setq bfn (buffer-file-name b))
  16940. (member (file-truename bfn) agenda-files)))))
  16941. (t (lambda (b) (with-current-buffer b
  16942. (or (derived-mode-p 'org-mode)
  16943. (string-match "\\*Org .*Export"
  16944. (buffer-name b)))))))))
  16945. (delq nil
  16946. (mapcar
  16947. (lambda(b)
  16948. (if (and (funcall filter b)
  16949. (or (not exclude-tmp)
  16950. (not (string-match "tmp" (buffer-name b)))))
  16951. b
  16952. nil))
  16953. (buffer-list)))))
  16954. (defun org-agenda-files (&optional unrestricted archives)
  16955. "Get the list of agenda files.
  16956. Optional UNRESTRICTED means return the full list even if a restriction
  16957. is currently in place.
  16958. When ARCHIVES is t, include all archive files that are really being
  16959. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16960. `org-agenda-archives-mode' is t."
  16961. (let ((files
  16962. (cond
  16963. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16964. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16965. ((listp org-agenda-files) org-agenda-files)
  16966. (t (error "Invalid value of `org-agenda-files'")))))
  16967. (setq files (apply 'append
  16968. (mapcar (lambda (f)
  16969. (if (file-directory-p f)
  16970. (directory-files
  16971. f t org-agenda-file-regexp)
  16972. (list f)))
  16973. files)))
  16974. (when org-agenda-skip-unavailable-files
  16975. (setq files (delq nil
  16976. (mapcar (function
  16977. (lambda (file)
  16978. (and (file-readable-p file) file)))
  16979. files))))
  16980. (when (or (eq archives t)
  16981. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16982. (setq files (org-add-archive-files files)))
  16983. files))
  16984. (defun org-agenda-file-p (&optional file)
  16985. "Return non-nil, if FILE is an agenda file.
  16986. If FILE is omitted, use the file associated with the current
  16987. buffer."
  16988. (let ((fname (or file (buffer-file-name))))
  16989. (and fname
  16990. (member (file-truename fname)
  16991. (mapcar #'file-truename (org-agenda-files t))))))
  16992. (defun org-edit-agenda-file-list ()
  16993. "Edit the list of agenda files.
  16994. Depending on setup, this either uses customize to edit the variable
  16995. `org-agenda-files', or it visits the file that is holding the list. In the
  16996. latter case, the buffer is set up in a way that saving it automatically kills
  16997. the buffer and restores the previous window configuration."
  16998. (interactive)
  16999. (if (stringp org-agenda-files)
  17000. (let ((cw (current-window-configuration)))
  17001. (find-file org-agenda-files)
  17002. (setq-local org-window-configuration cw)
  17003. (add-hook 'after-save-hook
  17004. (lambda ()
  17005. (set-window-configuration
  17006. (prog1 org-window-configuration
  17007. (kill-buffer (current-buffer))))
  17008. (org-install-agenda-files-menu)
  17009. (message "New agenda file list installed"))
  17010. nil 'local)
  17011. (message "%s" (substitute-command-keys
  17012. "Edit list and finish with \\[save-buffer]")))
  17013. (customize-variable 'org-agenda-files)))
  17014. (defun org-store-new-agenda-file-list (list)
  17015. "Set new value for the agenda file list and save it correctly."
  17016. (if (stringp org-agenda-files)
  17017. (let ((fe (org-read-agenda-file-list t)) b u)
  17018. (while (setq b (find-buffer-visiting org-agenda-files))
  17019. (kill-buffer b))
  17020. (with-temp-file org-agenda-files
  17021. (insert
  17022. (mapconcat
  17023. (lambda (f) ;; Keep un-expanded entries.
  17024. (if (setq u (assoc f fe))
  17025. (cdr u)
  17026. f))
  17027. list "\n")
  17028. "\n")))
  17029. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17030. (org-insert-mode-line-in-empty-file nil))
  17031. (setq org-agenda-files list)
  17032. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17033. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17034. "Read the list of agenda files from a file.
  17035. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17036. filenames, used by `org-store-new-agenda-file-list' to write back
  17037. un-expanded file names."
  17038. (when (file-directory-p org-agenda-files)
  17039. (error "`org-agenda-files' cannot be a single directory"))
  17040. (when (stringp org-agenda-files)
  17041. (with-temp-buffer
  17042. (insert-file-contents org-agenda-files)
  17043. (mapcar
  17044. (lambda (f)
  17045. (let ((e (expand-file-name (substitute-in-file-name f)
  17046. org-directory)))
  17047. (if pair-with-expansion
  17048. (cons e f)
  17049. e)))
  17050. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17051. ;;;###autoload
  17052. (defun org-cycle-agenda-files ()
  17053. "Cycle through the files in `org-agenda-files'.
  17054. If the current buffer visits an agenda file, find the next one in the list.
  17055. If the current buffer does not, find the first agenda file."
  17056. (interactive)
  17057. (let* ((fs (or (org-agenda-files t)
  17058. (user-error "No agenda files")))
  17059. (files (copy-sequence fs))
  17060. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17061. file)
  17062. (when tcf
  17063. (while (and (setq file (pop files))
  17064. (not (equal (file-truename file) tcf)))))
  17065. (find-file (car (or files fs)))
  17066. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17067. (defun org-agenda-file-to-front (&optional to-end)
  17068. "Move/add the current file to the top of the agenda file list.
  17069. If the file is not present in the list, it is added to the front. If it is
  17070. present, it is moved there. With optional argument TO-END, add/move to the
  17071. end of the list."
  17072. (interactive "P")
  17073. (let ((org-agenda-skip-unavailable-files nil)
  17074. (file-alist (mapcar (lambda (x)
  17075. (cons (file-truename x) x))
  17076. (org-agenda-files t)))
  17077. (ctf (file-truename
  17078. (or buffer-file-name
  17079. (user-error "Please save the current buffer to a file"))))
  17080. x had)
  17081. (setq x (assoc ctf file-alist) had x)
  17082. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17083. (if to-end
  17084. (setq file-alist (append (delq x file-alist) (list x)))
  17085. (setq file-alist (cons x (delq x file-alist))))
  17086. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17087. (org-install-agenda-files-menu)
  17088. (message "File %s to %s of agenda file list"
  17089. (if had "moved" "added") (if to-end "end" "front"))))
  17090. (defun org-remove-file (&optional file)
  17091. "Remove current file from the list of files in variable `org-agenda-files'.
  17092. These are the files which are being checked for agenda entries.
  17093. Optional argument FILE means use this file instead of the current."
  17094. (interactive)
  17095. (let* ((org-agenda-skip-unavailable-files nil)
  17096. (file (or file buffer-file-name
  17097. (user-error "Current buffer does not visit a file")))
  17098. (true-file (file-truename file))
  17099. (afile (abbreviate-file-name file))
  17100. (files (delq nil (mapcar
  17101. (lambda (x)
  17102. (unless (equal true-file
  17103. (file-truename x))
  17104. x))
  17105. (org-agenda-files t)))))
  17106. (if (not (= (length files) (length (org-agenda-files t))))
  17107. (progn
  17108. (org-store-new-agenda-file-list files)
  17109. (org-install-agenda-files-menu)
  17110. (message "Removed from Org Agenda list: %s" afile))
  17111. (message "File was not in list: %s (not removed)" afile))))
  17112. (defun org-file-menu-entry (file)
  17113. (vector file (list 'find-file file) t))
  17114. (defun org-check-agenda-file (file)
  17115. "Make sure FILE exists. If not, ask user what to do."
  17116. (unless (file-exists-p file)
  17117. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17118. (abbreviate-file-name file))
  17119. (let ((r (downcase (read-char-exclusive))))
  17120. (cond
  17121. ((equal r ?r)
  17122. (org-remove-file file)
  17123. (throw 'nextfile t))
  17124. (t (user-error "Abort"))))))
  17125. (defun org-get-agenda-file-buffer (file)
  17126. "Get an agenda buffer visiting FILE.
  17127. If the buffer needs to be created, add it to the list of buffers
  17128. which might be released later."
  17129. (let ((buf (org-find-base-buffer-visiting file)))
  17130. (if buf
  17131. buf ; just return it
  17132. ;; Make a new buffer and remember it
  17133. (setq buf (find-file-noselect file))
  17134. (when buf (push buf org-agenda-new-buffers))
  17135. buf)))
  17136. (defun org-release-buffers (blist)
  17137. "Release all buffers in list, asking the user for confirmation when needed.
  17138. When a buffer is unmodified, it is just killed. When modified, it is saved
  17139. \(if the user agrees) and then killed."
  17140. (let (file)
  17141. (dolist (buf blist)
  17142. (setq file (buffer-file-name buf))
  17143. (when (and (buffer-modified-p buf)
  17144. file
  17145. (y-or-n-p (format "Save file %s? " file)))
  17146. (with-current-buffer buf (save-buffer)))
  17147. (kill-buffer buf))))
  17148. (defun org-agenda-prepare-buffers (files)
  17149. "Create buffers for all agenda files, protect archived trees and comments."
  17150. (interactive)
  17151. (let ((pa '(:org-archived t))
  17152. (pc '(:org-comment t))
  17153. (pall '(:org-archived t :org-comment t))
  17154. (inhibit-read-only t)
  17155. (org-inhibit-startup org-agenda-inhibit-startup)
  17156. (rea (concat ":" org-archive-tag ":"))
  17157. re pos)
  17158. (setq org-tag-alist-for-agenda nil
  17159. org-tag-groups-alist-for-agenda nil)
  17160. (save-excursion
  17161. (save-restriction
  17162. (dolist (file files)
  17163. (catch 'nextfile
  17164. (if (bufferp file)
  17165. (set-buffer file)
  17166. (org-check-agenda-file file)
  17167. (set-buffer (org-get-agenda-file-buffer file)))
  17168. (widen)
  17169. (org-set-regexps-and-options 'tags-only)
  17170. (setq pos (point))
  17171. (or (memq 'category org-agenda-ignore-properties)
  17172. (org-refresh-category-properties))
  17173. (or (memq 'stats org-agenda-ignore-properties)
  17174. (org-refresh-stats-properties))
  17175. (or (memq 'effort org-agenda-ignore-properties)
  17176. (org-refresh-effort-properties))
  17177. (or (memq 'appt org-agenda-ignore-properties)
  17178. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17179. (setq org-todo-keywords-for-agenda
  17180. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17181. (setq org-done-keywords-for-agenda
  17182. (append org-done-keywords-for-agenda org-done-keywords))
  17183. (setq org-todo-keyword-alist-for-agenda
  17184. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17185. (setq org-tag-alist-for-agenda
  17186. (org-uniquify
  17187. (append org-tag-alist-for-agenda
  17188. org-current-tag-alist)))
  17189. ;; Merge current file's tag groups into global
  17190. ;; `org-tag-groups-alist-for-agenda'.
  17191. (when org-group-tags
  17192. (dolist (alist org-tag-groups-alist)
  17193. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17194. (if old
  17195. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17196. (push alist org-tag-groups-alist-for-agenda)))))
  17197. (org-with-silent-modifications
  17198. (save-excursion
  17199. (remove-text-properties (point-min) (point-max) pall)
  17200. (when org-agenda-skip-archived-trees
  17201. (goto-char (point-min))
  17202. (while (re-search-forward rea nil t)
  17203. (when (org-at-heading-p t)
  17204. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17205. (goto-char (point-min))
  17206. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17207. (while (re-search-forward re nil t)
  17208. (when (save-match-data (org-in-commented-heading-p t))
  17209. (add-text-properties
  17210. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17211. (goto-char pos)))))
  17212. (setq org-todo-keywords-for-agenda
  17213. (org-uniquify org-todo-keywords-for-agenda))
  17214. (setq org-todo-keyword-alist-for-agenda
  17215. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17216. ;;;; CDLaTeX minor mode
  17217. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17218. "Keymap for the minor `org-cdlatex-mode'.")
  17219. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17220. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17221. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17222. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17223. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17224. (defvar org-cdlatex-texmathp-advice-is-done nil
  17225. "Flag remembering if we have applied the advice to texmathp already.")
  17226. (define-minor-mode org-cdlatex-mode
  17227. "Toggle the minor `org-cdlatex-mode'.
  17228. This mode supports entering LaTeX environment and math in LaTeX fragments
  17229. in Org mode.
  17230. \\{org-cdlatex-mode-map}"
  17231. nil " OCDL" nil
  17232. (when org-cdlatex-mode
  17233. (require 'cdlatex)
  17234. (run-hooks 'cdlatex-mode-hook)
  17235. (cdlatex-compute-tables))
  17236. (unless org-cdlatex-texmathp-advice-is-done
  17237. (setq org-cdlatex-texmathp-advice-is-done t)
  17238. (defadvice texmathp (around org-math-always-on activate)
  17239. "Always return t in Org buffers.
  17240. This is because we want to insert math symbols without dollars even outside
  17241. the LaTeX math segments. If Org mode thinks that point is actually inside
  17242. an embedded LaTeX fragment, let `texmathp' do its job.
  17243. `\\[org-cdlatex-mode-map]'"
  17244. (interactive)
  17245. (let (p)
  17246. (cond
  17247. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17248. ((eq this-command 'cdlatex-math-symbol)
  17249. (setq ad-return-value t
  17250. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17251. (t
  17252. (let ((p (org-inside-LaTeX-fragment-p)))
  17253. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17254. (setq ad-return-value t
  17255. texmathp-why '("Org mode embedded math" . 0))
  17256. (when p ad-do-it)))))))))
  17257. (defun turn-on-org-cdlatex ()
  17258. "Unconditionally turn on `org-cdlatex-mode'."
  17259. (org-cdlatex-mode 1))
  17260. (defun org-try-cdlatex-tab ()
  17261. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17262. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17263. - inside a LaTeX fragment, or
  17264. - after the first word in a line, where an abbreviation expansion could
  17265. insert a LaTeX environment."
  17266. (when org-cdlatex-mode
  17267. (cond
  17268. ;; Before any word on the line: No expansion possible.
  17269. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17270. ;; Just after first word on the line: Expand it. Make sure it
  17271. ;; cannot happen on headlines, though.
  17272. ((save-excursion
  17273. (skip-chars-backward "a-zA-Z0-9*")
  17274. (skip-chars-backward " \t")
  17275. (and (bolp) (not (org-at-heading-p))))
  17276. (cdlatex-tab) t)
  17277. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17278. (defun org-cdlatex-underscore-caret (&optional _arg)
  17279. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17280. Revert to the normal definition outside of these fragments."
  17281. (interactive "P")
  17282. (if (org-inside-LaTeX-fragment-p)
  17283. (call-interactively 'cdlatex-sub-superscript)
  17284. (let (org-cdlatex-mode)
  17285. (call-interactively (key-binding (vector last-input-event))))))
  17286. (defun org-cdlatex-math-modify (&optional _arg)
  17287. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17288. Revert to the normal definition outside of these fragments."
  17289. (interactive "P")
  17290. (if (org-inside-LaTeX-fragment-p)
  17291. (call-interactively 'cdlatex-math-modify)
  17292. (let (org-cdlatex-mode)
  17293. (call-interactively (key-binding (vector last-input-event))))))
  17294. (defun org-cdlatex-environment-indent (&optional environment item)
  17295. "Execute `cdlatex-environment' and indent the inserted environment.
  17296. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17297. The inserted environment is indented to current indentation
  17298. unless point is at the beginning of the line, in which the
  17299. environment remains unintended."
  17300. (interactive)
  17301. ;; cdlatex-environment always return nil. Therefore, capture output
  17302. ;; first and determine if an environment was selected.
  17303. (let* ((beg (point-marker))
  17304. (end (copy-marker (point) t))
  17305. (inserted (progn
  17306. (ignore-errors (cdlatex-environment environment item))
  17307. (< beg end)))
  17308. ;; Figure out how many lines to move forward after the
  17309. ;; environment has been inserted.
  17310. (lines (when inserted
  17311. (save-excursion
  17312. (- (cl-loop while (< beg (point))
  17313. with x = 0
  17314. do (forward-line -1)
  17315. (cl-incf x)
  17316. finally return x)
  17317. (if (progn (goto-char beg)
  17318. (and (progn (skip-chars-forward " \t") (eolp))
  17319. (progn (skip-chars-backward " \t") (bolp))))
  17320. 1 0)))))
  17321. (env (org-trim (delete-and-extract-region beg end))))
  17322. (when inserted
  17323. ;; Get indentation of next line unless at column 0.
  17324. (let ((ind (if (bolp) 0
  17325. (save-excursion
  17326. (org-return-indent)
  17327. (prog1 (org-get-indentation)
  17328. (when (progn (skip-chars-forward " \t") (eolp))
  17329. (delete-region beg (point)))))))
  17330. (bol (progn (skip-chars-backward " \t") (bolp))))
  17331. ;; Insert a newline before environment unless at column zero
  17332. ;; to "escape" the current line. Insert a newline if
  17333. ;; something is one the same line as \end{ENVIRONMENT}.
  17334. (insert
  17335. (concat (unless bol "\n") env
  17336. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17337. (unless (zerop ind)
  17338. (save-excursion
  17339. (goto-char beg)
  17340. (while (< (point) end)
  17341. (unless (eolp) (indent-line-to ind))
  17342. (forward-line))))
  17343. (goto-char beg)
  17344. (forward-line lines)
  17345. (indent-line-to ind)))
  17346. (set-marker beg nil)
  17347. (set-marker end nil)))
  17348. ;;;; LaTeX fragments
  17349. (defun org-inside-LaTeX-fragment-p ()
  17350. "Test if point is inside a LaTeX fragment.
  17351. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17352. sequence appearing also before point.
  17353. Even though the matchers for math are configurable, this function assumes
  17354. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17355. delimiters are skipped when they have been removed by customization.
  17356. The return value is nil, or a cons cell with the delimiter and the
  17357. position of this delimiter.
  17358. This function does a reasonably good job, but can locally be fooled by
  17359. for example currency specifications. For example it will assume being in
  17360. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17361. fragments that are properly closed, but during editing, we have to live
  17362. with the uncertainty caused by missing closing delimiters. This function
  17363. looks only before point, not after."
  17364. (catch 'exit
  17365. (let ((pos (point))
  17366. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17367. (lim (save-excursion (org-backward-paragraph) (point)))
  17368. dd-on str (start 0) m re)
  17369. (goto-char pos)
  17370. (when dodollar
  17371. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17372. re (nth 1 (assoc "$" org-latex-regexps)))
  17373. (while (string-match re str start)
  17374. (cond
  17375. ((= (match-end 0) (length str))
  17376. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17377. ((= (match-end 0) (- (length str) 5))
  17378. (throw 'exit nil))
  17379. (t (setq start (match-end 0))))))
  17380. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17381. (goto-char pos)
  17382. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17383. (and (match-beginning 2) (throw 'exit nil))
  17384. ;; count $$
  17385. (while (re-search-backward "\\$\\$" lim t)
  17386. (setq dd-on (not dd-on)))
  17387. (goto-char pos)
  17388. (when dd-on (cons "$$" m))))))
  17389. (defun org-inside-latex-macro-p ()
  17390. "Is point inside a LaTeX macro or its arguments?"
  17391. (save-match-data
  17392. (org-in-regexp
  17393. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17394. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17395. "Build an overlay between BEG and END using IMAGE file.
  17396. Argument IMAGETYPE is the extension of the displayed image,
  17397. as a string. It defaults to \"png\"."
  17398. (let ((ov (make-overlay beg end))
  17399. (imagetype (or (intern imagetype) 'png)))
  17400. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17401. (overlay-put ov 'evaporate t)
  17402. (overlay-put ov
  17403. 'modification-hooks
  17404. (list (lambda (o _flag _beg _end &optional _l)
  17405. (delete-overlay o))))
  17406. (overlay-put ov
  17407. 'display
  17408. (list 'image :type imagetype :file image :ascent 'center))))
  17409. (defun org--list-latex-overlays (&optional beg end)
  17410. "List all Org LaTeX overlays in current buffer.
  17411. Limit to overlays between BEG and END when those are provided."
  17412. (cl-remove-if-not
  17413. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17414. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17415. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17416. "Remove all overlays with LaTeX fragment images in current buffer.
  17417. When optional arguments BEG and END are non-nil, remove all
  17418. overlays between them instead. Return a non-nil value when some
  17419. overlays were removed, nil otherwise."
  17420. (let ((overlays (org--list-latex-overlays beg end)))
  17421. (mapc #'delete-overlay overlays)
  17422. overlays))
  17423. (defun org-toggle-latex-fragment (&optional arg)
  17424. "Preview the LaTeX fragment at point, or all locally or globally.
  17425. If the cursor is on a LaTeX fragment, create the image and overlay
  17426. it over the source code, if there is none. Remove it otherwise.
  17427. If there is no fragment at point, display all fragments in the
  17428. current section.
  17429. With prefix ARG, preview or clear image for all fragments in the
  17430. current subtree or in the whole buffer when used before the first
  17431. headline. With a prefix ARG `\\[universal-argument] \
  17432. \\[universal-argument]' preview or clear images
  17433. for all fragments in the buffer."
  17434. (interactive "P")
  17435. (when (display-graphic-p)
  17436. (catch 'exit
  17437. (save-excursion
  17438. (let (beg end msg)
  17439. (cond
  17440. ((or (equal arg '(16))
  17441. (and (equal arg '(4))
  17442. (org-with-limited-levels (org-before-first-heading-p))))
  17443. (if (org-remove-latex-fragment-image-overlays)
  17444. (progn (message "LaTeX fragments images removed from buffer")
  17445. (throw 'exit nil))
  17446. (setq msg "Creating images for buffer...")))
  17447. ((equal arg '(4))
  17448. (org-with-limited-levels (org-back-to-heading t))
  17449. (setq beg (point))
  17450. (setq end (progn (org-end-of-subtree t) (point)))
  17451. (if (org-remove-latex-fragment-image-overlays beg end)
  17452. (progn
  17453. (message "LaTeX fragment images removed from subtree")
  17454. (throw 'exit nil))
  17455. (setq msg "Creating images for subtree...")))
  17456. ((let ((datum (org-element-context)))
  17457. (when (memq (org-element-type datum)
  17458. '(latex-environment latex-fragment))
  17459. (setq beg (org-element-property :begin datum))
  17460. (setq end (org-element-property :end datum))
  17461. (if (org-remove-latex-fragment-image-overlays beg end)
  17462. (progn (message "LaTeX fragment image removed")
  17463. (throw 'exit nil))
  17464. (setq msg "Creating image...")))))
  17465. (t
  17466. (org-with-limited-levels
  17467. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17468. (outline-previous-heading)
  17469. (point)))
  17470. (setq end (progn (outline-next-heading) (point)))
  17471. (if (org-remove-latex-fragment-image-overlays beg end)
  17472. (progn
  17473. (message "LaTeX fragment images removed from section")
  17474. (throw 'exit nil))
  17475. (setq msg "Creating images for section...")))))
  17476. (let ((file (buffer-file-name (buffer-base-buffer))))
  17477. (org-format-latex
  17478. (concat org-preview-latex-image-directory "org-ltximg")
  17479. beg end
  17480. ;; Emacs cannot overlay images from remote hosts. Create
  17481. ;; it in `temporary-file-directory' instead.
  17482. (if (or (not file) (file-remote-p file))
  17483. temporary-file-directory
  17484. default-directory)
  17485. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17486. (message (concat msg "done")))))))
  17487. (defun org-format-latex
  17488. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17489. "Replace LaTeX fragments with links to an image.
  17490. The function takes care of creating the replacement image.
  17491. Only consider fragments between BEG and END when those are
  17492. provided.
  17493. When optional argument OVERLAYS is non-nil, display the image on
  17494. top of the fragment instead of replacing it.
  17495. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17496. Some of the options can be changed using the variable
  17497. `org-format-latex-options', which see."
  17498. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17499. (unless (eq processing-type 'verbatim)
  17500. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17501. (cnt 0)
  17502. checkdir-flag)
  17503. (goto-char (or beg (point-min)))
  17504. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17505. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17506. (overlay-recenter (or end (point-max))))
  17507. (while (re-search-forward math-regexp end t)
  17508. (unless (and overlays
  17509. (eq (get-char-property (point) 'org-overlay-type)
  17510. 'org-latex-overlay))
  17511. (let* ((context (org-element-context))
  17512. (type (org-element-type context)))
  17513. (when (memq type '(latex-environment latex-fragment))
  17514. (let ((block-type (eq type 'latex-environment))
  17515. (value (org-element-property :value context))
  17516. (beg (org-element-property :begin context))
  17517. (end (save-excursion
  17518. (goto-char (org-element-property :end context))
  17519. (skip-chars-backward " \r\t\n")
  17520. (point))))
  17521. (cond
  17522. ((eq processing-type 'mathjax)
  17523. ;; Prepare for MathJax processing.
  17524. (if (not (string-match "\\`\\$\\$?" value))
  17525. (goto-char end)
  17526. (delete-region beg end)
  17527. (if (string= (match-string 0 value) "$$")
  17528. (insert "\\[" (substring value 2 -2) "\\]")
  17529. (insert "\\(" (substring value 1 -1) "\\)"))))
  17530. ((assq processing-type org-preview-latex-process-alist)
  17531. ;; Process to an image.
  17532. (cl-incf cnt)
  17533. (goto-char beg)
  17534. (let* ((processing-info
  17535. (cdr (assq processing-type org-preview-latex-process-alist)))
  17536. (face (face-at-point))
  17537. ;; Get the colors from the face at point.
  17538. (fg
  17539. (let ((color (plist-get org-format-latex-options
  17540. :foreground)))
  17541. (if (and forbuffer (eq color 'auto))
  17542. (face-attribute face :foreground nil 'default)
  17543. color)))
  17544. (bg
  17545. (let ((color (plist-get org-format-latex-options
  17546. :background)))
  17547. (if (and forbuffer (eq color 'auto))
  17548. (face-attribute face :background nil 'default)
  17549. color)))
  17550. (hash (sha1 (prin1-to-string
  17551. (list org-format-latex-header
  17552. org-latex-default-packages-alist
  17553. org-latex-packages-alist
  17554. org-format-latex-options
  17555. forbuffer value fg bg))))
  17556. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17557. (absprefix (expand-file-name prefix dir))
  17558. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17559. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17560. (sep (and block-type "\n\n"))
  17561. (link (concat sep "[[file:" linkfile "]]" sep))
  17562. (options
  17563. (org-combine-plists
  17564. org-format-latex-options
  17565. `(:foreground ,fg :background ,bg))))
  17566. (when msg (message msg cnt))
  17567. (unless checkdir-flag ; Ensure the directory exists.
  17568. (setq checkdir-flag t)
  17569. (let ((todir (file-name-directory absprefix)))
  17570. (unless (file-directory-p todir)
  17571. (make-directory todir t))))
  17572. (unless (file-exists-p movefile)
  17573. (org-create-formula-image
  17574. value movefile options forbuffer processing-type))
  17575. (if overlays
  17576. (progn
  17577. (dolist (o (overlays-in beg end))
  17578. (when (eq (overlay-get o 'org-overlay-type)
  17579. 'org-latex-overlay)
  17580. (delete-overlay o)))
  17581. (org--format-latex-make-overlay beg end movefile imagetype)
  17582. (goto-char end))
  17583. (delete-region beg end)
  17584. (insert
  17585. (org-add-props link
  17586. (list 'org-latex-src
  17587. (replace-regexp-in-string "\"" "" value)
  17588. 'org-latex-src-embed-type
  17589. (if block-type 'paragraph 'character)))))))
  17590. ((eq processing-type 'mathml)
  17591. ;; Process to MathML.
  17592. (unless (org-format-latex-mathml-available-p)
  17593. (user-error "LaTeX to MathML converter not configured"))
  17594. (cl-incf cnt)
  17595. (when msg (message msg cnt))
  17596. (goto-char beg)
  17597. (delete-region beg end)
  17598. (insert (org-format-latex-as-mathml
  17599. value block-type prefix dir)))
  17600. (t
  17601. (error "Unknown conversion process %s for LaTeX fragments"
  17602. processing-type)))))))))))
  17603. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17604. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17605. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17606. sucessful, return the portion between \"<math...> </math>\"
  17607. elements otherwise return nil. When MATHML-FILE is specified,
  17608. write the results in to that file. When invoked as an
  17609. interactive command, prompt for LATEX-FRAG, with initial value
  17610. set to the current active region and echo the results for user
  17611. inspection."
  17612. (interactive (list (let ((frag (when (org-region-active-p)
  17613. (buffer-substring-no-properties
  17614. (region-beginning) (region-end)))))
  17615. (read-string "LaTeX Fragment: " frag nil frag))))
  17616. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17617. (let* ((tmp-in-file
  17618. (let ((file (file-relative-name
  17619. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17620. (write-region latex-frag nil file)
  17621. file))
  17622. (tmp-out-file (file-relative-name
  17623. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17624. (cmd (format-spec
  17625. org-latex-to-mathml-convert-command
  17626. `((?j . ,(and org-latex-to-mathml-jar-file
  17627. (shell-quote-argument
  17628. (expand-file-name
  17629. org-latex-to-mathml-jar-file))))
  17630. (?I . ,(shell-quote-argument tmp-in-file))
  17631. (?i . ,latex-frag)
  17632. (?o . ,(shell-quote-argument tmp-out-file)))))
  17633. mathml shell-command-output)
  17634. (when (called-interactively-p 'any)
  17635. (unless (org-format-latex-mathml-available-p)
  17636. (user-error "LaTeX to MathML converter not configured")))
  17637. (message "Running %s" cmd)
  17638. (setq shell-command-output (shell-command-to-string cmd))
  17639. (setq mathml
  17640. (when (file-readable-p tmp-out-file)
  17641. (with-current-buffer (find-file-noselect tmp-out-file t)
  17642. (goto-char (point-min))
  17643. (when (re-search-forward
  17644. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17645. (regexp-quote
  17646. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17647. nil t)
  17648. (prog1 (match-string 0) (kill-buffer))))))
  17649. (cond
  17650. (mathml
  17651. (setq mathml
  17652. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17653. (when mathml-file
  17654. (write-region mathml nil mathml-file))
  17655. (when (called-interactively-p 'any)
  17656. (message mathml)))
  17657. ((message "LaTeX to MathML conversion failed")
  17658. (message shell-command-output)))
  17659. (delete-file tmp-in-file)
  17660. (when (file-exists-p tmp-out-file)
  17661. (delete-file tmp-out-file))
  17662. mathml))
  17663. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17664. prefix &optional dir)
  17665. "Use `org-create-math-formula' but check local cache first."
  17666. (let* ((absprefix (expand-file-name prefix dir))
  17667. (print-length nil) (print-level nil)
  17668. (formula-id (concat
  17669. "formula-"
  17670. (sha1
  17671. (prin1-to-string
  17672. (list latex-frag
  17673. org-latex-to-mathml-convert-command)))))
  17674. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17675. (formula-cache-dir (file-name-directory formula-cache)))
  17676. (unless (file-directory-p formula-cache-dir)
  17677. (make-directory formula-cache-dir t))
  17678. (unless (file-exists-p formula-cache)
  17679. (org-create-math-formula latex-frag formula-cache))
  17680. (if (file-exists-p formula-cache)
  17681. ;; Successful conversion. Return the link to MathML file.
  17682. (org-add-props
  17683. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17684. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17685. 'org-latex-src-embed-type (if latex-frag-type
  17686. 'paragraph 'character)))
  17687. ;; Failed conversion. Return the LaTeX fragment verbatim
  17688. latex-frag)))
  17689. (defun org--get-display-dpi ()
  17690. "Get the DPI of the display.
  17691. The function assumes that the display has the same pixel width in
  17692. the horizontal and vertical directions."
  17693. (if (display-graphic-p)
  17694. (round (/ (display-pixel-height)
  17695. (/ (display-mm-height) 25.4)))
  17696. (error "Attempt to calculate the dpi of a non-graphic display")))
  17697. (defun org-create-formula-image
  17698. (string tofile options buffer &optional processing-type)
  17699. "Create an image from LaTeX source using external processes.
  17700. The LaTeX STRING is saved to a temporary LaTeX file, then
  17701. converted to an image file by process PROCESSING-TYPE defined in
  17702. `org-preview-latex-process-alist'. A nil value defaults to
  17703. `org-preview-latex-default-process'.
  17704. The generated image file is eventually moved to TOFILE.
  17705. The OPTIONS argument controls the size, foreground color and
  17706. background color of the generated image.
  17707. When BUFFER non-nil, this function is used for LaTeX previewing.
  17708. Otherwise, it is used to deal with LaTeX snippets showed in
  17709. a HTML file."
  17710. (let* ((processing-type (or processing-type
  17711. org-preview-latex-default-process))
  17712. (processing-info
  17713. (cdr (assq processing-type org-preview-latex-process-alist)))
  17714. (programs (plist-get processing-info :programs))
  17715. (error-message (or (plist-get processing-info :message) ""))
  17716. (use-xcolor (plist-get processing-info :use-xcolor))
  17717. (image-input-type (plist-get processing-info :image-input-type))
  17718. (image-output-type (plist-get processing-info :image-output-type))
  17719. (post-clean (or (plist-get processing-info :post-clean)
  17720. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17721. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17722. (latex-header
  17723. (or (plist-get processing-info :latex-header)
  17724. (org-latex-make-preamble
  17725. (org-export-get-environment (org-export-get-backend 'latex))
  17726. org-format-latex-header
  17727. 'snippet)))
  17728. (latex-compiler (plist-get processing-info :latex-compiler))
  17729. (image-converter (plist-get processing-info :image-converter))
  17730. (tmpdir temporary-file-directory)
  17731. (texfilebase (make-temp-name
  17732. (expand-file-name "orgtex" tmpdir)))
  17733. (texfile (concat texfilebase ".tex"))
  17734. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17735. '(1.0 . 1.0)))
  17736. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17737. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17738. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17739. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17740. "Black"))
  17741. (bg (or (plist-get options (if buffer :background :html-background))
  17742. "Transparent"))
  17743. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17744. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17745. (dolist (program programs)
  17746. (org-check-external-command program error-message))
  17747. (if use-xcolor
  17748. (progn (if (eq fg 'default)
  17749. (setq fg (org-latex-color :foreground))
  17750. (setq fg (org-latex-color-format fg)))
  17751. (if (eq bg 'default)
  17752. (setq bg (org-latex-color :background))
  17753. (setq bg (org-latex-color-format
  17754. (if (string= bg "Transparent") "white" bg))))
  17755. (with-temp-file texfile
  17756. (insert latex-header)
  17757. (insert "\n\\begin{document}\n"
  17758. "\\definecolor{fg}{rgb}{" fg "}\n"
  17759. "\\definecolor{bg}{rgb}{" bg "}\n"
  17760. "\n\\pagecolor{bg}\n"
  17761. "\n{\\color{fg}\n"
  17762. string
  17763. "\n}\n"
  17764. "\n\\end{document}\n")))
  17765. (if (eq fg 'default)
  17766. (setq fg (org-dvipng-color :foreground))
  17767. (unless (string= fg "Transparent")
  17768. (setq fg (org-dvipng-color-format fg))))
  17769. (if (eq bg 'default)
  17770. (setq bg (org-dvipng-color :background))
  17771. (unless (string= bg "Transparent")
  17772. (setq bg (org-dvipng-color-format bg))))
  17773. (with-temp-file texfile
  17774. (insert latex-header)
  17775. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17776. (let* ((err-msg (format "Please adjust '%s' part of \
  17777. `org-preview-latex-process-alist'."
  17778. processing-type))
  17779. (image-input-file
  17780. (org-compile-file
  17781. texfile latex-compiler image-input-type err-msg log-buf))
  17782. (image-output-file
  17783. (org-compile-file
  17784. image-input-file image-converter image-output-type err-msg log-buf
  17785. `((?F . ,(shell-quote-argument fg))
  17786. (?B . ,(shell-quote-argument bg))
  17787. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17788. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17789. (copy-file image-output-file tofile 'replace)
  17790. (dolist (e post-clean)
  17791. (when (file-exists-p (concat texfilebase e))
  17792. (delete-file (concat texfilebase e))))
  17793. image-output-file)))
  17794. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17795. "Fill a LaTeX header template TPL.
  17796. In the template, the following place holders will be recognized:
  17797. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17798. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17799. [PACKAGES] \\usepackage statements for PKG
  17800. [NO-PACKAGES] do not include PKG
  17801. [EXTRA] the string EXTRA
  17802. [NO-EXTRA] do not include EXTRA
  17803. For backward compatibility, if both the positive and the negative place
  17804. holder is missing, the positive one (without the \"NO-\") will be
  17805. assumed to be present at the end of the template.
  17806. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17807. EXTRA is a string.
  17808. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17809. (let (rpl (end ""))
  17810. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17811. (setq rpl (if (or (match-end 1) (not def-pkg))
  17812. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17813. tpl (replace-match rpl t t tpl))
  17814. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17815. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17816. (setq rpl (if (or (match-end 1) (not pkg))
  17817. "" (org-latex-packages-to-string pkg snippets-p t))
  17818. tpl (replace-match rpl t t tpl))
  17819. (when pkg (setq end
  17820. (concat end "\n"
  17821. (org-latex-packages-to-string pkg snippets-p)))))
  17822. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17823. (setq rpl (if (or (match-end 1) (not extra))
  17824. "" (concat extra "\n"))
  17825. tpl (replace-match rpl t t tpl))
  17826. (when (and extra (string-match "\\S-" extra))
  17827. (setq end (concat end "\n" extra))))
  17828. (if (string-match "\\S-" end)
  17829. (concat tpl "\n" end)
  17830. tpl)))
  17831. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17832. "Turn an alist of packages into a string with the \\usepackage macros."
  17833. (setq pkg (mapconcat (lambda(p)
  17834. (cond
  17835. ((stringp p) p)
  17836. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17837. (format "%% Package %s omitted" (cadr p)))
  17838. ((equal "" (car p))
  17839. (format "\\usepackage{%s}" (cadr p)))
  17840. (t
  17841. (format "\\usepackage[%s]{%s}"
  17842. (car p) (cadr p)))))
  17843. pkg
  17844. "\n"))
  17845. (if newline (concat pkg "\n") pkg))
  17846. (defun org-dvipng-color (attr)
  17847. "Return a RGB color specification for dvipng."
  17848. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17849. (defun org-dvipng-color-format (color-name)
  17850. "Convert COLOR-NAME to a RGB color value for dvipng."
  17851. (apply #'format "rgb %s %s %s"
  17852. (mapcar 'org-normalize-color
  17853. (color-values color-name))))
  17854. (defun org-latex-color (attr)
  17855. "Return a RGB color for the LaTeX color package."
  17856. (org-latex-color-format (face-attribute 'default attr nil)))
  17857. (defun org-latex-color-format (color-name)
  17858. "Convert COLOR-NAME to a RGB color value."
  17859. (apply #'format "%s,%s,%s"
  17860. (mapcar 'org-normalize-color
  17861. (color-values color-name))))
  17862. (defun org-normalize-color (value)
  17863. "Return string to be used as color value for an RGB component."
  17864. (format "%g" (/ value 65535.0)))
  17865. ;; Image display
  17866. (defvar-local org-inline-image-overlays nil)
  17867. (defun org-toggle-inline-images (&optional include-linked)
  17868. "Toggle the display of inline images.
  17869. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17870. (interactive "P")
  17871. (if org-inline-image-overlays
  17872. (progn
  17873. (org-remove-inline-images)
  17874. (when (called-interactively-p 'interactive)
  17875. (message "Inline image display turned off")))
  17876. (org-display-inline-images include-linked)
  17877. (when (called-interactively-p 'interactive)
  17878. (message (if org-inline-image-overlays
  17879. (format "%d images displayed inline"
  17880. (length org-inline-image-overlays))
  17881. "No images to display inline")))))
  17882. (defun org-redisplay-inline-images ()
  17883. "Refresh the display of inline images."
  17884. (interactive)
  17885. (if (not org-inline-image-overlays)
  17886. (org-toggle-inline-images)
  17887. (org-toggle-inline-images)
  17888. (org-toggle-inline-images)))
  17889. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17890. "Display inline images.
  17891. An inline image is a link which follows either of these
  17892. conventions:
  17893. 1. Its path is a file with an extension matching return value
  17894. from `image-file-name-regexp' and it has no contents.
  17895. 2. Its description consists in a single link of the previous
  17896. type.
  17897. When optional argument INCLUDE-LINKED is non-nil, also links with
  17898. a text description part will be inlined. This can be nice for
  17899. a quick look at those images, but it does not reflect what
  17900. exported files will look like.
  17901. When optional argument REFRESH is non-nil, refresh existing
  17902. images between BEG and END. This will create new image displays
  17903. only if necessary. BEG and END default to the buffer
  17904. boundaries."
  17905. (interactive "P")
  17906. (when (display-graphic-p)
  17907. (unless refresh
  17908. (org-remove-inline-images)
  17909. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17910. (org-with-wide-buffer
  17911. (goto-char (or beg (point-min)))
  17912. (let ((case-fold-search t)
  17913. (file-extension-re (image-file-name-regexp)))
  17914. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17915. (let ((link (save-match-data (org-element-context))))
  17916. ;; Check if we're at an inline image.
  17917. (when (and (equal (org-element-property :type link) "file")
  17918. (or include-linked
  17919. (not (org-element-property :contents-begin link)))
  17920. (let ((parent (org-element-property :parent link)))
  17921. (or (not (eq (org-element-type parent) 'link))
  17922. (not (cdr (org-element-contents parent)))))
  17923. (string-match-p file-extension-re
  17924. (org-element-property :path link)))
  17925. (let ((file (expand-file-name
  17926. (org-link-unescape
  17927. (org-element-property :path link)))))
  17928. (when (file-exists-p file)
  17929. (let ((width
  17930. ;; Apply `org-image-actual-width' specifications.
  17931. (cond
  17932. ((not (image-type-available-p 'imagemagick)) nil)
  17933. ((eq org-image-actual-width t) nil)
  17934. ((listp org-image-actual-width)
  17935. (or
  17936. ;; First try to find a width among
  17937. ;; attributes associated to the paragraph
  17938. ;; containing link.
  17939. (let ((paragraph
  17940. (let ((e link))
  17941. (while (and (setq e (org-element-property
  17942. :parent e))
  17943. (not (eq (org-element-type e)
  17944. 'paragraph))))
  17945. e)))
  17946. (when paragraph
  17947. (save-excursion
  17948. (goto-char (org-element-property :begin paragraph))
  17949. (when
  17950. (re-search-forward
  17951. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17952. (org-element-property
  17953. :post-affiliated paragraph)
  17954. t)
  17955. (string-to-number (match-string 1))))))
  17956. ;; Otherwise, fall-back to provided number.
  17957. (car org-image-actual-width)))
  17958. ((numberp org-image-actual-width)
  17959. org-image-actual-width)))
  17960. (old (get-char-property-and-overlay
  17961. (org-element-property :begin link)
  17962. 'org-image-overlay)))
  17963. (if (and (car-safe old) refresh)
  17964. (image-refresh (overlay-get (cdr old) 'display))
  17965. (let ((image (create-image file
  17966. (and width 'imagemagick)
  17967. nil
  17968. :width width)))
  17969. (when image
  17970. (let* ((link
  17971. ;; If inline image is the description
  17972. ;; of another link, be sure to
  17973. ;; consider the latter as the one to
  17974. ;; apply the overlay on.
  17975. (let ((parent
  17976. (org-element-property :parent link)))
  17977. (if (eq (org-element-type parent) 'link)
  17978. parent
  17979. link)))
  17980. (ov (make-overlay
  17981. (org-element-property :begin link)
  17982. (progn
  17983. (goto-char
  17984. (org-element-property :end link))
  17985. (skip-chars-backward " \t")
  17986. (point)))))
  17987. (overlay-put ov 'display image)
  17988. (overlay-put ov 'face 'default)
  17989. (overlay-put ov 'org-image-overlay t)
  17990. (overlay-put
  17991. ov 'modification-hooks
  17992. (list 'org-display-inline-remove-overlay))
  17993. (push ov org-inline-image-overlays)))))))))))))))
  17994. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17995. "Remove inline-display overlay if a corresponding region is modified."
  17996. (let ((inhibit-modification-hooks t))
  17997. (when (and ov after)
  17998. (delete ov org-inline-image-overlays)
  17999. (delete-overlay ov))))
  18000. (defun org-remove-inline-images ()
  18001. "Remove inline display of images."
  18002. (interactive)
  18003. (mapc #'delete-overlay org-inline-image-overlays)
  18004. (setq org-inline-image-overlays nil))
  18005. ;;;; Key bindings
  18006. ;; Outline functions from `outline-mode-prefix-map'
  18007. ;; that can be remapped in Org:
  18008. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18009. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18010. (define-key org-mode-map [remap outline-forward-same-level]
  18011. 'org-forward-heading-same-level)
  18012. (define-key org-mode-map [remap outline-backward-same-level]
  18013. 'org-backward-heading-same-level)
  18014. (define-key org-mode-map [remap outline-show-branches]
  18015. 'org-kill-note-or-show-branches)
  18016. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18017. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18018. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18019. (define-key org-mode-map [remap outline-next-visible-heading]
  18020. 'org-next-visible-heading)
  18021. (define-key org-mode-map [remap outline-previous-visible-heading]
  18022. 'org-previous-visible-heading)
  18023. (define-key org-mode-map [remap show-children] 'org-show-children)
  18024. ;; Outline functions from `outline-mode-prefix-map' that can not
  18025. ;; be remapped in Org:
  18026. ;; - the column "key binding" shows whether the Outline function is still
  18027. ;; available in Org mode on the same key that it has been bound to in
  18028. ;; Outline mode:
  18029. ;; - "overridden": key used for a different functionality in Org mode
  18030. ;; - else: key still bound to the same Outline function in Org mode
  18031. ;; | Outline function | key binding | Org replacement |
  18032. ;; |------------------------------------+-------------+--------------------------|
  18033. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18034. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18035. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18036. ;; | `show-entry' | overridden | no replacement |
  18037. ;; | `show-branches' | `C-c C-k' | still same function |
  18038. ;; | `show-subtree' | overridden | visibility cycling |
  18039. ;; | `show-all' | overridden | no replacement |
  18040. ;; | `hide-subtree' | overridden | visibility cycling |
  18041. ;; | `hide-body' | overridden | no replacement |
  18042. ;; | `hide-entry' | overridden | visibility cycling |
  18043. ;; | `hide-leaves' | overridden | no replacement |
  18044. ;; | `hide-sublevels' | overridden | no replacement |
  18045. ;; | `hide-other' | overridden | no replacement |
  18046. ;; Make `C-c C-x' a prefix key
  18047. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18048. ;; TAB key with modifiers
  18049. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18050. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18051. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18052. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18053. ;; The following line is necessary under Suse GNU/Linux
  18054. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18055. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18056. (define-key org-mode-map [backtab] 'org-shifttab)
  18057. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18058. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18059. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18060. ;; Cursor keys with modifiers
  18061. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18062. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18063. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18064. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18065. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18066. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18067. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18068. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18069. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18070. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18071. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18072. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18073. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18074. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18075. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18076. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18077. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18078. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18079. ;; Babel keys
  18080. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18081. (dolist (pair org-babel-key-bindings)
  18082. (define-key org-babel-map (car pair) (cdr pair)))
  18083. ;;; Extra keys for tty access.
  18084. ;; We only set them when really needed because otherwise the
  18085. ;; menus don't show the simple keys
  18086. (when (or org-use-extra-keys (not window-system))
  18087. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18088. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18089. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18090. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18091. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18092. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18093. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18094. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18095. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18096. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18097. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18098. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18099. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18100. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18101. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18102. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18103. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18104. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18105. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18106. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18107. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18108. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18109. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18110. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18111. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18112. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18113. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18114. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18115. ;; All the other keys
  18116. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18117. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18118. (if (boundp 'narrow-map)
  18119. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18120. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18121. (if (boundp 'narrow-map)
  18122. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18123. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18124. (if (boundp 'narrow-map)
  18125. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18126. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18127. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18128. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18129. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18130. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18131. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18132. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18133. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18134. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18135. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18136. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18137. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18138. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18139. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18140. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18141. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18142. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18143. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18144. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18145. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18146. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18147. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18148. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18149. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18150. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18151. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18152. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18153. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18154. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18155. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18156. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18157. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18158. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18159. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18160. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18161. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18162. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18163. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18164. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18165. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18166. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18167. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18168. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18169. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18170. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18171. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18172. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18173. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18174. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18175. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18176. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18177. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18178. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18179. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18180. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18181. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18182. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18183. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18184. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18185. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18186. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18187. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18188. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18189. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18190. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18191. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18192. (org-defkey org-mode-map "\C-m" 'org-return)
  18193. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18194. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18195. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18196. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18197. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18198. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18199. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18200. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18201. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18202. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18203. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18204. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18205. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18206. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18207. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18208. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18209. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18210. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18211. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18212. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18213. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18214. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18215. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18216. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18217. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18218. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18219. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18220. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18221. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18222. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18223. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18224. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18225. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18226. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18227. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18228. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18229. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18230. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18231. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18232. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18233. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18234. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18235. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18236. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18237. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18238. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18239. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18240. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18241. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18242. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18243. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18244. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18245. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18246. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18247. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18248. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18249. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18250. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18251. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18252. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18253. (defconst org-speed-commands-default
  18254. '(
  18255. ("Outline Navigation")
  18256. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18257. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18258. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18259. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18260. ("F" . org-next-block)
  18261. ("B" . org-previous-block)
  18262. ("u" . (org-speed-move-safe 'outline-up-heading))
  18263. ("j" . org-goto)
  18264. ("g" . (org-refile t))
  18265. ("Outline Visibility")
  18266. ("c" . org-cycle)
  18267. ("C" . org-shifttab)
  18268. (" " . org-display-outline-path)
  18269. ("s" . org-narrow-to-subtree)
  18270. ("=" . org-columns)
  18271. ("Outline Structure Editing")
  18272. ("U" . org-metaup)
  18273. ("D" . org-metadown)
  18274. ("r" . org-metaright)
  18275. ("l" . org-metaleft)
  18276. ("R" . org-shiftmetaright)
  18277. ("L" . org-shiftmetaleft)
  18278. ("i" . (progn (forward-char 1) (call-interactively
  18279. 'org-insert-heading-respect-content)))
  18280. ("^" . org-sort)
  18281. ("w" . org-refile)
  18282. ("a" . org-archive-subtree-default-with-confirmation)
  18283. ("@" . org-mark-subtree)
  18284. ("#" . org-toggle-comment)
  18285. ("Clock Commands")
  18286. ("I" . org-clock-in)
  18287. ("O" . org-clock-out)
  18288. ("Meta Data Editing")
  18289. ("t" . org-todo)
  18290. ("," . (org-priority))
  18291. ("0" . (org-priority ?\ ))
  18292. ("1" . (org-priority ?A))
  18293. ("2" . (org-priority ?B))
  18294. ("3" . (org-priority ?C))
  18295. (":" . org-set-tags-command)
  18296. ("e" . org-set-effort)
  18297. ("E" . org-inc-effort)
  18298. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18299. (org-entry-put (point) "APPT_WARNTIME" m)))
  18300. ("Agenda Views etc")
  18301. ("v" . org-agenda)
  18302. ("/" . org-sparse-tree)
  18303. ("Misc")
  18304. ("o" . org-open-at-point)
  18305. ("?" . org-speed-command-help)
  18306. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18307. (">" . (org-agenda-remove-restriction-lock))
  18308. )
  18309. "The default speed commands.")
  18310. (defun org-print-speed-command (e)
  18311. (if (> (length (car e)) 1)
  18312. (progn
  18313. (princ "\n")
  18314. (princ (car e))
  18315. (princ "\n")
  18316. (princ (make-string (length (car e)) ?-))
  18317. (princ "\n"))
  18318. (princ (car e))
  18319. (princ " ")
  18320. (if (symbolp (cdr e))
  18321. (princ (symbol-name (cdr e)))
  18322. (prin1 (cdr e)))
  18323. (princ "\n")))
  18324. (defun org-speed-command-help ()
  18325. "Show the available speed commands."
  18326. (interactive)
  18327. (if (not org-use-speed-commands)
  18328. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18329. (with-output-to-temp-buffer "*Help*"
  18330. (princ "User-defined Speed commands\n===========================\n")
  18331. (mapc #'org-print-speed-command org-speed-commands-user)
  18332. (princ "\n")
  18333. (princ "Built-in Speed commands\n=======================\n")
  18334. (mapc #'org-print-speed-command org-speed-commands-default))
  18335. (with-current-buffer "*Help*"
  18336. (setq truncate-lines t))))
  18337. (defun org-speed-move-safe (cmd)
  18338. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18339. If not, return to the original position and throw an error."
  18340. (interactive)
  18341. (let ((pos (point)))
  18342. (call-interactively cmd)
  18343. (unless (and (bolp) (org-at-heading-p))
  18344. (goto-char pos)
  18345. (error "Boundary reached while executing %s" cmd))))
  18346. (defvar org-self-insert-command-undo-counter 0)
  18347. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18348. (defvar org-speed-command nil)
  18349. (defun org-speed-command-activate (keys)
  18350. "Hook for activating single-letter speed commands.
  18351. `org-speed-commands-default' specifies a minimal command set.
  18352. Use `org-speed-commands-user' for further customization."
  18353. (when (or (and (bolp) (looking-at org-outline-regexp))
  18354. (and (functionp org-use-speed-commands)
  18355. (funcall org-use-speed-commands)))
  18356. (cdr (assoc keys (append org-speed-commands-user
  18357. org-speed-commands-default)))))
  18358. (defun org-babel-speed-command-activate (keys)
  18359. "Hook for activating single-letter code block commands."
  18360. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18361. (cdr (assoc keys org-babel-key-bindings))))
  18362. (defcustom org-speed-command-hook
  18363. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18364. "Hook for activating speed commands at strategic locations.
  18365. Hook functions are called in sequence until a valid handler is
  18366. found.
  18367. Each hook takes a single argument, a user-pressed command key
  18368. which is also a `self-insert-command' from the global map.
  18369. Within the hook, examine the cursor position and the command key
  18370. and return nil or a valid handler as appropriate. Handler could
  18371. be one of an interactive command, a function, or a form.
  18372. Set `org-use-speed-commands' to non-nil value to enable this
  18373. hook. The default setting is `org-speed-command-activate'."
  18374. :group 'org-structure
  18375. :version "24.1"
  18376. :type 'hook)
  18377. (defun org-self-insert-command (N)
  18378. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18379. If the cursor is in a table looking at whitespace, the whitespace is
  18380. overwritten, and the table is not marked as requiring realignment."
  18381. (interactive "p")
  18382. (org-check-before-invisible-edit 'insert)
  18383. (cond
  18384. ((and org-use-speed-commands
  18385. (let ((kv (this-command-keys-vector)))
  18386. (setq org-speed-command
  18387. (run-hook-with-args-until-success
  18388. 'org-speed-command-hook
  18389. (make-string 1 (aref kv (1- (length kv))))))))
  18390. (cond
  18391. ((commandp org-speed-command)
  18392. (setq this-command org-speed-command)
  18393. (call-interactively org-speed-command))
  18394. ((functionp org-speed-command)
  18395. (funcall org-speed-command))
  18396. ((and org-speed-command (listp org-speed-command))
  18397. (eval org-speed-command))
  18398. (t (let (org-use-speed-commands)
  18399. (call-interactively 'org-self-insert-command)))))
  18400. ((and
  18401. (org-at-table-p)
  18402. (progn
  18403. ;; Check if we blank the field, and if that triggers align.
  18404. (and (featurep 'org-table) org-table-auto-blank-field
  18405. (memq last-command
  18406. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18407. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18408. ;; Got extra space, this field does not determine
  18409. ;; column width.
  18410. (let (org-table-may-need-update) (org-table-blank-field))
  18411. ;; No extra space, this field may determine column
  18412. ;; width.
  18413. (org-table-blank-field)))
  18414. t)
  18415. (eq N 1)
  18416. (looking-at "[^|\n]* \\( \\)|"))
  18417. ;; There is room for insertion without re-aligning the table.
  18418. (delete-region (match-beginning 1) (match-end 1))
  18419. (self-insert-command N))
  18420. (t
  18421. (setq org-table-may-need-update t)
  18422. (self-insert-command N)
  18423. (org-fix-tags-on-the-fly)
  18424. (when org-self-insert-cluster-for-undo
  18425. (if (not (eq last-command 'org-self-insert-command))
  18426. (setq org-self-insert-command-undo-counter 1)
  18427. (if (>= org-self-insert-command-undo-counter 20)
  18428. (setq org-self-insert-command-undo-counter 1)
  18429. (and (> org-self-insert-command-undo-counter 0)
  18430. buffer-undo-list (listp buffer-undo-list)
  18431. (not (cadr buffer-undo-list)) ; remove nil entry
  18432. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18433. (setq org-self-insert-command-undo-counter
  18434. (1+ org-self-insert-command-undo-counter))))))))
  18435. (defun org-check-before-invisible-edit (kind)
  18436. "Check is editing if kind KIND would be dangerous with invisible text around.
  18437. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18438. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18439. (when (and org-catch-invisible-edits
  18440. (or (not (boundp 'visible-mode)) (not visible-mode))
  18441. (or (get-char-property (point) 'invisible)
  18442. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18443. ;; OK, we need to take a closer look. Do not consider
  18444. ;; invisibility obtained through text properties (e.g., link
  18445. ;; fontification), as it cannot be toggled.
  18446. (let* ((invisible-at-point
  18447. (pcase (get-char-property-and-overlay (point) 'invisible)
  18448. (`(,_ . ,(and (pred overlayp) o)) o)))
  18449. ;; Assume that point cannot land in the middle of an
  18450. ;; overlay, or between two overlays.
  18451. (invisible-before-point
  18452. (and (not invisible-at-point)
  18453. (not (bobp))
  18454. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18455. (`(,_ . ,(and (pred overlayp) o)) o))))
  18456. (border-and-ok-direction
  18457. (or
  18458. ;; Check if we are acting predictably before invisible
  18459. ;; text.
  18460. (and invisible-at-point
  18461. (memq kind '(insert delete-backward)))
  18462. ;; Check if we are acting predictably after invisible text
  18463. ;; This works not well, and I have turned it off. It seems
  18464. ;; better to always show and stop after invisible text.
  18465. ;; (and (not invisible-at-point) invisible-before-point
  18466. ;; (memq kind '(insert delete)))
  18467. )))
  18468. (when (or invisible-at-point invisible-before-point)
  18469. (when (eq org-catch-invisible-edits 'error)
  18470. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18471. (if (and org-custom-properties-overlays
  18472. (y-or-n-p "Display invisible properties in this buffer? "))
  18473. (org-toggle-custom-properties-visibility)
  18474. ;; Make the area visible
  18475. (save-excursion
  18476. (when invisible-before-point
  18477. (goto-char
  18478. (previous-single-char-property-change (point) 'invisible)))
  18479. ;; Remove whatever overlay is currently making yet-to-be
  18480. ;; edited text invisible. Also remove nested invisibility
  18481. ;; related overlays.
  18482. (delete-overlay (or invisible-at-point invisible-before-point))
  18483. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18484. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18485. (`(,_ . ,(and (pred overlayp) o))
  18486. (delete-overlay o)
  18487. t)))))
  18488. (cond
  18489. ((eq org-catch-invisible-edits 'show)
  18490. ;; That's it, we do the edit after showing
  18491. (message
  18492. "Unfolding invisible region around point before editing")
  18493. (sit-for 1))
  18494. ((and (eq org-catch-invisible-edits 'smart)
  18495. border-and-ok-direction)
  18496. (message "Unfolding invisible region around point before editing"))
  18497. (t
  18498. ;; Don't do the edit, make the user repeat it in full visibility
  18499. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18500. (defun org-fix-tags-on-the-fly ()
  18501. "Align tags in headline at point.
  18502. Unlike to `org-set-tags', it ignores region and sorting."
  18503. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18504. (org-at-heading-p))
  18505. (let ((org-ignore-region t)
  18506. (org-tags-sort-function nil))
  18507. (org-set-tags nil t))))
  18508. (defun org-delete-backward-char (N)
  18509. "Like `delete-backward-char', insert whitespace at field end in tables.
  18510. When deleting backwards, in tables this function will insert whitespace in
  18511. front of the next \"|\" separator, to keep the table aligned. The table will
  18512. still be marked for re-alignment if the field did fill the entire column,
  18513. because, in this case the deletion might narrow the column."
  18514. (interactive "p")
  18515. (save-match-data
  18516. (org-check-before-invisible-edit 'delete-backward)
  18517. (if (and (org-at-table-p)
  18518. (eq N 1)
  18519. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18520. (looking-at ".*?|"))
  18521. (let ((pos (point))
  18522. (noalign (looking-at "[^|\n\r]* |"))
  18523. (c org-table-may-need-update))
  18524. (backward-delete-char N)
  18525. (unless overwrite-mode
  18526. (skip-chars-forward "^|")
  18527. (insert " ")
  18528. (goto-char (1- pos)))
  18529. ;; noalign: if there were two spaces at the end, this field
  18530. ;; does not determine the width of the column.
  18531. (when noalign (setq org-table-may-need-update c)))
  18532. (backward-delete-char N)
  18533. (org-fix-tags-on-the-fly))))
  18534. (defun org-delete-char (N)
  18535. "Like `delete-char', but insert whitespace at field end in tables.
  18536. When deleting characters, in tables this function will insert whitespace in
  18537. front of the next \"|\" separator, to keep the table aligned. The table will
  18538. still be marked for re-alignment if the field did fill the entire column,
  18539. because, in this case the deletion might narrow the column."
  18540. (interactive "p")
  18541. (save-match-data
  18542. (org-check-before-invisible-edit 'delete)
  18543. (if (and (org-at-table-p)
  18544. (not (bolp))
  18545. (not (= (char-after) ?|))
  18546. (eq N 1))
  18547. (if (looking-at ".*?|")
  18548. (let ((pos (point))
  18549. (noalign (looking-at "[^|\n\r]* |"))
  18550. (c org-table-may-need-update))
  18551. (replace-match
  18552. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18553. (goto-char pos)
  18554. ;; noalign: if there were two spaces at the end, this field
  18555. ;; does not determine the width of the column.
  18556. (when noalign (setq org-table-may-need-update c)))
  18557. (delete-char N))
  18558. (delete-char N)
  18559. (org-fix-tags-on-the-fly))))
  18560. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18561. (put 'org-self-insert-command 'delete-selection
  18562. (lambda ()
  18563. (not (run-hook-with-args-until-success
  18564. 'self-insert-uses-region-functions))))
  18565. (put 'orgtbl-self-insert-command 'delete-selection
  18566. (lambda ()
  18567. (not (run-hook-with-args-until-success
  18568. 'self-insert-uses-region-functions))))
  18569. (put 'org-delete-char 'delete-selection 'supersede)
  18570. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18571. (put 'org-yank 'delete-selection 'yank)
  18572. ;; Make `flyspell-mode' delay after some commands
  18573. (put 'org-self-insert-command 'flyspell-delayed t)
  18574. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18575. (put 'org-delete-char 'flyspell-delayed t)
  18576. (put 'org-delete-backward-char 'flyspell-delayed t)
  18577. ;; Make pabbrev-mode expand after Org mode commands
  18578. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18579. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18580. (defun org-remap (map &rest commands)
  18581. "In MAP, remap the functions given in COMMANDS.
  18582. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18583. (let (new old)
  18584. (while commands
  18585. (setq old (pop commands) new (pop commands))
  18586. (org-defkey map (vector 'remap old) new))))
  18587. (defun org-transpose-words ()
  18588. "Transpose words for Org.
  18589. This uses the `org-mode-transpose-word-syntax-table' syntax
  18590. table, which interprets characters in `org-emphasis-alist' as
  18591. word constituents."
  18592. (interactive)
  18593. (with-syntax-table org-mode-transpose-word-syntax-table
  18594. (call-interactively 'transpose-words)))
  18595. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18596. (when (eq org-enable-table-editor 'optimized)
  18597. ;; If the user wants maximum table support, we need to hijack
  18598. ;; some standard editing functions
  18599. (org-remap org-mode-map
  18600. 'self-insert-command 'org-self-insert-command
  18601. 'delete-char 'org-delete-char
  18602. 'delete-backward-char 'org-delete-backward-char)
  18603. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18604. (defvar org-ctrl-c-ctrl-c-hook nil
  18605. "Hook for functions attaching themselves to `C-c C-c'.
  18606. This can be used to add additional functionality to the C-c C-c
  18607. key which executes context-dependent commands. This hook is run
  18608. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18609. run after the last test.
  18610. Each function will be called with no arguments. The function
  18611. must check if the context is appropriate for it to act. If yes,
  18612. it should do its thing and then return a non-nil value. If the
  18613. context is wrong, just do nothing and return nil.")
  18614. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18615. "Hook for functions attaching themselves to `C-c C-c'.
  18616. This can be used to add additional functionality to the C-c C-c
  18617. key which executes context-dependent commands. This hook is run
  18618. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18619. before the first test.
  18620. Each function will be called with no arguments. The function
  18621. must check if the context is appropriate for it to act. If yes,
  18622. it should do its thing and then return a non-nil value. If the
  18623. context is wrong, just do nothing and return nil.")
  18624. (defvar org-tab-first-hook nil
  18625. "Hook for functions to attach themselves to TAB.
  18626. See `org-ctrl-c-ctrl-c-hook' for more information.
  18627. This hook runs as the first action when TAB is pressed, even before
  18628. `org-cycle' messes around with the `outline-regexp' to cater for
  18629. inline tasks and plain list item folding.
  18630. If any function in this hook returns t, any other actions that
  18631. would have been caused by TAB (such as table field motion or visibility
  18632. cycling) will not occur.")
  18633. (defvar org-tab-after-check-for-table-hook nil
  18634. "Hook for functions to attach themselves to TAB.
  18635. See `org-ctrl-c-ctrl-c-hook' for more information.
  18636. This hook runs after it has been established that the cursor is not in a
  18637. table, but before checking if the cursor is in a headline or if global cycling
  18638. should be done.
  18639. If any function in this hook returns t, not other actions like visibility
  18640. cycling will be done.")
  18641. (defvar org-tab-after-check-for-cycling-hook nil
  18642. "Hook for functions to attach themselves to TAB.
  18643. See `org-ctrl-c-ctrl-c-hook' for more information.
  18644. This hook runs after it has been established that not table field motion and
  18645. not visibility should be done because of current context. This is probably
  18646. the place where a package like yasnippets can hook in.")
  18647. (defvar org-tab-before-tab-emulation-hook nil
  18648. "Hook for functions to attach themselves to TAB.
  18649. See `org-ctrl-c-ctrl-c-hook' for more information.
  18650. This hook runs after every other options for TAB have been exhausted, but
  18651. before indentation and \t insertion takes place.")
  18652. (defvar org-metaleft-hook nil
  18653. "Hook for functions attaching themselves to `M-left'.
  18654. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18655. (defvar org-metaright-hook nil
  18656. "Hook for functions attaching themselves to `M-right'.
  18657. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18658. (defvar org-metaup-hook nil
  18659. "Hook for functions attaching themselves to `M-up'.
  18660. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18661. (defvar org-metadown-hook nil
  18662. "Hook for functions attaching themselves to `M-down'.
  18663. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18664. (defvar org-shiftmetaleft-hook nil
  18665. "Hook for functions attaching themselves to `M-S-left'.
  18666. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18667. (defvar org-shiftmetaright-hook nil
  18668. "Hook for functions attaching themselves to `M-S-right'.
  18669. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18670. (defvar org-shiftmetaup-hook nil
  18671. "Hook for functions attaching themselves to `M-S-up'.
  18672. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18673. (defvar org-shiftmetadown-hook nil
  18674. "Hook for functions attaching themselves to `M-S-down'.
  18675. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18676. (defvar org-metareturn-hook nil
  18677. "Hook for functions attaching themselves to `M-RET'.
  18678. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18679. (defvar org-shiftup-hook nil
  18680. "Hook for functions attaching themselves to `S-up'.
  18681. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18682. (defvar org-shiftup-final-hook nil
  18683. "Hook for functions attaching themselves to `S-up'.
  18684. This one runs after all other options except shift-select have been excluded.
  18685. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18686. (defvar org-shiftdown-hook nil
  18687. "Hook for functions attaching themselves to `S-down'.
  18688. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18689. (defvar org-shiftdown-final-hook nil
  18690. "Hook for functions attaching themselves to `S-down'.
  18691. This one runs after all other options except shift-select have been excluded.
  18692. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18693. (defvar org-shiftleft-hook nil
  18694. "Hook for functions attaching themselves to `S-left'.
  18695. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18696. (defvar org-shiftleft-final-hook nil
  18697. "Hook for functions attaching themselves to `S-left'.
  18698. This one runs after all other options except shift-select have been excluded.
  18699. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18700. (defvar org-shiftright-hook nil
  18701. "Hook for functions attaching themselves to `S-right'.
  18702. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18703. (defvar org-shiftright-final-hook nil
  18704. "Hook for functions attaching themselves to `S-right'.
  18705. This one runs after all other options except shift-select have been excluded.
  18706. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18707. (defun org-modifier-cursor-error ()
  18708. "Throw an error, a modified cursor command was applied in wrong context."
  18709. (user-error "This command is active in special context like tables, headlines or items"))
  18710. (defun org-shiftselect-error ()
  18711. "Throw an error because Shift-Cursor command was applied in wrong context."
  18712. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18713. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18714. (user-error "This command works only in special context like headlines or timestamps")))
  18715. (defun org-call-for-shift-select (cmd)
  18716. (let ((this-command-keys-shift-translated t))
  18717. (call-interactively cmd)))
  18718. (defun org-shifttab (&optional arg)
  18719. "Global visibility cycling or move to previous table field.
  18720. Call `org-table-previous-field' within a table.
  18721. When ARG is nil, cycle globally through visibility states.
  18722. When ARG is a numeric prefix, show contents of this level."
  18723. (interactive "P")
  18724. (cond
  18725. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18726. ((integerp arg)
  18727. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18728. (message "Content view to level: %d" arg)
  18729. (org-content (prefix-numeric-value arg2))
  18730. (org-cycle-show-empty-lines t)
  18731. (setq org-cycle-global-status 'overview)))
  18732. (t (call-interactively 'org-global-cycle))))
  18733. (defun org-shiftmetaleft ()
  18734. "Promote subtree or delete table column.
  18735. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18736. `org-table-delete-column', depending on context. See the
  18737. individual commands for more information."
  18738. (interactive)
  18739. (cond
  18740. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18741. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18742. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18743. ((if (not (org-region-active-p)) (org-at-item-p)
  18744. (save-excursion (goto-char (region-beginning))
  18745. (org-at-item-p)))
  18746. (call-interactively 'org-outdent-item-tree))
  18747. (t (org-modifier-cursor-error))))
  18748. (defun org-shiftmetaright ()
  18749. "Demote subtree or insert table column.
  18750. Calls `org-demote-subtree', `org-indent-item-tree', or
  18751. `org-table-insert-column', depending on context. See the
  18752. individual commands for more information."
  18753. (interactive)
  18754. (cond
  18755. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18756. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18757. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18758. ((if (not (org-region-active-p)) (org-at-item-p)
  18759. (save-excursion (goto-char (region-beginning))
  18760. (org-at-item-p)))
  18761. (call-interactively 'org-indent-item-tree))
  18762. (t (org-modifier-cursor-error))))
  18763. (defun org-shiftmetaup (&optional _arg)
  18764. "Drag the line at point up.
  18765. In a table, kill the current row.
  18766. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18767. but also adjust the previous clocked item in the clock history.
  18768. Everywhere else, drag the line at point up."
  18769. (interactive "P")
  18770. (cond
  18771. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18772. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18773. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18774. (call-interactively 'org-timestamp-up)))
  18775. (t (call-interactively 'org-drag-line-backward))))
  18776. (defun org-shiftmetadown (&optional _arg)
  18777. "Drag the line at point down.
  18778. In a table, insert an empty row at the current line.
  18779. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18780. but also adjust the previous clocked item in the clock history.
  18781. Everywhere else, drag the line at point down."
  18782. (interactive "P")
  18783. (cond
  18784. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18785. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18786. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18787. (call-interactively 'org-timestamp-down)))
  18788. (t (call-interactively 'org-drag-line-forward))))
  18789. (defsubst org-hidden-tree-error ()
  18790. (user-error
  18791. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18792. (defun org-metaleft (&optional _arg)
  18793. "Promote heading, list item at point or move table column left.
  18794. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18795. depending on context. With no specific context, calls the Emacs
  18796. default `backward-word'. See the individual commands for more
  18797. information.
  18798. This function runs the hook `org-metaleft-hook' as a first step,
  18799. and returns at first non-nil value."
  18800. (interactive "P")
  18801. (cond
  18802. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18803. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18804. ((org-with-limited-levels
  18805. (or (org-at-heading-p)
  18806. (and (org-region-active-p)
  18807. (save-excursion
  18808. (goto-char (region-beginning))
  18809. (org-at-heading-p)))))
  18810. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18811. (call-interactively 'org-do-promote))
  18812. ;; At an inline task.
  18813. ((org-at-heading-p)
  18814. (call-interactively 'org-inlinetask-promote))
  18815. ((or (org-at-item-p)
  18816. (and (org-region-active-p)
  18817. (save-excursion
  18818. (goto-char (region-beginning))
  18819. (org-at-item-p))))
  18820. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18821. (call-interactively 'org-outdent-item))
  18822. (t (call-interactively 'backward-word))))
  18823. (defun org-metaright (&optional _arg)
  18824. "Demote heading, list item at point or move table column right.
  18825. In front of a drawer or a block keyword, indent it correctly.
  18826. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18827. `org-indent-drawer' or `org-indent-block' depending on context.
  18828. With no specific context, calls the Emacs default `forward-word'.
  18829. See the individual commands for more information.
  18830. This function runs the hook `org-metaright-hook' as a first step,
  18831. and returns at first non-nil value."
  18832. (interactive "P")
  18833. (cond
  18834. ((run-hook-with-args-until-success 'org-metaright-hook))
  18835. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18836. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18837. ((org-at-block-p) (call-interactively 'org-indent-block))
  18838. ((org-with-limited-levels
  18839. (or (org-at-heading-p)
  18840. (and (org-region-active-p)
  18841. (save-excursion
  18842. (goto-char (region-beginning))
  18843. (org-at-heading-p)))))
  18844. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18845. (call-interactively 'org-do-demote))
  18846. ;; At an inline task.
  18847. ((org-at-heading-p)
  18848. (call-interactively 'org-inlinetask-demote))
  18849. ((or (org-at-item-p)
  18850. (and (org-region-active-p)
  18851. (save-excursion
  18852. (goto-char (region-beginning))
  18853. (org-at-item-p))))
  18854. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18855. (call-interactively 'org-indent-item))
  18856. (t (call-interactively 'forward-word))))
  18857. (defun org-check-for-hidden (what)
  18858. "Check if there are hidden headlines/items in the current visual line.
  18859. WHAT can be either `headlines' or `items'. If the current line is
  18860. an outline or item heading and it has a folded subtree below it,
  18861. this function returns t, nil otherwise."
  18862. (let ((re (cond
  18863. ((eq what 'headlines) org-outline-regexp-bol)
  18864. ((eq what 'items) (org-item-beginning-re))
  18865. (t (error "This should not happen"))))
  18866. beg end)
  18867. (save-excursion
  18868. (catch 'exit
  18869. (unless (org-region-active-p)
  18870. (setq beg (point-at-bol))
  18871. (beginning-of-line 2)
  18872. (while (and (not (eobp)) ;; this is like `next-line'
  18873. (get-char-property (1- (point)) 'invisible))
  18874. (beginning-of-line 2))
  18875. (setq end (point))
  18876. (goto-char beg)
  18877. (goto-char (point-at-eol))
  18878. (setq end (max end (point)))
  18879. (while (re-search-forward re end t)
  18880. (when (get-char-property (match-beginning 0) 'invisible)
  18881. (throw 'exit t))))
  18882. nil))))
  18883. (defun org-metaup (&optional _arg)
  18884. "Move subtree up or move table row up.
  18885. Calls `org-move-subtree-up' or `org-table-move-row' or
  18886. `org-move-item-up', depending on context. See the individual commands
  18887. for more information."
  18888. (interactive "P")
  18889. (cond
  18890. ((run-hook-with-args-until-success 'org-metaup-hook))
  18891. ((org-region-active-p)
  18892. (let* ((a (min (region-beginning) (region-end)))
  18893. (b (1- (max (region-beginning) (region-end))))
  18894. (c (save-excursion (goto-char a)
  18895. (move-beginning-of-line 0)))
  18896. (d (save-excursion (goto-char a)
  18897. (move-end-of-line 0) (point))))
  18898. (transpose-regions a b c d)
  18899. (goto-char c)))
  18900. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18901. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18902. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18903. (t (org-drag-element-backward))))
  18904. (defun org-metadown (&optional _arg)
  18905. "Move subtree down or move table row down.
  18906. Calls `org-move-subtree-down' or `org-table-move-row' or
  18907. `org-move-item-down', depending on context. See the individual
  18908. commands for more information."
  18909. (interactive "P")
  18910. (cond
  18911. ((run-hook-with-args-until-success 'org-metadown-hook))
  18912. ((org-region-active-p)
  18913. (let* ((a (min (region-beginning) (region-end)))
  18914. (b (max (region-beginning) (region-end)))
  18915. (c (save-excursion (goto-char b)
  18916. (move-beginning-of-line 1)))
  18917. (d (save-excursion (goto-char b)
  18918. (move-end-of-line 1) (1+ (point)))))
  18919. (transpose-regions a b c d)
  18920. (goto-char d)))
  18921. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18922. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18923. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18924. (t (org-drag-element-forward))))
  18925. (defun org-shiftup (&optional arg)
  18926. "Increase item in timestamp or increase priority of current headline.
  18927. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18928. depending on context. See the individual commands for more information."
  18929. (interactive "P")
  18930. (cond
  18931. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18932. ((and org-support-shift-select (org-region-active-p))
  18933. (org-call-for-shift-select 'previous-line))
  18934. ((org-at-timestamp-p t)
  18935. (call-interactively (if org-edit-timestamp-down-means-later
  18936. 'org-timestamp-down 'org-timestamp-up)))
  18937. ((and (not (eq org-support-shift-select 'always))
  18938. org-enable-priority-commands
  18939. (org-at-heading-p))
  18940. (call-interactively 'org-priority-up))
  18941. ((and (not org-support-shift-select) (org-at-item-p))
  18942. (call-interactively 'org-previous-item))
  18943. ((org-clocktable-try-shift 'up arg))
  18944. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18945. (org-support-shift-select
  18946. (org-call-for-shift-select 'previous-line))
  18947. (t (org-shiftselect-error))))
  18948. (defun org-shiftdown (&optional arg)
  18949. "Decrease item in timestamp or decrease priority of current headline.
  18950. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18951. depending on context. See the individual commands for more information."
  18952. (interactive "P")
  18953. (cond
  18954. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18955. ((and org-support-shift-select (org-region-active-p))
  18956. (org-call-for-shift-select 'next-line))
  18957. ((org-at-timestamp-p t)
  18958. (call-interactively (if org-edit-timestamp-down-means-later
  18959. 'org-timestamp-up 'org-timestamp-down)))
  18960. ((and (not (eq org-support-shift-select 'always))
  18961. org-enable-priority-commands
  18962. (org-at-heading-p))
  18963. (call-interactively 'org-priority-down))
  18964. ((and (not org-support-shift-select) (org-at-item-p))
  18965. (call-interactively 'org-next-item))
  18966. ((org-clocktable-try-shift 'down arg))
  18967. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18968. (org-support-shift-select
  18969. (org-call-for-shift-select 'next-line))
  18970. (t (org-shiftselect-error))))
  18971. (defun org-shiftright (&optional arg)
  18972. "Cycle the thing at point or in the current line, depending on context.
  18973. Depending on context, this does one of the following:
  18974. - switch a timestamp at point one day into the future
  18975. - on a headline, switch to the next TODO keyword.
  18976. - on an item, switch entire list to the next bullet type
  18977. - on a property line, switch to the next allowed value
  18978. - on a clocktable definition line, move time block into the future"
  18979. (interactive "P")
  18980. (cond
  18981. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18982. ((and org-support-shift-select (org-region-active-p))
  18983. (org-call-for-shift-select 'forward-char))
  18984. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  18985. ((and (not (eq org-support-shift-select 'always))
  18986. (org-at-heading-p))
  18987. (let ((org-inhibit-logging
  18988. (not org-treat-S-cursor-todo-selection-as-state-change))
  18989. (org-inhibit-blocking
  18990. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18991. (org-call-with-arg 'org-todo 'right)))
  18992. ((or (and org-support-shift-select
  18993. (not (eq org-support-shift-select 'always))
  18994. (org-at-item-bullet-p))
  18995. (and (not org-support-shift-select) (org-at-item-p)))
  18996. (org-call-with-arg 'org-cycle-list-bullet nil))
  18997. ((and (not (eq org-support-shift-select 'always))
  18998. (org-at-property-p))
  18999. (call-interactively 'org-property-next-allowed-value))
  19000. ((org-clocktable-try-shift 'right arg))
  19001. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19002. (org-support-shift-select
  19003. (org-call-for-shift-select 'forward-char))
  19004. (t (org-shiftselect-error))))
  19005. (defun org-shiftleft (&optional arg)
  19006. "Cycle the thing at point or in the current line, depending on context.
  19007. Depending on context, this does one of the following:
  19008. - switch a timestamp at point one day into the past
  19009. - on a headline, switch to the previous TODO keyword.
  19010. - on an item, switch entire list to the previous bullet type
  19011. - on a property line, switch to the previous allowed value
  19012. - on a clocktable definition line, move time block into the past"
  19013. (interactive "P")
  19014. (cond
  19015. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19016. ((and org-support-shift-select (org-region-active-p))
  19017. (org-call-for-shift-select 'backward-char))
  19018. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19019. ((and (not (eq org-support-shift-select 'always))
  19020. (org-at-heading-p))
  19021. (let ((org-inhibit-logging
  19022. (not org-treat-S-cursor-todo-selection-as-state-change))
  19023. (org-inhibit-blocking
  19024. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19025. (org-call-with-arg 'org-todo 'left)))
  19026. ((or (and org-support-shift-select
  19027. (not (eq org-support-shift-select 'always))
  19028. (org-at-item-bullet-p))
  19029. (and (not org-support-shift-select) (org-at-item-p)))
  19030. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19031. ((and (not (eq org-support-shift-select 'always))
  19032. (org-at-property-p))
  19033. (call-interactively 'org-property-previous-allowed-value))
  19034. ((org-clocktable-try-shift 'left arg))
  19035. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19036. (org-support-shift-select
  19037. (org-call-for-shift-select 'backward-char))
  19038. (t (org-shiftselect-error))))
  19039. (defun org-shiftcontrolright ()
  19040. "Switch to next TODO set."
  19041. (interactive)
  19042. (cond
  19043. ((and org-support-shift-select (org-region-active-p))
  19044. (org-call-for-shift-select 'forward-word))
  19045. ((and (not (eq org-support-shift-select 'always))
  19046. (org-at-heading-p))
  19047. (org-call-with-arg 'org-todo 'nextset))
  19048. (org-support-shift-select
  19049. (org-call-for-shift-select 'forward-word))
  19050. (t (org-shiftselect-error))))
  19051. (defun org-shiftcontrolleft ()
  19052. "Switch to previous TODO set."
  19053. (interactive)
  19054. (cond
  19055. ((and org-support-shift-select (org-region-active-p))
  19056. (org-call-for-shift-select 'backward-word))
  19057. ((and (not (eq org-support-shift-select 'always))
  19058. (org-at-heading-p))
  19059. (org-call-with-arg 'org-todo 'previousset))
  19060. (org-support-shift-select
  19061. (org-call-for-shift-select 'backward-word))
  19062. (t (org-shiftselect-error))))
  19063. (defun org-shiftcontrolup (&optional n)
  19064. "Change timestamps synchronously up in CLOCK log lines.
  19065. Optional argument N tells to change by that many units."
  19066. (interactive "P")
  19067. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19068. (let (org-support-shift-select)
  19069. (org-clock-timestamps-up n))
  19070. (user-error "Not at a clock log")))
  19071. (defun org-shiftcontroldown (&optional n)
  19072. "Change timestamps synchronously down in CLOCK log lines.
  19073. Optional argument N tells to change by that many units."
  19074. (interactive "P")
  19075. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19076. (let (org-support-shift-select)
  19077. (org-clock-timestamps-down n))
  19078. (user-error "Not at a clock log")))
  19079. (defun org-increase-number-at-point (&optional inc)
  19080. "Increment the number at point.
  19081. With an optional prefix numeric argument INC, increment using
  19082. this numeric value."
  19083. (interactive "p")
  19084. (if (not (number-at-point))
  19085. (user-error "Not on a number")
  19086. (unless inc (setq inc 1))
  19087. (let ((pos (point))
  19088. (beg (skip-chars-backward "-+^/*0-9eE."))
  19089. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19090. (setq nap (buffer-substring-no-properties
  19091. (+ pos beg) (+ pos beg end)))
  19092. (delete-region (+ pos beg) (+ pos beg end))
  19093. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19094. (when (org-at-table-p)
  19095. (org-table-align)
  19096. (org-table-end-of-field 1))))
  19097. (defun org-decrease-number-at-point (&optional inc)
  19098. "Decrement the number at point.
  19099. With an optional prefix numeric argument INC, decrement using
  19100. this numeric value."
  19101. (interactive "p")
  19102. (org-increase-number-at-point (- (or inc 1))))
  19103. (defun org-ctrl-c-ret ()
  19104. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19105. (interactive)
  19106. (cond
  19107. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19108. (t (call-interactively 'org-insert-heading))))
  19109. (defun org-find-visible ()
  19110. (let ((s (point)))
  19111. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19112. (get-char-property s 'invisible)))
  19113. s))
  19114. (defun org-find-invisible ()
  19115. (let ((s (point)))
  19116. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19117. (not (get-char-property s 'invisible))))
  19118. s))
  19119. (defun org-copy-visible (beg end)
  19120. "Copy the visible parts of the region."
  19121. (interactive "r")
  19122. (let (snippets s)
  19123. (save-excursion
  19124. (save-restriction
  19125. (narrow-to-region beg end)
  19126. (setq s (goto-char (point-min)))
  19127. (while (not (= (point) (point-max)))
  19128. (goto-char (org-find-invisible))
  19129. (push (buffer-substring s (point)) snippets)
  19130. (setq s (goto-char (org-find-visible))))))
  19131. (kill-new (apply 'concat (nreverse snippets)))))
  19132. (defun org-copy-special ()
  19133. "Copy region in table or copy current subtree.
  19134. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19135. context. See the individual commands for more information."
  19136. (interactive)
  19137. (call-interactively
  19138. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19139. (defun org-cut-special ()
  19140. "Cut region in table or cut current subtree.
  19141. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19142. context. See the individual commands for more information."
  19143. (interactive)
  19144. (call-interactively
  19145. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19146. (defun org-paste-special (arg)
  19147. "Paste rectangular region into table, or past subtree relative to level.
  19148. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19149. See the individual commands for more information."
  19150. (interactive "P")
  19151. (if (org-at-table-p)
  19152. (org-table-paste-rectangle)
  19153. (org-paste-subtree arg)))
  19154. (defun org-edit-special (&optional arg)
  19155. "Call a special editor for the element at point.
  19156. When at a table, call the formula editor with `org-table-edit-formulas'.
  19157. When in a source code block, call `org-edit-src-code'.
  19158. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19159. When in an export block, call `org-edit-export-block'.
  19160. When at an #+INCLUDE keyword, visit the included file.
  19161. When at a footnote reference, call `org-edit-footnote-reference'
  19162. On a link, call `ffap' to visit the link at point.
  19163. Otherwise, return a user error."
  19164. (interactive "P")
  19165. (let ((element (org-element-at-point)))
  19166. (barf-if-buffer-read-only)
  19167. (pcase (org-element-type element)
  19168. (`src-block
  19169. (if (not arg) (org-edit-src-code)
  19170. (let* ((info (org-babel-get-src-block-info))
  19171. (lang (nth 0 info))
  19172. (params (nth 2 info))
  19173. (session (cdr (assq :session params))))
  19174. (if (not session) (org-edit-src-code)
  19175. ;; At a src-block with a session and function called with
  19176. ;; an ARG: switch to the buffer related to the inferior
  19177. ;; process.
  19178. (switch-to-buffer
  19179. (funcall (intern (concat "org-babel-prep-session:" lang))
  19180. session params))))))
  19181. (`keyword
  19182. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19183. (org-open-link-from-string
  19184. (format "[[%s]]"
  19185. (expand-file-name
  19186. (let ((value (org-element-property :value element)))
  19187. (cond ((not (org-string-nw-p value))
  19188. (user-error "No file to edit"))
  19189. ((string-match "\\`\"\\(.*?\\)\"" value)
  19190. (match-string 1 value))
  19191. ((string-match "\\`[^ \t\"]\\S-*" value)
  19192. (match-string 0 value))
  19193. (t (user-error "No valid file specified")))))))
  19194. (user-error "No special environment to edit here")))
  19195. (`table
  19196. (if (eq (org-element-property :type element) 'table.el)
  19197. (org-edit-table.el)
  19198. (call-interactively 'org-table-edit-formulas)))
  19199. ;; Only Org tables contain `table-row' type elements.
  19200. (`table-row (call-interactively 'org-table-edit-formulas))
  19201. (`example-block (org-edit-src-code))
  19202. (`export-block (org-edit-export-block))
  19203. (`fixed-width (org-edit-fixed-width-region))
  19204. (_
  19205. ;; No notable element at point. Though, we may be at a link or
  19206. ;; a footnote reference, which are objects. Thus, scan deeper.
  19207. (let ((context (org-element-context element)))
  19208. (pcase (org-element-type context)
  19209. (`footnote-reference (org-edit-footnote-reference))
  19210. (`inline-src-block (org-edit-inline-src-code))
  19211. (`link (call-interactively #'ffap))
  19212. (_ (user-error "No special environment to edit here"))))))))
  19213. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19214. (defun org-ctrl-c-ctrl-c (&optional arg)
  19215. "Set tags in headline, or update according to changed information at point.
  19216. This command does many different things, depending on context:
  19217. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19218. this is what we do.
  19219. - If the cursor is on a statistics cookie, update it.
  19220. - If the cursor is in a headline, prompt for tags and insert them
  19221. into the current line, aligned to `org-tags-column'. When called
  19222. with prefix arg, realign all tags in the current buffer.
  19223. - If the cursor is in one of the special #+KEYWORD lines, this
  19224. triggers scanning the buffer for these lines and updating the
  19225. information.
  19226. - If the cursor is inside a table, realign the table. This command
  19227. works even if the automatic table editor has been turned off.
  19228. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19229. the entire table.
  19230. - If the cursor is at a footnote reference or definition, jump to
  19231. the corresponding definition or references, respectively.
  19232. - If the cursor is a the beginning of a dynamic block, update it.
  19233. - If the current buffer is a capture buffer, close note and file it.
  19234. - If the cursor is on a <<<target>>>, update radio targets and
  19235. corresponding links in this buffer.
  19236. - If the cursor is on a numbered item in a plain list, renumber the
  19237. ordered list.
  19238. - If the cursor is on a checkbox, toggle it.
  19239. - If the cursor is on a code block, evaluate it. The variable
  19240. `org-confirm-babel-evaluate' can be used to control prompting
  19241. before code block evaluation, by default every code block
  19242. evaluation requires confirmation. Code block evaluation can be
  19243. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19244. (interactive "P")
  19245. (cond
  19246. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19247. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19248. (org-remove-occur-highlights)
  19249. (message "Temporary highlights/overlays removed from current buffer"))
  19250. ((and (local-variable-p 'org-finish-function)
  19251. (fboundp org-finish-function))
  19252. (funcall org-finish-function))
  19253. ((org-babel-hash-at-point))
  19254. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19255. (t
  19256. (let* ((context
  19257. (org-element-lineage
  19258. (org-element-context)
  19259. ;; Limit to supported contexts.
  19260. '(babel-call clock dynamic-block footnote-definition
  19261. footnote-reference inline-babel-call inline-src-block
  19262. inlinetask item keyword node-property paragraph
  19263. plain-list property-drawer radio-target src-block
  19264. statistics-cookie table table-cell table-row
  19265. timestamp)
  19266. t))
  19267. (type (org-element-type context)))
  19268. ;; For convenience: at the first line of a paragraph on the same
  19269. ;; line as an item, apply function on that item instead.
  19270. (when (eq type 'paragraph)
  19271. (let ((parent (org-element-property :parent context)))
  19272. (when (and (eq (org-element-type parent) 'item)
  19273. (= (line-beginning-position)
  19274. (org-element-property :begin parent)))
  19275. (setq context parent)
  19276. (setq type 'item))))
  19277. ;; Act according to type of element or object at point.
  19278. ;;
  19279. ;; Do nothing on a blank line, except if it is contained in
  19280. ;; a src block. Hence, we first check if point is in such
  19281. ;; a block and then if it is at a blank line.
  19282. (pcase type
  19283. ((or `inline-src-block `src-block)
  19284. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19285. (org-babel-eval-wipe-error-buffer)
  19286. (org-babel-execute-src-block
  19287. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19288. ((guard (org-match-line "[ \t]*$"))
  19289. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19290. (user-error
  19291. (substitute-command-keys
  19292. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19293. ((or `babel-call `inline-babel-call)
  19294. (let ((info (org-babel-lob-get-info context)))
  19295. (when info (org-babel-execute-src-block nil info))))
  19296. (`clock (org-clock-update-time-maybe))
  19297. (`dynamic-block
  19298. (save-excursion
  19299. (goto-char (org-element-property :post-affiliated context))
  19300. (org-update-dblock)))
  19301. (`footnote-definition
  19302. (goto-char (org-element-property :post-affiliated context))
  19303. (call-interactively 'org-footnote-action))
  19304. (`footnote-reference (call-interactively #'org-footnote-action))
  19305. ((or `headline `inlinetask)
  19306. (save-excursion (goto-char (org-element-property :begin context))
  19307. (call-interactively #'org-set-tags)))
  19308. (`item
  19309. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19310. ;; unconditionally, whereas `C-u' will toggle its presence.
  19311. ;; Without a universal argument, if the item has a checkbox,
  19312. ;; toggle it. Otherwise repair the list.
  19313. (let* ((box (org-element-property :checkbox context))
  19314. (struct (org-element-property :structure context))
  19315. (old-struct (copy-tree struct))
  19316. (parents (org-list-parents-alist struct))
  19317. (prevs (org-list-prevs-alist struct))
  19318. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19319. (org-list-set-checkbox
  19320. (org-element-property :begin context) struct
  19321. (cond ((equal arg '(16)) "[-]")
  19322. ((and (not box) (equal arg '(4))) "[ ]")
  19323. ((or (not box) (equal arg '(4))) nil)
  19324. ((eq box 'on) "[ ]")
  19325. (t "[X]")))
  19326. ;; Mimic `org-list-write-struct' but with grabbing a return
  19327. ;; value from `org-list-struct-fix-box'.
  19328. (org-list-struct-fix-ind struct parents 2)
  19329. (org-list-struct-fix-item-end struct)
  19330. (org-list-struct-fix-bul struct prevs)
  19331. (org-list-struct-fix-ind struct parents)
  19332. (let ((block-item
  19333. (org-list-struct-fix-box struct parents prevs orderedp)))
  19334. (if (and box (equal struct old-struct))
  19335. (if (equal arg '(16))
  19336. (message "Checkboxes already reset")
  19337. (user-error "Cannot toggle this checkbox: %s"
  19338. (if (eq box 'on)
  19339. "all subitems checked"
  19340. "unchecked subitems")))
  19341. (org-list-struct-apply-struct struct old-struct)
  19342. (org-update-checkbox-count-maybe))
  19343. (when block-item
  19344. (message "Checkboxes were removed due to empty box at line %d"
  19345. (org-current-line block-item))))))
  19346. (`keyword
  19347. (let ((org-inhibit-startup-visibility-stuff t)
  19348. (org-startup-align-all-tables nil))
  19349. (when (boundp 'org-table-coordinate-overlays)
  19350. (mapc #'delete-overlay org-table-coordinate-overlays)
  19351. (setq org-table-coordinate-overlays nil))
  19352. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19353. (message "Local setup has been refreshed"))
  19354. (`plain-list
  19355. ;; At a plain list, with a double C-u argument, set
  19356. ;; checkboxes of each item to "[-]", whereas a single one
  19357. ;; will toggle their presence according to the state of the
  19358. ;; first item in the list. Without an argument, repair the
  19359. ;; list.
  19360. (let* ((begin (org-element-property :contents-begin context))
  19361. (beginm (move-marker (make-marker) begin))
  19362. (struct (org-element-property :structure context))
  19363. (old-struct (copy-tree struct))
  19364. (first-box (save-excursion
  19365. (goto-char begin)
  19366. (looking-at org-list-full-item-re)
  19367. (match-string-no-properties 3)))
  19368. (new-box (cond ((equal arg '(16)) "[-]")
  19369. ((equal arg '(4)) (unless first-box "[ ]"))
  19370. ((equal first-box "[X]") "[ ]")
  19371. (t "[X]"))))
  19372. (cond
  19373. (arg
  19374. (dolist (pos
  19375. (org-list-get-all-items
  19376. begin struct (org-list-prevs-alist struct)))
  19377. (org-list-set-checkbox pos struct new-box)))
  19378. ((and first-box (eq (point) begin))
  19379. ;; For convenience, when point is at bol on the first
  19380. ;; item of the list and no argument is provided, simply
  19381. ;; toggle checkbox of that item, if any.
  19382. (org-list-set-checkbox begin struct new-box)))
  19383. (org-list-write-struct
  19384. struct (org-list-parents-alist struct) old-struct)
  19385. (org-update-checkbox-count-maybe)
  19386. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19387. ((or `property-drawer `node-property)
  19388. (call-interactively #'org-property-action))
  19389. (`radio-target
  19390. (call-interactively #'org-update-radio-target-regexp))
  19391. (`statistics-cookie
  19392. (call-interactively #'org-update-statistics-cookies))
  19393. ((or `table `table-cell `table-row)
  19394. ;; At a table, recalculate every field and align it. Also
  19395. ;; send the table if necessary. If the table has
  19396. ;; a `table.el' type, just give up. At a table row or cell,
  19397. ;; maybe recalculate line but always align table.
  19398. (if (eq (org-element-property :type context) 'table.el)
  19399. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19400. Use `\\[org-edit-special]' to edit table.el tables"))
  19401. (let ((org-enable-table-editor t))
  19402. (if (or (eq type 'table)
  19403. ;; Check if point is at a TBLFM line.
  19404. (and (eq type 'table-row)
  19405. (= (point) (org-element-property :end context))))
  19406. (save-excursion
  19407. (if (org-at-TBLFM-p)
  19408. (progn (require 'org-table)
  19409. (org-table-calc-current-TBLFM))
  19410. (goto-char (org-element-property :contents-begin context))
  19411. (org-call-with-arg 'org-table-recalculate (or arg t))
  19412. (orgtbl-send-table 'maybe)))
  19413. (org-table-maybe-eval-formula)
  19414. (cond (arg (call-interactively #'org-table-recalculate))
  19415. ((org-table-maybe-recalculate-line))
  19416. (t (org-table-align)))))))
  19417. (`timestamp (org-timestamp-change 0 'day))
  19418. ((and `nil (guard (org-at-heading-p)))
  19419. ;; When point is on an unsupported object type, we can miss
  19420. ;; the fact that it also is at a heading. Handle it here.
  19421. (call-interactively #'org-set-tags))
  19422. ((guard
  19423. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19424. (_
  19425. (user-error
  19426. (substitute-command-keys
  19427. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19428. (defun org-mode-restart ()
  19429. (interactive)
  19430. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19431. (funcall major-mode)
  19432. (hack-local-variables)
  19433. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19434. (org-indent-mode -1)))
  19435. (message "%s restarted" major-mode))
  19436. (defun org-kill-note-or-show-branches ()
  19437. "Abort storing current note, or call `outline-show-branches'."
  19438. (interactive)
  19439. (if (not org-finish-function)
  19440. (progn
  19441. (outline-hide-subtree)
  19442. (call-interactively 'outline-show-branches))
  19443. (let ((org-note-abort t))
  19444. (funcall org-finish-function))))
  19445. (defun org-delete-indentation (&optional arg)
  19446. "Join current line to previous and fix whitespace at join.
  19447. If previous line is a headline add to headline title. Otherwise
  19448. the function calls `delete-indentation'.
  19449. With a non-nil optional argument, join it to the following one."
  19450. (interactive "*P")
  19451. (if (save-excursion
  19452. (beginning-of-line (if arg 1 0))
  19453. (let ((case-fold-search nil))
  19454. (looking-at org-complex-heading-regexp)))
  19455. ;; At headline.
  19456. (let ((tags-column (when (match-beginning 5)
  19457. (save-excursion (goto-char (match-beginning 5))
  19458. (current-column))))
  19459. (string (concat " " (progn (when arg (forward-line 1))
  19460. (org-trim (delete-and-extract-region
  19461. (line-beginning-position)
  19462. (line-end-position)))))))
  19463. (unless (bobp) (delete-region (point) (1- (point))))
  19464. (goto-char (or (match-end 4)
  19465. (match-beginning 5)
  19466. (match-end 0)))
  19467. (skip-chars-backward " \t")
  19468. (save-excursion (insert string))
  19469. ;; Adjust alignment of tags.
  19470. (cond
  19471. ((not tags-column)) ;no tags
  19472. (org-auto-align-tags (org-set-tags nil t))
  19473. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19474. (delete-indentation arg)))
  19475. (defun org-open-line (n)
  19476. "Insert a new row in tables, call `open-line' elsewhere.
  19477. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19478. As a special case, when a document starts with a table, allow to
  19479. call `open-line' on the very first character."
  19480. (interactive "*p")
  19481. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19482. (org-table-insert-row)
  19483. (open-line n)))
  19484. (defun org-return (&optional indent)
  19485. "Goto next table row or insert a newline.
  19486. Calls `org-table-next-row' or `newline', depending on context.
  19487. When optional INDENT argument is non-nil, call
  19488. `newline-and-indent' instead of `newline'.
  19489. When `org-return-follows-link' is non-nil and point is on
  19490. a timestamp or a link, call `org-open-at-point'. However, it
  19491. will not happen if point is in a table or on a \"dead\"
  19492. object (e.g., within a comment). In these case, you need to use
  19493. `org-open-at-point' directly."
  19494. (interactive)
  19495. (let ((context (if org-return-follows-link (org-element-context)
  19496. (org-element-at-point))))
  19497. (cond
  19498. ;; In a table, call `org-table-next-row'.
  19499. ((or (and (eq (org-element-type context) 'table)
  19500. (>= (point) (org-element-property :contents-begin context))
  19501. (< (point) (org-element-property :contents-end context)))
  19502. (org-element-lineage context '(table-row table-cell) t))
  19503. (org-table-justify-field-maybe)
  19504. (call-interactively #'org-table-next-row))
  19505. ;; On a link or a timestamp, call `org-open-at-point' if
  19506. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19507. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19508. ((and org-return-follows-link
  19509. (or (org-in-regexp org-ts-regexp-both nil t)
  19510. (org-in-regexp org-tsr-regexp-both nil t)
  19511. (org-in-regexp org-any-link-re nil t)))
  19512. (call-interactively #'org-open-at-point))
  19513. ;; Insert newline in heading, but preserve tags.
  19514. ((and (not (bolp))
  19515. (save-excursion (beginning-of-line)
  19516. (let ((case-fold-search nil))
  19517. (looking-at org-complex-heading-regexp))))
  19518. ;; At headline. Split line. However, if point is on keyword,
  19519. ;; priority cookie or tags, do not break any of them: add
  19520. ;; a newline after the headline instead.
  19521. (let ((tags-column (and (match-beginning 5)
  19522. (save-excursion (goto-char (match-beginning 5))
  19523. (current-column))))
  19524. (string
  19525. (when (and (match-end 4) (org-point-in-group (point) 4))
  19526. (delete-and-extract-region (point) (match-end 4)))))
  19527. ;; Adjust tag alignment.
  19528. (cond
  19529. ((not (and tags-column string)))
  19530. (org-auto-align-tags (org-set-tags nil t))
  19531. (t (org--align-tags-here tags-column))) ;preserve tags column
  19532. (end-of-line)
  19533. (org-show-entry)
  19534. (if indent (newline-and-indent) (newline))
  19535. (when string (save-excursion (insert (org-trim string))))))
  19536. ;; In a list, make sure indenting keeps trailing text within.
  19537. ((and indent
  19538. (not (eolp))
  19539. (org-element-lineage context '(item)))
  19540. (let ((trailing-data
  19541. (delete-and-extract-region (point) (line-end-position))))
  19542. (newline-and-indent)
  19543. (save-excursion (insert trailing-data))))
  19544. (t (if indent (newline-and-indent) (newline))))))
  19545. (defun org-return-indent ()
  19546. "Goto next table row or insert a newline and indent.
  19547. Calls `org-table-next-row' or `newline-and-indent', depending on
  19548. context. See the individual commands for more information."
  19549. (interactive)
  19550. (org-return t))
  19551. (defun org-ctrl-c-star ()
  19552. "Compute table, or change heading status of lines.
  19553. Calls `org-table-recalculate' or `org-toggle-heading',
  19554. depending on context."
  19555. (interactive)
  19556. (cond
  19557. ((org-at-table-p)
  19558. (call-interactively 'org-table-recalculate))
  19559. (t
  19560. ;; Convert all lines in region to list items
  19561. (call-interactively 'org-toggle-heading))))
  19562. (defun org-ctrl-c-minus ()
  19563. "Insert separator line in table or modify bullet status of line.
  19564. Also turns a plain line or a region of lines into list items.
  19565. Calls `org-table-insert-hline', `org-toggle-item', or
  19566. `org-cycle-list-bullet', depending on context."
  19567. (interactive)
  19568. (cond
  19569. ((org-at-table-p)
  19570. (call-interactively 'org-table-insert-hline))
  19571. ((org-region-active-p)
  19572. (call-interactively 'org-toggle-item))
  19573. ((org-in-item-p)
  19574. (call-interactively 'org-cycle-list-bullet))
  19575. (t
  19576. (call-interactively 'org-toggle-item))))
  19577. (defun org-toggle-heading (&optional nstars)
  19578. "Convert headings to normal text, or items or text to headings.
  19579. If there is no active region, only convert the current line.
  19580. With a `\\[universal-argument]' prefix, convert the whole list at
  19581. point into heading.
  19582. In a region:
  19583. - If the first non blank line is a headline, remove the stars
  19584. from all headlines in the region.
  19585. - If it is a normal line, turn each and every normal line (i.e.,
  19586. not an heading or an item) in the region into headings. If you
  19587. want to convert only the first line of this region, use one
  19588. universal prefix argument.
  19589. - If it is a plain list item, turn all plain list items into headings.
  19590. When converting a line into a heading, the number of stars is chosen
  19591. such that the lines become children of the current entry. However,
  19592. when a numeric prefix argument is given, its value determines the
  19593. number of stars to add."
  19594. (interactive "P")
  19595. (let ((skip-blanks
  19596. (function
  19597. ;; Return beginning of first non-blank line, starting from
  19598. ;; line at POS.
  19599. (lambda (pos)
  19600. (save-excursion
  19601. (goto-char pos)
  19602. (while (org-at-comment-p) (forward-line))
  19603. (skip-chars-forward " \r\t\n")
  19604. (point-at-bol)))))
  19605. beg end toggled)
  19606. ;; Determine boundaries of changes. If a universal prefix has
  19607. ;; been given, put the list in a region. If region ends at a bol,
  19608. ;; do not consider the last line to be in the region.
  19609. (when (and current-prefix-arg (org-at-item-p))
  19610. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19611. (org-mark-element))
  19612. (if (org-region-active-p)
  19613. (setq beg (funcall skip-blanks (region-beginning))
  19614. end (copy-marker (save-excursion
  19615. (goto-char (region-end))
  19616. (if (bolp) (point) (point-at-eol)))))
  19617. (setq beg (funcall skip-blanks (point-at-bol))
  19618. end (copy-marker (point-at-eol))))
  19619. ;; Ensure inline tasks don't count as headings.
  19620. (org-with-limited-levels
  19621. (save-excursion
  19622. (goto-char beg)
  19623. (cond
  19624. ;; Case 1. Started at an heading: de-star headings.
  19625. ((org-at-heading-p)
  19626. (while (< (point) end)
  19627. (when (org-at-heading-p t)
  19628. (looking-at org-outline-regexp) (replace-match "")
  19629. (setq toggled t))
  19630. (forward-line)))
  19631. ;; Case 2. Started at an item: change items into headlines.
  19632. ;; One star will be added by `org-list-to-subtree'.
  19633. ((org-at-item-p)
  19634. (while (< (point) end)
  19635. (when (org-at-item-p)
  19636. ;; Pay attention to cases when region ends before list.
  19637. (let* ((struct (org-list-struct))
  19638. (list-end
  19639. (min (org-list-get-bottom-point struct) (1+ end))))
  19640. (save-restriction
  19641. (narrow-to-region (point) list-end)
  19642. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19643. (setq toggled t))
  19644. (forward-line)))
  19645. ;; Case 3. Started at normal text: make every line an heading,
  19646. ;; skipping headlines and items.
  19647. (t (let* ((stars
  19648. (make-string
  19649. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19650. (add-stars
  19651. (cond (nstars "") ; stars from prefix only
  19652. ((equal stars "") "*") ; before first heading
  19653. (org-odd-levels-only "**") ; inside heading, odd
  19654. (t "*"))) ; inside heading, oddeven
  19655. (rpl (concat stars add-stars " "))
  19656. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19657. (while (< (point) (if (equal nstars '(4)) lend end))
  19658. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19659. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19660. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19661. (forward-line)))))))
  19662. (unless toggled (message "Cannot toggle heading from here"))))
  19663. (defun org-meta-return (&optional _arg)
  19664. "Insert a new heading or wrap a region in a table.
  19665. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19666. on context. See the individual commands for more information."
  19667. (interactive)
  19668. (org-check-before-invisible-edit 'insert)
  19669. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19670. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19671. #'org-insert-heading))))
  19672. ;;; Menu entries
  19673. (defsubst org-in-subtree-not-table-p ()
  19674. "Are we in a subtree and not in a table?"
  19675. (and (not (org-before-first-heading-p))
  19676. (not (org-at-table-p))))
  19677. ;; Define the Org mode menus
  19678. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19679. '("Tbl"
  19680. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19681. ["Next Field" org-cycle (org-at-table-p)]
  19682. ["Previous Field" org-shifttab (org-at-table-p)]
  19683. ["Next Row" org-return (org-at-table-p)]
  19684. "--"
  19685. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19686. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19687. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19688. "--"
  19689. ("Column"
  19690. ["Move Column Left" org-metaleft (org-at-table-p)]
  19691. ["Move Column Right" org-metaright (org-at-table-p)]
  19692. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19693. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19694. ("Row"
  19695. ["Move Row Up" org-metaup (org-at-table-p)]
  19696. ["Move Row Down" org-metadown (org-at-table-p)]
  19697. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19698. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19699. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19700. "--"
  19701. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19702. ("Rectangle"
  19703. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19704. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19705. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19706. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19707. "--"
  19708. ("Calculate"
  19709. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19710. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19711. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19712. "--"
  19713. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19714. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19715. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19716. "--"
  19717. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19718. "--"
  19719. ["Sum Column/Rectangle" org-table-sum
  19720. (or (org-at-table-p) (org-region-active-p))]
  19721. ["Which Column?" org-table-current-column (org-at-table-p)])
  19722. ["Debug Formulas"
  19723. org-table-toggle-formula-debugger
  19724. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19725. ["Show Col/Row Numbers"
  19726. org-table-toggle-coordinate-overlays
  19727. :style toggle
  19728. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19729. "--"
  19730. ["Create" org-table-create (and (not (org-at-table-p))
  19731. org-enable-table-editor)]
  19732. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19733. ["Import from File" org-table-import (not (org-at-table-p))]
  19734. ["Export to File" org-table-export (org-at-table-p)]
  19735. "--"
  19736. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19737. "--"
  19738. ("Plot"
  19739. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19740. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19741. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19742. '("Org"
  19743. ("Show/Hide"
  19744. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19745. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19746. ["Sparse Tree..." org-sparse-tree t]
  19747. ["Reveal Context" org-reveal t]
  19748. ["Show All" outline-show-all t]
  19749. "--"
  19750. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19751. "--"
  19752. ["New Heading" org-insert-heading t]
  19753. ("Navigate Headings"
  19754. ["Up" outline-up-heading t]
  19755. ["Next" outline-next-visible-heading t]
  19756. ["Previous" outline-previous-visible-heading t]
  19757. ["Next Same Level" outline-forward-same-level t]
  19758. ["Previous Same Level" outline-backward-same-level t]
  19759. "--"
  19760. ["Jump" org-goto t])
  19761. ("Edit Structure"
  19762. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19763. "--"
  19764. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19765. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19766. "--"
  19767. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19768. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19769. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19770. "--"
  19771. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19772. "--"
  19773. ["Copy visible text" org-copy-visible t]
  19774. "--"
  19775. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19776. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19777. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19778. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19779. "--"
  19780. ["Sort Region/Children" org-sort t]
  19781. "--"
  19782. ["Convert to odd levels" org-convert-to-odd-levels t]
  19783. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19784. ("Editing"
  19785. ["Emphasis..." org-emphasize t]
  19786. ["Edit Source Example" org-edit-special t]
  19787. "--"
  19788. ["Footnote new/jump" org-footnote-action t]
  19789. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19790. ("Archive"
  19791. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19792. "--"
  19793. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19794. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19795. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19796. )
  19797. "--"
  19798. ("Hyperlinks"
  19799. ["Store Link (Global)" org-store-link t]
  19800. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19801. ["Insert Link" org-insert-link t]
  19802. ["Follow Link" org-open-at-point t]
  19803. "--"
  19804. ["Next link" org-next-link t]
  19805. ["Previous link" org-previous-link t]
  19806. "--"
  19807. ["Descriptive Links"
  19808. org-toggle-link-display
  19809. :style radio
  19810. :selected org-descriptive-links
  19811. ]
  19812. ["Literal Links"
  19813. org-toggle-link-display
  19814. :style radio
  19815. :selected (not org-descriptive-links)])
  19816. "--"
  19817. ("TODO Lists"
  19818. ["TODO/DONE/-" org-todo t]
  19819. ("Select keyword"
  19820. ["Next keyword" org-shiftright (org-at-heading-p)]
  19821. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19822. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19823. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19824. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19825. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19826. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19827. "--"
  19828. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19829. :selected org-enforce-todo-dependencies :style toggle :active t]
  19830. "Settings for tree at point"
  19831. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19832. :selected (org-entry-get nil "ORDERED")
  19833. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19834. ["Do Children parallel" org-toggle-ordered-property :style radio
  19835. :selected (not (org-entry-get nil "ORDERED"))
  19836. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19837. "--"
  19838. ["Set Priority" org-priority t]
  19839. ["Priority Up" org-shiftup t]
  19840. ["Priority Down" org-shiftdown t]
  19841. "--"
  19842. ["Get news from all feeds" org-feed-update-all t]
  19843. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19844. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19845. ("TAGS and Properties"
  19846. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19847. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19848. "--"
  19849. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19850. ["Column view of properties" org-columns t]
  19851. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19852. ("Dates and Scheduling"
  19853. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19854. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19855. ("Change Date"
  19856. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19857. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19858. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19859. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19860. ["Compute Time Range" org-evaluate-time-range t]
  19861. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19862. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19863. "--"
  19864. ["Custom time format" org-toggle-time-stamp-overlays
  19865. :style radio :selected org-display-custom-times]
  19866. "--"
  19867. ["Goto Calendar" org-goto-calendar t]
  19868. ["Date from Calendar" org-date-from-calendar t]
  19869. "--"
  19870. ["Start/Restart Timer" org-timer-start t]
  19871. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19872. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19873. ["Insert Timer String" org-timer t]
  19874. ["Insert Timer Item" org-timer-item t])
  19875. ("Logging work"
  19876. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19877. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19878. ["Clock out" org-clock-out t]
  19879. ["Clock cancel" org-clock-cancel t]
  19880. "--"
  19881. ["Mark as default task" org-clock-mark-default-task t]
  19882. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19883. ["Goto running clock" org-clock-goto t]
  19884. "--"
  19885. ["Display times" org-clock-display t]
  19886. ["Create clock table" org-clock-report t]
  19887. "--"
  19888. ["Record DONE time"
  19889. (progn (setq org-log-done (not org-log-done))
  19890. (message "Switching to %s will %s record a timestamp"
  19891. (car org-done-keywords)
  19892. (if org-log-done "automatically" "not")))
  19893. :style toggle :selected org-log-done])
  19894. "--"
  19895. ["Agenda Command..." org-agenda t]
  19896. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19897. ("File List for Agenda")
  19898. ("Special views current file"
  19899. ["TODO Tree" org-show-todo-tree t]
  19900. ["Check Deadlines" org-check-deadlines t]
  19901. ["Timeline" org-timeline t]
  19902. ["Tags/Property tree" org-match-sparse-tree t])
  19903. "--"
  19904. ["Export/Publish..." org-export-dispatch t]
  19905. ("LaTeX"
  19906. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19907. :selected org-cdlatex-mode]
  19908. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19909. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19910. ["Modify math symbol" org-cdlatex-math-modify
  19911. (org-inside-LaTeX-fragment-p)]
  19912. ["Insert citation" org-reftex-citation t])
  19913. "--"
  19914. ("MobileOrg"
  19915. ["Push Files and Views" org-mobile-push t]
  19916. ["Get Captured and Flagged" org-mobile-pull t]
  19917. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19918. "--"
  19919. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19920. "--"
  19921. ("Documentation"
  19922. ["Show Version" org-version t]
  19923. ["Info Documentation" org-info t])
  19924. ("Customize"
  19925. ["Browse Org Group" org-customize t]
  19926. "--"
  19927. ["Expand This Menu" org-create-customize-menu
  19928. (fboundp 'customize-menu-create)])
  19929. ["Send bug report" org-submit-bug-report t]
  19930. "--"
  19931. ("Refresh/Reload"
  19932. ["Refresh setup current buffer" org-mode-restart t]
  19933. ["Reload Org (after update)" org-reload t]
  19934. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19935. ))
  19936. (defun org-info (&optional node)
  19937. "Read documentation for Org in the info system.
  19938. With optional NODE, go directly to that node."
  19939. (interactive)
  19940. (info (format "(org)%s" (or node ""))))
  19941. ;;;###autoload
  19942. (defun org-submit-bug-report ()
  19943. "Submit a bug report on Org via mail.
  19944. Don't hesitate to report any problems or inaccurate documentation.
  19945. If you don't have setup sending mail from (X)Emacs, please copy the
  19946. output buffer into your mail program, as it gives us important
  19947. information about your Org version and configuration."
  19948. (interactive)
  19949. (require 'reporter)
  19950. (defvar reporter-prompt-for-summary-p)
  19951. (org-load-modules-maybe)
  19952. (org-require-autoloaded-modules)
  19953. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19954. (reporter-submit-bug-report
  19955. "emacs-orgmode@gnu.org"
  19956. (org-version nil 'full)
  19957. (let (list)
  19958. (save-window-excursion
  19959. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19960. (delete-other-windows)
  19961. (erase-buffer)
  19962. (insert "You are about to submit a bug report to the Org mailing list.
  19963. We would like to add your full Org and Outline configuration to the
  19964. bug report. This greatly simplifies the work of the maintainer and
  19965. other experts on the mailing list.
  19966. HOWEVER, some variables you have customized may contain private
  19967. information. The names of customers, colleagues, or friends, might
  19968. appear in the form of file names, tags, todo states, or search strings.
  19969. If you answer yes to the prompt, you might want to check and remove
  19970. such private information before sending the email.")
  19971. (add-text-properties (point-min) (point-max) '(face org-warning))
  19972. (when (yes-or-no-p "Include your Org configuration ")
  19973. (mapatoms
  19974. (lambda (v)
  19975. (and (boundp v)
  19976. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19977. (or (and (symbol-value v)
  19978. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19979. (and
  19980. (get v 'custom-type) (get v 'standard-value)
  19981. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19982. (push v list)))))
  19983. (kill-buffer (get-buffer "*Warn about privacy*"))
  19984. list))
  19985. nil nil
  19986. "Remember to cover the basics, that is, what you expected to happen and
  19987. what in fact did happen. You don't know how to make a good report? See
  19988. http://orgmode.org/manual/Feedback.html#Feedback
  19989. Your bug report will be posted to the Org mailing list.
  19990. ------------------------------------------------------------------------")
  19991. (save-excursion
  19992. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19993. (replace-match "\\1Bug: \\3 [\\2]")))))
  19994. (defun org-install-agenda-files-menu ()
  19995. (let ((bl (buffer-list)))
  19996. (save-excursion
  19997. (while bl
  19998. (set-buffer (pop bl))
  19999. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20000. (when (derived-mode-p 'org-mode)
  20001. (easy-menu-change
  20002. '("Org") "File List for Agenda"
  20003. (append
  20004. (list
  20005. ["Edit File List" (org-edit-agenda-file-list) t]
  20006. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20007. ["Remove Current File from List" org-remove-file t]
  20008. ["Cycle through agenda files" org-cycle-agenda-files t]
  20009. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20010. "--")
  20011. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20012. ;;;; Documentation
  20013. (defun org-require-autoloaded-modules ()
  20014. (interactive)
  20015. (mapc #'require
  20016. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20017. org-table org-timer)))
  20018. ;;;###autoload
  20019. (defun org-reload (&optional uncompiled)
  20020. "Reload all org lisp files.
  20021. With prefix arg UNCOMPILED, load the uncompiled versions."
  20022. (interactive "P")
  20023. (require 'loadhist)
  20024. (let* ((org-dir (org-find-library-dir "org"))
  20025. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20026. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20027. (remove-re (format "\\`%s\\'"
  20028. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20029. (feats (delete-dups
  20030. (mapcar 'file-name-sans-extension
  20031. (mapcar 'file-name-nondirectory
  20032. (delq nil
  20033. (mapcar 'feature-file
  20034. features))))))
  20035. (lfeat (append
  20036. (sort
  20037. (setq feats
  20038. (delq nil (mapcar
  20039. (lambda (f)
  20040. (if (and (string-match feature-re f)
  20041. (not (string-match remove-re f)))
  20042. f nil))
  20043. feats)))
  20044. 'string-lessp)
  20045. (list "org-version" "org")))
  20046. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20047. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20048. load-uncore load-misses)
  20049. (setq load-misses
  20050. (delq 't
  20051. (mapcar (lambda (f)
  20052. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20053. (and (string= org-dir contrib-dir)
  20054. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20055. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20056. (add-to-list 'load-uncore f 'append)
  20057. 't)
  20058. f))
  20059. lfeat)))
  20060. (when load-uncore
  20061. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20062. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20063. (if load-misses
  20064. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20065. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20066. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20067. ;;;###autoload
  20068. (defun org-customize ()
  20069. "Call the customize function with org as argument."
  20070. (interactive)
  20071. (org-load-modules-maybe)
  20072. (org-require-autoloaded-modules)
  20073. (customize-browse 'org))
  20074. (defun org-create-customize-menu ()
  20075. "Create a full customization menu for Org mode, insert it into the menu."
  20076. (interactive)
  20077. (org-load-modules-maybe)
  20078. (org-require-autoloaded-modules)
  20079. (if (fboundp 'customize-menu-create)
  20080. (progn
  20081. (easy-menu-change
  20082. '("Org") "Customize"
  20083. `(["Browse Org group" org-customize t]
  20084. "--"
  20085. ,(customize-menu-create 'org)
  20086. ["Set" Custom-set t]
  20087. ["Save" Custom-save t]
  20088. ["Reset to Current" Custom-reset-current t]
  20089. ["Reset to Saved" Custom-reset-saved t]
  20090. ["Reset to Standard Settings" Custom-reset-standard t]))
  20091. (message "\"Org\"-menu now contains full customization menu"))
  20092. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20093. ;;;; Miscellaneous stuff
  20094. ;;; Generally useful functions
  20095. (defun org-get-at-eol (property n)
  20096. "Get text property PROPERTY at the end of line less N characters."
  20097. (get-text-property (- (point-at-eol) n) property))
  20098. (defun org-find-text-property-in-string (prop s)
  20099. "Return the first non-nil value of property PROP in string S."
  20100. (or (get-text-property 0 prop s)
  20101. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20102. prop s)))
  20103. (defun org-display-warning (message)
  20104. "Display the given MESSAGE as a warning."
  20105. (display-warning 'org message :warning))
  20106. (defun org-eval (form)
  20107. "Eval FORM and return result."
  20108. (condition-case error
  20109. (eval form)
  20110. (error (format "%%![Error: %s]" error))))
  20111. (defun org-in-clocktable-p ()
  20112. "Check if the cursor is in a clocktable."
  20113. (let ((pos (point)) start)
  20114. (save-excursion
  20115. (end-of-line 1)
  20116. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20117. (setq start (match-beginning 0))
  20118. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20119. (>= (match-end 0) pos)
  20120. start))))
  20121. (defun org-in-verbatim-emphasis ()
  20122. (save-match-data
  20123. (and (org-in-regexp org-emph-re 2)
  20124. (>= (point) (match-beginning 3))
  20125. (<= (point) (match-end 4))
  20126. (member (match-string 3) '("=" "~")))))
  20127. (defun org-overlay-display (ovl text &optional face evap)
  20128. "Make overlay OVL display TEXT with face FACE."
  20129. (overlay-put ovl 'display text)
  20130. (if face (overlay-put ovl 'face face))
  20131. (if evap (overlay-put ovl 'evaporate t)))
  20132. (defun org-overlay-before-string (ovl text &optional face evap)
  20133. "Make overlay OVL display TEXT with face FACE."
  20134. (if face (org-add-props text nil 'face face))
  20135. (overlay-put ovl 'before-string text)
  20136. (if evap (overlay-put ovl 'evaporate t)))
  20137. (defun org-find-overlays (prop &optional pos delete)
  20138. "Find all overlays specifying PROP at POS or point.
  20139. If DELETE is non-nil, delete all those overlays."
  20140. (let (found)
  20141. (dolist (ov (overlays-at (or pos (point))) found)
  20142. (cond ((not (overlay-get ov prop)))
  20143. (delete (delete-overlay ov))
  20144. (t (push ov found))))))
  20145. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20146. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20147. (if (and marker (marker-buffer marker)
  20148. (buffer-live-p (marker-buffer marker)))
  20149. (progn
  20150. (pop-to-buffer-same-window (marker-buffer marker))
  20151. (when (or (> marker (point-max)) (< marker (point-min)))
  20152. (widen))
  20153. (goto-char marker)
  20154. (org-show-context 'org-goto))
  20155. (if bookmark
  20156. (bookmark-jump bookmark)
  20157. (error "Cannot find location"))))
  20158. (defun org-quote-csv-field (s)
  20159. "Quote field for inclusion in CSV material."
  20160. (if (string-match "[\",]" s)
  20161. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20162. s))
  20163. (defun org-force-self-insert (N)
  20164. "Needed to enforce self-insert under remapping."
  20165. (interactive "p")
  20166. (self-insert-command N))
  20167. (defun org-string-width (s)
  20168. "Compute width of string, ignoring invisible characters.
  20169. This ignores character with invisibility property `org-link', and also
  20170. characters with property `org-cwidth', because these will become invisible
  20171. upon the next fontification round."
  20172. (let (b l)
  20173. (when (or (eq t buffer-invisibility-spec)
  20174. (assq 'org-link buffer-invisibility-spec))
  20175. (while (setq b (text-property-any 0 (length s)
  20176. 'invisible 'org-link s))
  20177. (setq s (concat (substring s 0 b)
  20178. (substring s (or (next-single-property-change
  20179. b 'invisible s)
  20180. (length s)))))))
  20181. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20182. (setq s (concat (substring s 0 b)
  20183. (substring s (or (next-single-property-change
  20184. b 'org-cwidth s)
  20185. (length s))))))
  20186. (setq l (string-width s) b -1)
  20187. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20188. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20189. l))
  20190. (defun org-shorten-string (s maxlength)
  20191. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20192. If the string is shorter or has length MAXLENGTH, just return the
  20193. original string. If it is longer, the functions finds a space in the
  20194. string, breaks this string off at that locations and adds three dots
  20195. as ellipsis. Including the ellipsis, the string will not be longer
  20196. than MAXLENGTH. If finding a good breaking point in the string does
  20197. not work, the string is just chopped off in the middle of a word
  20198. if necessary."
  20199. (if (<= (length s) maxlength)
  20200. s
  20201. (let* ((n (max (- maxlength 4) 1))
  20202. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20203. (if (string-match re s)
  20204. (concat (match-string 1 s) "...")
  20205. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20206. (defun org-get-indentation (&optional line)
  20207. "Get the indentation of the current line, interpreting tabs.
  20208. When LINE is given, assume it represents a line and compute its indentation."
  20209. (if line
  20210. (when (string-match "^ *" (org-remove-tabs line))
  20211. (match-end 0))
  20212. (save-excursion
  20213. (beginning-of-line 1)
  20214. (skip-chars-forward " \t")
  20215. (current-column))))
  20216. (defun org-get-string-indentation (s)
  20217. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20218. (let ((n -1) (i 0) (w tab-width) c)
  20219. (catch 'exit
  20220. (while (< (setq n (1+ n)) (length s))
  20221. (setq c (aref s n))
  20222. (cond ((= c ?\ ) (setq i (1+ i)))
  20223. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20224. (t (throw 'exit t)))))
  20225. i))
  20226. (defun org-remove-tabs (s &optional width)
  20227. "Replace tabulators in S with spaces.
  20228. Assumes that s is a single line, starting in column 0."
  20229. (setq width (or width tab-width))
  20230. (while (string-match "\t" s)
  20231. (setq s (replace-match
  20232. (make-string
  20233. (- (* width (/ (+ (match-beginning 0) width) width))
  20234. (match-beginning 0)) ?\ )
  20235. t t s)))
  20236. s)
  20237. (defun org-fix-indentation (line ind)
  20238. "Fix indentation in LINE.
  20239. IND is a cons cell with target and minimum indentation.
  20240. If the current indentation in LINE is smaller than the minimum,
  20241. leave it alone. If it is larger than ind, set it to the target."
  20242. (let* ((l (org-remove-tabs line))
  20243. (i (org-get-indentation l))
  20244. (i1 (car ind)) (i2 (cdr ind)))
  20245. (when (>= i i2) (setq l (substring line i2)))
  20246. (if (> i1 0)
  20247. (concat (make-string i1 ?\ ) l)
  20248. l)))
  20249. (defun org-remove-indentation (code &optional n)
  20250. "Remove maximum common indentation in string CODE and return it.
  20251. N may optionally be the number of columns to remove. Return CODE
  20252. as-is if removal failed."
  20253. (with-temp-buffer
  20254. (insert code)
  20255. (if (org-do-remove-indentation n) (buffer-string) code)))
  20256. (defun org-do-remove-indentation (&optional n)
  20257. "Remove the maximum common indentation from the buffer.
  20258. When optional argument N is a positive integer, remove exactly
  20259. that much characters from indentation, if possible. Return nil
  20260. if it fails."
  20261. (catch :exit
  20262. (goto-char (point-min))
  20263. ;; Find maximum common indentation, if not specified.
  20264. (let ((n (or n
  20265. (let ((min-ind (point-max)))
  20266. (save-excursion
  20267. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20268. (let ((ind (1- (current-column))))
  20269. (if (zerop ind) (throw :exit nil)
  20270. (setq min-ind (min min-ind ind))))))
  20271. min-ind))))
  20272. (if (zerop n) (throw :exit nil)
  20273. ;; Remove exactly N indentation, but give up if not possible.
  20274. (while (not (eobp))
  20275. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20276. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20277. ((< ind n) (throw :exit nil))
  20278. (t (indent-line-to (- ind n))))
  20279. (forward-line)))
  20280. ;; Signal success.
  20281. t))))
  20282. (defun org-fill-template (template alist)
  20283. "Find each %key of ALIST in TEMPLATE and replace it."
  20284. (let ((case-fold-search nil))
  20285. (dolist (entry (sort (copy-sequence alist)
  20286. (lambda (a b) (< (length (car a)) (length (car b))))))
  20287. (setq template
  20288. (replace-regexp-in-string
  20289. (concat "%" (regexp-quote (car entry)))
  20290. (or (cdr entry) "") template t t)))
  20291. template))
  20292. (defun org-base-buffer (buffer)
  20293. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20294. (if (not buffer)
  20295. buffer
  20296. (or (buffer-base-buffer buffer)
  20297. buffer)))
  20298. (defun org-wrap (string &optional width lines)
  20299. "Wrap string to either a number of lines, or a width in characters.
  20300. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20301. that costs. If there is a word longer than WIDTH, the text is actually
  20302. wrapped to the length of that word.
  20303. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20304. many lines, whatever width that takes.
  20305. The return value is a list of lines, without newlines at the end."
  20306. (let* ((words (org-split-string string "[ \t\n]+"))
  20307. (maxword (apply 'max (mapcar 'org-string-width words)))
  20308. w ll)
  20309. (cond (width
  20310. (org-do-wrap words (max maxword width)))
  20311. (lines
  20312. (setq w maxword)
  20313. (setq ll (org-do-wrap words maxword))
  20314. (if (<= (length ll) lines)
  20315. ll
  20316. (setq ll words)
  20317. (while (> (length ll) lines)
  20318. (setq w (1+ w))
  20319. (setq ll (org-do-wrap words w)))
  20320. ll))
  20321. (t (error "Cannot wrap this")))))
  20322. (defun org-do-wrap (words width)
  20323. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20324. (let (lines line)
  20325. (while words
  20326. (setq line (pop words))
  20327. (while (and words (< (+ (length line) (length (car words))) width))
  20328. (setq line (concat line " " (pop words))))
  20329. (setq lines (push line lines)))
  20330. (nreverse lines)))
  20331. (defun org-split-string (string &optional separators)
  20332. "Splits STRING into substrings at SEPARATORS.
  20333. SEPARATORS is a regular expression.
  20334. No empty strings are returned if there are matches at the beginning
  20335. and end of string."
  20336. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20337. (let ((start 0) notfirst list)
  20338. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20339. (if (and notfirst
  20340. (= start (match-beginning 0))
  20341. (< start (length string)))
  20342. (1+ start) start))
  20343. (< (match-beginning 0) (length string)))
  20344. (setq notfirst t)
  20345. (or (eq (match-beginning 0) 0)
  20346. (and (eq (match-beginning 0) (match-end 0))
  20347. (eq (match-beginning 0) start))
  20348. (push (substring string start (match-beginning 0)) list))
  20349. (setq start (match-end 0)))
  20350. (or (eq start (length string))
  20351. (push (substring string start) list))
  20352. (nreverse list)))
  20353. (defun org-quote-vert (s)
  20354. "Replace \"|\" with \"\\vert\"."
  20355. (while (string-match "|" s)
  20356. (setq s (replace-match "\\vert" t t s)))
  20357. s)
  20358. (defun org-uuidgen-p (s)
  20359. "Is S an ID created by UUIDGEN?"
  20360. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20361. (defun org-in-src-block-p (&optional inside)
  20362. "Whether point is in a code source block.
  20363. When INSIDE is non-nil, don't consider we are within a src block
  20364. when point is at #+BEGIN_SRC or #+END_SRC."
  20365. (let ((case-fold-search t))
  20366. (or (and (eq (get-char-property (point) 'src-block) t))
  20367. (and (not inside)
  20368. (save-match-data
  20369. (save-excursion
  20370. (beginning-of-line)
  20371. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20372. (defun org-context ()
  20373. "Return a list of contexts of the current cursor position.
  20374. If several contexts apply, all are returned.
  20375. Each context entry is a list with a symbol naming the context, and
  20376. two positions indicating start and end of the context. Possible
  20377. contexts are:
  20378. :headline anywhere in a headline
  20379. :headline-stars on the leading stars in a headline
  20380. :todo-keyword on a TODO keyword (including DONE) in a headline
  20381. :tags on the TAGS in a headline
  20382. :priority on the priority cookie in a headline
  20383. :item on the first line of a plain list item
  20384. :item-bullet on the bullet/number of a plain list item
  20385. :checkbox on the checkbox in a plain list item
  20386. :table in an Org table
  20387. :table-special on a special filed in a table
  20388. :table-table in a table.el table
  20389. :clocktable in a clocktable
  20390. :src-block in a source block
  20391. :link on a hyperlink
  20392. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20393. :target on a <<target>>
  20394. :radio-target on a <<<radio-target>>>
  20395. :latex-fragment on a LaTeX fragment
  20396. :latex-preview on a LaTeX fragment with overlaid preview image
  20397. This function expects the position to be visible because it uses font-lock
  20398. faces as a help to recognize the following contexts: :table-special, :link,
  20399. and :keyword."
  20400. (let* ((f (get-text-property (point) 'face))
  20401. (faces (if (listp f) f (list f)))
  20402. (case-fold-search t)
  20403. (p (point)) clist o)
  20404. ;; First the large context
  20405. (cond
  20406. ((org-at-heading-p t)
  20407. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20408. (when (progn
  20409. (beginning-of-line 1)
  20410. (looking-at org-todo-line-tags-regexp))
  20411. (push (org-point-in-group p 1 :headline-stars) clist)
  20412. (push (org-point-in-group p 2 :todo-keyword) clist)
  20413. (push (org-point-in-group p 4 :tags) clist))
  20414. (goto-char p)
  20415. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20416. (when (looking-at "\\[#[A-Z0-9]\\]")
  20417. (push (org-point-in-group p 0 :priority) clist)))
  20418. ((org-at-item-p)
  20419. (push (org-point-in-group p 2 :item-bullet) clist)
  20420. (push (list :item (point-at-bol)
  20421. (save-excursion (org-end-of-item) (point)))
  20422. clist)
  20423. (and (org-at-item-checkbox-p)
  20424. (push (org-point-in-group p 0 :checkbox) clist)))
  20425. ((org-at-table-p)
  20426. (push (list :table (org-table-begin) (org-table-end)) clist)
  20427. (when (memq 'org-formula faces)
  20428. (push (list :table-special
  20429. (previous-single-property-change p 'face)
  20430. (next-single-property-change p 'face)) clist)))
  20431. ((org-at-table-p 'any)
  20432. (push (list :table-table) clist)))
  20433. (goto-char p)
  20434. (let ((case-fold-search t))
  20435. ;; New the "medium" contexts: clocktables, source blocks
  20436. (cond ((org-in-clocktable-p)
  20437. (push (list :clocktable
  20438. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20439. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20440. (match-beginning 1))
  20441. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20442. (match-end 0))) clist))
  20443. ((org-in-src-block-p)
  20444. (push (list :src-block
  20445. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20446. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20447. (match-beginning 1))
  20448. (and (search-forward "#+END_SRC" nil t)
  20449. (match-beginning 0))) clist))))
  20450. (goto-char p)
  20451. ;; Now the small context
  20452. (cond
  20453. ((org-at-timestamp-p)
  20454. (push (org-point-in-group p 0 :timestamp) clist))
  20455. ((memq 'org-link faces)
  20456. (push (list :link
  20457. (previous-single-property-change p 'face)
  20458. (next-single-property-change p 'face)) clist))
  20459. ((memq 'org-special-keyword faces)
  20460. (push (list :keyword
  20461. (previous-single-property-change p 'face)
  20462. (next-single-property-change p 'face)) clist))
  20463. ((org-at-target-p)
  20464. (push (org-point-in-group p 0 :target) clist)
  20465. (goto-char (1- (match-beginning 0)))
  20466. (when (looking-at org-radio-target-regexp)
  20467. (push (org-point-in-group p 0 :radio-target) clist))
  20468. (goto-char p))
  20469. ((setq o (cl-some
  20470. (lambda (o)
  20471. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20472. o))
  20473. (overlays-at (point))))
  20474. (push (list :latex-fragment
  20475. (overlay-start o) (overlay-end o)) clist)
  20476. (push (list :latex-preview
  20477. (overlay-start o) (overlay-end o)) clist))
  20478. ((org-inside-LaTeX-fragment-p)
  20479. ;; FIXME: positions wrong.
  20480. (push (list :latex-fragment (point) (point)) clist)))
  20481. (setq clist (nreverse (delq nil clist)))
  20482. clist))
  20483. (defun org-in-regexp (regexp &optional nlines visually)
  20484. "Check if point is inside a match of REGEXP.
  20485. Normally only the current line is checked, but you can include
  20486. NLINES extra lines around point into the search. If VISUALLY is
  20487. set, require that the cursor is not after the match but really
  20488. on, so that the block visually is on the match.
  20489. Return nil or a cons cell (BEG . END) where BEG and END are,
  20490. respectively, the positions at the beginning and the end of the
  20491. match."
  20492. (catch :exit
  20493. (let ((pos (point))
  20494. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20495. (save-excursion
  20496. (beginning-of-line (- 1 (or nlines 0)))
  20497. (while (and (re-search-forward regexp eol t)
  20498. (<= (match-beginning 0) pos))
  20499. (let ((end (match-end 0)))
  20500. (when (or (> end pos) (and (= end pos) (not visually)))
  20501. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20502. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20503. "Non-nil when point is between matches of START-RE and END-RE.
  20504. Also return a non-nil value when point is on one of the matches.
  20505. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20506. buffer positions. Default values are the positions of headlines
  20507. surrounding the point.
  20508. The functions returns a cons cell whose car (resp. cdr) is the
  20509. position before START-RE (resp. after END-RE)."
  20510. (save-match-data
  20511. (let ((pos (point))
  20512. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20513. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20514. beg end)
  20515. (save-excursion
  20516. ;; Point is on a block when on START-RE or if START-RE can be
  20517. ;; found before it...
  20518. (and (or (org-in-regexp start-re)
  20519. (re-search-backward start-re limit-up t))
  20520. (setq beg (match-beginning 0))
  20521. ;; ... and END-RE after it...
  20522. (goto-char (match-end 0))
  20523. (re-search-forward end-re limit-down t)
  20524. (> (setq end (match-end 0)) pos)
  20525. ;; ... without another START-RE in-between.
  20526. (goto-char (match-beginning 0))
  20527. (not (re-search-backward start-re (1+ beg) t))
  20528. ;; Return value.
  20529. (cons beg end))))))
  20530. (defun org-in-block-p (names)
  20531. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20532. NAMES is a list of strings containing names of blocks.
  20533. Return first block name matched, or nil. Beware that in case of
  20534. nested blocks, the returned name may not belong to the closest
  20535. block from point."
  20536. (save-match-data
  20537. (catch 'exit
  20538. (let ((case-fold-search t)
  20539. (lim-up (save-excursion (outline-previous-heading)))
  20540. (lim-down (save-excursion (outline-next-heading))))
  20541. (dolist (name names)
  20542. (let ((n (regexp-quote name)))
  20543. (when (org-between-regexps-p
  20544. (concat "^[ \t]*#\\+begin_" n)
  20545. (concat "^[ \t]*#\\+end_" n)
  20546. lim-up lim-down)
  20547. (throw 'exit n)))))
  20548. nil)))
  20549. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20550. "Call `multi-occur' with buffers for all agenda files."
  20551. (interactive "sOrg-files matching: ")
  20552. (let* ((files (org-agenda-files))
  20553. (tnames (mapcar #'file-truename files))
  20554. (extra org-agenda-text-search-extra-files))
  20555. (when (eq (car extra) 'agenda-archives)
  20556. (setq extra (cdr extra))
  20557. (setq files (org-add-archive-files files)))
  20558. (dolist (f extra)
  20559. (unless (member (file-truename f) tnames)
  20560. (unless (member f files) (setq files (append files (list f))))
  20561. (setq tnames (append tnames (list (file-truename f))))))
  20562. (multi-occur
  20563. (mapcar (lambda (x)
  20564. (with-current-buffer
  20565. ;; FIXME: Why not just (find-file-noselect x)?
  20566. ;; Is it to avoid the "revert buffer" prompt?
  20567. (or (get-file-buffer x) (find-file-noselect x))
  20568. (widen)
  20569. (current-buffer)))
  20570. files)
  20571. regexp)))
  20572. (add-hook 'occur-mode-find-occurrence-hook
  20573. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20574. (defun org-occur-link-in-agenda-files ()
  20575. "Create a link and search for it in the agendas.
  20576. The link is not stored in `org-stored-links', it is just created
  20577. for the search purpose."
  20578. (interactive)
  20579. (let ((link (condition-case nil
  20580. (org-store-link nil)
  20581. (error "Unable to create a link to here"))))
  20582. (org-occur-in-agenda-files (regexp-quote link))))
  20583. (defun org-reverse-string (string)
  20584. "Return the reverse of STRING."
  20585. (apply 'string (reverse (string-to-list string))))
  20586. ;; defsubst org-uniquify must be defined before first use
  20587. (defun org-uniquify-alist (alist)
  20588. "Merge elements of ALIST with the same key.
  20589. For example, in this alist:
  20590. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20591. => \\='((a 1 3) (b 2))
  20592. merge (a 1) and (a 3) into (a 1 3).
  20593. The function returns the new ALIST."
  20594. (let (rtn)
  20595. (dolist (e alist rtn)
  20596. (let (n)
  20597. (if (not (assoc (car e) rtn))
  20598. (push e rtn)
  20599. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20600. (setq rtn (assq-delete-all (car e) rtn))
  20601. (push n rtn))))))
  20602. (defun org-delete-all (elts list)
  20603. "Remove all elements in ELTS from LIST.
  20604. Comparison is done with `equal'. It is a destructive operation
  20605. that may remove elements by altering the list structure."
  20606. (while elts
  20607. (setq list (delete (pop elts) list)))
  20608. list)
  20609. (defun org-back-over-empty-lines ()
  20610. "Move backwards over whitespace, to the beginning of the first empty line.
  20611. Returns the number of empty lines passed."
  20612. (let ((pos (point)))
  20613. (if (cdr (assq 'heading org-blank-before-new-entry))
  20614. (skip-chars-backward " \t\n\r")
  20615. (unless (eobp)
  20616. (forward-line -1)))
  20617. (beginning-of-line 2)
  20618. (goto-char (min (point) pos))
  20619. (count-lines (point) pos)))
  20620. (defun org-skip-whitespace ()
  20621. (skip-chars-forward " \t\n\r"))
  20622. (defun org-point-in-group (point group &optional context)
  20623. "Check if POINT is in match-group GROUP.
  20624. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20625. match. If the match group does not exist or point is not inside it,
  20626. return nil."
  20627. (and (match-beginning group)
  20628. (>= point (match-beginning group))
  20629. (<= point (match-end group))
  20630. (if context
  20631. (list context (match-beginning group) (match-end group))
  20632. t)))
  20633. (defun org-switch-to-buffer-other-window (&rest args)
  20634. "Switch to buffer in a second window on the current frame.
  20635. In particular, do not allow pop-up frames.
  20636. Returns the newly created buffer."
  20637. (org-no-popups
  20638. (apply 'switch-to-buffer-other-window args)))
  20639. (defun org-combine-plists (&rest plists)
  20640. "Create a single property list from all plists in PLISTS.
  20641. The process starts by copying the first list, and then setting properties
  20642. from the other lists. Settings in the last list are the most significant
  20643. ones and overrule settings in the other lists."
  20644. (let ((rtn (copy-sequence (pop plists)))
  20645. p v ls)
  20646. (while plists
  20647. (setq ls (pop plists))
  20648. (while ls
  20649. (setq p (pop ls) v (pop ls))
  20650. (setq rtn (plist-put rtn p v))))
  20651. rtn))
  20652. (defun org-replace-escapes (string table)
  20653. "Replace %-escapes in STRING with values in TABLE.
  20654. TABLE is an association list with keys like \"%a\" and string values.
  20655. The sequences in STRING may contain normal field width and padding information,
  20656. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20657. so values can contain further %-escapes if they are define later in TABLE."
  20658. (let ((tbl (copy-alist table))
  20659. (case-fold-search nil)
  20660. (pchg 0)
  20661. re rpl)
  20662. (dolist (e tbl)
  20663. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20664. (when (and (cdr e) (string-match re (cdr e)))
  20665. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20666. (safe "SREF"))
  20667. (add-text-properties 0 3 (list 'sref sref) safe)
  20668. (setcdr e (replace-match safe t t (cdr e)))))
  20669. (while (string-match re string)
  20670. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20671. (cdr e)))
  20672. (setq string (replace-match rpl t t string))))
  20673. (while (setq pchg (next-property-change pchg string))
  20674. (let ((sref (get-text-property pchg 'sref string)))
  20675. (when (and sref (string-match "SREF" string pchg))
  20676. (setq string (replace-match sref t t string)))))
  20677. string))
  20678. (defun org-find-base-buffer-visiting (file)
  20679. "Like `find-buffer-visiting' but always return the base buffer and
  20680. not an indirect buffer."
  20681. (let ((buf (or (get-file-buffer file)
  20682. (find-buffer-visiting file))))
  20683. (if buf
  20684. (or (buffer-base-buffer buf) buf)
  20685. nil)))
  20686. ;;; TODO: Only called once, from ox-odt which should probably use
  20687. ;;; org-export-inline-image-p or something.
  20688. (defun org-file-image-p (file)
  20689. "Return non-nil if FILE is an image."
  20690. (save-match-data
  20691. (string-match (image-file-name-regexp) file)))
  20692. (defun org-get-cursor-date (&optional with-time)
  20693. "Return the date at cursor in as a time.
  20694. This works in the calendar and in the agenda, anywhere else it just
  20695. returns the current time.
  20696. If WITH-TIME is non-nil, returns the time of the event at point (in
  20697. the agenda) or the current time of the day."
  20698. (let (date day defd tp hod mod)
  20699. (when with-time
  20700. (setq tp (get-text-property (point) 'time))
  20701. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20702. (setq hod (string-to-number (match-string 1 tp))
  20703. mod (string-to-number (match-string 2 tp))))
  20704. (or tp (let ((now (decode-time)))
  20705. (setq hod (nth 2 now)
  20706. mod (nth 1 now)))))
  20707. (cond
  20708. ((eq major-mode 'calendar-mode)
  20709. (setq date (calendar-cursor-to-date)
  20710. defd (encode-time 0 (or mod 0) (or hod 0)
  20711. (nth 1 date) (nth 0 date) (nth 2 date))))
  20712. ((eq major-mode 'org-agenda-mode)
  20713. (setq day (get-text-property (point) 'day))
  20714. (when day
  20715. (setq date (calendar-gregorian-from-absolute day)
  20716. defd (encode-time 0 (or mod 0) (or hod 0)
  20717. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20718. (or defd (current-time))))
  20719. (defun org-mark-subtree (&optional up)
  20720. "Mark the current subtree.
  20721. This puts point at the start of the current subtree, and mark at
  20722. the end. If a numeric prefix UP is given, move up into the
  20723. hierarchy of headlines by UP levels before marking the subtree."
  20724. (interactive "P")
  20725. (org-with-limited-levels
  20726. (cond ((org-at-heading-p) (beginning-of-line))
  20727. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20728. (t (outline-previous-visible-heading 1))))
  20729. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20730. (if (called-interactively-p 'any)
  20731. (call-interactively 'org-mark-element)
  20732. (org-mark-element)))
  20733. (defun org-file-newer-than-p (file time)
  20734. "Non-nil if FILE is newer than TIME.
  20735. FILE is a filename, as a string, TIME is a list of integers, as
  20736. returned by, e.g., `current-time'."
  20737. (and (file-exists-p file)
  20738. ;; Only compare times up to whole seconds as some file-systems
  20739. ;; (e.g. HFS+) do not retain any finer granularity. As
  20740. ;; a consequence, make sure we return non-nil when the two
  20741. ;; times are equal.
  20742. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20743. (cl-subseq time 0 2)))))
  20744. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20745. "Compile a SOURCE file using PROCESS.
  20746. PROCESS is either a function or a list of shell commands, as
  20747. strings. EXT is a file extension, without the leading dot, as
  20748. a string. It is used to check if the process actually succeeded.
  20749. PROCESS must create a file with the same base name and directory
  20750. as SOURCE, but ending with EXT. The function then returns its
  20751. filename. Otherwise, it raises an error. The error message can
  20752. then be refined by providing string ERR-MSG, which is appended to
  20753. the standard message.
  20754. If PROCESS is a function, it is called with a single argument:
  20755. the SOURCE file.
  20756. If it is a list of commands, each of them is called using
  20757. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20758. %O are replaced with, respectively, SOURCE base name, name, full
  20759. name, directory and absolute output file name. It is possible,
  20760. however, to use more place-holders by specifying them in optional
  20761. argument SPEC, as an alist following the pattern
  20762. (CHARACTER . REPLACEMENT-STRING).
  20763. When PROCESS is a list of commands, optional argument LOG-BUF can
  20764. be set to a buffer or a buffer name. `shell-command' then uses
  20765. it for output."
  20766. (let* ((base-name (file-name-base source))
  20767. (full-name (file-truename source))
  20768. (out-dir (or (file-name-directory source) "./"))
  20769. (output (expand-file-name (concat base-name "." ext) out-dir))
  20770. (time (current-time))
  20771. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20772. (save-window-excursion
  20773. (pcase process
  20774. ((pred functionp) (funcall process (shell-quote-argument source)))
  20775. ((pred consp)
  20776. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20777. (spec (append spec
  20778. `((?b . ,(shell-quote-argument base-name))
  20779. (?f . ,(shell-quote-argument source))
  20780. (?F . ,(shell-quote-argument full-name))
  20781. (?o . ,(shell-quote-argument out-dir))
  20782. (?O . ,(shell-quote-argument output))))))
  20783. (dolist (command process)
  20784. (shell-command (format-spec command spec) log-buf))))
  20785. (_ (error "No valid command to process %S%s" source err-msg))))
  20786. ;; Check for process failure. Output file is expected to be
  20787. ;; located in the same directory as SOURCE.
  20788. (unless (org-file-newer-than-p output time)
  20789. (error (format "File %S wasn't produced%s" output err-msg)))
  20790. output))
  20791. ;;; Indentation
  20792. (defvar org-element-greater-elements)
  20793. (defun org--get-expected-indentation (element contentsp)
  20794. "Expected indentation column for current line, according to ELEMENT.
  20795. ELEMENT is an element containing point. CONTENTSP is non-nil
  20796. when indentation is to be computed according to contents of
  20797. ELEMENT."
  20798. (let ((type (org-element-type element))
  20799. (start (org-element-property :begin element))
  20800. (post-affiliated (org-element-property :post-affiliated element)))
  20801. (org-with-wide-buffer
  20802. (cond
  20803. (contentsp
  20804. (cl-case type
  20805. ((diary-sexp footnote-definition) 0)
  20806. ((headline inlinetask nil)
  20807. (if (not org-adapt-indentation) 0
  20808. (let ((level (org-current-level)))
  20809. (if level (1+ level) 0))))
  20810. ((item plain-list) (org-list-item-body-column post-affiliated))
  20811. (t
  20812. (goto-char start)
  20813. (org-get-indentation))))
  20814. ((memq type '(headline inlinetask nil))
  20815. (if (org-match-line "[ \t]*$")
  20816. (org--get-expected-indentation element t)
  20817. 0))
  20818. ((memq type '(diary-sexp footnote-definition)) 0)
  20819. ;; First paragraph of a footnote definition or an item.
  20820. ;; Indent like parent.
  20821. ((< (line-beginning-position) start)
  20822. (org--get-expected-indentation
  20823. (org-element-property :parent element) t))
  20824. ;; At first line: indent according to previous sibling, if any,
  20825. ;; ignoring footnote definitions and inline tasks, or parent's
  20826. ;; contents.
  20827. ((= (line-beginning-position) start)
  20828. (catch 'exit
  20829. (while t
  20830. (if (= (point-min) start) (throw 'exit 0)
  20831. (goto-char (1- start))
  20832. (let* ((previous (org-element-at-point))
  20833. (parent previous))
  20834. (while (and parent (<= (org-element-property :end parent) start))
  20835. (setq previous parent
  20836. parent (org-element-property :parent parent)))
  20837. (cond
  20838. ((not previous) (throw 'exit 0))
  20839. ((> (org-element-property :end previous) start)
  20840. (throw 'exit (org--get-expected-indentation previous t)))
  20841. ((memq (org-element-type previous)
  20842. '(footnote-definition inlinetask))
  20843. (setq start (org-element-property :begin previous)))
  20844. (t (goto-char (org-element-property :begin previous))
  20845. (throw 'exit
  20846. (if (bolp) (org-get-indentation)
  20847. ;; At first paragraph in an item or
  20848. ;; a footnote definition.
  20849. (org--get-expected-indentation
  20850. (org-element-property :parent previous) t))))))))))
  20851. ;; Otherwise, move to the first non-blank line above.
  20852. (t
  20853. (beginning-of-line)
  20854. (let ((pos (point)))
  20855. (skip-chars-backward " \r\t\n")
  20856. (cond
  20857. ;; Two blank lines end a footnote definition or a plain
  20858. ;; list. When we indent an empty line after them, the
  20859. ;; containing list or footnote definition is over, so it
  20860. ;; qualifies as a previous sibling. Therefore, we indent
  20861. ;; like its first line.
  20862. ((and (memq type '(footnote-definition plain-list))
  20863. (> (count-lines (point) pos) 2))
  20864. (goto-char start)
  20865. (org-get-indentation))
  20866. ;; Line above is the first one of a paragraph at the
  20867. ;; beginning of an item or a footnote definition. Indent
  20868. ;; like parent.
  20869. ((< (line-beginning-position) start)
  20870. (org--get-expected-indentation
  20871. (org-element-property :parent element) t))
  20872. ;; Line above is the beginning of an element, i.e., point
  20873. ;; was originally on the blank lines between element's start
  20874. ;; and contents.
  20875. ((= (line-beginning-position) post-affiliated)
  20876. (org--get-expected-indentation element t))
  20877. ;; POS is after contents in a greater element. Indent like
  20878. ;; the beginning of the element.
  20879. ((and (memq type org-element-greater-elements)
  20880. (let ((cend (org-element-property :contents-end element)))
  20881. (and cend (<= cend pos))))
  20882. ;; As a special case, if point is at the end of a footnote
  20883. ;; definition or an item, indent like the very last element
  20884. ;; within. If that last element is an item, indent like
  20885. ;; its contents.
  20886. (if (memq type '(footnote-definition item plain-list))
  20887. (let ((last (org-element-at-point)))
  20888. (goto-char pos)
  20889. (org--get-expected-indentation
  20890. last (eq (org-element-type last) 'item)))
  20891. (goto-char start)
  20892. (org-get-indentation)))
  20893. ;; In any other case, indent like the current line.
  20894. (t (org-get-indentation)))))))))
  20895. (defun org--align-node-property ()
  20896. "Align node property at point.
  20897. Alignment is done according to `org-property-format', which see."
  20898. (when (save-excursion
  20899. (beginning-of-line)
  20900. (looking-at org-property-re))
  20901. (replace-match
  20902. (concat (match-string 4)
  20903. (org-trim
  20904. (format org-property-format (match-string 1) (match-string 3))))
  20905. t t)))
  20906. (defun org-indent-line ()
  20907. "Indent line depending on context.
  20908. Indentation is done according to the following rules:
  20909. - Footnote definitions, diary sexps, headlines and inline tasks
  20910. have to start at column 0.
  20911. - On the very first line of an element, consider, in order, the
  20912. next rules until one matches:
  20913. 1. If there's a sibling element before, ignoring footnote
  20914. definitions and inline tasks, indent like its first line.
  20915. 2. If element has a parent, indent like its contents. More
  20916. precisely, if parent is an item, indent after the
  20917. description part, if any, or the bullet (see
  20918. `org-list-description-max-indent'). Else, indent like
  20919. parent's first line.
  20920. 3. Otherwise, indent relatively to current level, if
  20921. `org-adapt-indentation' is non-nil, or to left margin.
  20922. - On a blank line at the end of an element, indent according to
  20923. the type of the element. More precisely
  20924. 1. If element is a plain list, an item, or a footnote
  20925. definition, indent like the very last element within.
  20926. 2. If element is a paragraph, indent like its last non blank
  20927. line.
  20928. 3. Otherwise, indent like its very first line.
  20929. - In the code part of a source block, use language major mode
  20930. to indent current line if `org-src-tab-acts-natively' is
  20931. non-nil. If it is nil, do nothing.
  20932. - Otherwise, indent like the first non-blank line above.
  20933. The function doesn't indent an item as it could break the whole
  20934. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20935. `\\[org-shiftmetaright]'.
  20936. Also align node properties according to `org-property-format'."
  20937. (interactive)
  20938. (cond
  20939. (orgstruct-is-++
  20940. (let ((indent-line-function
  20941. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20942. (indent-according-to-mode)))
  20943. ((org-at-heading-p) 'noindent)
  20944. (t
  20945. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20946. (type (org-element-type element)))
  20947. (cond ((and (memq type '(plain-list item))
  20948. (= (line-beginning-position)
  20949. (org-element-property :post-affiliated element)))
  20950. 'noindent)
  20951. ((and (eq type 'latex-environment)
  20952. (>= (point) (org-element-property :post-affiliated element))
  20953. (< (point) (org-with-wide-buffer
  20954. (goto-char (org-element-property :end element))
  20955. (skip-chars-backward " \r\t\n")
  20956. (line-beginning-position 2))))
  20957. 'noindent)
  20958. ((and (eq type 'src-block)
  20959. org-src-tab-acts-natively
  20960. (> (line-beginning-position)
  20961. (org-element-property :post-affiliated element))
  20962. (< (line-beginning-position)
  20963. (org-with-wide-buffer
  20964. (goto-char (org-element-property :end element))
  20965. (skip-chars-backward " \r\t\n")
  20966. (line-beginning-position))))
  20967. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20968. (t
  20969. (let ((column (org--get-expected-indentation element nil)))
  20970. ;; Preserve current column.
  20971. (if (<= (current-column) (current-indentation))
  20972. (indent-line-to column)
  20973. (save-excursion (indent-line-to column))))
  20974. ;; Align node property. Also preserve current column.
  20975. (when (eq type 'node-property)
  20976. (let ((column (current-column)))
  20977. (org--align-node-property)
  20978. (org-move-to-column column)))))))))
  20979. (defun org-indent-region (start end)
  20980. "Indent each non-blank line in the region.
  20981. Called from a program, START and END specify the region to
  20982. indent. The function will not indent contents of example blocks,
  20983. verse blocks and export blocks as leading white spaces are
  20984. assumed to be significant there."
  20985. (interactive "r")
  20986. (save-excursion
  20987. (goto-char start)
  20988. (skip-chars-forward " \r\t\n")
  20989. (unless (eobp) (beginning-of-line))
  20990. (let ((indent-to
  20991. (lambda (ind pos)
  20992. ;; Set IND as indentation for all lines between point and
  20993. ;; POS. Blank lines are ignored. Leave point after POS
  20994. ;; once done.
  20995. (let ((limit (copy-marker pos)))
  20996. (while (< (point) limit)
  20997. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20998. (forward-line))
  20999. (set-marker limit nil))))
  21000. (end (copy-marker end)))
  21001. (while (< (point) end)
  21002. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21003. (let* ((element (org-element-at-point))
  21004. (type (org-element-type element))
  21005. (element-end (copy-marker (org-element-property :end element)))
  21006. (ind (org--get-expected-indentation element nil)))
  21007. (cond
  21008. ;; Element indented as a single block. Example blocks
  21009. ;; preserving indentation are a special case since the
  21010. ;; "contents" must not be indented whereas the block
  21011. ;; boundaries can.
  21012. ((or (memq type '(export-block latex-environment))
  21013. (and (eq type 'example-block)
  21014. (not
  21015. (or org-src-preserve-indentation
  21016. (org-element-property :preserve-indent element)))))
  21017. (let ((offset (- ind (org-get-indentation))))
  21018. (unless (zerop offset)
  21019. (indent-rigidly (org-element-property :begin element)
  21020. (org-element-property :end element)
  21021. offset)))
  21022. (goto-char element-end))
  21023. ;; Elements indented line wise. Be sure to exclude
  21024. ;; example blocks (preserving indentation) and source
  21025. ;; blocks from this category as they are treated
  21026. ;; specially later.
  21027. ((or (memq type '(paragraph table table-row))
  21028. (not (or (org-element-property :contents-begin element)
  21029. (memq type '(example-block src-block)))))
  21030. (when (eq type 'node-property)
  21031. (org--align-node-property)
  21032. (beginning-of-line))
  21033. (funcall indent-to ind (min element-end end)))
  21034. ;; Elements consisting of three parts: before the
  21035. ;; contents, the contents, and after the contents. The
  21036. ;; contents are treated specially, according to the
  21037. ;; element type, or not indented at all. Other parts are
  21038. ;; indented as a single block.
  21039. (t
  21040. (let* ((post (copy-marker
  21041. (org-element-property :post-affiliated element)))
  21042. (cbeg
  21043. (copy-marker
  21044. (cond
  21045. ((not (org-element-property :contents-begin element))
  21046. ;; Fake contents for source blocks.
  21047. (org-with-wide-buffer
  21048. (goto-char post)
  21049. (line-beginning-position 2)))
  21050. ((memq type '(footnote-definition item plain-list))
  21051. ;; Contents in these elements could start on
  21052. ;; the same line as the beginning of the
  21053. ;; element. Make sure we start indenting
  21054. ;; from the second line.
  21055. (org-with-wide-buffer
  21056. (goto-char post)
  21057. (end-of-line)
  21058. (skip-chars-forward " \r\t\n")
  21059. (if (eobp) (point) (line-beginning-position))))
  21060. (t (org-element-property :contents-begin element)))))
  21061. (cend (copy-marker
  21062. (or (org-element-property :contents-end element)
  21063. ;; Fake contents for source blocks.
  21064. (org-with-wide-buffer
  21065. (goto-char element-end)
  21066. (skip-chars-backward " \r\t\n")
  21067. (line-beginning-position)))
  21068. t)))
  21069. ;; Do not change items indentation individually as it
  21070. ;; might break the list as a whole. On the other
  21071. ;; hand, when at a plain list, indent it as a whole.
  21072. (cond ((eq type 'plain-list)
  21073. (let ((offset (- ind (org-get-indentation))))
  21074. (unless (zerop offset)
  21075. (indent-rigidly (org-element-property :begin element)
  21076. (org-element-property :end element)
  21077. offset))
  21078. (goto-char cbeg)))
  21079. ((eq type 'item) (goto-char cbeg))
  21080. (t (funcall indent-to ind (min cbeg end))))
  21081. (when (< (point) end)
  21082. (cl-case type
  21083. ((example-block verse-block))
  21084. (src-block
  21085. ;; In a source block, indent source code
  21086. ;; according to language major mode, but only if
  21087. ;; `org-src-tab-acts-natively' is non-nil.
  21088. (when (and (< (point) end) org-src-tab-acts-natively)
  21089. (ignore-errors
  21090. (org-babel-do-in-edit-buffer
  21091. (indent-region (point-min) (point-max))))))
  21092. (t (org-indent-region (point) (min cend end))))
  21093. (goto-char (min cend end))
  21094. (when (< (point) end)
  21095. (funcall indent-to ind (min element-end end))))
  21096. (set-marker post nil)
  21097. (set-marker cbeg nil)
  21098. (set-marker cend nil))))
  21099. (set-marker element-end nil))))
  21100. (set-marker end nil))))
  21101. (defun org-indent-drawer ()
  21102. "Indent the drawer at point."
  21103. (interactive)
  21104. (unless (save-excursion
  21105. (beginning-of-line)
  21106. (looking-at-p org-drawer-regexp))
  21107. (user-error "Not at a drawer"))
  21108. (let ((element (org-element-at-point)))
  21109. (unless (memq (org-element-type element) '(drawer property-drawer))
  21110. (user-error "Not at a drawer"))
  21111. (org-with-wide-buffer
  21112. (org-indent-region (org-element-property :begin element)
  21113. (org-element-property :end element))))
  21114. (message "Drawer at point indented"))
  21115. (defun org-indent-block ()
  21116. "Indent the block at point."
  21117. (interactive)
  21118. (unless (save-excursion
  21119. (beginning-of-line)
  21120. (let ((case-fold-search t))
  21121. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21122. (user-error "Not at a block"))
  21123. (let ((element (org-element-at-point)))
  21124. (unless (memq (org-element-type element)
  21125. '(comment-block center-block dynamic-block example-block
  21126. export-block quote-block special-block
  21127. src-block verse-block))
  21128. (user-error "Not at a block"))
  21129. (org-with-wide-buffer
  21130. (org-indent-region (org-element-property :begin element)
  21131. (org-element-property :end element))))
  21132. (message "Block at point indented"))
  21133. ;;; Filling
  21134. ;; We use our own fill-paragraph and auto-fill functions.
  21135. ;; `org-fill-paragraph' relies on adaptive filling and context
  21136. ;; checking. Appropriate `fill-prefix' is computed with
  21137. ;; `org-adaptive-fill-function'.
  21138. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21139. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21140. ;; `org-adaptive-fill-function' value. Internally,
  21141. ;; `org-comment-line-break-function' breaks the line.
  21142. ;; `org-setup-filling' installs filling and auto-filling related
  21143. ;; variables during `org-mode' initialization.
  21144. (defvar org-element-paragraph-separate) ; org-element.el
  21145. (defun org-setup-filling ()
  21146. (require 'org-element)
  21147. ;; Prevent auto-fill from inserting unwanted new items.
  21148. (when (boundp 'fill-nobreak-predicate)
  21149. (setq-local
  21150. fill-nobreak-predicate
  21151. (org-uniquify
  21152. (append fill-nobreak-predicate
  21153. '(org-fill-line-break-nobreak-p
  21154. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21155. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21156. (setq-local paragraph-start paragraph-ending)
  21157. (setq-local paragraph-separate paragraph-ending))
  21158. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21159. (setq-local auto-fill-inhibit-regexp nil)
  21160. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21161. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21162. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21163. (defun org-fill-line-break-nobreak-p ()
  21164. "Non-nil when a new line at point would create an Org line break."
  21165. (save-excursion
  21166. (skip-chars-backward "[ \t]")
  21167. (skip-chars-backward "\\\\")
  21168. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21169. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21170. "Non-nil when a new line at point would split a timestamp."
  21171. (and (org-at-timestamp-p t)
  21172. (not (looking-at org-ts-regexp-both))))
  21173. (declare-function message-in-body-p "message" ())
  21174. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21175. (defun org-adaptive-fill-function ()
  21176. "Compute a fill prefix for the current line.
  21177. Return fill prefix, as a string, or nil if current line isn't
  21178. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21179. matches in paragraphs or comments, use it."
  21180. (catch 'exit
  21181. (when (derived-mode-p 'message-mode)
  21182. (save-excursion
  21183. (beginning-of-line)
  21184. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21185. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21186. ((looking-at message-cite-prefix-regexp)
  21187. (throw 'exit (match-string-no-properties 0)))
  21188. ((looking-at org-outline-regexp)
  21189. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21190. (org-with-wide-buffer
  21191. (unless (org-at-heading-p)
  21192. (let* ((p (line-beginning-position))
  21193. (element (save-excursion
  21194. (beginning-of-line)
  21195. (org-element-at-point)))
  21196. (type (org-element-type element))
  21197. (post-affiliated (org-element-property :post-affiliated element)))
  21198. (unless (< p post-affiliated)
  21199. (cl-case type
  21200. (comment
  21201. (save-excursion
  21202. (beginning-of-line)
  21203. (looking-at "[ \t]*")
  21204. (concat (match-string 0) "# ")))
  21205. (footnote-definition "")
  21206. ((item plain-list)
  21207. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21208. (paragraph
  21209. ;; Fill prefix is usually the same as the current line,
  21210. ;; unless the paragraph is at the beginning of an item.
  21211. (let ((parent (org-element-property :parent element)))
  21212. (save-excursion
  21213. (beginning-of-line)
  21214. (cond ((eq (org-element-type parent) 'item)
  21215. (make-string (org-list-item-body-column
  21216. (org-element-property :begin parent))
  21217. ?\s))
  21218. ((and adaptive-fill-regexp
  21219. ;; Locally disable
  21220. ;; `adaptive-fill-function' to let
  21221. ;; `fill-context-prefix' handle
  21222. ;; `adaptive-fill-regexp' variable.
  21223. (let (adaptive-fill-function)
  21224. (fill-context-prefix
  21225. post-affiliated
  21226. (org-element-property :end element)))))
  21227. ((looking-at "[ \t]+") (match-string 0))
  21228. (t "")))))
  21229. (comment-block
  21230. ;; Only fill contents if P is within block boundaries.
  21231. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21232. (forward-line)
  21233. (point)))
  21234. (cend (save-excursion
  21235. (goto-char (org-element-property :end element))
  21236. (skip-chars-backward " \r\t\n")
  21237. (line-beginning-position))))
  21238. (when (and (>= p cbeg) (< p cend))
  21239. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21240. (match-string 0)
  21241. "")))))))))))
  21242. (declare-function message-goto-body "message" ())
  21243. (defvar message-cite-prefix-regexp) ; From message.el
  21244. (defun org-fill-paragraph (&optional justify)
  21245. "Fill element at point, when applicable.
  21246. This function only applies to comment blocks, comments, example
  21247. blocks and paragraphs. Also, as a special case, re-align table
  21248. when point is at one.
  21249. If JUSTIFY is non-nil (interactively, with prefix argument),
  21250. justify as well. If `sentence-end-double-space' is non-nil, then
  21251. period followed by one space does not end a sentence, so don't
  21252. break a line there. The variable `fill-column' controls the
  21253. width for filling.
  21254. For convenience, when point is at a plain list, an item or
  21255. a footnote definition, try to fill the first paragraph within."
  21256. (interactive)
  21257. (if (and (derived-mode-p 'message-mode)
  21258. (or (not (message-in-body-p))
  21259. (save-excursion (move-beginning-of-line 1)
  21260. (looking-at message-cite-prefix-regexp))))
  21261. ;; First ensure filling is correct in message-mode.
  21262. (let ((fill-paragraph-function
  21263. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21264. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21265. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21266. (paragraph-separate
  21267. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21268. (fill-paragraph nil))
  21269. (with-syntax-table org-mode-transpose-word-syntax-table
  21270. ;; Move to end of line in order to get the first paragraph
  21271. ;; within a plain list or a footnote definition.
  21272. (let ((element (save-excursion
  21273. (end-of-line)
  21274. (or (ignore-errors (org-element-at-point))
  21275. (user-error "An element cannot be parsed line %d"
  21276. (line-number-at-pos (point)))))))
  21277. ;; First check if point is in a blank line at the beginning of
  21278. ;; the buffer. In that case, ignore filling.
  21279. (cl-case (org-element-type element)
  21280. ;; Use major mode filling function is src blocks.
  21281. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21282. ;; Align Org tables, leave table.el tables as-is.
  21283. (table-row (org-table-align) t)
  21284. (table
  21285. (when (eq (org-element-property :type element) 'org)
  21286. (save-excursion
  21287. (goto-char (org-element-property :post-affiliated element))
  21288. (org-table-align)))
  21289. t)
  21290. (paragraph
  21291. ;; Paragraphs may contain `line-break' type objects.
  21292. (let ((beg (max (point-min)
  21293. (org-element-property :contents-begin element)))
  21294. (end (min (point-max)
  21295. (org-element-property :contents-end element))))
  21296. ;; Do nothing if point is at an affiliated keyword.
  21297. (if (< (line-end-position) beg) t
  21298. (when (derived-mode-p 'message-mode)
  21299. ;; In `message-mode', do not fill following citation
  21300. ;; in current paragraph nor text before message body.
  21301. (let ((body-start (save-excursion (message-goto-body))))
  21302. (when body-start (setq beg (max body-start beg))))
  21303. (when (save-excursion
  21304. (re-search-forward
  21305. (concat "^" message-cite-prefix-regexp) end t))
  21306. (setq end (match-beginning 0))))
  21307. ;; Fill paragraph, taking line breaks into account.
  21308. (save-excursion
  21309. (goto-char beg)
  21310. (let ((cuts (list beg)))
  21311. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21312. (when (eq 'line-break
  21313. (org-element-type
  21314. (save-excursion (backward-char)
  21315. (org-element-context))))
  21316. (push (point) cuts)))
  21317. (dolist (c (delq end cuts))
  21318. (fill-region-as-paragraph c end justify)
  21319. (setq end c))))
  21320. t)))
  21321. ;; Contents of `comment-block' type elements should be
  21322. ;; filled as plain text, but only if point is within block
  21323. ;; markers.
  21324. (comment-block
  21325. (let* ((case-fold-search t)
  21326. (beg (save-excursion
  21327. (goto-char (org-element-property :begin element))
  21328. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21329. (forward-line)
  21330. (point)))
  21331. (end (save-excursion
  21332. (goto-char (org-element-property :end element))
  21333. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21334. (line-beginning-position))))
  21335. (if (or (< (point) beg) (> (point) end)) t
  21336. (fill-region-as-paragraph
  21337. (save-excursion (end-of-line)
  21338. (re-search-backward "^[ \t]*$" beg 'move)
  21339. (line-beginning-position))
  21340. (save-excursion (beginning-of-line)
  21341. (re-search-forward "^[ \t]*$" end 'move)
  21342. (line-beginning-position))
  21343. justify))))
  21344. ;; Fill comments.
  21345. (comment
  21346. (let ((begin (org-element-property :post-affiliated element))
  21347. (end (org-element-property :end element)))
  21348. (when (and (>= (point) begin) (<= (point) end))
  21349. (let ((begin (save-excursion
  21350. (end-of-line)
  21351. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21352. (progn (forward-line) (point))
  21353. begin)))
  21354. (end (save-excursion
  21355. (end-of-line)
  21356. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21357. (1- (line-beginning-position))
  21358. (skip-chars-backward " \r\t\n")
  21359. (line-end-position)))))
  21360. ;; Do not fill comments when at a blank line.
  21361. (when (> end begin)
  21362. (let ((fill-prefix
  21363. (save-excursion
  21364. (beginning-of-line)
  21365. (looking-at "[ \t]*#")
  21366. (let ((comment-prefix (match-string 0)))
  21367. (goto-char (match-end 0))
  21368. (if (looking-at adaptive-fill-regexp)
  21369. (concat comment-prefix (match-string 0))
  21370. (concat comment-prefix " "))))))
  21371. (save-excursion
  21372. (fill-region-as-paragraph begin end justify))))))
  21373. t))
  21374. ;; Ignore every other element.
  21375. (otherwise t))))))
  21376. (defun org-auto-fill-function ()
  21377. "Auto-fill function."
  21378. ;; Check if auto-filling is meaningful.
  21379. (let ((fc (current-fill-column)))
  21380. (when (and fc (> (current-column) fc))
  21381. (let* ((fill-prefix (org-adaptive-fill-function))
  21382. ;; Enforce empty fill prefix, if required. Otherwise, it
  21383. ;; will be computed again.
  21384. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21385. (when fill-prefix (do-auto-fill))))))
  21386. (defun org-comment-line-break-function (&optional soft)
  21387. "Break line at point and indent, continuing comment if within one.
  21388. The inserted newline is marked hard if variable
  21389. `use-hard-newlines' is true, unless optional argument SOFT is
  21390. non-nil."
  21391. (if soft (insert-and-inherit ?\n) (newline 1))
  21392. (save-excursion (forward-char -1) (delete-horizontal-space))
  21393. (delete-horizontal-space)
  21394. (indent-to-left-margin)
  21395. (insert-before-markers-and-inherit fill-prefix))
  21396. ;;; Fixed Width Areas
  21397. (defun org-toggle-fixed-width ()
  21398. "Toggle fixed-width markup.
  21399. Add or remove fixed-width markup on current line, whenever it
  21400. makes sense. Return an error otherwise.
  21401. If a region is active and if it contains only fixed-width areas
  21402. or blank lines, remove all fixed-width markup in it. If the
  21403. region contains anything else, convert all non-fixed-width lines
  21404. to fixed-width ones.
  21405. Blank lines at the end of the region are ignored unless the
  21406. region only contains such lines."
  21407. (interactive)
  21408. (if (not (org-region-active-p))
  21409. ;; No region:
  21410. ;;
  21411. ;; Remove fixed width marker only in a fixed-with element.
  21412. ;;
  21413. ;; Add fixed width maker in paragraphs, in blank lines after
  21414. ;; elements or at the beginning of a headline or an inlinetask,
  21415. ;; and before any one-line elements (e.g., a clock).
  21416. (progn
  21417. (beginning-of-line)
  21418. (let* ((element (org-element-at-point))
  21419. (type (org-element-type element)))
  21420. (cond
  21421. ((and (eq type 'fixed-width)
  21422. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21423. (replace-match
  21424. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21425. ((and (memq type '(babel-call clock comment diary-sexp headline
  21426. horizontal-rule keyword paragraph
  21427. planning))
  21428. (<= (org-element-property :post-affiliated element) (point)))
  21429. (skip-chars-forward " \t")
  21430. (insert ": "))
  21431. ((and (looking-at-p "[ \t]*$")
  21432. (or (eq type 'inlinetask)
  21433. (save-excursion
  21434. (skip-chars-forward " \r\t\n")
  21435. (<= (org-element-property :end element) (point)))))
  21436. (delete-region (point) (line-end-position))
  21437. (org-indent-line)
  21438. (insert ": "))
  21439. (t (user-error "Cannot insert a fixed-width line here")))))
  21440. ;; Region active.
  21441. (let* ((begin (save-excursion
  21442. (goto-char (region-beginning))
  21443. (line-beginning-position)))
  21444. (end (copy-marker
  21445. (save-excursion
  21446. (goto-char (region-end))
  21447. (unless (eolp) (beginning-of-line))
  21448. (if (save-excursion (re-search-backward "\\S-" begin t))
  21449. (progn (skip-chars-backward " \r\t\n") (point))
  21450. (point)))))
  21451. (all-fixed-width-p
  21452. (catch 'not-all-p
  21453. (save-excursion
  21454. (goto-char begin)
  21455. (skip-chars-forward " \r\t\n")
  21456. (when (eobp) (throw 'not-all-p nil))
  21457. (while (< (point) end)
  21458. (let ((element (org-element-at-point)))
  21459. (if (eq (org-element-type element) 'fixed-width)
  21460. (goto-char (org-element-property :end element))
  21461. (throw 'not-all-p nil))))
  21462. t))))
  21463. (if all-fixed-width-p
  21464. (save-excursion
  21465. (goto-char begin)
  21466. (while (< (point) end)
  21467. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21468. (replace-match
  21469. "" nil nil nil
  21470. (if (= (line-end-position) (match-end 0)) 0 1)))
  21471. (forward-line)))
  21472. (let ((min-ind (point-max)))
  21473. ;; Find minimum indentation across all lines.
  21474. (save-excursion
  21475. (goto-char begin)
  21476. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21477. (setq min-ind 0)
  21478. (catch 'zerop
  21479. (while (< (point) end)
  21480. (unless (looking-at-p "[ \t]*$")
  21481. (let ((ind (org-get-indentation)))
  21482. (setq min-ind (min min-ind ind))
  21483. (when (zerop ind) (throw 'zerop t))))
  21484. (forward-line)))))
  21485. ;; Loop over all lines and add fixed-width markup everywhere
  21486. ;; but in fixed-width lines.
  21487. (save-excursion
  21488. (goto-char begin)
  21489. (while (< (point) end)
  21490. (cond
  21491. ((org-at-heading-p)
  21492. (insert ": ")
  21493. (forward-line)
  21494. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21495. (insert ":")
  21496. (forward-line)))
  21497. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21498. (let* ((element (org-element-at-point))
  21499. (element-end (org-element-property :end element)))
  21500. (if (eq (org-element-type element) 'fixed-width)
  21501. (progn (goto-char element-end)
  21502. (skip-chars-backward " \r\t\n")
  21503. (forward-line))
  21504. (let ((limit (min end element-end)))
  21505. (while (< (point) limit)
  21506. (org-move-to-column min-ind t)
  21507. (insert ": ")
  21508. (forward-line))))))
  21509. (t
  21510. (org-move-to-column min-ind t)
  21511. (insert ": ")
  21512. (forward-line)))))))
  21513. (set-marker end nil))))
  21514. ;;; Comments
  21515. ;; Org comments syntax is quite complex. It requires the entire line
  21516. ;; to be just a comment. Also, even with the right syntax at the
  21517. ;; beginning of line, some some elements (i.e. verse-block or
  21518. ;; example-block) don't accept comments. Usual Emacs comment commands
  21519. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21520. ;; Org still relies on `comment-dwim', but cannot trust
  21521. ;; `comment-only-p'. So, `comment-region-function' and
  21522. ;; `uncomment-region-function' both point
  21523. ;; to`org-comment-or-uncomment-region'. Eventually,
  21524. ;; `org-insert-comment' takes care of insertion of comments at the
  21525. ;; beginning of line.
  21526. ;; `org-setup-comments-handling' install comments related variables
  21527. ;; during `org-mode' initialization.
  21528. (defun org-setup-comments-handling ()
  21529. (interactive)
  21530. (setq-local comment-use-syntax nil)
  21531. (setq-local comment-start "# ")
  21532. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21533. (setq-local comment-insert-comment-function 'org-insert-comment)
  21534. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21535. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21536. (defun org-insert-comment ()
  21537. "Insert an empty comment above current line.
  21538. If the line is empty, insert comment at its beginning. When
  21539. point is within a source block, comment according to the related
  21540. major mode."
  21541. (if (let ((element (org-element-at-point)))
  21542. (and (eq (org-element-type element) 'src-block)
  21543. (< (save-excursion
  21544. (goto-char (org-element-property :post-affiliated element))
  21545. (line-end-position))
  21546. (point))
  21547. (> (save-excursion
  21548. (goto-char (org-element-property :end element))
  21549. (skip-chars-backward " \r\t\n")
  21550. (line-beginning-position))
  21551. (point))))
  21552. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21553. (beginning-of-line)
  21554. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21555. (open-line 1))
  21556. (org-indent-line)
  21557. (insert "# ")))
  21558. (defvar comment-empty-lines) ; From newcomment.el.
  21559. (defun org-comment-or-uncomment-region (beg end &rest _)
  21560. "Comment or uncomment each non-blank line in the region.
  21561. Uncomment each non-blank line between BEG and END if it only
  21562. contains commented lines. Otherwise, comment them. If region is
  21563. strictly within a source block, use appropriate comment syntax."
  21564. (if (let ((element (org-element-at-point)))
  21565. (and (eq (org-element-type element) 'src-block)
  21566. (< (save-excursion
  21567. (goto-char (org-element-property :post-affiliated element))
  21568. (line-end-position))
  21569. beg)
  21570. (>= (save-excursion
  21571. (goto-char (org-element-property :end element))
  21572. (skip-chars-backward " \r\t\n")
  21573. (line-beginning-position))
  21574. end)))
  21575. ;; Translate region boundaries for the Org buffer to the source
  21576. ;; buffer.
  21577. (let ((offset (- end beg)))
  21578. (save-excursion
  21579. (goto-char beg)
  21580. (org-babel-do-in-edit-buffer
  21581. (comment-or-uncomment-region (point) (+ offset (point))))))
  21582. (save-restriction
  21583. ;; Restrict region
  21584. (narrow-to-region (save-excursion (goto-char beg)
  21585. (skip-chars-forward " \r\t\n" end)
  21586. (line-beginning-position))
  21587. (save-excursion (goto-char end)
  21588. (skip-chars-backward " \r\t\n" beg)
  21589. (line-end-position)))
  21590. (let ((uncommentp
  21591. ;; UNCOMMENTP is non-nil when every non blank line between
  21592. ;; BEG and END is a comment.
  21593. (save-excursion
  21594. (goto-char (point-min))
  21595. (while (and (not (eobp))
  21596. (let ((element (org-element-at-point)))
  21597. (and (eq (org-element-type element) 'comment)
  21598. (goto-char (min (point-max)
  21599. (org-element-property
  21600. :end element)))))))
  21601. (eobp))))
  21602. (if uncommentp
  21603. ;; Only blank lines and comments in region: uncomment it.
  21604. (save-excursion
  21605. (goto-char (point-min))
  21606. (while (not (eobp))
  21607. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21608. (replace-match "" nil nil nil 1))
  21609. (forward-line)))
  21610. ;; Comment each line in region.
  21611. (let ((min-indent (point-max)))
  21612. ;; First find the minimum indentation across all lines.
  21613. (save-excursion
  21614. (goto-char (point-min))
  21615. (while (and (not (eobp)) (not (zerop min-indent)))
  21616. (unless (looking-at "[ \t]*$")
  21617. (setq min-indent (min min-indent (current-indentation))))
  21618. (forward-line)))
  21619. ;; Then loop over all lines.
  21620. (save-excursion
  21621. (goto-char (point-min))
  21622. (while (not (eobp))
  21623. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21624. ;; Don't get fooled by invisible text (e.g. link path)
  21625. ;; when moving to column MIN-INDENT.
  21626. (let ((buffer-invisibility-spec nil))
  21627. (org-move-to-column min-indent t))
  21628. (insert comment-start))
  21629. (forward-line)))))))))
  21630. (defun org-comment-dwim (_arg)
  21631. "Call `comment-dwim' within a source edit buffer if needed."
  21632. (interactive "*P")
  21633. (if (org-in-src-block-p)
  21634. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21635. (call-interactively 'comment-dwim)))
  21636. ;;; Timestamps API
  21637. ;; This section contains tools to operate on timestamp objects, as
  21638. ;; returned by, e.g. `org-element-context'.
  21639. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21640. "Encode TIMESTAMP object into Emacs internal time.
  21641. Use end of date range or time range when END is non-nil."
  21642. (apply #'encode-time
  21643. (cons 0
  21644. (mapcar
  21645. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21646. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21647. '(:minute-start :hour-start :day-start :month-start
  21648. :year-start))))))
  21649. (defun org-timestamp-has-time-p (timestamp)
  21650. "Non-nil when TIMESTAMP has a time specified."
  21651. (org-element-property :hour-start timestamp))
  21652. (defun org-timestamp-format (timestamp format &optional end utc)
  21653. "Format a TIMESTAMP object into a string.
  21654. FORMAT is a format specifier to be passed to
  21655. `format-time-string'.
  21656. When optional argument END is non-nil, use end of date-range or
  21657. time-range, if possible.
  21658. When optional argument UTC is non-nil, time will be expressed as
  21659. Universal Time."
  21660. (format-time-string
  21661. format (org-timestamp--to-internal-time timestamp end)
  21662. (and utc t)))
  21663. (defun org-timestamp-split-range (timestamp &optional end)
  21664. "Extract a TIMESTAMP object from a date or time range.
  21665. END, when non-nil, means extract the end of the range.
  21666. Otherwise, extract its start.
  21667. Return a new timestamp object."
  21668. (let ((type (org-element-property :type timestamp)))
  21669. (if (memq type '(active inactive diary)) timestamp
  21670. (let ((split-ts (org-element-copy timestamp)))
  21671. ;; Set new type.
  21672. (org-element-put-property
  21673. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21674. ;; Copy start properties over end properties if END is
  21675. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21676. (let ((p-alist '((:minute-start . :minute-end)
  21677. (:hour-start . :hour-end)
  21678. (:day-start . :day-end)
  21679. (:month-start . :month-end)
  21680. (:year-start . :year-end))))
  21681. (dolist (p-cell p-alist)
  21682. (org-element-put-property
  21683. split-ts
  21684. (funcall (if end #'car #'cdr) p-cell)
  21685. (org-element-property
  21686. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21687. ;; Eventually refresh `:raw-value'.
  21688. (org-element-put-property split-ts :raw-value nil)
  21689. (org-element-put-property
  21690. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21691. (defun org-timestamp-translate (timestamp &optional boundary)
  21692. "Translate TIMESTAMP object to custom format.
  21693. Format string is defined in `org-time-stamp-custom-formats',
  21694. which see.
  21695. When optional argument BOUNDARY is non-nil, it is either the
  21696. symbol `start' or `end'. In this case, only translate the
  21697. starting or ending part of TIMESTAMP if it is a date or time
  21698. range. Otherwise, translate both parts.
  21699. Return timestamp as-is if `org-display-custom-times' is nil or if
  21700. it has a `diary' type."
  21701. (let ((type (org-element-property :type timestamp)))
  21702. (if (or (not org-display-custom-times) (eq type 'diary))
  21703. (org-element-interpret-data timestamp)
  21704. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21705. org-time-stamp-custom-formats)))
  21706. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21707. (concat (org-timestamp-format timestamp fmt)
  21708. "--"
  21709. (org-timestamp-format timestamp fmt t))
  21710. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21711. ;;; Other stuff.
  21712. (defvar reftex-docstruct-symbol)
  21713. (defvar org--rds)
  21714. (defun org-reftex-citation ()
  21715. "Use reftex-citation to insert a citation into the buffer.
  21716. This looks for a line like
  21717. #+BIBLIOGRAPHY: foo plain option:-d
  21718. and derives from it that foo.bib is the bibliography file relevant
  21719. for this document. It then installs the necessary environment for RefTeX
  21720. to work in this buffer and calls `reftex-citation' to insert a citation
  21721. into the buffer.
  21722. Export of such citations to both LaTeX and HTML is handled by the contributed
  21723. package ox-bibtex by Taru Karttunen."
  21724. (interactive)
  21725. (let ((reftex-docstruct-symbol 'org--rds)
  21726. org--rds bib)
  21727. (org-with-wide-buffer
  21728. (let ((case-fold-search t)
  21729. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21730. (if (not (save-excursion
  21731. (or (re-search-forward re nil t)
  21732. (re-search-backward re nil t))))
  21733. (user-error "No bibliography defined in file")
  21734. (setq bib (concat (match-string 1) ".bib")
  21735. org--rds (list (list 'bib bib))))))
  21736. (call-interactively 'reftex-citation)))
  21737. ;;;; Functions extending outline functionality
  21738. (defun org-beginning-of-line (&optional n)
  21739. "Go to the beginning of the current visible line.
  21740. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21741. tags on the first attempt, and only move to after the tags when
  21742. the cursor is already beyond the end of the headline.
  21743. With argument N not nil or 1, move forward N - 1 lines first."
  21744. (interactive "^p")
  21745. (let ((origin (point))
  21746. (special (pcase org-special-ctrl-a/e
  21747. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21748. deactivate-mark)
  21749. ;; First move to a visible line.
  21750. (if (bound-and-true-p visual-line-mode)
  21751. (beginning-of-visual-line n)
  21752. (move-beginning-of-line n)
  21753. ;; `move-beginning-of-line' may leave point after invisible
  21754. ;; characters if line starts with such of these (e.g., with
  21755. ;; a link at column 0). Really move to the beginning of the
  21756. ;; current visible line.
  21757. (beginning-of-line))
  21758. (cond
  21759. ;; No special behavior. Point is already at the beginning of
  21760. ;; a line, logical or visual.
  21761. ((not special))
  21762. ;; `beginning-of-visual-line' left point before logical beginning
  21763. ;; of line: point is at the beginning of a visual line. Bail
  21764. ;; out.
  21765. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21766. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21767. ;; At a headline, special position is before the title, but
  21768. ;; after any TODO keyword or priority cookie.
  21769. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21770. (line-end-position)))
  21771. (bol (point)))
  21772. (if (eq special 'reversed)
  21773. (when (and (= origin bol) (eq last-command this-command))
  21774. (goto-char refpos))
  21775. (when (or (> origin refpos) (= origin bol))
  21776. (goto-char refpos)))))
  21777. ((and (looking-at org-list-full-item-re)
  21778. (memq (org-element-type (save-match-data (org-element-at-point)))
  21779. '(item plain-list)))
  21780. ;; Set special position at first white space character after
  21781. ;; bullet, and check-box, if any.
  21782. (let ((after-bullet
  21783. (let ((box (match-end 3)))
  21784. (cond ((not box) (match-end 1))
  21785. ((eq (char-after box) ?\s) (1+ box))
  21786. (t box)))))
  21787. (if (eq special 'reversed)
  21788. (when (and (= (point) origin) (eq last-command this-command))
  21789. (goto-char after-bullet))
  21790. (when (or (> origin after-bullet) (= (point) origin))
  21791. (goto-char after-bullet)))))
  21792. ;; No special context. Point is already at beginning of line.
  21793. (t nil))))
  21794. (defun org-end-of-line (&optional n)
  21795. "Go to the end of the line, but before ellipsis, if any.
  21796. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21797. tags on the first attempt, and only move to after the tags when
  21798. the cursor is already beyond the end of the headline.
  21799. With argument N not nil or 1, move forward N - 1 lines first."
  21800. (interactive "^p")
  21801. (let ((origin (point))
  21802. (special (pcase org-special-ctrl-a/e
  21803. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21804. deactivate-mark)
  21805. ;; First move to a visible line.
  21806. (if (bound-and-true-p visual-line-mode)
  21807. (beginning-of-visual-line n)
  21808. (move-beginning-of-line n))
  21809. (cond
  21810. ;; At a headline, with tags.
  21811. ((and special
  21812. (save-excursion
  21813. (beginning-of-line)
  21814. (let ((case-fold-search nil))
  21815. (looking-at org-complex-heading-regexp)))
  21816. (match-end 5))
  21817. (let ((tags (save-excursion
  21818. (goto-char (match-beginning 5))
  21819. (skip-chars-backward " \t")
  21820. (point)))
  21821. (visual-end (and (bound-and-true-p visual-line-mode)
  21822. (save-excursion
  21823. (end-of-visual-line)
  21824. (point)))))
  21825. ;; If `end-of-visual-line' brings us before end of line or
  21826. ;; even tags, i.e., the headline spans over multiple visual
  21827. ;; lines, move there.
  21828. (cond ((and visual-end
  21829. (< visual-end tags)
  21830. (<= origin visual-end))
  21831. (goto-char visual-end))
  21832. ((eq special 'reversed)
  21833. (if (and (= origin (line-end-position))
  21834. (eq this-command last-command))
  21835. (goto-char tags)
  21836. (end-of-line)))
  21837. (t
  21838. (if (or (< origin tags) (= origin (line-end-position)))
  21839. (goto-char tags)
  21840. (end-of-line))))))
  21841. ((bound-and-true-p visual-line-mode)
  21842. (let ((bol (line-beginning-position)))
  21843. (end-of-visual-line)
  21844. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21845. ;; end of a line, backtrack and use `end-of-line' instead.
  21846. (when (/= bol (line-beginning-position))
  21847. (goto-char bol)
  21848. (end-of-line))))
  21849. (t (end-of-line)))))
  21850. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21851. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21852. (defun org-backward-sentence (&optional _arg)
  21853. "Go to beginning of sentence, or beginning of table field.
  21854. This will call `backward-sentence' or `org-table-beginning-of-field',
  21855. depending on context."
  21856. (interactive)
  21857. (let* ((element (org-element-at-point))
  21858. (contents-begin (org-element-property :contents-begin element))
  21859. (table (org-element-lineage element '(table) t)))
  21860. (if (and table
  21861. (> (point) contents-begin)
  21862. (<= (point) (org-element-property :contents-end table)))
  21863. (call-interactively #'org-table-beginning-of-field)
  21864. (save-restriction
  21865. (when (and contents-begin
  21866. (< (point-min) contents-begin)
  21867. (> (point) contents-begin))
  21868. (narrow-to-region contents-begin
  21869. (org-element-property :contents-end element)))
  21870. (call-interactively #'backward-sentence)))))
  21871. (defun org-forward-sentence (&optional _arg)
  21872. "Go to end of sentence, or end of table field.
  21873. This will call `forward-sentence' or `org-table-end-of-field',
  21874. depending on context."
  21875. (interactive)
  21876. (let* ((element (org-element-at-point))
  21877. (contents-end (org-element-property :contents-end element))
  21878. (table (org-element-lineage element '(table) t)))
  21879. (if (and table
  21880. (>= (point) (org-element-property :contents-begin table))
  21881. (< (point) contents-end))
  21882. (call-interactively #'org-table-end-of-field)
  21883. (save-restriction
  21884. (when (and contents-end
  21885. (> (point-max) contents-end)
  21886. ;; Skip blank lines between elements.
  21887. (< (org-element-property :end element)
  21888. (save-excursion (goto-char contents-end)
  21889. (skip-chars-forward " \r\t\n"))))
  21890. (narrow-to-region (org-element-property :contents-begin element)
  21891. contents-end))
  21892. (call-interactively #'forward-sentence)))))
  21893. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21894. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21895. (defun org-kill-line (&optional _arg)
  21896. "Kill line, to tags or end of line."
  21897. (interactive)
  21898. (cond
  21899. ((or (not org-special-ctrl-k)
  21900. (bolp)
  21901. (not (org-at-heading-p)))
  21902. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21903. org-ctrl-k-protect-subtree
  21904. (or (eq org-ctrl-k-protect-subtree 'error)
  21905. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21906. (user-error "C-k aborted as it would kill a hidden subtree"))
  21907. (call-interactively
  21908. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21909. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21910. (kill-region (point) (match-beginning 1))
  21911. (org-set-tags nil t))
  21912. (t (kill-region (point) (point-at-eol)))))
  21913. (define-key org-mode-map "\C-k" 'org-kill-line)
  21914. (defun org-yank (&optional arg)
  21915. "Yank. If the kill is a subtree, treat it specially.
  21916. This command will look at the current kill and check if is a single
  21917. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21918. cursor is at the beginning of a line or after the stars of a currently
  21919. empty headline, then the yank is handled specially. How exactly depends
  21920. on the value of the following variables.
  21921. `org-yank-folded-subtrees'
  21922. By default, this variable is non-nil, which results in
  21923. subtree(s) being folded after insertion, except if doing so
  21924. would swallow text after the yanked text.
  21925. `org-yank-adjusted-subtrees'
  21926. When non-nil (the default value is nil), the subtree will be
  21927. promoted or demoted in order to fit into the local outline tree
  21928. structure, which means that the level will be adjusted so that it
  21929. becomes the smaller one of the two *visible* surrounding headings.
  21930. Any prefix to this command will cause `yank' to be called directly with
  21931. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21932. will just
  21933. plainly yank the text as it is.
  21934. \[1] The test checks if the first non-white line is a heading
  21935. and if there are no other headings with fewer stars."
  21936. (interactive "P")
  21937. (org-yank-generic 'yank arg))
  21938. (defun org-yank-generic (command arg)
  21939. "Perform some yank-like command.
  21940. This function implements the behavior described in the `org-yank'
  21941. documentation. However, it has been generalized to work for any
  21942. interactive command with similar behavior."
  21943. ;; pretend to be command COMMAND
  21944. (setq this-command command)
  21945. (if arg
  21946. (call-interactively command)
  21947. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21948. (and (org-kill-is-subtree-p)
  21949. (or (bolp)
  21950. (and (looking-at "[ \t]*$")
  21951. (string-match
  21952. "\\`\\*+\\'"
  21953. (buffer-substring (point-at-bol) (point)))))))
  21954. swallowp)
  21955. (cond
  21956. ((and subtreep org-yank-folded-subtrees)
  21957. (let ((beg (point))
  21958. end)
  21959. (if (and subtreep org-yank-adjusted-subtrees)
  21960. (org-paste-subtree nil nil 'for-yank)
  21961. (call-interactively command))
  21962. (setq end (point))
  21963. (goto-char beg)
  21964. (when (and (bolp) subtreep
  21965. (not (setq swallowp
  21966. (org-yank-folding-would-swallow-text beg end))))
  21967. (org-with-limited-levels
  21968. (or (looking-at org-outline-regexp)
  21969. (re-search-forward org-outline-regexp-bol end t))
  21970. (while (and (< (point) end) (looking-at org-outline-regexp))
  21971. (outline-hide-subtree)
  21972. (org-cycle-show-empty-lines 'folded)
  21973. (condition-case nil
  21974. (outline-forward-same-level 1)
  21975. (error (goto-char end))))))
  21976. (when swallowp
  21977. (message
  21978. "Inserted text not folded because that would swallow text"))
  21979. (goto-char end)
  21980. (skip-chars-forward " \t\n\r")
  21981. (beginning-of-line 1)
  21982. (push-mark beg 'nomsg)))
  21983. ((and subtreep org-yank-adjusted-subtrees)
  21984. (let ((beg (point-at-bol)))
  21985. (org-paste-subtree nil nil 'for-yank)
  21986. (push-mark beg 'nomsg)))
  21987. (t
  21988. (call-interactively command))))))
  21989. (defun org-yank-folding-would-swallow-text (beg end)
  21990. "Would hide-subtree at BEG swallow any text after END?"
  21991. (let (level)
  21992. (org-with-limited-levels
  21993. (save-excursion
  21994. (goto-char beg)
  21995. (when (or (looking-at org-outline-regexp)
  21996. (re-search-forward org-outline-regexp-bol end t))
  21997. (setq level (org-outline-level)))
  21998. (goto-char end)
  21999. (skip-chars-forward " \t\r\n\v\f")
  22000. (not (or (eobp)
  22001. (and (bolp) (looking-at-p org-outline-regexp)
  22002. (<= (org-outline-level) level))))))))
  22003. (define-key org-mode-map "\C-y" 'org-yank)
  22004. (defun org-truely-invisible-p ()
  22005. "Check if point is at a character currently not visible.
  22006. This version does not only check the character property, but also
  22007. `visible-mode'."
  22008. (unless (bound-and-true-p visible-mode)
  22009. (org-invisible-p)))
  22010. (defun org-invisible-p2 ()
  22011. "Check if point is at a character currently not visible.
  22012. If the point is at EOL (and not at the beginning of a buffer too),
  22013. move it back by one char before doing this check."
  22014. (save-excursion
  22015. (when (and (eolp) (not (bobp)))
  22016. (backward-char 1))
  22017. (org-invisible-p)))
  22018. (defun org-back-to-heading (&optional invisible-ok)
  22019. "Call `outline-back-to-heading', but provide a better error message."
  22020. (condition-case nil
  22021. (outline-back-to-heading invisible-ok)
  22022. (error (error "Before first headline at position %d in buffer %s"
  22023. (point) (current-buffer)))))
  22024. (defun org-before-first-heading-p ()
  22025. "Before first heading?"
  22026. (save-excursion
  22027. (end-of-line)
  22028. (null (re-search-backward org-outline-regexp-bol nil t))))
  22029. (defun org-at-heading-p (&optional ignored)
  22030. (outline-on-heading-p t))
  22031. (defun org-in-commented-heading-p (&optional no-inheritance)
  22032. "Non-nil if point is under a commented heading.
  22033. This function also checks ancestors of the current headline,
  22034. unless optional argument NO-INHERITANCE is non-nil."
  22035. (cond
  22036. ((org-before-first-heading-p) nil)
  22037. ((let ((headline (nth 4 (org-heading-components))))
  22038. (and headline
  22039. (let ((case-fold-search nil))
  22040. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22041. headline)))))
  22042. (no-inheritance nil)
  22043. (t
  22044. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22045. (defun org-at-comment-p nil
  22046. "Is cursor in a commented line?"
  22047. (save-excursion
  22048. (save-match-data
  22049. (beginning-of-line)
  22050. (looking-at "^[ \t]*# "))))
  22051. (defun org-at-drawer-p nil
  22052. "Is cursor at a drawer keyword?"
  22053. (save-excursion
  22054. (move-beginning-of-line 1)
  22055. (looking-at org-drawer-regexp)))
  22056. (defun org-at-block-p nil
  22057. "Is cursor at a block keyword?"
  22058. (save-excursion
  22059. (move-beginning-of-line 1)
  22060. (looking-at org-block-regexp)))
  22061. (defun org-point-at-end-of-empty-headline ()
  22062. "If point is at the end of an empty headline, return t, else nil.
  22063. If the heading only contains a TODO keyword, it is still still considered
  22064. empty."
  22065. (let ((case-fold-search nil))
  22066. (and (looking-at "[ \t]*$")
  22067. org-todo-line-regexp
  22068. (save-excursion
  22069. (beginning-of-line)
  22070. (looking-at org-todo-line-regexp)
  22071. (string= (match-string 3) "")))))
  22072. (defun org-at-heading-or-item-p ()
  22073. (or (org-at-heading-p) (org-at-item-p)))
  22074. (defun org-at-target-p ()
  22075. (or (org-in-regexp org-radio-target-regexp)
  22076. (org-in-regexp org-target-regexp)))
  22077. ;; Compatibility alias with Org versions < 7.8.03
  22078. (defalias 'org-on-target-p 'org-at-target-p)
  22079. (defun org-up-heading-all (arg)
  22080. "Move to the heading line of which the present line is a subheading.
  22081. This function considers both visible and invisible heading lines.
  22082. With argument, move up ARG levels."
  22083. (outline-up-heading arg t))
  22084. (defun org-up-heading-safe ()
  22085. "Move to the heading line of which the present line is a subheading.
  22086. This version will not throw an error. It will return the level of the
  22087. headline found, or nil if no higher level is found.
  22088. Also, this function will be a lot faster than `outline-up-heading',
  22089. because it relies on stars being the outline starters. This can really
  22090. make a significant difference in outlines with very many siblings."
  22091. (when (ignore-errors (org-back-to-heading t))
  22092. (let ((level-up (1- (funcall outline-level))))
  22093. (and (> level-up 0)
  22094. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22095. (funcall outline-level)))))
  22096. (defun org-first-sibling-p ()
  22097. "Is this heading the first child of its parents?"
  22098. (interactive)
  22099. (let ((re org-outline-regexp-bol)
  22100. level l)
  22101. (unless (org-at-heading-p t)
  22102. (user-error "Not at a heading"))
  22103. (setq level (funcall outline-level))
  22104. (save-excursion
  22105. (if (not (re-search-backward re nil t))
  22106. t
  22107. (setq l (funcall outline-level))
  22108. (< l level)))))
  22109. (defun org-goto-sibling (&optional previous)
  22110. "Goto the next sibling, even if it is invisible.
  22111. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22112. when a sibling was found. When none is found, return nil and don't
  22113. move point."
  22114. (let ((fun (if previous 're-search-backward 're-search-forward))
  22115. (pos (point))
  22116. (re org-outline-regexp-bol)
  22117. level l)
  22118. (when (ignore-errors (org-back-to-heading t))
  22119. (setq level (funcall outline-level))
  22120. (catch 'exit
  22121. (or previous (forward-char 1))
  22122. (while (funcall fun re nil t)
  22123. (setq l (funcall outline-level))
  22124. (when (< l level) (goto-char pos) (throw 'exit nil))
  22125. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22126. (goto-char pos)
  22127. nil))))
  22128. (defun org-show-siblings ()
  22129. "Show all siblings of the current headline."
  22130. (save-excursion
  22131. (while (org-goto-sibling) (org-flag-heading nil)))
  22132. (save-excursion
  22133. (while (org-goto-sibling 'previous)
  22134. (org-flag-heading nil))))
  22135. (defun org-goto-first-child ()
  22136. "Goto the first child, even if it is invisible.
  22137. Return t when a child was found. Otherwise don't move point and
  22138. return nil."
  22139. (let (level (pos (point)) (re org-outline-regexp-bol))
  22140. (when (ignore-errors (org-back-to-heading t))
  22141. (setq level (outline-level))
  22142. (forward-char 1)
  22143. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22144. (progn (goto-char (match-beginning 0)) t)
  22145. (goto-char pos) nil))))
  22146. (defun org-show-hidden-entry ()
  22147. "Show an entry where even the heading is hidden."
  22148. (save-excursion
  22149. (org-show-entry)))
  22150. (defun org-flag-heading (flag &optional entry)
  22151. "Flag the current heading. FLAG non-nil means make invisible.
  22152. When ENTRY is non-nil, show the entire entry."
  22153. (save-excursion
  22154. (org-back-to-heading t)
  22155. ;; Check if we should show the entire entry
  22156. (if entry
  22157. (progn
  22158. (org-show-entry)
  22159. (save-excursion
  22160. (and (outline-next-heading)
  22161. (org-flag-heading nil))))
  22162. (outline-flag-region (max (point-min) (1- (point)))
  22163. (save-excursion (outline-end-of-heading) (point))
  22164. flag))))
  22165. (defun org-get-next-sibling ()
  22166. "Move to next heading of the same level, and return point.
  22167. If there is no such heading, return nil.
  22168. This is like outline-next-sibling, but invisible headings are ok."
  22169. (let ((level (funcall outline-level)))
  22170. (outline-next-heading)
  22171. (while (and (not (eobp)) (> (funcall outline-level) level))
  22172. (outline-next-heading))
  22173. (unless (or (eobp) (< (funcall outline-level) level))
  22174. (point))))
  22175. (defun org-get-last-sibling ()
  22176. "Move to previous heading of the same level, and return point.
  22177. If there is no such heading, return nil."
  22178. (let ((opoint (point))
  22179. (level (funcall outline-level)))
  22180. (outline-previous-heading)
  22181. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22182. (while (and (> (funcall outline-level) level)
  22183. (not (bobp)))
  22184. (outline-previous-heading))
  22185. (unless (< (funcall outline-level) level)
  22186. (point)))))
  22187. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22188. "Goto to the end of a subtree."
  22189. ;; This contains an exact copy of the original function, but it uses
  22190. ;; `org-back-to-heading', to make it work also in invisible
  22191. ;; trees. And is uses an invisible-ok argument.
  22192. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22193. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22194. ;; with many children and grandchildren etc, this can be much faster
  22195. ;; than the outline version.
  22196. (org-back-to-heading invisible-ok)
  22197. (let ((first t)
  22198. (level (funcall outline-level)))
  22199. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22200. ;; A true heading (not a plain list item), in Org
  22201. ;; This means we can easily find the end by looking
  22202. ;; only for the right number of stars. Using a regexp to do
  22203. ;; this is so much faster than using a Lisp loop.
  22204. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22205. (forward-char 1)
  22206. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22207. ;; something else, do it the slow way
  22208. (while (and (not (eobp))
  22209. (or first (> (funcall outline-level) level)))
  22210. (setq first nil)
  22211. (outline-next-heading)))
  22212. (unless to-heading
  22213. (when (memq (preceding-char) '(?\n ?\^M))
  22214. ;; Go to end of line before heading
  22215. (forward-char -1)
  22216. (when (memq (preceding-char) '(?\n ?\^M))
  22217. ;; leave blank line before heading
  22218. (forward-char -1)))))
  22219. (point))
  22220. (defun org-end-of-meta-data (&optional full)
  22221. "Skip planning line and properties drawer in current entry.
  22222. When optional argument FULL is non-nil, also skip empty lines,
  22223. clocking lines and regular drawers at the beginning of the
  22224. entry."
  22225. (org-back-to-heading t)
  22226. (forward-line)
  22227. (when (looking-at-p org-planning-line-re) (forward-line))
  22228. (when (looking-at org-property-drawer-re)
  22229. (goto-char (match-end 0))
  22230. (forward-line))
  22231. (when (and full (not (org-at-heading-p)))
  22232. (catch 'exit
  22233. (let ((end (save-excursion (outline-next-heading) (point)))
  22234. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22235. (while (not (eobp))
  22236. (cond ((looking-at-p org-drawer-regexp)
  22237. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22238. (forward-line)
  22239. (throw 'exit t)))
  22240. ((looking-at-p re) (forward-line))
  22241. (t (throw 'exit t))))))))
  22242. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22243. "Move forward to the ARG'th subheading at same level as this one.
  22244. Stop at the first and last subheadings of a superior heading.
  22245. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22246. non-nil it will also look at invisible ones."
  22247. (interactive "p")
  22248. (let ((backward? (and arg (< arg 0))))
  22249. (if (org-before-first-heading-p)
  22250. (if backward? (goto-char (point-min)) (outline-next-heading))
  22251. (org-back-to-heading invisible-ok)
  22252. (unless backward? (end-of-line)) ;do not match current headline
  22253. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22254. (f (if backward? #'re-search-backward #'re-search-forward))
  22255. (count (if arg (abs arg) 1))
  22256. (result (point)))
  22257. (while (and (> count 0)
  22258. (funcall f org-outline-regexp-bol nil 'move))
  22259. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22260. (cond ((< l level) (setq count 0))
  22261. ((and (= l level)
  22262. (or invisible-ok
  22263. (not (org-invisible-p
  22264. (line-beginning-position)))))
  22265. (cl-decf count)
  22266. (when (= l level) (setq result (point)))))))
  22267. (goto-char result))
  22268. (beginning-of-line))))
  22269. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22270. "Move backward to the ARG'th subheading at same level as this one.
  22271. Stop at the first and last subheadings of a superior heading."
  22272. (interactive "p")
  22273. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22274. (defun org-next-visible-heading (arg)
  22275. "Move to the next visible heading.
  22276. This function wraps `outline-next-visible-heading' with
  22277. `org-with-limited-levels' in order to skip over inline tasks and
  22278. respect customization of `org-odd-levels-only'."
  22279. (interactive "p")
  22280. (org-with-limited-levels
  22281. (outline-next-visible-heading arg)))
  22282. (defun org-previous-visible-heading (arg)
  22283. "Move to the previous visible heading.
  22284. This function wraps `outline-previous-visible-heading' with
  22285. `org-with-limited-levels' in order to skip over inline tasks and
  22286. respect customization of `org-odd-levels-only'."
  22287. (interactive "p")
  22288. (org-with-limited-levels
  22289. (outline-previous-visible-heading arg)))
  22290. (defun org-next-block (arg &optional backward block-regexp)
  22291. "Jump to the next block.
  22292. With a prefix argument ARG, jump forward ARG many blocks.
  22293. When BACKWARD is non-nil, jump to the previous block.
  22294. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22295. Match data is set according to this regexp when the function
  22296. returns.
  22297. Return point at beginning of the opening line of found block.
  22298. Throw an error if no block is found."
  22299. (interactive "p")
  22300. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22301. (case-fold-search t)
  22302. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22303. (count (or arg 1))
  22304. (origin (point))
  22305. last-element)
  22306. (if backward (beginning-of-line) (end-of-line))
  22307. (while (and (> count 0) (funcall search-fn re nil t))
  22308. (let ((element (save-excursion
  22309. (goto-char (match-beginning 0))
  22310. (save-match-data (org-element-at-point)))))
  22311. (when (and (memq (org-element-type element)
  22312. '(center-block comment-block dynamic-block
  22313. example-block export-block quote-block
  22314. special-block src-block verse-block))
  22315. (<= (match-beginning 0)
  22316. (org-element-property :post-affiliated element)))
  22317. (setq last-element element)
  22318. (cl-decf count))))
  22319. (if (= count 0)
  22320. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22321. (save-match-data (org-show-context)))
  22322. (goto-char origin)
  22323. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22324. (defun org-previous-block (arg &optional block-regexp)
  22325. "Jump to the previous block.
  22326. With a prefix argument ARG, jump backward ARG many source blocks.
  22327. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22328. (interactive "p")
  22329. (org-next-block arg t block-regexp))
  22330. (defun org-forward-paragraph ()
  22331. "Move forward to beginning of next paragraph or equivalent.
  22332. The function moves point to the beginning of the next visible
  22333. structural element, which can be a paragraph, a table, a list
  22334. item, etc. It also provides some special moves for convenience:
  22335. - On an affiliated keyword, jump to the beginning of the
  22336. relative element.
  22337. - On an item or a footnote definition, move to the second
  22338. element inside, if any.
  22339. - On a table or a property drawer, jump after it.
  22340. - On a verse or source block, stop after blank lines."
  22341. (interactive)
  22342. (when (eobp) (user-error "Cannot move further down"))
  22343. (let* ((deactivate-mark nil)
  22344. (element (org-element-at-point))
  22345. (type (org-element-type element))
  22346. (post-affiliated (org-element-property :post-affiliated element))
  22347. (contents-begin (org-element-property :contents-begin element))
  22348. (contents-end (org-element-property :contents-end element))
  22349. (end (let ((end (org-element-property :end element)) (parent element))
  22350. (while (and (setq parent (org-element-property :parent parent))
  22351. (= (org-element-property :contents-end parent) end))
  22352. (setq end (org-element-property :end parent)))
  22353. end)))
  22354. (cond ((not element)
  22355. (skip-chars-forward " \r\t\n")
  22356. (or (eobp) (beginning-of-line)))
  22357. ;; On affiliated keywords, move to element's beginning.
  22358. ((< (point) post-affiliated)
  22359. (goto-char post-affiliated))
  22360. ;; At a table row, move to the end of the table. Similarly,
  22361. ;; at a node property, move to the end of the property
  22362. ;; drawer.
  22363. ((memq type '(node-property table-row))
  22364. (goto-char (org-element-property
  22365. :end (org-element-property :parent element))))
  22366. ((memq type '(property-drawer table)) (goto-char end))
  22367. ;; Consider blank lines as separators in verse and source
  22368. ;; blocks to ease editing.
  22369. ((memq type '(src-block verse-block))
  22370. (when (eq type 'src-block)
  22371. (setq contents-end
  22372. (save-excursion (goto-char end)
  22373. (skip-chars-backward " \r\t\n")
  22374. (line-beginning-position))))
  22375. (beginning-of-line)
  22376. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22377. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22378. (goto-char end)
  22379. (skip-chars-forward " \r\t\n")
  22380. (if (= (point) contents-end) (goto-char end)
  22381. (beginning-of-line))))
  22382. ;; With no contents, just skip element.
  22383. ((not contents-begin) (goto-char end))
  22384. ;; If contents are invisible, skip the element altogether.
  22385. ((org-invisible-p (line-end-position))
  22386. (cl-case type
  22387. (headline
  22388. (org-with-limited-levels (outline-next-visible-heading 1)))
  22389. ;; At a plain list, make sure we move to the next item
  22390. ;; instead of skipping the whole list.
  22391. (plain-list (forward-char)
  22392. (org-forward-paragraph))
  22393. (otherwise (goto-char end))))
  22394. ((>= (point) contents-end) (goto-char end))
  22395. ((>= (point) contents-begin)
  22396. ;; This can only happen on paragraphs and plain lists.
  22397. (cl-case type
  22398. (paragraph (goto-char end))
  22399. ;; At a plain list, try to move to second element in
  22400. ;; first item, if possible.
  22401. (plain-list (end-of-line)
  22402. (org-forward-paragraph))))
  22403. ;; When contents start on the middle of a line (e.g. in
  22404. ;; items and footnote definitions), try to reach first
  22405. ;; element starting after current line.
  22406. ((> (line-end-position) contents-begin)
  22407. (end-of-line)
  22408. (org-forward-paragraph))
  22409. (t (goto-char contents-begin)))))
  22410. (defun org-backward-paragraph ()
  22411. "Move backward to start of previous paragraph or equivalent.
  22412. The function moves point to the beginning of the current
  22413. structural element, which can be a paragraph, a table, a list
  22414. item, etc., or to the beginning of the previous visible one if
  22415. point is already there. It also provides some special moves for
  22416. convenience:
  22417. - On an affiliated keyword, jump to the first one.
  22418. - On a table or a property drawer, move to its beginning.
  22419. - On a verse or source block, stop before blank lines."
  22420. (interactive)
  22421. (when (bobp) (user-error "Cannot move further up"))
  22422. (let* ((deactivate-mark nil)
  22423. (element (org-element-at-point))
  22424. (type (org-element-type element))
  22425. (contents-begin (org-element-property :contents-begin element))
  22426. (contents-end (org-element-property :contents-end element))
  22427. (post-affiliated (org-element-property :post-affiliated element))
  22428. (begin (org-element-property :begin element)))
  22429. (cond
  22430. ((not element) (goto-char (point-min)))
  22431. ((= (point) begin)
  22432. (backward-char)
  22433. (org-backward-paragraph))
  22434. ((<= (point) post-affiliated) (goto-char begin))
  22435. ((memq type '(node-property table-row))
  22436. (goto-char (org-element-property
  22437. :post-affiliated (org-element-property :parent element))))
  22438. ((memq type '(property-drawer table)) (goto-char begin))
  22439. ((memq type '(src-block verse-block))
  22440. (when (eq type 'src-block)
  22441. (setq contents-begin
  22442. (save-excursion (goto-char begin) (forward-line) (point))))
  22443. (if (= (point) contents-begin) (goto-char post-affiliated)
  22444. ;; Inside a verse block, see blank lines as paragraph
  22445. ;; separators.
  22446. (let ((origin (point)))
  22447. (skip-chars-backward " \r\t\n" contents-begin)
  22448. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22449. (skip-chars-forward " \r\t\n" origin)
  22450. (if (= (point) origin) (goto-char contents-begin)
  22451. (beginning-of-line))))))
  22452. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22453. ((eq type 'paragraph)
  22454. (goto-char contents-begin)
  22455. ;; When at first paragraph in an item or a footnote definition,
  22456. ;; move directly to beginning of line.
  22457. (let ((parent-contents
  22458. (org-element-property
  22459. :contents-begin (org-element-property :parent element))))
  22460. (when (and parent-contents (= parent-contents contents-begin))
  22461. (beginning-of-line))))
  22462. ;; At the end of a greater element, move to the beginning of the
  22463. ;; last element within.
  22464. ((>= (point) contents-end)
  22465. (goto-char (1- contents-end))
  22466. (org-backward-paragraph))
  22467. (t (goto-char (or post-affiliated begin))))
  22468. ;; Ensure we never leave point invisible.
  22469. (when (org-invisible-p (point)) (beginning-of-visual-line))))
  22470. (defun org-forward-element ()
  22471. "Move forward by one element.
  22472. Move to the next element at the same level, when possible."
  22473. (interactive)
  22474. (cond ((eobp) (user-error "Cannot move further down"))
  22475. ((org-with-limited-levels (org-at-heading-p))
  22476. (let ((origin (point)))
  22477. (goto-char (org-end-of-subtree nil t))
  22478. (unless (org-with-limited-levels (org-at-heading-p))
  22479. (goto-char origin)
  22480. (user-error "Cannot move further down"))))
  22481. (t
  22482. (let* ((elem (org-element-at-point))
  22483. (end (org-element-property :end elem))
  22484. (parent (org-element-property :parent elem)))
  22485. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22486. (goto-char (org-element-property :end parent)))
  22487. ((integer-or-marker-p end) (goto-char end))
  22488. (t (message "No element at point")))))))
  22489. (defun org-backward-element ()
  22490. "Move backward by one element.
  22491. Move to the previous element at the same level, when possible."
  22492. (interactive)
  22493. (cond ((bobp) (user-error "Cannot move further up"))
  22494. ((org-with-limited-levels (org-at-heading-p))
  22495. ;; At a headline, move to the previous one, if any, or stay
  22496. ;; here.
  22497. (let ((origin (point)))
  22498. (org-with-limited-levels (org-backward-heading-same-level 1))
  22499. ;; When current headline has no sibling above, move to its
  22500. ;; parent.
  22501. (when (= (point) origin)
  22502. (or (org-with-limited-levels (org-up-heading-safe))
  22503. (progn (goto-char origin)
  22504. (user-error "Cannot move further up"))))))
  22505. (t
  22506. (let* ((elem (org-element-at-point))
  22507. (beg (org-element-property :begin elem)))
  22508. (cond
  22509. ;; Move to beginning of current element if point isn't
  22510. ;; there already.
  22511. ((null beg) (message "No element at point"))
  22512. ((/= (point) beg) (goto-char beg))
  22513. (t (goto-char beg)
  22514. (skip-chars-backward " \r\t\n")
  22515. (unless (bobp)
  22516. (let ((prev (org-element-at-point)))
  22517. (goto-char (org-element-property :begin prev))
  22518. (while (and (setq prev (org-element-property :parent prev))
  22519. (<= (org-element-property :end prev) beg))
  22520. (goto-char (org-element-property :begin prev)))))))))))
  22521. (defun org-up-element ()
  22522. "Move to upper element."
  22523. (interactive)
  22524. (if (org-with-limited-levels (org-at-heading-p))
  22525. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22526. (let* ((elem (org-element-at-point))
  22527. (parent (org-element-property :parent elem)))
  22528. (if parent (goto-char (org-element-property :begin parent))
  22529. (if (org-with-limited-levels (org-before-first-heading-p))
  22530. (user-error "No surrounding element")
  22531. (org-with-limited-levels (org-back-to-heading)))))))
  22532. (defun org-down-element ()
  22533. "Move to inner element."
  22534. (interactive)
  22535. (let ((element (org-element-at-point)))
  22536. (cond
  22537. ((memq (org-element-type element) '(plain-list table))
  22538. (goto-char (org-element-property :contents-begin element))
  22539. (forward-char))
  22540. ((memq (org-element-type element) org-element-greater-elements)
  22541. ;; If contents are hidden, first disclose them.
  22542. (when (org-invisible-p (line-end-position)) (org-cycle))
  22543. (goto-char (or (org-element-property :contents-begin element)
  22544. (user-error "No content for this element"))))
  22545. (t (user-error "No inner element")))))
  22546. (defun org-drag-element-backward ()
  22547. "Move backward element at point."
  22548. (interactive)
  22549. (let ((elem (or (org-element-at-point)
  22550. (user-error "No element at point"))))
  22551. (if (eq (org-element-type elem) 'headline)
  22552. ;; Preserve point when moving a whole tree, even if point was
  22553. ;; on blank lines below the headline.
  22554. (let ((offset (skip-chars-backward " \t\n")))
  22555. (unwind-protect (org-move-subtree-up)
  22556. (forward-char (- offset))))
  22557. (let ((prev-elem
  22558. (save-excursion
  22559. (goto-char (org-element-property :begin elem))
  22560. (skip-chars-backward " \r\t\n")
  22561. (unless (bobp)
  22562. (let* ((beg (org-element-property :begin elem))
  22563. (prev (org-element-at-point))
  22564. (up prev))
  22565. (while (and (setq up (org-element-property :parent up))
  22566. (<= (org-element-property :end up) beg))
  22567. (setq prev up))
  22568. prev)))))
  22569. ;; Error out if no previous element or previous element is
  22570. ;; a parent of the current one.
  22571. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22572. (user-error "Cannot drag element backward")
  22573. (let ((pos (point)))
  22574. (org-element-swap-A-B prev-elem elem)
  22575. (goto-char (+ (org-element-property :begin prev-elem)
  22576. (- pos (org-element-property :begin elem))))))))))
  22577. (defun org-drag-element-forward ()
  22578. "Move forward element at point."
  22579. (interactive)
  22580. (let* ((pos (point))
  22581. (elem (or (org-element-at-point)
  22582. (user-error "No element at point"))))
  22583. (when (= (point-max) (org-element-property :end elem))
  22584. (user-error "Cannot drag element forward"))
  22585. (goto-char (org-element-property :end elem))
  22586. (let ((next-elem (org-element-at-point)))
  22587. (when (or (org-element-nested-p elem next-elem)
  22588. (and (eq (org-element-type next-elem) 'headline)
  22589. (not (eq (org-element-type elem) 'headline))))
  22590. (goto-char pos)
  22591. (user-error "Cannot drag element forward"))
  22592. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22593. ;; body's length (without final blanks) and by the length of
  22594. ;; blanks between ELEM and NEXT-ELEM.
  22595. (let ((size-next (- (save-excursion
  22596. (goto-char (org-element-property :end next-elem))
  22597. (skip-chars-backward " \r\t\n")
  22598. (forward-line)
  22599. ;; Small correction if buffer doesn't end
  22600. ;; with a newline character.
  22601. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22602. (org-element-property :begin next-elem)))
  22603. (size-blank (- (org-element-property :end elem)
  22604. (save-excursion
  22605. (goto-char (org-element-property :end elem))
  22606. (skip-chars-backward " \r\t\n")
  22607. (forward-line)
  22608. (point)))))
  22609. (org-element-swap-A-B elem next-elem)
  22610. (goto-char (+ pos size-next size-blank))))))
  22611. (defun org-drag-line-forward (arg)
  22612. "Drag the line at point ARG lines forward."
  22613. (interactive "p")
  22614. (dotimes (_ (abs arg))
  22615. (let ((c (current-column)))
  22616. (if (< 0 arg)
  22617. (progn
  22618. (beginning-of-line 2)
  22619. (transpose-lines 1)
  22620. (beginning-of-line 0))
  22621. (transpose-lines 1)
  22622. (beginning-of-line -1))
  22623. (org-move-to-column c))))
  22624. (defun org-drag-line-backward (arg)
  22625. "Drag the line at point ARG lines backward."
  22626. (interactive "p")
  22627. (org-drag-line-forward (- arg)))
  22628. (defun org-mark-element ()
  22629. "Put point at beginning of this element, mark at end.
  22630. Interactively, if this command is repeated or (in Transient Mark
  22631. mode) if the mark is active, it marks the next element after the
  22632. ones already marked."
  22633. (interactive)
  22634. (let (deactivate-mark)
  22635. (if (and (called-interactively-p 'any)
  22636. (or (and (eq last-command this-command) (mark t))
  22637. (and transient-mark-mode mark-active)))
  22638. (set-mark
  22639. (save-excursion
  22640. (goto-char (mark))
  22641. (goto-char (org-element-property :end (org-element-at-point)))))
  22642. (let ((element (org-element-at-point)))
  22643. (end-of-line)
  22644. (push-mark (org-element-property :end element) t t)
  22645. (goto-char (org-element-property :begin element))))))
  22646. (defun org-narrow-to-element ()
  22647. "Narrow buffer to current element."
  22648. (interactive)
  22649. (let ((elem (org-element-at-point)))
  22650. (cond
  22651. ((eq (car elem) 'headline)
  22652. (narrow-to-region
  22653. (org-element-property :begin elem)
  22654. (org-element-property :end elem)))
  22655. ((memq (car elem) org-element-greater-elements)
  22656. (narrow-to-region
  22657. (org-element-property :contents-begin elem)
  22658. (org-element-property :contents-end elem)))
  22659. (t
  22660. (narrow-to-region
  22661. (org-element-property :begin elem)
  22662. (org-element-property :end elem))))))
  22663. (defun org-transpose-element ()
  22664. "Transpose current and previous elements, keeping blank lines between.
  22665. Point is moved after both elements."
  22666. (interactive)
  22667. (org-skip-whitespace)
  22668. (let ((end (org-element-property :end (org-element-at-point))))
  22669. (org-drag-element-backward)
  22670. (goto-char end)))
  22671. (defun org-unindent-buffer ()
  22672. "Un-indent the visible part of the buffer.
  22673. Relative indentation (between items, inside blocks, etc.) isn't
  22674. modified."
  22675. (interactive)
  22676. (unless (eq major-mode 'org-mode)
  22677. (user-error "Cannot un-indent a buffer not in Org mode"))
  22678. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22679. (unindent-tree
  22680. (lambda (contents)
  22681. (dolist (element (reverse contents))
  22682. (if (memq (org-element-type element) '(headline section))
  22683. (funcall unindent-tree (org-element-contents element))
  22684. (save-excursion
  22685. (save-restriction
  22686. (narrow-to-region
  22687. (org-element-property :begin element)
  22688. (org-element-property :end element))
  22689. (org-do-remove-indentation))))))))
  22690. (funcall unindent-tree (org-element-contents parse-tree))))
  22691. (defun org-show-children (&optional level)
  22692. "Show all direct subheadings of this heading.
  22693. Prefix arg LEVEL is how many levels below the current level
  22694. should be shown. Default is enough to cause the following
  22695. heading to appear."
  22696. (interactive "p")
  22697. ;; If `orgstruct-mode' is active, use the slower version.
  22698. (if orgstruct-mode (call-interactively #'outline-show-children)
  22699. (save-excursion
  22700. (org-back-to-heading t)
  22701. (let* ((current-level (funcall outline-level))
  22702. (max-level (org-get-valid-level
  22703. current-level
  22704. (if level (prefix-numeric-value level) 1)))
  22705. (end (save-excursion (org-end-of-subtree t t)))
  22706. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22707. (past-first-child nil)
  22708. ;; Make sure to skip inlinetasks.
  22709. (re (format regexp-fmt
  22710. current-level
  22711. (cond
  22712. ((not (featurep 'org-inlinetask)) "")
  22713. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22714. 3))
  22715. (t (1- org-inlinetask-min-level))))))
  22716. ;; Display parent heading.
  22717. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22718. (forward-line)
  22719. ;; Display children. First child may be deeper than expected
  22720. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22721. ;; MAX-LEVEL accordingly.
  22722. (while (re-search-forward re end t)
  22723. (unless past-first-child
  22724. (setq re (format regexp-fmt
  22725. current-level
  22726. (max (funcall outline-level) max-level)))
  22727. (setq past-first-child t))
  22728. (outline-flag-region
  22729. (line-end-position 0) (line-end-position) nil))))))
  22730. (defun org-show-subtree ()
  22731. "Show everything after this heading at deeper levels."
  22732. (interactive)
  22733. (outline-flag-region
  22734. (point)
  22735. (save-excursion
  22736. (org-end-of-subtree t t))
  22737. nil))
  22738. (defun org-show-entry ()
  22739. "Show the body directly following this heading.
  22740. Show the heading too, if it is currently invisible."
  22741. (interactive)
  22742. (save-excursion
  22743. (ignore-errors
  22744. (org-back-to-heading t)
  22745. (outline-flag-region
  22746. (max (point-min) (1- (point)))
  22747. (save-excursion
  22748. (if (re-search-forward
  22749. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22750. (match-beginning 1)
  22751. (point-max)))
  22752. nil)
  22753. (org-cycle-hide-drawers 'children))))
  22754. (defun org-make-options-regexp (kwds &optional extra)
  22755. "Make a regular expression for keyword lines.
  22756. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22757. when non-nil, is a regexp matching keywords names."
  22758. (concat "^[ \t]*#\\+\\("
  22759. (regexp-opt kwds)
  22760. (and extra (concat (and kwds "\\|") extra))
  22761. "\\):[ \t]*\\(.*\\)"))
  22762. ;;;; Integration with and fixes for other packages
  22763. ;;; Imenu support
  22764. (defvar-local org-imenu-markers nil
  22765. "All markers currently used by Imenu.")
  22766. (defun org-imenu-new-marker (&optional pos)
  22767. "Return a new marker for use by Imenu, and remember the marker."
  22768. (let ((m (make-marker)))
  22769. (move-marker m (or pos (point)))
  22770. (push m org-imenu-markers)
  22771. m))
  22772. (defun org-imenu-get-tree ()
  22773. "Produce the index for Imenu."
  22774. (dolist (x org-imenu-markers) (move-marker x nil))
  22775. (setq org-imenu-markers nil)
  22776. (let* ((case-fold-search nil)
  22777. (n org-imenu-depth)
  22778. (re (concat "^" (org-get-limited-outline-regexp)))
  22779. (subs (make-vector (1+ n) nil))
  22780. (last-level 0)
  22781. m level head0 head)
  22782. (org-with-wide-buffer
  22783. (goto-char (point-max))
  22784. (while (re-search-backward re nil t)
  22785. (setq level (org-reduced-level (funcall outline-level)))
  22786. (when (and (<= level n)
  22787. (looking-at org-complex-heading-regexp)
  22788. (setq head0 (match-string-no-properties 4)))
  22789. (setq head (org-link-display-format head0)
  22790. m (org-imenu-new-marker))
  22791. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22792. (if (>= level last-level)
  22793. (push (cons head m) (aref subs level))
  22794. (push (cons head (aref subs (1+ level))) (aref subs level))
  22795. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22796. (setq last-level level))))
  22797. (aref subs 1)))
  22798. (eval-after-load "imenu"
  22799. '(progn
  22800. (add-hook 'imenu-after-jump-hook
  22801. (lambda ()
  22802. (when (derived-mode-p 'org-mode)
  22803. (org-show-context 'org-goto))))))
  22804. (defun org-link-display-format (s)
  22805. "Replace links in string S with their description.
  22806. If there is no description, use the link target."
  22807. (save-match-data
  22808. (replace-regexp-in-string
  22809. org-bracket-link-analytic-regexp
  22810. (lambda (m)
  22811. (if (match-end 5) (match-string 5 m)
  22812. (concat (match-string 1 m) (match-string 3 m))))
  22813. s nil t)))
  22814. (defun org-toggle-link-display ()
  22815. "Toggle the literal or descriptive display of links."
  22816. (interactive)
  22817. (if org-descriptive-links
  22818. (progn (org-remove-from-invisibility-spec '(org-link))
  22819. (org-restart-font-lock)
  22820. (setq org-descriptive-links nil))
  22821. (progn (add-to-invisibility-spec '(org-link))
  22822. (org-restart-font-lock)
  22823. (setq org-descriptive-links t))))
  22824. ;; Speedbar support
  22825. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22826. "Overlay marking the agenda restriction line in speedbar.")
  22827. (overlay-put org-speedbar-restriction-lock-overlay
  22828. 'face 'org-agenda-restriction-lock)
  22829. (overlay-put org-speedbar-restriction-lock-overlay
  22830. 'help-echo "Agendas are currently limited to this item.")
  22831. (delete-overlay org-speedbar-restriction-lock-overlay)
  22832. (defun org-speedbar-set-agenda-restriction ()
  22833. "Restrict future agenda commands to the location at point in speedbar.
  22834. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22835. (interactive)
  22836. (require 'org-agenda)
  22837. (let (p m tp np dir txt)
  22838. (cond
  22839. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22840. 'org-imenu t))
  22841. (setq m (get-text-property p 'org-imenu-marker))
  22842. (with-current-buffer (marker-buffer m)
  22843. (goto-char m)
  22844. (org-agenda-set-restriction-lock 'subtree)))
  22845. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22846. 'speedbar-function 'speedbar-find-file))
  22847. (setq tp (previous-single-property-change
  22848. (1+ p) 'speedbar-function)
  22849. np (next-single-property-change
  22850. tp 'speedbar-function)
  22851. dir (speedbar-line-directory)
  22852. txt (buffer-substring-no-properties (or tp (point-min))
  22853. (or np (point-max))))
  22854. (with-current-buffer (find-file-noselect
  22855. (let ((default-directory dir))
  22856. (expand-file-name txt)))
  22857. (unless (derived-mode-p 'org-mode)
  22858. (user-error "Cannot restrict to non-Org mode file"))
  22859. (org-agenda-set-restriction-lock 'file)))
  22860. (t (user-error "Don't know how to restrict Org mode agenda")))
  22861. (move-overlay org-speedbar-restriction-lock-overlay
  22862. (point-at-bol) (point-at-eol))
  22863. (setq current-prefix-arg nil)
  22864. (org-agenda-maybe-redo)))
  22865. (defvar speedbar-file-key-map)
  22866. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22867. (eval-after-load "speedbar"
  22868. '(progn
  22869. (speedbar-add-supported-extension ".org")
  22870. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22871. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22872. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22873. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22874. (add-hook 'speedbar-visiting-tag-hook
  22875. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22876. ;;; Fixes and Hacks for problems with other packages
  22877. (defun org--flyspell-object-check-p (element)
  22878. "Non-nil when Flyspell can check object at point.
  22879. ELEMENT is the element at point."
  22880. (let ((object (save-excursion
  22881. (when (looking-at-p "\\>") (backward-char))
  22882. (org-element-context element))))
  22883. (cl-case (org-element-type object)
  22884. ;; Prevent checks in links due to keybinding conflict with
  22885. ;; Flyspell.
  22886. ((code entity export-snippet inline-babel-call
  22887. inline-src-block line-break latex-fragment link macro
  22888. statistics-cookie target timestamp verbatim)
  22889. nil)
  22890. (footnote-reference
  22891. ;; Only in inline footnotes, within the definition.
  22892. (and (eq (org-element-property :type object) 'inline)
  22893. (< (save-excursion
  22894. (goto-char (org-element-property :begin object))
  22895. (search-forward ":" nil t 2))
  22896. (point))))
  22897. (otherwise t))))
  22898. (defun org-mode-flyspell-verify ()
  22899. "Function used for `flyspell-generic-check-word-predicate'."
  22900. (if (org-at-heading-p)
  22901. ;; At a headline or an inlinetask, check title only. This is
  22902. ;; faster than relying on `org-element-at-point'.
  22903. (and (save-excursion (beginning-of-line)
  22904. (and (let ((case-fold-search t))
  22905. (not (looking-at-p "\\*+ END[ \t]*$")))
  22906. (let ((case-fold-search nil))
  22907. (looking-at org-complex-heading-regexp))))
  22908. (match-beginning 4)
  22909. (>= (point) (match-beginning 4))
  22910. (or (not (match-beginning 5))
  22911. (< (point) (match-beginning 5))))
  22912. (let* ((element (org-element-at-point))
  22913. (post-affiliated (org-element-property :post-affiliated element)))
  22914. (cond
  22915. ;; Ignore checks in all affiliated keywords but captions.
  22916. ((< (point) post-affiliated)
  22917. (and (save-excursion
  22918. (beginning-of-line)
  22919. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22920. (> (point) (match-end 0))
  22921. (org--flyspell-object-check-p element)))
  22922. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22923. ((let ((log (org-log-into-drawer)))
  22924. (and log
  22925. (let ((drawer (org-element-lineage element '(drawer))))
  22926. (and drawer
  22927. (eq (compare-strings
  22928. log nil nil
  22929. (org-element-property :drawer-name drawer) nil nil t)
  22930. t)))))
  22931. nil)
  22932. (t
  22933. (cl-case (org-element-type element)
  22934. ((comment quote-section) t)
  22935. (comment-block
  22936. ;; Allow checks between block markers, not on them.
  22937. (and (> (line-beginning-position) post-affiliated)
  22938. (save-excursion
  22939. (end-of-line)
  22940. (skip-chars-forward " \r\t\n")
  22941. (< (point) (org-element-property :end element)))))
  22942. ;; Arbitrary list of keywords where checks are meaningful.
  22943. ;; Make sure point is on the value part of the element.
  22944. (keyword
  22945. (and (member (org-element-property :key element)
  22946. '("DESCRIPTION" "TITLE"))
  22947. (save-excursion
  22948. (search-backward ":" (line-beginning-position) t))))
  22949. ;; Check is globally allowed in paragraphs verse blocks and
  22950. ;; table rows (after affiliated keywords) but some objects
  22951. ;; must not be affected.
  22952. ((paragraph table-row verse-block)
  22953. (let ((cbeg (org-element-property :contents-begin element))
  22954. (cend (org-element-property :contents-end element)))
  22955. (and cbeg (>= (point) cbeg) (< (point) cend)
  22956. (org--flyspell-object-check-p element))))))))))
  22957. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22958. (defun org-remove-flyspell-overlays-in (beg end)
  22959. "Remove flyspell overlays in region."
  22960. (and (bound-and-true-p flyspell-mode)
  22961. (fboundp 'flyspell-delete-region-overlays)
  22962. (flyspell-delete-region-overlays beg end)))
  22963. (defvar flyspell-delayed-commands)
  22964. (eval-after-load "flyspell"
  22965. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22966. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22967. (eval-after-load "bookmark"
  22968. '(if (boundp 'bookmark-after-jump-hook)
  22969. ;; We can use the hook
  22970. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22971. ;; Hook not available, use advice
  22972. (defadvice bookmark-jump (after org-make-visible activate)
  22973. "Make the position visible."
  22974. (org-bookmark-jump-unhide))))
  22975. ;; Make sure saveplace shows the location if it was hidden
  22976. (eval-after-load "saveplace"
  22977. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22978. "Make the position visible."
  22979. (org-bookmark-jump-unhide)))
  22980. ;; Make sure ecb shows the location if it was hidden
  22981. (eval-after-load "ecb"
  22982. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22983. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22984. (when (derived-mode-p 'org-mode)
  22985. (org-show-context))))
  22986. (defun org-bookmark-jump-unhide ()
  22987. "Unhide the current position, to show the bookmark location."
  22988. (and (derived-mode-p 'org-mode)
  22989. (or (org-invisible-p)
  22990. (save-excursion (goto-char (max (point-min) (1- (point))))
  22991. (org-invisible-p)))
  22992. (org-show-context 'bookmark-jump)))
  22993. (defun org-mark-jump-unhide ()
  22994. "Make the point visible with `org-show-context' after jumping to the mark."
  22995. (when (and (derived-mode-p 'org-mode)
  22996. (org-invisible-p))
  22997. (org-show-context 'mark-goto)))
  22998. (eval-after-load "simple"
  22999. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23000. "Make the point visible with `org-show-context'."
  23001. (org-mark-jump-unhide)))
  23002. (eval-after-load "simple"
  23003. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23004. "Make the point visible with `org-show-context'."
  23005. (org-mark-jump-unhide)))
  23006. (eval-after-load "simple"
  23007. '(defadvice pop-global-mark (after org-make-visible activate)
  23008. "Make the point visible with `org-show-context'."
  23009. (org-mark-jump-unhide)))
  23010. ;; Make session.el ignore our circular variable
  23011. (defvar session-globals-exclude)
  23012. (eval-after-load "session"
  23013. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23014. ;;;; Finish up
  23015. (provide 'org)
  23016. (run-hooks 'org-load-hook)
  23017. ;;; org.el ends here