org.el 949 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102
  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-2016 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"
  105. (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  108. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  109. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  110. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  111. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  112. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  113. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  114. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  115. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  116. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  117. (declare-function org-clock-update-time-maybe "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  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. (defsubst org-uniquify (list)
  162. "Non-destructively remove duplicate elements from LIST."
  163. (let ((res (copy-sequence list))) (delete-dups res)))
  164. (defsubst org-get-at-bol (property)
  165. "Get text property PROPERTY at the beginning of line."
  166. (get-text-property (point-at-bol) property))
  167. (defsubst org-trim (s &optional keep-lead)
  168. "Remove whitespace at the beginning and the end of string S.
  169. When optional argument KEEP-LEAD is non-nil, removing blank lines
  170. at the beginning of the string does not affect leading indentation."
  171. (replace-regexp-in-string
  172. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  173. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  174. ;; load languages based on value of `org-babel-load-languages'
  175. (defvar org-babel-load-languages)
  176. ;;;###autoload
  177. (defun org-babel-do-load-languages (sym value)
  178. "Load the languages defined in `org-babel-load-languages'."
  179. (set-default sym value)
  180. (dolist (pair org-babel-load-languages)
  181. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  182. (if active
  183. (require (intern (concat "ob-" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-execute:" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-expand-body:" lang)))))))
  188. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  189. ;;;###autoload
  190. (defun org-babel-load-file (file &optional compile)
  191. "Load Emacs Lisp source code blocks in the Org FILE.
  192. This function exports the source code using `org-babel-tangle'
  193. and then loads the resulting file using `load-file'. With prefix
  194. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  195. file to byte-code before it is loaded."
  196. (interactive "fFile to load: \nP")
  197. (let* ((age (lambda (file)
  198. (float-time
  199. (time-subtract (current-time)
  200. (nth 5 (or (file-attributes (file-truename file))
  201. (file-attributes file)))))))
  202. (base-name (file-name-sans-extension file))
  203. (exported-file (concat base-name ".el")))
  204. ;; tangle if the Org file is newer than the elisp file
  205. (unless (and (file-exists-p exported-file)
  206. (> (funcall age file) (funcall age exported-file)))
  207. ;; Tangle-file traversal returns reversed list of tangled files
  208. ;; and we want to evaluate the first target.
  209. (setq exported-file
  210. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  211. (message "%s %s"
  212. (if compile
  213. (progn (byte-compile-file exported-file 'load)
  214. "Compiled and loaded")
  215. (progn (load-file exported-file) "Loaded"))
  216. exported-file)))
  217. (defcustom org-babel-load-languages '((emacs-lisp . t))
  218. "Languages which can be evaluated in Org buffers.
  219. This list can be used to load support for any of the languages
  220. below, note that each language will depend on a different set of
  221. system executables and/or Emacs modes. When a language is
  222. \"loaded\", then code blocks in that language can be evaluated
  223. with `org-babel-execute-src-block' bound by default to C-c
  224. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  225. be set to remove code block evaluation from the C-c C-c
  226. keybinding. By default only Emacs Lisp (which has no
  227. requirements) is loaded."
  228. :group 'org-babel
  229. :set 'org-babel-do-load-languages
  230. :version "24.1"
  231. :type '(alist :tag "Babel Languages"
  232. :key-type
  233. (choice
  234. (const :tag "Awk" awk)
  235. (const :tag "C" C)
  236. (const :tag "R" R)
  237. (const :tag "Asymptote" asymptote)
  238. (const :tag "Calc" calc)
  239. (const :tag "Clojure" clojure)
  240. (const :tag "CSS" css)
  241. (const :tag "Ditaa" ditaa)
  242. (const :tag "Dot" dot)
  243. (const :tag "Emacs Lisp" emacs-lisp)
  244. (const :tag "Forth" forth)
  245. (const :tag "Fortran" fortran)
  246. (const :tag "Gnuplot" gnuplot)
  247. (const :tag "Haskell" haskell)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "ebnf2ps" ebnf2ps))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-comment-string "COMMENT"
  462. "Entries starting with this keyword will never be exported.
  463. \\<org-mode-map>
  464. An entry can be toggled between COMMENT and normal with
  465. `\\[org-toggle-comment]'.")
  466. ;;;; LaTeX Environments and Fragments
  467. (defconst org-latex-regexps
  468. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  469. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  470. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  471. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  472. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  473. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  474. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  475. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  476. "Regular expressions for matching embedded LaTeX.")
  477. ;;;; Node Property
  478. (defconst org-effort-property "Effort"
  479. "The property that is being used to keep track of effort estimates.
  480. Effort estimates given in this property need to have the format H:MM.")
  481. ;;;; Table
  482. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  483. "Detect an org-type or table-type table.")
  484. (defconst org-table-line-regexp "^[ \t]*|"
  485. "Detect an org-type table line.")
  486. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  487. "Detect an org-type table line.")
  488. (defconst org-table-hline-regexp "^[ \t]*|-"
  489. "Detect an org-type table hline.")
  490. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  491. "Detect a table-type table hline.")
  492. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  493. "Detect the first line outside a table when searching from within it.
  494. This works for both table types.")
  495. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  496. "Detect a #+TBLFM line.")
  497. ;;;; Timestamp
  498. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  499. "Regular expression for fast time stamp matching.")
  500. (defconst org-ts-regexp-inactive
  501. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  502. "Regular expression for fast inactive time stamp matching.")
  503. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  504. "Regular expression for fast time stamp matching.")
  505. (defconst org-ts-regexp0
  506. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.
  508. This one does not require the space after the date, so it can be used
  509. on a string that terminates immediately after the date.")
  510. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  511. "Regular expression matching time strings for analysis.")
  512. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  513. "Regular expression matching time stamps, with groups.")
  514. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  515. "Regular expression matching time stamps (also [..]), with groups.")
  516. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  517. "Regular expression matching a time stamp range.")
  518. (defconst org-tr-regexp-both
  519. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  522. org-ts-regexp "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.")
  524. (defconst org-tsr-regexp-both
  525. (concat org-ts-regexp-both "\\(--?-?"
  526. org-ts-regexp-both "\\)?")
  527. "Regular expression matching a time stamp or time stamp range.
  528. The time stamps may be either active or inactive.")
  529. (defconst org-repeat-re
  530. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "24.4"
  584. :package-version '(Org . "8.0")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to doc-view buffers" org-docview)
  592. (const :tag " eww: Store link to url of eww" org-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" org-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  603. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  604. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  605. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  606. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  607. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  608. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  609. (const :tag "C collector: Collect properties into tables" org-collector)
  610. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  611. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  612. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  613. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  614. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  615. (const :tag "C eval: Include command output as text" org-eval)
  616. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  617. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  618. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  619. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  620. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  621. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  622. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  623. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  624. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  625. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  626. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  627. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  628. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  629. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  630. (const :tag "C registry: A registry for Org links" org-registry)
  631. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  632. (const :tag "C secretary: Team management with org-mode" org-secretary)
  633. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  634. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  635. (const :tag "C track: Keep up with Org mode development" org-track)
  636. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  637. (const :tag "C vm: Links to VM folders/messages" org-vm)
  638. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  639. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  640. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  641. (defvar org-export-registered-backends) ; From ox.el.
  642. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  643. (declare-function org-export-backend-name "ox" (backend) t)
  644. (defcustom org-export-backends '(ascii html icalendar latex odt)
  645. "List of export back-ends that should be always available.
  646. If a description starts with <C>, the file is not part of Emacs
  647. and loading it will require that you have downloaded and properly
  648. installed the Org mode distribution.
  649. Unlike to `org-modules', libraries in this list will not be
  650. loaded along with Org, but only once the export framework is
  651. needed.
  652. This variable needs to be set before org.el is loaded. If you
  653. need to make a change while Emacs is running, use the customize
  654. interface or run the following code, where VAL stands for the new
  655. value of the variable, after updating it:
  656. (progn
  657. (setq org-export-registered-backends
  658. (cl-remove-if-not
  659. (lambda (backend)
  660. (let ((name (org-export-backend-name backend)))
  661. (or (memq name val)
  662. (catch \\='parentp
  663. (dolist (b val)
  664. (and (org-export-derived-backend-p b name)
  665. (throw \\='parentp t)))))))
  666. org-export-registered-backends))
  667. (let ((new-list (mapcar #\\='org-export-backend-name
  668. org-export-registered-backends)))
  669. (dolist (backend val)
  670. (cond
  671. ((not (load (format \"ox-%s\" backend) t t))
  672. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  673. backend))
  674. ((not (memq backend new-list)) (push backend new-list))))
  675. (set-default \\='org-export-backends new-list)))
  676. Adding a back-end to this list will also pull the back-end it
  677. depends on, if any."
  678. :group 'org
  679. :group 'org-export
  680. :version "25.2"
  681. :package-version '(Org . "9.0")
  682. :initialize 'custom-initialize-set
  683. :set (lambda (var val)
  684. (if (not (featurep 'ox)) (set-default var val)
  685. ;; Any back-end not required anymore (not present in VAL and not
  686. ;; a parent of any back-end in the new value) is removed from the
  687. ;; list of registered back-ends.
  688. (setq org-export-registered-backends
  689. (cl-remove-if-not
  690. (lambda (backend)
  691. (let ((name (org-export-backend-name backend)))
  692. (or (memq name val)
  693. (catch 'parentp
  694. (dolist (b val)
  695. (and (org-export-derived-backend-p b name)
  696. (throw 'parentp t)))))))
  697. org-export-registered-backends))
  698. ;; Now build NEW-LIST of both new back-ends and required
  699. ;; parents.
  700. (let ((new-list (mapcar #'org-export-backend-name
  701. org-export-registered-backends)))
  702. (dolist (backend val)
  703. (cond
  704. ((not (load (format "ox-%s" backend) t t))
  705. (message "Problems while trying to load export back-end `%s'"
  706. backend))
  707. ((not (memq backend new-list)) (push backend new-list))))
  708. ;; Set VAR to that list with fixed dependencies.
  709. (set-default var new-list))))
  710. :type '(set :greedy t
  711. (const :tag " ascii Export buffer to ASCII format" ascii)
  712. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  713. (const :tag " html Export buffer to HTML format" html)
  714. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  715. (const :tag " latex Export buffer to LaTeX format" latex)
  716. (const :tag " man Export buffer to MAN format" man)
  717. (const :tag " md Export buffer to Markdown format" md)
  718. (const :tag " odt Export buffer to ODT format" odt)
  719. (const :tag " org Export buffer to Org format" org)
  720. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  721. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  722. (const :tag "C deck Export buffer to deck.js presentations" deck)
  723. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  724. (const :tag "C groff Export buffer to Groff format" groff)
  725. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  726. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  727. (const :tag "C s5 Export buffer to s5 presentations" s5)
  728. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  729. (eval-after-load 'ox
  730. '(dolist (backend org-export-backends)
  731. (condition-case nil (require (intern (format "ox-%s" backend)))
  732. (error (message "Problems while trying to load export back-end `%s'"
  733. backend)))))
  734. (defcustom org-support-shift-select nil
  735. "Non-nil means make shift-cursor commands select text when possible.
  736. \\<org-mode-map>\
  737. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  738. start selecting a region, or enlarge regions started in this way.
  739. In Org mode, in special contexts, these same keys are used for
  740. other purposes, important enough to compete with shift selection.
  741. Org tries to balance these needs by supporting `shift-select-mode'
  742. outside these special contexts, under control of this variable.
  743. The default of this variable is nil, to avoid confusing behavior. Shifted
  744. cursor keys will then execute Org commands in the following contexts:
  745. - on a headline, changing TODO state (left/right) and priority (up/down)
  746. - on a time stamp, changing the time
  747. - in a plain list item, changing the bullet type
  748. - in a property definition line, switching between allowed values
  749. - in the BEGIN line of a clock table (changing the time block).
  750. Outside these contexts, the commands will throw an error.
  751. When this variable is t and the cursor is not in a special
  752. context, Org mode will support shift-selection for making and
  753. enlarging regions. To make this more effective, the bullet
  754. cycling will no longer happen anywhere in an item line, but only
  755. if the cursor is exactly on the bullet.
  756. If you set this variable to the symbol `always', then the keys
  757. will not be special in headlines, property lines, and item lines,
  758. to make shift selection work there as well. If this is what you
  759. want, you can use the following alternative commands:
  760. `\\[org-todo]' and `\\[org-priority]' \
  761. to change TODO state and priority,
  762. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  763. can be used to switch TODO sets,
  764. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  765. and properties can be edited by hand or in column view.
  766. However, when the cursor is on a timestamp, shift-cursor commands
  767. will still edit the time stamp - this is just too good to give up."
  768. :group 'org
  769. :type '(choice
  770. (const :tag "Never" nil)
  771. (const :tag "When outside special context" t)
  772. (const :tag "Everywhere except timestamps" always)))
  773. (defcustom org-loop-over-headlines-in-active-region nil
  774. "Shall some commands act upon headlines in the active region?
  775. When set to t, some commands will be performed in all headlines
  776. within the active region.
  777. When set to `start-level', some commands will be performed in all
  778. headlines within the active region, provided that these headlines
  779. are of the same level than the first one.
  780. When set to a string, those commands will be performed on the
  781. matching headlines within the active region. Such string must be
  782. a tags/property/todo match as it is used in the agenda tags view.
  783. The list of commands is: `org-schedule', `org-deadline',
  784. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  785. `org-archive-to-archive-sibling'. The archiving commands skip
  786. already archived entries."
  787. :type '(choice (const :tag "Don't loop" nil)
  788. (const :tag "All headlines in active region" t)
  789. (const :tag "In active region, headlines at the same level than the first one" start-level)
  790. (string :tag "Tags/Property/Todo matcher"))
  791. :version "24.1"
  792. :group 'org-todo
  793. :group 'org-archive)
  794. (defgroup org-startup nil
  795. "Options concerning startup of Org mode."
  796. :tag "Org Startup"
  797. :group 'org)
  798. (defcustom org-startup-folded t
  799. "Non-nil means entering Org mode will switch to OVERVIEW.
  800. This can also be configured on a per-file basis by adding one of
  801. the following lines anywhere in the buffer:
  802. #+STARTUP: fold (or `overview', this is equivalent)
  803. #+STARTUP: nofold (or `showall', this is equivalent)
  804. #+STARTUP: content
  805. #+STARTUP: showeverything
  806. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  807. to ignore this option when Org opens agenda files for the first
  808. time."
  809. :group 'org-startup
  810. :type '(choice
  811. (const :tag "nofold: show all" nil)
  812. (const :tag "fold: overview" t)
  813. (const :tag "content: all headlines" content)
  814. (const :tag "show everything, even drawers" showeverything)))
  815. (defcustom org-startup-truncated t
  816. "Non-nil means entering Org mode will set `truncate-lines'.
  817. This is useful since some lines containing links can be very long and
  818. uninteresting. Also tables look terrible when wrapped.
  819. The variable `org-startup-truncated' allows to configure
  820. truncation for Org mode different to the other modes that use the
  821. variable `truncate-lines' and as a shortcut instead of putting
  822. the variable `truncate-lines' into the `org-mode-hook'. If one
  823. wants to configure truncation for Org mode not statically but
  824. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  825. the variable `truncate-lines' has to be used because in such a
  826. case it is too late to set the variable `org-startup-truncated'."
  827. :group 'org-startup
  828. :type 'boolean)
  829. (defcustom org-startup-indented nil
  830. "Non-nil means turn on `org-indent-mode' on startup.
  831. This can also be configured on a per-file basis by adding one of
  832. the following lines anywhere in the buffer:
  833. #+STARTUP: indent
  834. #+STARTUP: noindent"
  835. :group 'org-structure
  836. :type '(choice
  837. (const :tag "Not" nil)
  838. (const :tag "Globally (slow on startup in large files)" t)))
  839. (defcustom org-use-sub-superscripts t
  840. "Non-nil means interpret \"_\" and \"^\" for display.
  841. If you want to control how Org exports those characters, see
  842. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  843. used to be an alias for `org-export-with-sub-superscripts' in
  844. Org <8.0, it is not anymore.
  845. When this option is turned on, you can use TeX-like syntax for
  846. sub- and superscripts within the buffer. Several characters after
  847. \"_\" or \"^\" will be considered as a single item - so grouping
  848. with {} is normally not needed. For example, the following things
  849. will be parsed as single sub- or superscripts:
  850. 10^24 or 10^tau several digits will be considered 1 item.
  851. 10^-12 or 10^-tau a leading sign with digits or a word
  852. x^2-y^3 will be read as x^2 - y^3, because items are
  853. terminated by almost any nonword/nondigit char.
  854. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  855. Still, ambiguity is possible. So when in doubt, use {} to enclose
  856. the sub/superscript. If you set this variable to the symbol `{}',
  857. the braces are *required* in order to trigger interpretations as
  858. sub/superscript. This can be helpful in documents that need \"_\"
  859. frequently in plain text."
  860. :group 'org-startup
  861. :version "24.4"
  862. :package-version '(Org . "8.0")
  863. :type '(choice
  864. (const :tag "Always interpret" t)
  865. (const :tag "Only with braces" {})
  866. (const :tag "Never interpret" nil)))
  867. (defcustom org-startup-with-beamer-mode nil
  868. "Non-nil means turn on `org-beamer-mode' on startup.
  869. This can also be configured on a per-file basis by adding one of
  870. the following lines anywhere in the buffer:
  871. #+STARTUP: beamer"
  872. :group 'org-startup
  873. :version "24.1"
  874. :type 'boolean)
  875. (defcustom org-startup-align-all-tables nil
  876. "Non-nil means align all tables when visiting a file.
  877. This is useful when the column width in tables is forced with <N> cookies
  878. in table fields. Such tables will look correct only after the first re-align.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: align
  882. #+STARTUP: noalign"
  883. :group 'org-startup
  884. :type 'boolean)
  885. (defcustom org-startup-with-inline-images nil
  886. "Non-nil means show inline images when loading a new Org file.
  887. This can also be configured on a per-file basis by adding one of
  888. the following lines anywhere in the buffer:
  889. #+STARTUP: inlineimages
  890. #+STARTUP: noinlineimages"
  891. :group 'org-startup
  892. :version "24.1"
  893. :type 'boolean)
  894. (defcustom org-startup-with-latex-preview nil
  895. "Non-nil means preview LaTeX fragments when loading a new Org file.
  896. This can also be configured on a per-file basis by adding one of
  897. the following lines anywhere in the buffer:
  898. #+STARTUP: latexpreview
  899. #+STARTUP: nolatexpreview"
  900. :group 'org-startup
  901. :version "24.4"
  902. :package-version '(Org . "8.0")
  903. :type 'boolean)
  904. (defcustom org-insert-mode-line-in-empty-file nil
  905. "Non-nil means insert the first line setting Org mode in empty files.
  906. When the function `org-mode' is called interactively in an empty file, this
  907. normally means that the file name does not automatically trigger Org mode.
  908. To ensure that the file will always be in Org mode in the future, a
  909. line enforcing Org mode will be inserted into the buffer, if this option
  910. has been set."
  911. :group 'org-startup
  912. :type 'boolean)
  913. (defcustom org-replace-disputed-keys nil
  914. "Non-nil means use alternative key bindings for some keys.
  915. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  916. These keys are also used by other packages like shift-selection-mode'
  917. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  918. If you want to use Org mode together with one of these other modes,
  919. or more generally if you would like to move some Org mode commands to
  920. other keys, set this variable and configure the keys with the variable
  921. `org-disputed-keys'.
  922. This option is only relevant at load-time of Org mode, and must be set
  923. *before* org.el is loaded. Changing it requires a restart of Emacs to
  924. become effective."
  925. :group 'org-startup
  926. :type 'boolean)
  927. (defcustom org-use-extra-keys nil
  928. "Non-nil means use extra key sequence definitions for certain commands.
  929. This happens automatically if `window-system' is nil. This
  930. variable lets you do the same manually. You must set it before
  931. loading Org."
  932. :group 'org-startup
  933. :type 'boolean)
  934. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  935. (defcustom org-disputed-keys
  936. '(([(shift up)] . [(meta p)])
  937. ([(shift down)] . [(meta n)])
  938. ([(shift left)] . [(meta -)])
  939. ([(shift right)] . [(meta +)])
  940. ([(control shift right)] . [(meta shift +)])
  941. ([(control shift left)] . [(meta shift -)]))
  942. "Keys for which Org mode and other modes compete.
  943. This is an alist, cars are the default keys, second element specifies
  944. the alternative to use when `org-replace-disputed-keys' is t.
  945. Keys can be specified in any syntax supported by `define-key'.
  946. The value of this option takes effect only at Org mode startup,
  947. therefore you'll have to restart Emacs to apply it after changing."
  948. :group 'org-startup
  949. :type 'alist)
  950. (defun org-key (key)
  951. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  952. Or return the original if not disputed."
  953. (when org-replace-disputed-keys
  954. (let* ((nkey (key-description key))
  955. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  956. org-disputed-keys)))
  957. (setq key (if x (cdr x) key))))
  958. key)
  959. (defun org-defkey (keymap key def)
  960. "Define a key, possibly translated, as returned by `org-key'."
  961. (define-key keymap (org-key key) def))
  962. (defcustom org-ellipsis nil
  963. "The ellipsis to use in the Org mode outline.
  964. When nil, just use the standard three dots.
  965. When a string, use that string instead.
  966. The change affects only Org mode (which will then use its own display table).
  967. Changing this requires executing `\\[org-mode]' in a buffer to become
  968. effective."
  969. :group 'org-startup
  970. :type '(choice (const :tag "Default" nil)
  971. (string :tag "String" :value "...#"))
  972. :safe #'string-or-null-p)
  973. (defvar org-display-table nil
  974. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  975. (defgroup org-keywords nil
  976. "Keywords in Org mode."
  977. :tag "Org Keywords"
  978. :group 'org)
  979. (defcustom org-closed-keep-when-no-todo nil
  980. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  981. :group 'org-todo
  982. :group 'org-keywords
  983. :version "24.4"
  984. :package-version '(Org . "8.0")
  985. :type 'boolean)
  986. (defgroup org-structure nil
  987. "Options concerning the general structure of Org files."
  988. :tag "Org Structure"
  989. :group 'org)
  990. (defgroup org-reveal-location nil
  991. "Options about how to make context of a location visible."
  992. :tag "Org Reveal Location"
  993. :group 'org-structure)
  994. (defcustom org-show-context-detail '((agenda . local)
  995. (bookmark-jump . lineage)
  996. (isearch . lineage)
  997. (default . ancestors))
  998. "Alist between context and visibility span when revealing a location.
  999. \\<org-mode-map>Some actions may move point into invisible
  1000. locations. As a consequence, Org always expose a neighborhood
  1001. around point. How much is shown depends on the initial action,
  1002. or context. Valid contexts are
  1003. agenda when exposing an entry from the agenda
  1004. org-goto when using the command `org-goto' (`\\[org-goto]')
  1005. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1006. tags-tree when constructing a sparse tree based on tags matches
  1007. link-search when exposing search matches associated with a link
  1008. mark-goto when exposing the jump goal of a mark
  1009. bookmark-jump when exposing a bookmark location
  1010. isearch when exiting from an incremental search
  1011. default default for all contexts not set explicitly
  1012. Allowed visibility spans are
  1013. minimal show current headline; if point is not on headline,
  1014. also show entry
  1015. local show current headline, entry and next headline
  1016. ancestors show current headline and its direct ancestors; if
  1017. point is not on headline, also show entry
  1018. lineage show current headline, its direct ancestors and all
  1019. their children; if point is not on headline, also show
  1020. entry and first child
  1021. tree show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and all children
  1024. canonical show current headline, its direct ancestors along with
  1025. their entries and children; if point is not located on
  1026. the headline, also show current entry and all children
  1027. As special cases, a nil or t value means show all contexts in
  1028. `minimal' or `canonical' view, respectively.
  1029. Some views can make displayed information very compact, but also
  1030. make it harder to edit the location of the match. In such
  1031. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1032. more context."
  1033. :group 'org-reveal-location
  1034. :version "25.2"
  1035. :package-version '(Org . "9.0")
  1036. :type '(choice
  1037. (const :tag "Canonical" t)
  1038. (const :tag "Minimal" nil)
  1039. (repeat :greedy t :tag "Individual contexts"
  1040. (cons
  1041. (choice :tag "Context"
  1042. (const agenda)
  1043. (const org-goto)
  1044. (const occur-tree)
  1045. (const tags-tree)
  1046. (const link-search)
  1047. (const mark-goto)
  1048. (const bookmark-jump)
  1049. (const isearch)
  1050. (const default))
  1051. (choice :tag "Detail level"
  1052. (const minimal)
  1053. (const local)
  1054. (const ancestors)
  1055. (const lineage)
  1056. (const tree)
  1057. (const canonical))))))
  1058. (defcustom org-indirect-buffer-display 'other-window
  1059. "How should indirect tree buffers be displayed?
  1060. This applies to indirect buffers created with the commands
  1061. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1062. Valid values are:
  1063. current-window Display in the current window
  1064. other-window Just display in another window.
  1065. dedicated-frame Create one new frame, and re-use it each time.
  1066. new-frame Make a new frame each time. Note that in this case
  1067. previously-made indirect buffers are kept, and you need to
  1068. kill these buffers yourself."
  1069. :group 'org-structure
  1070. :group 'org-agenda-windows
  1071. :type '(choice
  1072. (const :tag "In current window" current-window)
  1073. (const :tag "In current frame, other window" other-window)
  1074. (const :tag "Each time a new frame" new-frame)
  1075. (const :tag "One dedicated frame" dedicated-frame)))
  1076. (defcustom org-use-speed-commands nil
  1077. "Non-nil means activate single letter commands at beginning of a headline.
  1078. This may also be a function to test for appropriate locations where speed
  1079. commands should be active.
  1080. For example, to activate speed commands when the point is on any
  1081. star at the beginning of the headline, you can do this:
  1082. (setq org-use-speed-commands
  1083. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1084. :group 'org-structure
  1085. :type '(choice
  1086. (const :tag "Never" nil)
  1087. (const :tag "At beginning of headline stars" t)
  1088. (function)))
  1089. (defcustom org-speed-commands-user nil
  1090. "Alist of additional speed commands.
  1091. This list will be checked before `org-speed-commands-default'
  1092. when the variable `org-use-speed-commands' is non-nil
  1093. and when the cursor is at the beginning of a headline.
  1094. The car if each entry is a string with a single letter, which must
  1095. be assigned to `self-insert-command' in the global map.
  1096. The cdr is either a command to be called interactively, a function
  1097. to be called, or a form to be evaluated.
  1098. An entry that is just a list with a single string will be interpreted
  1099. as a descriptive headline that will be added when listing the speed
  1100. commands in the Help buffer using the `?' speed command."
  1101. :group 'org-structure
  1102. :type '(repeat :value ("k" . ignore)
  1103. (choice :value ("k" . ignore)
  1104. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1105. (cons :tag "Letter and Command"
  1106. (string :tag "Command letter")
  1107. (choice
  1108. (function)
  1109. (sexp))))))
  1110. (defcustom org-bookmark-names-plist
  1111. '(:last-capture "org-capture-last-stored"
  1112. :last-refile "org-refile-last-stored"
  1113. :last-capture-marker "org-capture-last-stored-marker")
  1114. "Names for bookmarks automatically set by some Org commands.
  1115. This can provide strings as names for a number of bookmarks Org sets
  1116. automatically. The following keys are currently implemented:
  1117. :last-capture
  1118. :last-capture-marker
  1119. :last-refile
  1120. When a key does not show up in the property list, the corresponding bookmark
  1121. is not set."
  1122. :group 'org-structure
  1123. :type 'plist)
  1124. (defgroup org-cycle nil
  1125. "Options concerning visibility cycling in Org mode."
  1126. :tag "Org Cycle"
  1127. :group 'org-structure)
  1128. (defcustom org-cycle-skip-children-state-if-no-children t
  1129. "Non-nil means skip CHILDREN state in entries that don't have any."
  1130. :group 'org-cycle
  1131. :type 'boolean)
  1132. (defcustom org-cycle-max-level nil
  1133. "Maximum level which should still be subject to visibility cycling.
  1134. Levels higher than this will, for cycling, be treated as text, not a headline.
  1135. When `org-odd-levels-only' is set, a value of N in this variable actually
  1136. means 2N-1 stars as the limiting headline.
  1137. When nil, cycle all levels.
  1138. Note that the limiting level of cycling is also influenced by
  1139. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1140. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1141. than its value."
  1142. :group 'org-cycle
  1143. :type '(choice
  1144. (const :tag "No limit" nil)
  1145. (integer :tag "Maximum level")))
  1146. (defcustom org-hide-block-startup nil
  1147. "Non-nil means entering Org mode will fold all blocks.
  1148. This can also be set in on a per-file basis with
  1149. #+STARTUP: hideblocks
  1150. #+STARTUP: showblocks"
  1151. :group 'org-startup
  1152. :group 'org-cycle
  1153. :type 'boolean)
  1154. (defcustom org-cycle-global-at-bob nil
  1155. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1156. This makes it possible to do global cycling without having to use `S-TAB'
  1157. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1158. line of the buffer
  1159. must not be a headline -- it may be empty or some other text.
  1160. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1161. sure the cursor stays at the beginning of the buffer.
  1162. When this option is nil, don't do anything special at the beginning of
  1163. the buffer."
  1164. :group 'org-cycle
  1165. :type 'boolean)
  1166. (defcustom org-cycle-level-after-item/entry-creation t
  1167. "Non-nil means cycle entry level or item indentation in new empty entries.
  1168. When the cursor is at the end of an empty headline, i.e., with only stars
  1169. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1170. and then all possible ancestor states, before returning to the original state.
  1171. This makes data entry extremely fast: M-RET to create a new headline,
  1172. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1173. When the cursor is at the end of an empty plain list item, one TAB will
  1174. make it a subitem, two or more tabs will back up to make this an item
  1175. higher up in the item hierarchy."
  1176. :group 'org-cycle
  1177. :type 'boolean)
  1178. (defcustom org-cycle-emulate-tab t
  1179. "Where should `org-cycle' emulate TAB.
  1180. nil Never
  1181. white Only in completely white lines
  1182. whitestart Only at the beginning of lines, before the first non-white char
  1183. t Everywhere except in headlines
  1184. exc-hl-bol Everywhere except at the start of a headline
  1185. If TAB is used in a place where it does not emulate TAB, the current subtree
  1186. visibility is cycled."
  1187. :group 'org-cycle
  1188. :type '(choice (const :tag "Never" nil)
  1189. (const :tag "Only in completely white lines" white)
  1190. (const :tag "Before first char in a line" whitestart)
  1191. (const :tag "Everywhere except in headlines" t)
  1192. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1193. (defcustom org-cycle-separator-lines 2
  1194. "Number of empty lines needed to keep an empty line between collapsed trees.
  1195. If you leave an empty line between the end of a subtree and the following
  1196. headline, this empty line is hidden when the subtree is folded.
  1197. Org mode will leave (exactly) one empty line visible if the number of
  1198. empty lines is equal or larger to the number given in this variable.
  1199. So the default 2 means at least 2 empty lines after the end of a subtree
  1200. are needed to produce free space between a collapsed subtree and the
  1201. following headline.
  1202. If the number is negative, and the number of empty lines is at least -N,
  1203. all empty lines are shown.
  1204. Special case: when 0, never leave empty lines in collapsed view."
  1205. :group 'org-cycle
  1206. :type 'integer)
  1207. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1208. (defcustom org-pre-cycle-hook nil
  1209. "Hook that is run before visibility cycling is happening.
  1210. The function(s) in this hook must accept a single argument which indicates
  1211. the new state that will be set right after running this hook. The
  1212. argument is a symbol. Before a global state change, it can have the values
  1213. `overview', `content', or `all'. Before a local state change, it can have
  1214. the values `folded', `children', or `subtree'."
  1215. :group 'org-cycle
  1216. :type 'hook)
  1217. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1218. org-cycle-hide-drawers
  1219. org-cycle-show-empty-lines
  1220. org-optimize-window-after-visibility-change)
  1221. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1222. The function(s) in this hook must accept a single argument which indicates
  1223. the new state that was set by the most recent `org-cycle' command. The
  1224. argument is a symbol. After a global state change, it can have the values
  1225. `overview', `contents', or `all'. After a local state change, it can have
  1226. the values `folded', `children', or `subtree'."
  1227. :group 'org-cycle
  1228. :type 'hook
  1229. :version "25.2"
  1230. :package-version '(Org . "8.3"))
  1231. (defgroup org-edit-structure nil
  1232. "Options concerning structure editing in Org mode."
  1233. :tag "Org Edit Structure"
  1234. :group 'org-structure)
  1235. (defcustom org-odd-levels-only nil
  1236. "Non-nil means skip even levels and only use odd levels for the outline.
  1237. This has the effect that two stars are being added/taken away in
  1238. promotion/demotion commands. It also influences how levels are
  1239. handled by the exporters.
  1240. Changing it requires restart of `font-lock-mode' to become effective
  1241. for fontification also in regions already fontified.
  1242. You may also set this on a per-file basis by adding one of the following
  1243. lines to the buffer:
  1244. #+STARTUP: odd
  1245. #+STARTUP: oddeven"
  1246. :group 'org-edit-structure
  1247. :group 'org-appearance
  1248. :type 'boolean)
  1249. (defcustom org-adapt-indentation t
  1250. "Non-nil means adapt indentation to outline node level.
  1251. When this variable is set, Org assumes that you write outlines by
  1252. indenting text in each node to align with the headline (after the
  1253. stars). The following issues are influenced by this variable:
  1254. - The indentation is increased by one space in a demotion
  1255. command, and decreased by one in a promotion command. However,
  1256. in the latter case, if shifting some line in the entry body
  1257. would alter document structure (e.g., insert a new headline),
  1258. indentation is not changed at all.
  1259. - Property drawers and planning information is inserted indented
  1260. when this variable is set. When nil, they will not be indented.
  1261. - TAB indents a line relative to current level. The lines below
  1262. a headline will be indented when this variable is set.
  1263. Note that this is all about true indentation, by adding and
  1264. removing space characters. See also `org-indent.el' which does
  1265. level-dependent indentation in a virtual way, i.e. at display
  1266. time in Emacs."
  1267. :group 'org-edit-structure
  1268. :type 'boolean)
  1269. (defcustom org-special-ctrl-a/e nil
  1270. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1271. When t, `C-a' will bring back the cursor to the beginning of the
  1272. headline text, i.e. after the stars and after a possible TODO
  1273. keyword. In an item, this will be the position after bullet and
  1274. check-box, if any. When the cursor is already at that position,
  1275. another `C-a' will bring it to the beginning of the line.
  1276. `C-e' will jump to the end of the headline, ignoring the presence
  1277. of tags in the headline. A second `C-e' will then jump to the
  1278. true end of the line, after any tags. This also means that, when
  1279. this variable is non-nil, `C-e' also will never jump beyond the
  1280. end of the heading of a folded section, i.e. not after the
  1281. ellipses.
  1282. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1283. normally, going to the true line boundary first. Only a directly
  1284. following, identical keypress will bring the cursor to the
  1285. special positions.
  1286. This may also be a cons cell where the behavior for `C-a' and
  1287. `C-e' is set separately."
  1288. :group 'org-edit-structure
  1289. :type '(choice
  1290. (const :tag "off" nil)
  1291. (const :tag "on: after stars/bullet and before tags first" t)
  1292. (const :tag "reversed: true line boundary first" reversed)
  1293. (cons :tag "Set C-a and C-e separately"
  1294. (choice :tag "Special C-a"
  1295. (const :tag "off" nil)
  1296. (const :tag "on: after stars/bullet first" t)
  1297. (const :tag "reversed: before stars/bullet first" reversed))
  1298. (choice :tag "Special C-e"
  1299. (const :tag "off" nil)
  1300. (const :tag "on: before tags first" t)
  1301. (const :tag "reversed: after tags first" reversed)))))
  1302. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1303. (defcustom org-special-ctrl-k nil
  1304. "Non-nil means `C-k' will behave specially in headlines.
  1305. When nil, `C-k' will call the default `kill-line' command.
  1306. When t, the following will happen while the cursor is in the headline:
  1307. - When the cursor is at the beginning of a headline, kill the entire
  1308. line and possible the folded subtree below the line.
  1309. - When in the middle of the headline text, kill the headline up to the tags.
  1310. - When after the headline text, kill the tags."
  1311. :group 'org-edit-structure
  1312. :type 'boolean)
  1313. (defcustom org-ctrl-k-protect-subtree nil
  1314. "Non-nil means, do not delete a hidden subtree with C-k.
  1315. When set to the symbol `error', simply throw an error when C-k is
  1316. used to kill (part-of) a headline that has hidden text behind it.
  1317. Any other non-nil value will result in a query to the user, if it is
  1318. OK to kill that hidden subtree. When nil, kill without remorse."
  1319. :group 'org-edit-structure
  1320. :version "24.1"
  1321. :type '(choice
  1322. (const :tag "Do not protect hidden subtrees" nil)
  1323. (const :tag "Protect hidden subtrees with a security query" t)
  1324. (const :tag "Never kill a hidden subtree with C-k" error)))
  1325. (defcustom org-special-ctrl-o t
  1326. "Non-nil means, make `C-o' insert a row in tables."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-catch-invisible-edits nil
  1330. "Check if in invisible region before inserting or deleting a character.
  1331. Valid values are:
  1332. nil Do not check, so just do invisible edits.
  1333. error Throw an error and do nothing.
  1334. show Make point visible, and do the requested edit.
  1335. show-and-error Make point visible, then throw an error and abort the edit.
  1336. smart Make point visible, and do insertion/deletion if it is
  1337. adjacent to visible text and the change feels predictable.
  1338. Never delete a previously invisible character or add in the
  1339. middle or right after an invisible region. Basically, this
  1340. allows insertion and backward-delete right before ellipses.
  1341. FIXME: maybe in this case we should not even show?"
  1342. :group 'org-edit-structure
  1343. :version "24.1"
  1344. :type '(choice
  1345. (const :tag "Do not check" nil)
  1346. (const :tag "Throw error when trying to edit" error)
  1347. (const :tag "Unhide, but do not do the edit" show-and-error)
  1348. (const :tag "Show invisible part and do the edit" show)
  1349. (const :tag "Be smart and do the right thing" smart)))
  1350. (defcustom org-yank-folded-subtrees t
  1351. "Non-nil means when yanking subtrees, fold them.
  1352. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1353. it starts with a heading and all other headings in it are either children
  1354. or siblings, then fold all the subtrees. However, do this only if no
  1355. text after the yank would be swallowed into a folded tree by this action."
  1356. :group 'org-edit-structure
  1357. :type 'boolean)
  1358. (defcustom org-yank-adjusted-subtrees nil
  1359. "Non-nil means when yanking subtrees, adjust the level.
  1360. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1361. this function for details."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-M-RET-may-split-line '((default . t))
  1365. "Non-nil means M-RET will split the line at the cursor position.
  1366. When nil, it will go to the end of the line before making a
  1367. new line.
  1368. You may also set this option in a different way for different
  1369. contexts. Valid contexts are:
  1370. headline when creating a new headline
  1371. item when creating a new item
  1372. table in a table field
  1373. default the value to be used for all contexts not explicitly
  1374. customized"
  1375. :group 'org-structure
  1376. :group 'org-table
  1377. :type '(choice
  1378. (const :tag "Always" t)
  1379. (const :tag "Never" nil)
  1380. (repeat :greedy t :tag "Individual contexts"
  1381. (cons
  1382. (choice :tag "Context"
  1383. (const headline)
  1384. (const item)
  1385. (const table)
  1386. (const default))
  1387. (boolean)))))
  1388. (defcustom org-insert-heading-respect-content nil
  1389. "Non-nil means insert new headings after the current subtree.
  1390. \\<org-mode-map>
  1391. When nil, the new heading is created directly after the current line.
  1392. The commands `\\[org-insert-heading-respect-content]' and \
  1393. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1394. for the duration of the command."
  1395. :group 'org-structure
  1396. :type 'boolean)
  1397. (defcustom org-blank-before-new-entry '((heading . auto)
  1398. (plain-list-item . auto))
  1399. "Should `org-insert-heading' leave a blank line before new heading/item?
  1400. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1401. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1402. which case Org will look at the surrounding headings/items and try to
  1403. make an intelligent decision whether to insert a blank line or not."
  1404. :group 'org-edit-structure
  1405. :type '(list
  1406. (cons (const heading)
  1407. (choice (const :tag "Never" nil)
  1408. (const :tag "Always" t)
  1409. (const :tag "Auto" auto)))
  1410. (cons (const plain-list-item)
  1411. (choice (const :tag "Never" nil)
  1412. (const :tag "Always" t)
  1413. (const :tag "Auto" auto)))))
  1414. (defcustom org-insert-heading-hook nil
  1415. "Hook being run after inserting a new heading."
  1416. :group 'org-edit-structure
  1417. :type 'hook)
  1418. (defcustom org-enable-fixed-width-editor t
  1419. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1420. This currently only means they are never auto-wrapped.
  1421. When nil, such lines will be treated like ordinary lines."
  1422. :group 'org-edit-structure
  1423. :type 'boolean)
  1424. (defcustom org-goto-auto-isearch t
  1425. "Non-nil means typing characters in `org-goto' starts incremental search.
  1426. When nil, you can use these keybindings to navigate the buffer:
  1427. q Quit the org-goto interface
  1428. n Go to the next visible heading
  1429. p Go to the previous visible heading
  1430. f Go one heading forward on same level
  1431. b Go one heading backward on same level
  1432. u Go one heading up"
  1433. :group 'org-edit-structure
  1434. :type 'boolean)
  1435. (defgroup org-sparse-trees nil
  1436. "Options concerning sparse trees in Org mode."
  1437. :tag "Org Sparse Trees"
  1438. :group 'org-structure)
  1439. (defcustom org-highlight-sparse-tree-matches t
  1440. "Non-nil means highlight all matches that define a sparse tree.
  1441. The highlights will automatically disappear the next time the buffer is
  1442. changed by an edit command."
  1443. :group 'org-sparse-trees
  1444. :type 'boolean)
  1445. (defcustom org-remove-highlights-with-change t
  1446. "Non-nil means any change to the buffer will remove temporary highlights.
  1447. \\<org-mode-map>\
  1448. Such highlights are created by `org-occur' and `org-clock-display'.
  1449. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1450. to get rid of the highlights.
  1451. The highlights created by `org-toggle-latex-fragment' always need
  1452. `\\[org-toggle-latex-fragment]' to be removed."
  1453. :group 'org-sparse-trees
  1454. :group 'org-time
  1455. :type 'boolean)
  1456. (defcustom org-occur-case-fold-search t
  1457. "Non-nil means `org-occur' should be case-insensitive.
  1458. If set to `smart' the search will be case-insensitive only if it
  1459. doesn't specify any upper case character."
  1460. :group 'org-sparse-trees
  1461. :version "25.2"
  1462. :type '(choice
  1463. (const :tag "Case-sensitive" nil)
  1464. (const :tag "Case-insensitive" t)
  1465. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1466. (defcustom org-occur-hook '(org-first-headline-recenter)
  1467. "Hook that is run after `org-occur' has constructed a sparse tree.
  1468. This can be used to recenter the window to show as much of the structure
  1469. as possible."
  1470. :group 'org-sparse-trees
  1471. :type 'hook)
  1472. (defgroup org-imenu-and-speedbar nil
  1473. "Options concerning imenu and speedbar in Org mode."
  1474. :tag "Org Imenu and Speedbar"
  1475. :group 'org-structure)
  1476. (defcustom org-imenu-depth 2
  1477. "The maximum level for Imenu access to Org headlines.
  1478. This also applied for speedbar access."
  1479. :group 'org-imenu-and-speedbar
  1480. :type 'integer)
  1481. (defgroup org-table nil
  1482. "Options concerning tables in Org mode."
  1483. :tag "Org Table"
  1484. :group 'org)
  1485. (defcustom org-enable-table-editor 'optimized
  1486. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1487. When nil, such lines will be treated like ordinary lines.
  1488. When equal to the symbol `optimized', the table editor will be optimized to
  1489. do the following:
  1490. - Automatic overwrite mode in front of whitespace in table fields.
  1491. This makes the structure of the table stay in tact as long as the edited
  1492. field does not exceed the column width.
  1493. - Minimize the number of realigns. Normally, the table is aligned each time
  1494. TAB or RET are pressed to move to another field. With optimization this
  1495. happens only if changes to a field might have changed the column width.
  1496. Optimization requires replacing the functions `self-insert-command',
  1497. `delete-char', and `backward-delete-char' in Org buffers, with a
  1498. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1499. good at guessing when a re-align will be necessary, but you can always
  1500. force one with `\\[org-ctrl-c-ctrl-c]'.
  1501. If you would like to use the optimized version in Org mode, but the
  1502. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1503. This variable can be used to turn on and off the table editor during a session,
  1504. but in order to toggle optimization, a restart is required.
  1505. See also the variable `org-table-auto-blank-field'."
  1506. :group 'org-table
  1507. :type '(choice
  1508. (const :tag "off" nil)
  1509. (const :tag "on" t)
  1510. (const :tag "on, optimized" optimized)))
  1511. (defcustom org-self-insert-cluster-for-undo nil
  1512. "Non-nil means cluster self-insert commands for undo when possible.
  1513. If this is set, then, like in the Emacs command loop, 20 consecutive
  1514. characters will be undone together.
  1515. This is configurable, because there is some impact on typing performance."
  1516. :group 'org-table
  1517. :type 'boolean)
  1518. (defcustom org-table-tab-recognizes-table.el t
  1519. "Non-nil means TAB will automatically notice a table.el table.
  1520. When it sees such a table, it moves point into it and - if necessary -
  1521. calls `table-recognize-table'."
  1522. :group 'org-table-editing
  1523. :type 'boolean)
  1524. (defgroup org-link nil
  1525. "Options concerning links in Org mode."
  1526. :tag "Org Link"
  1527. :group 'org)
  1528. (defvar-local org-link-abbrev-alist-local nil
  1529. "Buffer-local version of `org-link-abbrev-alist', which see.
  1530. The value of this is taken from the #+LINK lines.")
  1531. (defcustom org-link-parameters
  1532. '(("doi" :follow org--open-doi-link)
  1533. ("elisp" :follow org--open-elisp-link)
  1534. ("file" :complete org-file-complete-link)
  1535. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1536. ("help" :follow org--open-help-link)
  1537. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1538. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1539. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1540. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1541. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1542. ("shell" :follow org--open-shell-link))
  1543. "An alist of properties that defines all the links in Org mode.
  1544. The key in each association is a string of the link type.
  1545. Subsequent optional elements make up a p-list of link properties.
  1546. :follow - A function that takes the link path as an argument.
  1547. :export - A function that takes the link path, description and
  1548. export-backend as arguments.
  1549. :store - A function responsible for storing the link. See the
  1550. function `org-store-link-functions'.
  1551. :complete - A function that inserts a link with completion. The
  1552. function takes one optional prefix arg.
  1553. :face - A face for the link, or a function that returns a face.
  1554. The function takes one argument which is the link path. The
  1555. default face is `org-link'.
  1556. :mouse-face - The mouse-face. The default is `highlight'.
  1557. :display - `full' will not fold the link in descriptive
  1558. display. Default is `org-link'.
  1559. :help-echo - A string or function that takes (window object position)
  1560. as arguments and returns a string.
  1561. :keymap - A keymap that is active on the link. The default is
  1562. `org-mouse-map'.
  1563. :htmlize-link - A function for the htmlize-link. Defaults
  1564. to (list :uri \"type:path\")
  1565. :activate-func - A function to run at the end of font-lock
  1566. activation. The function must accept (link-start link-end path bracketp)
  1567. as arguments."
  1568. :group 'org-link
  1569. :type '(alist :tag "Link display parameters"
  1570. :value-type plist))
  1571. (defun org-link-get-parameter (type key)
  1572. "Get TYPE link property for KEY.
  1573. TYPE is a string and KEY is a plist keyword."
  1574. (plist-get
  1575. (cdr (assoc type org-link-parameters))
  1576. key))
  1577. (defun org-link-set-parameters (type &rest parameters)
  1578. "Set link TYPE properties to PARAMETERS.
  1579. PARAMETERS should be :key val pairs."
  1580. (let ((data (assoc type org-link-parameters)))
  1581. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1582. (push (cons type parameters) org-link-parameters)
  1583. (org-make-link-regexps)
  1584. (org-element-update-syntax))))
  1585. (defun org-link-types ()
  1586. "Return a list of known link types."
  1587. (mapcar #'car org-link-parameters))
  1588. (defcustom org-link-abbrev-alist nil
  1589. "Alist of link abbreviations.
  1590. The car of each element is a string, to be replaced at the start of a link.
  1591. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1592. links in Org buffers can have an optional tag after a double colon, e.g.,
  1593. [[linkkey:tag][description]]
  1594. The `linkkey' must be a single word, starting with a letter, followed
  1595. by letters, numbers, `-' or `_'.
  1596. If REPLACE is a string, the tag will simply be appended to create the link.
  1597. If the string contains \"%s\", the tag will be inserted there. If the string
  1598. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1599. at that point (see the function `url-hexify-string'). If the string contains
  1600. the specifier \"%(my-function)\", then the custom function `my-function' will
  1601. be invoked: this function takes the tag as its only argument and must return
  1602. a string.
  1603. REPLACE may also be a function that will be called with the tag as the
  1604. only argument to create the link, which should be returned as a string.
  1605. See the manual for examples."
  1606. :group 'org-link
  1607. :type '(repeat
  1608. (cons
  1609. (string :tag "Protocol")
  1610. (choice
  1611. (string :tag "Format")
  1612. (function)))))
  1613. (defcustom org-descriptive-links t
  1614. "Non-nil means Org will display descriptive links.
  1615. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1616. \"Org Website\", hiding the link itself and just displaying its
  1617. description. When set to nil, Org will display the full links
  1618. literally.
  1619. You can interactively set the value of this variable by calling
  1620. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1621. :group 'org-link
  1622. :type 'boolean)
  1623. (defcustom org-link-file-path-type 'adaptive
  1624. "How the path name in file links should be stored.
  1625. Valid values are:
  1626. relative Relative to the current directory, i.e. the directory of the file
  1627. into which the link is being inserted.
  1628. absolute Absolute path, if possible with ~ for home directory.
  1629. noabbrev Absolute path, no abbreviation of home directory.
  1630. adaptive Use relative path for files in the current directory and sub-
  1631. directories of it. For other files, use an absolute path."
  1632. :group 'org-link
  1633. :type '(choice
  1634. (const relative)
  1635. (const absolute)
  1636. (const noabbrev)
  1637. (const adaptive)))
  1638. (defvaralias 'org-activate-links 'org-highlight-links)
  1639. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1640. "Types of links that should be highlighted in Org files.
  1641. This is a list of symbols, each one of them leading to the
  1642. highlighting of a certain link type.
  1643. You can still open links that are not highlighted.
  1644. In principle, it does not hurt to turn on highlighting for all
  1645. link types. There may be a small gain when turning off unused
  1646. link types. The types are:
  1647. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1648. angle Links in angular brackets that may contain whitespace like
  1649. <bbdb:Carsten Dominik>.
  1650. plain Plain links in normal text, no whitespace, like http://google.com.
  1651. radio Text that is matched by a radio target, see manual for details.
  1652. tag Tag settings in a headline (link to tag search).
  1653. date Time stamps (link to calendar).
  1654. footnote Footnote labels.
  1655. If you set this variable during an Emacs session, use `org-mode-restart'
  1656. in the Org buffer so that the change takes effect."
  1657. :group 'org-link
  1658. :group 'org-appearance
  1659. :type '(set :greedy t
  1660. (const :tag "Double bracket links" bracket)
  1661. (const :tag "Angular bracket links" angle)
  1662. (const :tag "Plain text links" plain)
  1663. (const :tag "Radio target matches" radio)
  1664. (const :tag "Tags" tag)
  1665. (const :tag "Timestamps" date)
  1666. (const :tag "Footnotes" footnote)))
  1667. (defcustom org-make-link-description-function nil
  1668. "Function to use for generating link descriptions from links.
  1669. When nil, the link location will be used. This function must take
  1670. two parameters: the first one is the link, the second one is the
  1671. description generated by `org-insert-link'. The function should
  1672. return the description to use."
  1673. :group 'org-link
  1674. :type '(choice (const nil) (function)))
  1675. (defgroup org-link-store nil
  1676. "Options concerning storing links in Org mode."
  1677. :tag "Org Store Link"
  1678. :group 'org-link)
  1679. (defcustom org-url-hexify-p t
  1680. "When non-nil, hexify URL when creating a link."
  1681. :type 'boolean
  1682. :version "24.3"
  1683. :group 'org-link-store)
  1684. (defcustom org-email-link-description-format "Email %c: %.30s"
  1685. "Format of the description part of a link to an email or usenet message.
  1686. The following %-escapes will be replaced by corresponding information:
  1687. %F full \"From\" field
  1688. %f name, taken from \"From\" field, address if no name
  1689. %T full \"To\" field
  1690. %t first name in \"To\" field, address if no name
  1691. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1692. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1693. %s subject
  1694. %d date
  1695. %m message-id.
  1696. You may use normal field width specification between the % and the letter.
  1697. This is for example useful to limit the length of the subject.
  1698. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1699. :group 'org-link-store
  1700. :type 'string)
  1701. (defcustom org-from-is-user-regexp
  1702. (let (r1 r2)
  1703. (when (and user-mail-address (not (string= user-mail-address "")))
  1704. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1705. (when (and user-full-name (not (string= user-full-name "")))
  1706. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1707. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1708. "Regexp matched against the \"From:\" header of an email or usenet message.
  1709. It should match if the message is from the user him/herself."
  1710. :group 'org-link-store
  1711. :type 'regexp)
  1712. (defcustom org-context-in-file-links t
  1713. "Non-nil means file links from `org-store-link' contain context.
  1714. \\<org-mode-map>
  1715. A search string will be added to the file name with :: as separator
  1716. and used to find the context when the link is activated by the command
  1717. `org-open-at-point'. When this option is t, the entire active region
  1718. will be placed in the search string of the file link. If set to a
  1719. positive integer, only the first n lines of context will be stored.
  1720. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1721. \\[org-store-link]')
  1722. negates this setting for the duration of the command."
  1723. :group 'org-link-store
  1724. :type '(choice boolean integer))
  1725. (defcustom org-keep-stored-link-after-insertion nil
  1726. "Non-nil means keep link in list for entire session.
  1727. \\<org-mode-map>
  1728. The command `org-store-link' adds a link pointing to the current
  1729. location to an internal list. These links accumulate during a session.
  1730. The command `org-insert-link' can be used to insert links into any
  1731. Org file (offering completion for all stored links).
  1732. When this option is nil, every link which has been inserted once using
  1733. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1734. unused
  1735. links more efficient."
  1736. :group 'org-link-store
  1737. :type 'boolean)
  1738. (defgroup org-link-follow nil
  1739. "Options concerning following links in Org mode."
  1740. :tag "Org Follow Link"
  1741. :group 'org-link)
  1742. (defcustom org-link-translation-function nil
  1743. "Function to translate links with different syntax to Org syntax.
  1744. This can be used to translate links created for example by the Planner
  1745. or emacs-wiki packages to Org syntax.
  1746. The function must accept two parameters, a TYPE containing the link
  1747. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1748. which is everything after the link protocol. It should return a cons
  1749. with possibly modified values of type and path.
  1750. Org contains a function for this, so if you set this variable to
  1751. `org-translate-link-from-planner', you should be able follow many
  1752. links created by planner."
  1753. :group 'org-link-follow
  1754. :type '(choice (const nil) (function)))
  1755. (defcustom org-follow-link-hook nil
  1756. "Hook that is run after a link has been followed."
  1757. :group 'org-link-follow
  1758. :type 'hook)
  1759. (defcustom org-tab-follows-link nil
  1760. "Non-nil means on links TAB will follow the link.
  1761. Needs to be set before org.el is loaded.
  1762. This really should not be used, it does not make sense, and the
  1763. implementation is bad."
  1764. :group 'org-link-follow
  1765. :type 'boolean)
  1766. (defcustom org-return-follows-link nil
  1767. "Non-nil means on links RET will follow the link.
  1768. In tables, the special behavior of RET has precedence."
  1769. :group 'org-link-follow
  1770. :type 'boolean)
  1771. (defcustom org-mouse-1-follows-link
  1772. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1773. "Non-nil means mouse-1 on a link will follow the link.
  1774. A longer mouse click will still set point. Needs to be set
  1775. before org.el is loaded."
  1776. :group 'org-link-follow
  1777. :version "24.4"
  1778. :package-version '(Org . "8.3")
  1779. :type '(choice
  1780. (const :tag "A double click follows the link" double)
  1781. (const :tag "Unconditionally follow the link with mouse-1" t)
  1782. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1783. (defcustom org-mark-ring-length 4
  1784. "Number of different positions to be recorded in the ring.
  1785. Changing this requires a restart of Emacs to work correctly."
  1786. :group 'org-link-follow
  1787. :type 'integer)
  1788. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1789. "Non-nil means internal fuzzy links can only match headlines.
  1790. When nil, the a fuzzy link may point to a target or a named
  1791. construct in the document. When set to the special value
  1792. `query-to-create', offer to create a new headline when none
  1793. matched.
  1794. Spaces and statistics cookies are ignored during heading searches."
  1795. :group 'org-link-follow
  1796. :version "24.1"
  1797. :type '(choice
  1798. (const :tag "Use fuzzy text search" nil)
  1799. (const :tag "Match only exact headline" t)
  1800. (const :tag "Match exact headline or query to create it"
  1801. query-to-create))
  1802. :safe #'symbolp)
  1803. (defcustom org-link-frame-setup
  1804. '((vm . vm-visit-folder-other-frame)
  1805. (vm-imap . vm-visit-imap-folder-other-frame)
  1806. (gnus . org-gnus-no-new-news)
  1807. (file . find-file-other-window)
  1808. (wl . wl-other-frame))
  1809. "Setup the frame configuration for following links.
  1810. When following a link with Emacs, it may often be useful to display
  1811. this link in another window or frame. This variable can be used to
  1812. set this up for the different types of links.
  1813. For VM, use any of
  1814. `vm-visit-folder'
  1815. `vm-visit-folder-other-window'
  1816. `vm-visit-folder-other-frame'
  1817. For Gnus, use any of
  1818. `gnus'
  1819. `gnus-other-frame'
  1820. `org-gnus-no-new-news'
  1821. For FILE, use any of
  1822. `find-file'
  1823. `find-file-other-window'
  1824. `find-file-other-frame'
  1825. For Wanderlust use any of
  1826. `wl'
  1827. `wl-other-frame'
  1828. For the calendar, use the variable `calendar-setup'.
  1829. For BBDB, it is currently only possible to display the matches in
  1830. another window."
  1831. :group 'org-link-follow
  1832. :type '(list
  1833. (cons (const vm)
  1834. (choice
  1835. (const vm-visit-folder)
  1836. (const vm-visit-folder-other-window)
  1837. (const vm-visit-folder-other-frame)))
  1838. (cons (const vm-imap)
  1839. (choice
  1840. (const vm-visit-imap-folder)
  1841. (const vm-visit-imap-folder-other-window)
  1842. (const vm-visit-imap-folder-other-frame)))
  1843. (cons (const gnus)
  1844. (choice
  1845. (const gnus)
  1846. (const gnus-other-frame)
  1847. (const org-gnus-no-new-news)))
  1848. (cons (const file)
  1849. (choice
  1850. (const find-file)
  1851. (const find-file-other-window)
  1852. (const find-file-other-frame)))
  1853. (cons (const wl)
  1854. (choice
  1855. (const wl)
  1856. (const wl-other-frame)))))
  1857. (defcustom org-display-internal-link-with-indirect-buffer nil
  1858. "Non-nil means use indirect buffer to display infile links.
  1859. Activating internal links (from one location in a file to another location
  1860. in the same file) normally just jumps to the location. When the link is
  1861. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1862. is displayed in
  1863. another window. When this option is set, the other window actually displays
  1864. an indirect buffer clone of the current buffer, to avoid any visibility
  1865. changes to the current buffer."
  1866. :group 'org-link-follow
  1867. :type 'boolean)
  1868. (defcustom org-open-non-existing-files nil
  1869. "Non-nil means `org-open-file' will open non-existing files.
  1870. When nil, an error will be generated.
  1871. This variable applies only to external applications because they
  1872. might choke on non-existing files. If the link is to a file that
  1873. will be opened in Emacs, the variable is ignored."
  1874. :group 'org-link-follow
  1875. :type 'boolean)
  1876. (defcustom org-open-directory-means-index-dot-org nil
  1877. "Non-nil means a link to a directory really means to index.org.
  1878. When nil, following a directory link will run dired or open a finder/explorer
  1879. window on that directory."
  1880. :group 'org-link-follow
  1881. :type 'boolean)
  1882. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1883. "Non-nil means ask for confirmation before executing shell links.
  1884. Shell links can be dangerous: just think about a link
  1885. [[shell:rm -rf ~/*][Google Search]]
  1886. This link would show up in your Org document as \"Google Search\",
  1887. but really it would remove your entire home directory.
  1888. Therefore we advise against setting this variable to nil.
  1889. Just change it to `y-or-n-p' if you want to confirm with a
  1890. single keystroke rather than having to type \"yes\"."
  1891. :group 'org-link-follow
  1892. :type '(choice
  1893. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1894. (const :tag "with y-or-n (faster)" y-or-n-p)
  1895. (const :tag "no confirmation (dangerous)" nil)))
  1896. (put 'org-confirm-shell-link-function
  1897. 'safe-local-variable
  1898. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1899. (defcustom org-confirm-shell-link-not-regexp ""
  1900. "A regexp to skip confirmation for shell links."
  1901. :group 'org-link-follow
  1902. :version "24.1"
  1903. :type 'regexp)
  1904. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1905. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1906. Elisp links can be dangerous: just think about a link
  1907. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1908. This link would show up in your Org document as \"Google Search\",
  1909. but really it would remove your entire home directory.
  1910. Therefore we advise against setting this variable to nil.
  1911. Just change it to `y-or-n-p' if you want to confirm with a
  1912. single keystroke rather than having to type \"yes\"."
  1913. :group 'org-link-follow
  1914. :type '(choice
  1915. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1916. (const :tag "with y-or-n (faster)" y-or-n-p)
  1917. (const :tag "no confirmation (dangerous)" nil)))
  1918. (put 'org-confirm-shell-link-function
  1919. 'safe-local-variable
  1920. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1921. (defcustom org-confirm-elisp-link-not-regexp ""
  1922. "A regexp to skip confirmation for Elisp links."
  1923. :group 'org-link-follow
  1924. :version "24.1"
  1925. :type 'regexp)
  1926. (defconst org-file-apps-defaults-gnu
  1927. '((remote . emacs)
  1928. (system . mailcap)
  1929. (t . mailcap))
  1930. "Default file applications on a UNIX or GNU/Linux system.
  1931. See `org-file-apps'.")
  1932. (defconst org-file-apps-defaults-macosx
  1933. '((remote . emacs)
  1934. (system . "open %s")
  1935. ("ps.gz" . "gv %s")
  1936. ("eps.gz" . "gv %s")
  1937. ("dvi" . "xdvi %s")
  1938. ("fig" . "xfig %s")
  1939. (t . "open %s"))
  1940. "Default file applications on a macOS system.
  1941. The system \"open\" is known as a default, but we use X11 applications
  1942. for some files for which the OS does not have a good default.
  1943. See `org-file-apps'.")
  1944. (defconst org-file-apps-defaults-windowsnt
  1945. (list '(remote . emacs)
  1946. (cons 'system (lambda (file _path)
  1947. (with-no-warnings (w32-shell-execute "open" file))))
  1948. (cons t (lambda (file _path)
  1949. (with-no-warnings (w32-shell-execute "open" file)))))
  1950. "Default file applications on a Windows NT system.
  1951. The system \"open\" is used for most files.
  1952. See `org-file-apps'.")
  1953. (defcustom org-file-apps
  1954. '((auto-mode . emacs)
  1955. ("\\.mm\\'" . default)
  1956. ("\\.x?html?\\'" . default)
  1957. ("\\.pdf\\'" . default))
  1958. "External applications for opening `file:path' items in a document.
  1959. \\<org-mode-map>\
  1960. Org mode uses system defaults for different file types, but
  1961. you can use this variable to set the application for a given file
  1962. extension. The entries in this list are cons cells where the car identifies
  1963. files and the cdr the corresponding command.
  1964. Possible values for the file identifier are:
  1965. \"string\" A string as a file identifier can be interpreted in different
  1966. ways, depending on its contents:
  1967. - Alphanumeric characters only:
  1968. Match links with this file extension.
  1969. Example: (\"pdf\" . \"evince %s\")
  1970. to open PDFs with evince.
  1971. - Regular expression: Match links where the
  1972. filename matches the regexp. If you want to
  1973. use groups here, use shy groups.
  1974. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1975. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1976. to open *.html and *.xhtml with firefox.
  1977. - Regular expression which contains (non-shy) groups:
  1978. Match links where the whole link, including \"::\", and
  1979. anything after that, matches the regexp.
  1980. In a custom command string, %1, %2, etc. are replaced with
  1981. the parts of the link that were matched by the groups.
  1982. For backwards compatibility, if a command string is given
  1983. that does not use any of the group matches, this case is
  1984. handled identically to the second one (i.e. match against
  1985. file name only).
  1986. In a custom function, you can access the group matches with
  1987. (match-string n link).
  1988. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1989. \"evince -p %1 %s\")
  1990. to open [[file:document.pdf::5]] with evince at page 5.
  1991. `directory' Matches a directory
  1992. `remote' Matches a remote file, accessible through tramp or efs.
  1993. Remote files most likely should be visited through Emacs
  1994. because external applications cannot handle such paths.
  1995. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1996. so all files Emacs knows how to handle. Using this with
  1997. command `emacs' will open most files in Emacs. Beware that this
  1998. will also open html files inside Emacs, unless you add
  1999. (\"html\" . default) to the list as well.
  2000. `system' The system command to open files, like `open' on Windows
  2001. and macOS, and mailcap under GNU/Linux. This is the command
  2002. that will be selected if you call `org-open-at-point' with a
  2003. double prefix argument (`\\[universal-argument] \
  2004. \\[universal-argument] \\[org-open-at-point]').
  2005. t Default for files not matched by any of the other options.
  2006. Possible values for the command are:
  2007. `emacs' The file will be visited by the current Emacs process.
  2008. `default' Use the default application for this file type, which is the
  2009. association for t in the list, most likely in the system-specific
  2010. part. This can be used to overrule an unwanted setting in the
  2011. system-specific variable.
  2012. `system' Use the system command for opening files, like \"open\".
  2013. This command is specified by the entry whose car is `system'.
  2014. Most likely, the system-specific version of this variable
  2015. does define this command, but you can overrule/replace it
  2016. here.
  2017. `mailcap' Use command specified in the mailcaps.
  2018. string A command to be executed by a shell; %s will be replaced
  2019. by the path to the file.
  2020. function A Lisp function, which will be called with two arguments:
  2021. the file path and the original link string, without the
  2022. \"file:\" prefix.
  2023. For more examples, see the system specific constants
  2024. `org-file-apps-defaults-macosx'
  2025. `org-file-apps-defaults-windowsnt'
  2026. `org-file-apps-defaults-gnu'."
  2027. :group 'org-link-follow
  2028. :type '(repeat
  2029. (cons (choice :value ""
  2030. (string :tag "Extension")
  2031. (const :tag "System command to open files" system)
  2032. (const :tag "Default for unrecognized files" t)
  2033. (const :tag "Remote file" remote)
  2034. (const :tag "Links to a directory" directory)
  2035. (const :tag "Any files that have Emacs modes"
  2036. auto-mode))
  2037. (choice :value ""
  2038. (const :tag "Visit with Emacs" emacs)
  2039. (const :tag "Use default" default)
  2040. (const :tag "Use the system command" system)
  2041. (string :tag "Command")
  2042. (function :tag "Function")))))
  2043. (defcustom org-doi-server-url "http://dx.doi.org/"
  2044. "The URL of the DOI server."
  2045. :type 'string
  2046. :version "24.3"
  2047. :group 'org-link-follow)
  2048. (defgroup org-refile nil
  2049. "Options concerning refiling entries in Org mode."
  2050. :tag "Org Refile"
  2051. :group 'org)
  2052. (defcustom org-directory "~/org"
  2053. "Directory with Org files.
  2054. This is just a default location to look for Org files. There is no need
  2055. at all to put your files into this directory. It is used in the
  2056. following situations:
  2057. 1. When a capture template specifies a target file that is not an
  2058. absolute path. The path will then be interpreted relative to
  2059. `org-directory'
  2060. 2. When the value of variable `org-agenda-files' is a single file, any
  2061. relative paths in this file will be taken as relative to
  2062. `org-directory'."
  2063. :group 'org-refile
  2064. :group 'org-capture
  2065. :type 'directory)
  2066. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2067. "Default target for storing notes.
  2068. Used as a fall back file for org-capture.el, for templates that
  2069. do not specify a target file."
  2070. :group 'org-refile
  2071. :group 'org-capture
  2072. :type 'file)
  2073. (defcustom org-goto-interface 'outline
  2074. "The default interface to be used for `org-goto'.
  2075. Allowed values are:
  2076. outline The interface shows an outline of the relevant file
  2077. and the correct heading is found by moving through
  2078. the outline or by searching with incremental search.
  2079. outline-path-completion Headlines in the current buffer are offered via
  2080. completion. This is the interface also used by
  2081. the refile command."
  2082. :group 'org-refile
  2083. :type '(choice
  2084. (const :tag "Outline" outline)
  2085. (const :tag "Outline-path-completion" outline-path-completion)))
  2086. (defcustom org-goto-max-level 5
  2087. "Maximum target level when running `org-goto' with refile interface."
  2088. :group 'org-refile
  2089. :type 'integer)
  2090. (defcustom org-reverse-note-order nil
  2091. "Non-nil means store new notes at the beginning of a file or entry.
  2092. When nil, new notes will be filed to the end of a file or entry.
  2093. This can also be a list with cons cells of regular expressions that
  2094. are matched against file names, and values."
  2095. :group 'org-capture
  2096. :group 'org-refile
  2097. :type '(choice
  2098. (const :tag "Reverse always" t)
  2099. (const :tag "Reverse never" nil)
  2100. (repeat :tag "By file name regexp"
  2101. (cons regexp boolean))))
  2102. (defcustom org-log-refile nil
  2103. "Information to record when a task is refiled.
  2104. Possible values are:
  2105. nil Don't add anything
  2106. time Add a time stamp to the task
  2107. note Prompt for a note and add it with template `org-log-note-headings'
  2108. This option can also be set with on a per-file-basis with
  2109. #+STARTUP: nologrefile
  2110. #+STARTUP: logrefile
  2111. #+STARTUP: lognoterefile
  2112. You can have local logging settings for a subtree by setting the LOGGING
  2113. property to one or more of these keywords.
  2114. When bulk-refiling from the agenda, the value `note' is forbidden and
  2115. will temporarily be changed to `time'."
  2116. :group 'org-refile
  2117. :group 'org-progress
  2118. :version "24.1"
  2119. :type '(choice
  2120. (const :tag "No logging" nil)
  2121. (const :tag "Record timestamp" time)
  2122. (const :tag "Record timestamp with note." note)))
  2123. (defcustom org-refile-targets nil
  2124. "Targets for refiling entries with `\\[org-refile]'.
  2125. This is a list of cons cells. Each cell contains:
  2126. - a specification of the files to be considered, either a list of files,
  2127. or a symbol whose function or variable value will be used to retrieve
  2128. a file name or a list of file names. If you use `org-agenda-files' for
  2129. that, all agenda files will be scanned for targets. Nil means consider
  2130. headings in the current buffer.
  2131. - A specification of how to find candidate refile targets. This may be
  2132. any of:
  2133. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2134. This tag has to be present in all target headlines, inheritance will
  2135. not be considered.
  2136. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2137. todo keyword.
  2138. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2139. headlines that are refiling targets.
  2140. - a cons cell (:level . N). Any headline of level N is considered a target.
  2141. Note that, when `org-odd-levels-only' is set, level corresponds to
  2142. order in hierarchy, not to the number of stars.
  2143. - a cons cell (:maxlevel . N). Any headline with level <= N is 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. Each element of this list generates a set of possible targets.
  2147. The union of these sets is presented (with completion) to
  2148. the user by `org-refile'.
  2149. You can set the variable `org-refile-target-verify-function' to a function
  2150. to verify each headline found by the simple criteria above.
  2151. When this variable is nil, all top-level headlines in the current buffer
  2152. are used, equivalent to the value `((nil . (:level . 1))'."
  2153. :group 'org-refile
  2154. :type '(repeat
  2155. (cons
  2156. (choice :value org-agenda-files
  2157. (const :tag "All agenda files" org-agenda-files)
  2158. (const :tag "Current buffer" nil)
  2159. (function) (variable) (file))
  2160. (choice :tag "Identify target headline by"
  2161. (cons :tag "Specific tag" (const :value :tag) (string))
  2162. (cons :tag "TODO keyword" (const :value :todo) (string))
  2163. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2164. (cons :tag "Level number" (const :value :level) (integer))
  2165. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2166. (defcustom org-refile-target-verify-function nil
  2167. "Function to verify if the headline at point should be a refile target.
  2168. The function will be called without arguments, with point at the
  2169. beginning of the headline. It should return t and leave point
  2170. where it is if the headline is a valid target for refiling.
  2171. If the target should not be selected, the function must return nil.
  2172. In addition to this, it may move point to a place from where the search
  2173. should be continued. For example, the function may decide that the entire
  2174. subtree of the current entry should be excluded and move point to the end
  2175. of the subtree."
  2176. :group 'org-refile
  2177. :type '(choice
  2178. (const nil)
  2179. (function)))
  2180. (defcustom org-refile-use-cache nil
  2181. "Non-nil means cache refile targets to speed up the process.
  2182. \\<org-mode-map>\
  2183. The cache for a particular file will be updated automatically when
  2184. the buffer has been killed, or when any of the marker used for flagging
  2185. refile targets no longer points at a live buffer.
  2186. If you have added new entries to a buffer that might themselves be targets,
  2187. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2188. if you find that easier, \
  2189. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2190. \\[org-refile]'."
  2191. :group 'org-refile
  2192. :version "24.1"
  2193. :type 'boolean)
  2194. (defcustom org-refile-use-outline-path nil
  2195. "Non-nil means provide refile targets as paths.
  2196. So a level 3 headline will be available as level1/level2/level3.
  2197. When the value is `file', also include the file name (without directory)
  2198. into the path. In this case, you can also stop the completion after
  2199. the file name, to get entries inserted as top level in the file.
  2200. When `full-file-path', include the full file path."
  2201. :group 'org-refile
  2202. :type '(choice
  2203. (const :tag "Not" nil)
  2204. (const :tag "Yes" t)
  2205. (const :tag "Start with file name" file)
  2206. (const :tag "Start with full file path" full-file-path)))
  2207. (defcustom org-outline-path-complete-in-steps t
  2208. "Non-nil means complete the outline path in hierarchical steps.
  2209. When Org uses the refile interface to select an outline path (see
  2210. `org-refile-use-outline-path'), the completion of the path can be
  2211. done in a single go, or it can be done in steps down the headline
  2212. hierarchy. Going in steps is probably the best if you do not use
  2213. a special completion package like `ido' or `icicles'. However,
  2214. when using these packages, going in one step can be very fast,
  2215. while still showing the whole path to the entry."
  2216. :group 'org-refile
  2217. :type 'boolean)
  2218. (defcustom org-refile-allow-creating-parent-nodes nil
  2219. "Non-nil means allow the creation of new nodes as refile targets.
  2220. New nodes are then created by adding \"/new node name\" to the completion
  2221. of an existing node. When the value of this variable is `confirm',
  2222. new node creation must be confirmed by the user (recommended).
  2223. When nil, the completion must match an existing entry.
  2224. Note that, if the new heading is not seen by the criteria
  2225. listed in `org-refile-targets', multiple instances of the same
  2226. heading would be created by trying again to file under the new
  2227. heading."
  2228. :group 'org-refile
  2229. :type '(choice
  2230. (const :tag "Never" nil)
  2231. (const :tag "Always" t)
  2232. (const :tag "Prompt for confirmation" confirm)))
  2233. (defcustom org-refile-active-region-within-subtree nil
  2234. "Non-nil means also refile active region within a subtree.
  2235. By default `org-refile' doesn't allow refiling regions if they
  2236. don't contain a set of subtrees, but it might be convenient to
  2237. do so sometimes: in that case, the first line of the region is
  2238. converted to a headline before refiling."
  2239. :group 'org-refile
  2240. :version "24.1"
  2241. :type 'boolean)
  2242. (defgroup org-todo nil
  2243. "Options concerning TODO items in Org mode."
  2244. :tag "Org TODO"
  2245. :group 'org)
  2246. (defgroup org-progress nil
  2247. "Options concerning Progress logging in Org mode."
  2248. :tag "Org Progress"
  2249. :group 'org-time)
  2250. (defvar org-todo-interpretation-widgets
  2251. '((:tag "Sequence (cycling hits every state)" sequence)
  2252. (:tag "Type (cycling directly to DONE)" type))
  2253. "The available interpretation symbols for customizing `org-todo-keywords'.
  2254. Interested libraries should add to this list.")
  2255. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2256. "List of TODO entry keyword sequences and their interpretation.
  2257. \\<org-mode-map>This is a list of sequences.
  2258. Each sequence starts with a symbol, either `sequence' or `type',
  2259. indicating if the keywords should be interpreted as a sequence of
  2260. action steps, or as different types of TODO items. The first
  2261. keywords are states requiring action - these states will select a headline
  2262. for inclusion into the global TODO list Org produces. If one of the
  2263. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2264. signify that no further action is necessary. If \"|\" is not found,
  2265. the last keyword is treated as the only DONE state of the sequence.
  2266. The command `\\[org-todo]' cycles an entry through these states, and one
  2267. additional state where no keyword is present. For details about this
  2268. cycling, see the manual.
  2269. TODO keywords and interpretation can also be set on a per-file basis with
  2270. the special #+SEQ_TODO and #+TYP_TODO lines.
  2271. Each keyword can optionally specify a character for fast state selection
  2272. \(in combination with the variable `org-use-fast-todo-selection')
  2273. and specifiers for state change logging, using the same syntax that
  2274. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2275. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2276. indicates to record a time stamp each time this state is selected.
  2277. Each keyword may also specify if a timestamp or a note should be
  2278. recorded when entering or leaving the state, by adding additional
  2279. characters in the parenthesis after the keyword. This looks like this:
  2280. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2281. record only the time of the state change. With X and Y being either
  2282. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2283. Y when leaving the state if and only if the *target* state does not
  2284. define X. You may omit any of the fast-selection key or X or /Y,
  2285. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2286. For backward compatibility, this variable may also be just a list
  2287. of keywords. In this case the interpretation (sequence or type) will be
  2288. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2289. :group 'org-todo
  2290. :group 'org-keywords
  2291. :type '(choice
  2292. (repeat :tag "Old syntax, just keywords"
  2293. (string :tag "Keyword"))
  2294. (repeat :tag "New syntax"
  2295. (cons
  2296. (choice
  2297. :tag "Interpretation"
  2298. ;;Quick and dirty way to see
  2299. ;;`org-todo-interpretations'. This takes the
  2300. ;;place of item arguments
  2301. :convert-widget
  2302. (lambda (widget)
  2303. (widget-put widget
  2304. :args (mapcar
  2305. (lambda (x)
  2306. (widget-convert
  2307. (cons 'const x)))
  2308. org-todo-interpretation-widgets))
  2309. widget))
  2310. (repeat
  2311. (string :tag "Keyword"))))))
  2312. (defvar-local org-todo-keywords-1 nil
  2313. "All TODO and DONE keywords active in a buffer.")
  2314. (defvar org-todo-keywords-for-agenda nil)
  2315. (defvar org-done-keywords-for-agenda nil)
  2316. (defvar org-todo-keyword-alist-for-agenda nil)
  2317. (defvar org-tag-alist-for-agenda nil
  2318. "Alist of all tags from all agenda files.")
  2319. (defvar org-tag-groups-alist-for-agenda nil
  2320. "Alist of all groups tags from all current agenda files.")
  2321. (defvar-local org-tag-groups-alist nil)
  2322. (defvar org-agenda-contributing-files nil)
  2323. (defvar-local org-current-tag-alist nil
  2324. "Alist of all tag groups in current buffer.
  2325. This variable takes into consideration `org-tag-alist',
  2326. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2327. (defvar-local org-not-done-keywords nil)
  2328. (defvar-local org-done-keywords nil)
  2329. (defvar-local org-todo-heads nil)
  2330. (defvar-local org-todo-sets nil)
  2331. (defvar-local org-todo-log-states nil)
  2332. (defvar-local org-todo-kwd-alist nil)
  2333. (defvar-local org-todo-key-alist nil)
  2334. (defvar-local org-todo-key-trigger nil)
  2335. (defcustom org-todo-interpretation 'sequence
  2336. "Controls how TODO keywords are interpreted.
  2337. This variable is in principle obsolete and is only used for
  2338. backward compatibility, if the interpretation of todo keywords is
  2339. not given already in `org-todo-keywords'. See that variable for
  2340. more information."
  2341. :group 'org-todo
  2342. :group 'org-keywords
  2343. :type '(choice (const sequence)
  2344. (const type)))
  2345. (defcustom org-use-fast-todo-selection t
  2346. "\\<org-mode-map>\
  2347. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2348. This variable describes if and under what circumstances the cycling
  2349. mechanism for TODO keywords will be replaced by a single-key, direct
  2350. selection scheme.
  2351. When nil, fast selection is never used.
  2352. When the symbol `prefix', it will be used when `org-todo' is called
  2353. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2354. in an Org buffer, and
  2355. `\\[universal-argument] t' in an agenda buffer.
  2356. When t, fast selection is used by default. In this case, the prefix
  2357. argument forces cycling instead.
  2358. In all cases, the special interface is only used if access keys have
  2359. actually been assigned by the user, i.e. if keywords in the configuration
  2360. are followed by a letter in parenthesis, like TODO(t)."
  2361. :group 'org-todo
  2362. :type '(choice
  2363. (const :tag "Never" nil)
  2364. (const :tag "By default" t)
  2365. (const :tag "Only with C-u C-c C-t" prefix)))
  2366. (defcustom org-provide-todo-statistics t
  2367. "Non-nil means update todo statistics after insert and toggle.
  2368. ALL-HEADLINES means update todo statistics by including headlines
  2369. with no TODO keyword as well, counting them as not done.
  2370. A list of TODO keywords means the same, but skip keywords that are
  2371. not in this list.
  2372. When set to a list of two lists, the first list contains keywords
  2373. to consider as TODO keywords, the second list contains keywords
  2374. to consider as DONE keywords.
  2375. When this is set, todo statistics is updated in the parent of the
  2376. current entry each time a todo state is changed."
  2377. :group 'org-todo
  2378. :type '(choice
  2379. (const :tag "Yes, only for TODO entries" t)
  2380. (const :tag "Yes, including all entries" all-headlines)
  2381. (repeat :tag "Yes, for TODOs in this list"
  2382. (string :tag "TODO keyword"))
  2383. (list :tag "Yes, for TODOs and DONEs in these lists"
  2384. (repeat (string :tag "TODO keyword"))
  2385. (repeat (string :tag "DONE keyword")))
  2386. (other :tag "No TODO statistics" nil)))
  2387. (defcustom org-hierarchical-todo-statistics t
  2388. "Non-nil means TODO statistics covers just direct children.
  2389. When nil, all entries in the subtree are considered.
  2390. This has only an effect if `org-provide-todo-statistics' is set.
  2391. To set this to nil for only a single subtree, use a COOKIE_DATA
  2392. property and include the word \"recursive\" into the value."
  2393. :group 'org-todo
  2394. :type 'boolean)
  2395. (defcustom org-after-todo-state-change-hook nil
  2396. "Hook which is run after the state of a TODO item was changed.
  2397. The new state (a string with a TODO keyword, or nil) is available in the
  2398. Lisp variable `org-state'."
  2399. :group 'org-todo
  2400. :type 'hook)
  2401. (defvar org-blocker-hook nil
  2402. "Hook for functions that are allowed to block a state change.
  2403. Functions in this hook should not modify the buffer.
  2404. Each function gets as its single argument a property list,
  2405. see `org-trigger-hook' for more information about this list.
  2406. If any of the functions in this hook returns nil, the state change
  2407. is blocked.")
  2408. (defvar org-trigger-hook nil
  2409. "Hook for functions that are triggered by a state change.
  2410. Each function gets as its single argument a property list with at
  2411. least the following elements:
  2412. (:type type-of-change :position pos-at-entry-start
  2413. :from old-state :to new-state)
  2414. Depending on the type, more properties may be present.
  2415. This mechanism is currently implemented for:
  2416. TODO state changes
  2417. ------------------
  2418. :type todo-state-change
  2419. :from previous state (keyword as a string), or nil, or a symbol
  2420. `todo' or `done', to indicate the general type of state.
  2421. :to new state, like in :from")
  2422. (defcustom org-enforce-todo-dependencies nil
  2423. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2424. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2425. be blocked if any prior sibling is not yet done.
  2426. Finally, if the parent is blocked because of ordered siblings of its own,
  2427. the child will also be blocked."
  2428. :set (lambda (var val)
  2429. (set var val)
  2430. (if val
  2431. (add-hook 'org-blocker-hook
  2432. 'org-block-todo-from-children-or-siblings-or-parent)
  2433. (remove-hook 'org-blocker-hook
  2434. 'org-block-todo-from-children-or-siblings-or-parent)))
  2435. :group 'org-todo
  2436. :type 'boolean)
  2437. (defcustom org-enforce-todo-checkbox-dependencies nil
  2438. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2439. When this is nil, checkboxes have no influence on switching TODO states.
  2440. When non-nil, you first need to check off all check boxes before the TODO
  2441. entry can be switched to DONE.
  2442. This variable needs to be set before org.el is loaded, and you need to
  2443. restart Emacs after a change to make the change effective. The only way
  2444. to change is while Emacs is running is through the customize interface."
  2445. :set (lambda (var val)
  2446. (set var val)
  2447. (if val
  2448. (add-hook 'org-blocker-hook
  2449. 'org-block-todo-from-checkboxes)
  2450. (remove-hook 'org-blocker-hook
  2451. 'org-block-todo-from-checkboxes)))
  2452. :group 'org-todo
  2453. :type 'boolean)
  2454. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2455. "Non-nil means inserting a TODO heading is treated as state change.
  2456. So when the command `\\[org-insert-todo-heading]' is used, state change
  2457. logging will apply if appropriate. When nil, the new TODO item will
  2458. be inserted directly, and no logging will take place."
  2459. :group 'org-todo
  2460. :type 'boolean)
  2461. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2462. "Non-nil means switching TODO states with S-cursor counts as state change.
  2463. This is the default behavior. However, setting this to nil allows a
  2464. convenient way to select a TODO state and bypass any logging associated
  2465. with that."
  2466. :group 'org-todo
  2467. :type 'boolean)
  2468. (defcustom org-todo-state-tags-triggers nil
  2469. "Tag changes that should be triggered by TODO state changes.
  2470. This is a list. Each entry is
  2471. (state-change (tag . flag) .......)
  2472. State-change can be a string with a state, and empty string to indicate the
  2473. state that has no TODO keyword, or it can be one of the symbols `todo'
  2474. or `done', meaning any not-done or done state, respectively."
  2475. :group 'org-todo
  2476. :group 'org-tags
  2477. :type '(repeat
  2478. (cons (choice :tag "When changing to"
  2479. (const :tag "Not-done state" todo)
  2480. (const :tag "Done state" done)
  2481. (string :tag "State"))
  2482. (repeat
  2483. (cons :tag "Tag action"
  2484. (string :tag "Tag")
  2485. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2486. (defcustom org-log-done nil
  2487. "Information to record when a task moves to the DONE state.
  2488. Possible values are:
  2489. nil Don't add anything, just change the keyword
  2490. time Add a time stamp to the task
  2491. note Prompt for a note and add it with template `org-log-note-headings'
  2492. This option can also be set with on a per-file-basis with
  2493. #+STARTUP: nologdone
  2494. #+STARTUP: logdone
  2495. #+STARTUP: lognotedone
  2496. You can have local logging settings for a subtree by setting the LOGGING
  2497. property to one or more of these keywords."
  2498. :group 'org-todo
  2499. :group 'org-progress
  2500. :type '(choice
  2501. (const :tag "No logging" nil)
  2502. (const :tag "Record CLOSED timestamp" time)
  2503. (const :tag "Record CLOSED timestamp with note." note)))
  2504. ;; Normalize old uses of org-log-done.
  2505. (cond
  2506. ((eq org-log-done t) (setq org-log-done 'time))
  2507. ((and (listp org-log-done) (memq 'done org-log-done))
  2508. (setq org-log-done 'note)))
  2509. (defcustom org-log-reschedule nil
  2510. "Information to record when the scheduling date of a tasks is modified.
  2511. Possible values are:
  2512. nil Don't add anything, just change the date
  2513. time Add a time stamp to the task
  2514. note Prompt for a note and add it with template `org-log-note-headings'
  2515. This option can also be set with on a per-file-basis with
  2516. #+STARTUP: nologreschedule
  2517. #+STARTUP: logreschedule
  2518. #+STARTUP: lognotereschedule"
  2519. :group 'org-todo
  2520. :group 'org-progress
  2521. :type '(choice
  2522. (const :tag "No logging" nil)
  2523. (const :tag "Record timestamp" time)
  2524. (const :tag "Record timestamp with note." note)))
  2525. (defcustom org-log-redeadline nil
  2526. "Information to record when the deadline date of a tasks is modified.
  2527. Possible values are:
  2528. nil Don't add anything, just change the date
  2529. time Add a time stamp to the task
  2530. note Prompt for a note and add it with template `org-log-note-headings'
  2531. This option can also be set with on a per-file-basis with
  2532. #+STARTUP: nologredeadline
  2533. #+STARTUP: logredeadline
  2534. #+STARTUP: lognoteredeadline
  2535. You can have local logging settings for a subtree by setting the LOGGING
  2536. property to one or more of these keywords."
  2537. :group 'org-todo
  2538. :group 'org-progress
  2539. :type '(choice
  2540. (const :tag "No logging" nil)
  2541. (const :tag "Record timestamp" time)
  2542. (const :tag "Record timestamp with note." note)))
  2543. (defcustom org-log-note-clock-out nil
  2544. "Non-nil means record a note when clocking out of an item.
  2545. This can also be configured on a per-file basis by adding one of
  2546. the following lines anywhere in the buffer:
  2547. #+STARTUP: lognoteclock-out
  2548. #+STARTUP: nolognoteclock-out"
  2549. :group 'org-todo
  2550. :group 'org-progress
  2551. :type 'boolean)
  2552. (defcustom org-log-done-with-time t
  2553. "Non-nil means the CLOSED time stamp will contain date and time.
  2554. When nil, only the date will be recorded."
  2555. :group 'org-progress
  2556. :type 'boolean)
  2557. (defcustom org-log-note-headings
  2558. '((done . "CLOSING NOTE %t")
  2559. (state . "State %-12s from %-12S %t")
  2560. (note . "Note taken on %t")
  2561. (reschedule . "Rescheduled from %S on %t")
  2562. (delschedule . "Not scheduled, was %S on %t")
  2563. (redeadline . "New deadline from %S on %t")
  2564. (deldeadline . "Removed deadline, was %S on %t")
  2565. (refile . "Refiled on %t")
  2566. (clock-out . ""))
  2567. "Headings for notes added to entries.
  2568. The value is an alist, with the car being a symbol indicating the
  2569. note context, and the cdr is the heading to be used. The heading
  2570. may also be the empty string. The following placeholders can be
  2571. used:
  2572. %t a time stamp.
  2573. %T an active time stamp instead the default inactive one
  2574. %d a short-format time stamp.
  2575. %D an active short-format time stamp.
  2576. %s the new TODO state or time stamp (inactive), in double quotes.
  2577. %S the old TODO state or time stamp (inactive), in double quotes.
  2578. %u the user name.
  2579. %U full user name.
  2580. In fact, it is not a good idea to change the `state' entry,
  2581. because Agenda Log mode depends on the format of these entries."
  2582. :group 'org-todo
  2583. :group 'org-progress
  2584. :type '(list :greedy t
  2585. (cons (const :tag "Heading when closing an item" done) string)
  2586. (cons (const :tag
  2587. "Heading when changing todo state (todo sequence only)"
  2588. state) string)
  2589. (cons (const :tag "Heading when just taking a note" note) string)
  2590. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2591. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2592. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2593. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2594. (cons (const :tag "Heading when refiling" refile) string)
  2595. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2596. (unless (assq 'note org-log-note-headings)
  2597. (push '(note . "%t") org-log-note-headings))
  2598. (defcustom org-log-into-drawer nil
  2599. "Non-nil means insert state change notes and time stamps into a drawer.
  2600. When nil, state changes notes will be inserted after the headline and
  2601. any scheduling and clock lines, but not inside a drawer.
  2602. The value of this variable should be the name of the drawer to use.
  2603. LOGBOOK is proposed as the default drawer for this purpose, you can
  2604. also set this to a string to define the drawer of your choice.
  2605. A value of t is also allowed, representing \"LOGBOOK\".
  2606. A value of t or nil can also be set with on a per-file-basis with
  2607. #+STARTUP: logdrawer
  2608. #+STARTUP: nologdrawer
  2609. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2610. will be ignored.
  2611. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2612. a subtree.
  2613. Do not check directly this variable in a Lisp program. Call
  2614. function `org-log-into-drawer' instead."
  2615. :group 'org-todo
  2616. :group 'org-progress
  2617. :type '(choice
  2618. (const :tag "Not into a drawer" nil)
  2619. (const :tag "LOGBOOK" t)
  2620. (string :tag "Other")))
  2621. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2622. (defun org-log-into-drawer ()
  2623. "Name of the log drawer, as a string, or nil.
  2624. This is the value of `org-log-into-drawer'. However, if the
  2625. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2626. be used instead of the default value."
  2627. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2628. (cond ((equal p "nil") nil)
  2629. ((equal p "t") "LOGBOOK")
  2630. ((stringp p) p)
  2631. (p "LOGBOOK")
  2632. ((stringp org-log-into-drawer) org-log-into-drawer)
  2633. (org-log-into-drawer "LOGBOOK"))))
  2634. (defcustom org-log-state-notes-insert-after-drawers nil
  2635. "Non-nil means insert state change notes after any drawers in entry.
  2636. Only the drawers that *immediately* follow the headline and the
  2637. deadline/scheduled line are skipped.
  2638. When nil, insert notes right after the heading and perhaps the line
  2639. with deadline/scheduling if present.
  2640. This variable will have no effect if `org-log-into-drawer' is
  2641. set."
  2642. :group 'org-todo
  2643. :group 'org-progress
  2644. :type 'boolean)
  2645. (defcustom org-log-states-order-reversed t
  2646. "Non-nil means the latest state note will be directly after heading.
  2647. When nil, the state change notes will be ordered according to time.
  2648. This option can also be set with on a per-file-basis with
  2649. #+STARTUP: logstatesreversed
  2650. #+STARTUP: nologstatesreversed"
  2651. :group 'org-todo
  2652. :group 'org-progress
  2653. :type 'boolean)
  2654. (defcustom org-todo-repeat-to-state nil
  2655. "The TODO state to which a repeater should return the repeating task.
  2656. By default this is the first task in a TODO sequence, or the previous state
  2657. in a TODO_TYP set. But you can specify another task here.
  2658. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2659. :group 'org-todo
  2660. :version "24.1"
  2661. :type '(choice (const :tag "Head of sequence" nil)
  2662. (string :tag "Specific state")))
  2663. (defcustom org-log-repeat 'time
  2664. "Non-nil means record moving through the DONE state when triggering repeat.
  2665. An auto-repeating task is immediately switched back to TODO when
  2666. marked DONE. If you are not logging state changes (by adding \"@\"
  2667. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2668. record a closing note, there will be no record of the task moving
  2669. through DONE. This variable forces taking a note anyway.
  2670. nil Don't force a record
  2671. time Record a time stamp
  2672. note Prompt for a note and add it with template `org-log-note-headings'
  2673. This option can also be set with on a per-file-basis with
  2674. #+STARTUP: nologrepeat
  2675. #+STARTUP: logrepeat
  2676. #+STARTUP: lognoterepeat
  2677. You can have local logging settings for a subtree by setting the LOGGING
  2678. property to one or more of these keywords."
  2679. :group 'org-todo
  2680. :group 'org-progress
  2681. :type '(choice
  2682. (const :tag "Don't force a record" nil)
  2683. (const :tag "Force recording the DONE state" time)
  2684. (const :tag "Force recording a note with the DONE state" note)))
  2685. (defgroup org-priorities nil
  2686. "Priorities in Org mode."
  2687. :tag "Org Priorities"
  2688. :group 'org-todo)
  2689. (defcustom org-enable-priority-commands t
  2690. "Non-nil means priority commands are active.
  2691. When nil, these commands will be disabled, so that you never accidentally
  2692. set a priority."
  2693. :group 'org-priorities
  2694. :type 'boolean)
  2695. (defcustom org-highest-priority ?A
  2696. "The highest priority of TODO items. A character like ?A, ?B etc.
  2697. Must have a smaller ASCII number than `org-lowest-priority'."
  2698. :group 'org-priorities
  2699. :type 'character)
  2700. (defcustom org-lowest-priority ?C
  2701. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2702. Must have a larger ASCII number than `org-highest-priority'."
  2703. :group 'org-priorities
  2704. :type 'character)
  2705. (defcustom org-default-priority ?B
  2706. "The default priority of TODO items.
  2707. This is the priority an item gets if no explicit priority is given.
  2708. When starting to cycle on an empty priority the first step in the cycle
  2709. depends on `org-priority-start-cycle-with-default'. The resulting first
  2710. step priority must not exceed the range from `org-highest-priority' to
  2711. `org-lowest-priority' which means that `org-default-priority' has to be
  2712. in this range exclusive or inclusive the range boundaries. Else the
  2713. first step refuses to set the default and the second will fall back
  2714. to (depending on the command used) the highest or lowest priority."
  2715. :group 'org-priorities
  2716. :type 'character)
  2717. (defcustom org-priority-start-cycle-with-default t
  2718. "Non-nil means start with default priority when starting to cycle.
  2719. When this is nil, the first step in the cycle will be (depending on the
  2720. command used) one higher or lower than the default priority.
  2721. See also `org-default-priority'."
  2722. :group 'org-priorities
  2723. :type 'boolean)
  2724. (defcustom org-get-priority-function nil
  2725. "Function to extract the priority from a string.
  2726. The string is normally the headline. If this is nil Org computes the
  2727. priority from the priority cookie like [#A] in the headline. It returns
  2728. an integer, increasing by 1000 for each priority level.
  2729. The user can set a different function here, which should take a string
  2730. as an argument and return the numeric priority."
  2731. :group 'org-priorities
  2732. :version "24.1"
  2733. :type '(choice
  2734. (const nil)
  2735. (function)))
  2736. (defgroup org-time nil
  2737. "Options concerning time stamps and deadlines in Org mode."
  2738. :tag "Org Time"
  2739. :group 'org)
  2740. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2741. "Number of minutes to round time stamps to.
  2742. \\<org-mode-map>\
  2743. These are two values, the first applies when first creating a time stamp.
  2744. The second applies when changing it with the commands `S-up' and `S-down'.
  2745. When changing the time stamp, this means that it will change in steps
  2746. of N minutes, as given by the second value.
  2747. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2748. numbers should be factors of 60, so for example 5, 10, 15.
  2749. When this is larger than 1, you can still force an exact time stamp by using
  2750. a double prefix argument to a time stamp command like \
  2751. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2752. and by using a prefix arg to `S-up/down' to specify the exact number
  2753. of minutes to shift."
  2754. :group 'org-time
  2755. :get (lambda (var) ; Make sure both elements are there
  2756. (if (integerp (default-value var))
  2757. (list (default-value var) 5)
  2758. (default-value var)))
  2759. :type '(list
  2760. (integer :tag "when inserting times")
  2761. (integer :tag "when modifying times")))
  2762. ;; Normalize old customizations of this variable.
  2763. (when (integerp org-time-stamp-rounding-minutes)
  2764. (setq org-time-stamp-rounding-minutes
  2765. (list org-time-stamp-rounding-minutes
  2766. org-time-stamp-rounding-minutes)))
  2767. (defcustom org-display-custom-times nil
  2768. "Non-nil means overlay custom formats over all time stamps.
  2769. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2770. To turn this on on a per-file basis, insert anywhere in the file:
  2771. #+STARTUP: customtime"
  2772. :group 'org-time
  2773. :set 'set-default
  2774. :type 'sexp)
  2775. (make-variable-buffer-local 'org-display-custom-times)
  2776. (defcustom org-time-stamp-custom-formats
  2777. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2778. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2779. These are overlaid over the default ISO format if the variable
  2780. `org-display-custom-times' is set. Time like %H:%M should be at the
  2781. end of the second format. The custom formats are also honored by export
  2782. commands, if custom time display is turned on at the time of export."
  2783. :group 'org-time
  2784. :type 'sexp)
  2785. (defun org-time-stamp-format (&optional long inactive)
  2786. "Get the right format for a time string."
  2787. (let ((f (if long (cdr org-time-stamp-formats)
  2788. (car org-time-stamp-formats))))
  2789. (if inactive
  2790. (concat "[" (substring f 1 -1) "]")
  2791. f)))
  2792. (defcustom org-time-clocksum-format
  2793. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2794. "The format string used when creating CLOCKSUM lines.
  2795. This is also used when Org mode generates a time duration.
  2796. The value can be a single format string containing two
  2797. %-sequences, which will be filled with the number of hours and
  2798. minutes in that order.
  2799. Alternatively, the value can be a plist associating any of the
  2800. keys :years, :months, :weeks, :days, :hours or :minutes with
  2801. format strings. The time duration is formatted using only the
  2802. time components that are needed and concatenating the results.
  2803. If a time unit in absent, it falls back to the next smallest
  2804. unit.
  2805. The keys :require-years, :require-months, :require-days,
  2806. :require-weeks, :require-hours, :require-minutes are also
  2807. meaningful. A non-nil value for these keys indicates that the
  2808. corresponding time component should always be included, even if
  2809. its value is 0.
  2810. For example,
  2811. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2812. :require-minutes t)
  2813. means durations longer than a day will be expressed in days,
  2814. hours and minutes, and durations less than a day will always be
  2815. expressed in hours and minutes (even for durations less than an
  2816. hour).
  2817. The value
  2818. (:days \"%dd\" :minutes \"%dm\")
  2819. means durations longer than a day will be expressed in days and
  2820. minutes, and durations less than a day will be expressed entirely
  2821. in minutes (even for durations longer than an hour)."
  2822. :group 'org-time
  2823. :group 'org-clock
  2824. :version "24.4"
  2825. :package-version '(Org . "8.0")
  2826. :type '(choice (string :tag "Format string")
  2827. (set :tag "Plist"
  2828. (group :inline t (const :tag "Years" :years)
  2829. (string :tag "Format string"))
  2830. (group :inline t
  2831. (const :tag "Always show years" :require-years)
  2832. (const t))
  2833. (group :inline t (const :tag "Months" :months)
  2834. (string :tag "Format string"))
  2835. (group :inline t
  2836. (const :tag "Always show months" :require-months)
  2837. (const t))
  2838. (group :inline t (const :tag "Weeks" :weeks)
  2839. (string :tag "Format string"))
  2840. (group :inline t
  2841. (const :tag "Always show weeks" :require-weeks)
  2842. (const t))
  2843. (group :inline t (const :tag "Days" :days)
  2844. (string :tag "Format string"))
  2845. (group :inline t
  2846. (const :tag "Always show days" :require-days)
  2847. (const t))
  2848. (group :inline t (const :tag "Hours" :hours)
  2849. (string :tag "Format string"))
  2850. (group :inline t
  2851. (const :tag "Always show hours" :require-hours)
  2852. (const t))
  2853. (group :inline t (const :tag "Minutes" :minutes)
  2854. (string :tag "Format string"))
  2855. (group :inline t
  2856. (const :tag "Always show minutes" :require-minutes)
  2857. (const t)))))
  2858. (defcustom org-time-clocksum-use-fractional nil
  2859. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2860. See `org-time-clocksum-format' for more on time clock formats."
  2861. :group 'org-time
  2862. :group 'org-clock
  2863. :version "24.3"
  2864. :type 'boolean)
  2865. (defcustom org-time-clocksum-use-effort-durations nil
  2866. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2867. E.g. by default, one day is considered to be a 8 hours effort,
  2868. so a task that has been clocked for 16 hours will be displayed
  2869. as during 2 days in the clock display or in the clocktable.
  2870. See `org-effort-durations' on how to set effort durations
  2871. and `org-time-clocksum-format' for more on time clock formats."
  2872. :group 'org-time
  2873. :group 'org-clock
  2874. :version "24.4"
  2875. :package-version '(Org . "8.0")
  2876. :type 'boolean)
  2877. (defcustom org-time-clocksum-fractional-format "%.2f"
  2878. "The format string used when creating CLOCKSUM lines,
  2879. or when Org mode generates a time duration, if
  2880. `org-time-clocksum-use-fractional' is enabled.
  2881. The value can be a single format string containing one
  2882. %-sequence, which will be filled with the number of hours as
  2883. a float.
  2884. Alternatively, the value can be a plist associating any of the
  2885. keys :years, :months, :weeks, :days, :hours or :minutes with
  2886. a format string. The time duration is formatted using the
  2887. largest time unit which gives a non-zero integer part. If all
  2888. specified formats have zero integer part, the smallest time unit
  2889. is used."
  2890. :group 'org-time
  2891. :type '(choice (string :tag "Format string")
  2892. (set (group :inline t (const :tag "Years" :years)
  2893. (string :tag "Format string"))
  2894. (group :inline t (const :tag "Months" :months)
  2895. (string :tag "Format string"))
  2896. (group :inline t (const :tag "Weeks" :weeks)
  2897. (string :tag "Format string"))
  2898. (group :inline t (const :tag "Days" :days)
  2899. (string :tag "Format string"))
  2900. (group :inline t (const :tag "Hours" :hours)
  2901. (string :tag "Format string"))
  2902. (group :inline t (const :tag "Minutes" :minutes)
  2903. (string :tag "Format string")))))
  2904. (defcustom org-deadline-warning-days 14
  2905. "Number of days before expiration during which a deadline becomes active.
  2906. This variable governs the display in sparse trees and in the agenda.
  2907. When 0 or negative, it means use this number (the absolute value of it)
  2908. even if a deadline has a different individual lead time specified.
  2909. Custom commands can set this variable in the options section."
  2910. :group 'org-time
  2911. :group 'org-agenda-daily/weekly
  2912. :type 'integer)
  2913. (defcustom org-scheduled-delay-days 0
  2914. "Number of days before a scheduled item becomes active.
  2915. This variable governs the display in sparse trees and in the agenda.
  2916. The default value (i.e. 0) means: don't delay scheduled item.
  2917. When negative, it means use this number (the absolute value of it)
  2918. even if a scheduled item has a different individual delay time
  2919. specified.
  2920. Custom commands can set this variable in the options section."
  2921. :group 'org-time
  2922. :group 'org-agenda-daily/weekly
  2923. :version "24.4"
  2924. :package-version '(Org . "8.0")
  2925. :type 'integer)
  2926. (defcustom org-read-date-prefer-future t
  2927. "Non-nil means assume future for incomplete date input from user.
  2928. This affects the following situations:
  2929. 1. The user gives a month but not a year.
  2930. For example, if it is April and you enter \"feb 2\", this will be read
  2931. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2932. 2. The user gives a day, but no month.
  2933. For example, if today is the 15th, and you enter \"3\", Org will read
  2934. this as the third of *next* month. However, if you enter \"17\",
  2935. it will be considered as *this* month.
  2936. If you set this variable to the symbol `time', then also the following
  2937. will work:
  2938. 3. If the user gives a time.
  2939. If the time is before now, it will be interpreted as tomorrow.
  2940. Currently none of this works for ISO week specifications.
  2941. When this option is nil, the current day, month and year will always be
  2942. used as defaults.
  2943. See also `org-agenda-jump-prefer-future'."
  2944. :group 'org-time
  2945. :type '(choice
  2946. (const :tag "Never" nil)
  2947. (const :tag "Check month and day" t)
  2948. (const :tag "Check month, day, and time" time)))
  2949. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2950. "Should the agenda jump command prefer the future for incomplete dates?
  2951. The default is to do the same as configured in `org-read-date-prefer-future'.
  2952. But you can also set a deviating value here.
  2953. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2954. :group 'org-agenda
  2955. :group 'org-time
  2956. :version "24.1"
  2957. :type '(choice
  2958. (const :tag "Use org-read-date-prefer-future"
  2959. org-read-date-prefer-future)
  2960. (const :tag "Never" nil)
  2961. (const :tag "Always" t)))
  2962. (defcustom org-read-date-force-compatible-dates t
  2963. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2964. Depending on the system Emacs is running on, certain dates cannot
  2965. be represented with the type used internally to represent time.
  2966. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2967. correctly. Some systems allow for earlier dates, some for later,
  2968. some for both. One way to find out it to insert any date into an
  2969. Org buffer, putting the cursor on the year and hitting S-up and
  2970. S-down to test the range.
  2971. When this variable is set to t, the date/time prompt will not let
  2972. you specify dates outside the 1970-2037 range, so it is certain that
  2973. these dates will work in whatever version of Emacs you are
  2974. running, and also that you can move a file from one Emacs implementation
  2975. to another. WHenever Org is forcing the year for you, it will display
  2976. a message and beep.
  2977. When this variable is nil, Org will check if the date is
  2978. representable in the specific Emacs implementation you are using.
  2979. If not, it will force a year, usually the current year, and beep
  2980. to remind you. Currently this setting is not recommended because
  2981. the likelihood that you will open your Org files in an Emacs that
  2982. has limited date range is not negligible.
  2983. A workaround for this problem is to use diary sexp dates for time
  2984. stamps outside of this range."
  2985. :group 'org-time
  2986. :version "24.1"
  2987. :type 'boolean)
  2988. (defcustom org-read-date-display-live t
  2989. "Non-nil means display current interpretation of date prompt live.
  2990. This display will be in an overlay, in the minibuffer."
  2991. :group 'org-time
  2992. :type 'boolean)
  2993. (defcustom org-read-date-popup-calendar t
  2994. "Non-nil means pop up a calendar when prompting for a date.
  2995. In the calendar, the date can be selected with mouse-1. However, the
  2996. minibuffer will also be active, and you can simply enter the date as well.
  2997. When nil, only the minibuffer will be available."
  2998. :group 'org-time
  2999. :type 'boolean)
  3000. (defvaralias 'org-popup-calendar-for-date-prompt
  3001. 'org-read-date-popup-calendar)
  3002. (defcustom org-extend-today-until 0
  3003. "The hour when your day really ends. Must be an integer.
  3004. This has influence for the following applications:
  3005. - When switching the agenda to \"today\". It it is still earlier than
  3006. the time given here, the day recognized as TODAY is actually yesterday.
  3007. - When a date is read from the user and it is still before the time given
  3008. here, the current date and time will be assumed to be yesterday, 23:59.
  3009. Also, timestamps inserted in capture templates follow this rule.
  3010. IMPORTANT: This is a feature whose implementation is and likely will
  3011. remain incomplete. Really, it is only here because past midnight seems to
  3012. be the favorite working time of John Wiegley :-)"
  3013. :group 'org-time
  3014. :type 'integer)
  3015. (defcustom org-use-effective-time nil
  3016. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3017. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3018. \"effective time\" of any timestamps between midnight and 8am will be
  3019. 23:59 of the previous day."
  3020. :group 'org-time
  3021. :version "24.1"
  3022. :type 'boolean)
  3023. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3024. "When non-nil, use the last clock out time for `org-todo'.
  3025. Note that this option has precedence over the combined use of
  3026. `org-use-effective-time' and `org-extend-today-until'."
  3027. :group 'org-time
  3028. :version "24.4"
  3029. :package-version '(Org . "8.0")
  3030. :type 'boolean)
  3031. (defcustom org-edit-timestamp-down-means-later nil
  3032. "Non-nil means S-down will increase the time in a time stamp.
  3033. When nil, S-up will increase."
  3034. :group 'org-time
  3035. :type 'boolean)
  3036. (defcustom org-calendar-follow-timestamp-change t
  3037. "Non-nil means make the calendar window follow timestamp changes.
  3038. When a timestamp is modified and the calendar window is visible, it will be
  3039. moved to the new date."
  3040. :group 'org-time
  3041. :type 'boolean)
  3042. (defgroup org-tags nil
  3043. "Options concerning tags in Org mode."
  3044. :tag "Org Tags"
  3045. :group 'org)
  3046. (defcustom org-tag-alist nil
  3047. "Default tags available in Org files.
  3048. The value of this variable is an alist. Associations either:
  3049. (TAG)
  3050. (TAG . SELECT)
  3051. (SPECIAL)
  3052. where TAG is a tag as a string, SELECT is character, used to
  3053. select that tag through the fast tag selection interface, and
  3054. SPECIAL is one of the following keywords: `:startgroup',
  3055. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3056. `:newline'. These keywords are used to define a hierarchy of
  3057. tags. See manual for details.
  3058. When this variable is nil, Org mode bases tag input on what is
  3059. already in the buffer. The value can be overridden locally by
  3060. using a TAGS keyword, e.g.,
  3061. #+TAGS: tag1 tag2
  3062. See also `org-tag-persistent-alist' to sidestep this behavior."
  3063. :group 'org-tags
  3064. :type '(repeat
  3065. (choice
  3066. (cons (string :tag "Tag name")
  3067. (character :tag "Access char"))
  3068. (const :tag "Start radio group" (:startgroup))
  3069. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3070. (const :tag "Group tags delimiter" (:grouptags))
  3071. (const :tag "End radio group" (:endgroup))
  3072. (const :tag "End tag group, non distinct" (:endgrouptag))
  3073. (const :tag "New line" (:newline)))))
  3074. (defcustom org-tag-persistent-alist nil
  3075. "Tags always available in Org files.
  3076. The value of this variable is an alist. Associations either:
  3077. (TAG)
  3078. (TAG . SELECT)
  3079. (SPECIAL)
  3080. where TAG is a tag as a string, SELECT is a character, used to
  3081. select that tag through the fast tag selection interface, and
  3082. SPECIAL is one of the following keywords: `:startgroup',
  3083. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3084. `:newline'. These keywords are used to define a hierarchy of
  3085. tags. See manual for details.
  3086. Unlike to `org-tag-alist', tags defined in this variable do not
  3087. depend on a local TAGS keyword. Instead, to disable these tags
  3088. on a per-file basis, insert anywhere in the file:
  3089. #+STARTUP: noptag"
  3090. :group 'org-tags
  3091. :type '(repeat
  3092. (choice
  3093. (cons (string :tag "Tag name")
  3094. (character :tag "Access char"))
  3095. (const :tag "Start radio group" (:startgroup))
  3096. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3097. (const :tag "Group tags delimiter" (:grouptags))
  3098. (const :tag "End radio group" (:endgroup))
  3099. (const :tag "End tag group, non distinct" (:endgrouptag))
  3100. (const :tag "New line" (:newline)))))
  3101. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3102. "If non-nil, always offer completion for all tags of all agenda files.
  3103. Instead of customizing this variable directly, you might want to
  3104. set it locally for capture buffers, because there no list of
  3105. tags in that file can be created dynamically (there are none).
  3106. (add-hook \\='org-capture-mode-hook
  3107. (lambda ()
  3108. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3109. :group 'org-tags
  3110. :version "24.1"
  3111. :type 'boolean)
  3112. (defvar org-file-tags nil
  3113. "List of tags that can be inherited by all entries in the file.
  3114. The tags will be inherited if the variable `org-use-tag-inheritance'
  3115. says they should be.
  3116. This variable is populated from #+FILETAGS lines.")
  3117. (defcustom org-use-fast-tag-selection 'auto
  3118. "Non-nil means use fast tag selection scheme.
  3119. This is a special interface to select and deselect tags with single keys.
  3120. When nil, fast selection is never used.
  3121. When the symbol `auto', fast selection is used if and only if selection
  3122. characters for tags have been configured, either through the variable
  3123. `org-tag-alist' or through a #+TAGS line in the buffer.
  3124. When t, fast selection is always used and selection keys are assigned
  3125. automatically if necessary."
  3126. :group 'org-tags
  3127. :type '(choice
  3128. (const :tag "Always" t)
  3129. (const :tag "Never" nil)
  3130. (const :tag "When selection characters are configured" auto)))
  3131. (defcustom org-fast-tag-selection-single-key nil
  3132. "Non-nil means fast tag selection exits after first change.
  3133. When nil, you have to press RET to exit it.
  3134. During fast tag selection, you can toggle this flag with `C-c'.
  3135. This variable can also have the value `expert'. In this case, the window
  3136. displaying the tags menu is not even shown, until you press C-c again."
  3137. :group 'org-tags
  3138. :type '(choice
  3139. (const :tag "No" nil)
  3140. (const :tag "Yes" t)
  3141. (const :tag "Expert" expert)))
  3142. (defvar org-fast-tag-selection-include-todo nil
  3143. "Non-nil means fast tags selection interface will also offer TODO states.
  3144. This is an undocumented feature, you should not rely on it.")
  3145. (defcustom org-tags-column -77
  3146. "The column to which tags should be indented in a headline.
  3147. If this number is positive, it specifies the column. If it is negative,
  3148. it means that the tags should be flushright to that column. For example,
  3149. -80 works well for a normal 80 character screen.
  3150. When 0, place tags directly after headline text, with only one space in
  3151. between."
  3152. :group 'org-tags
  3153. :type 'integer)
  3154. (defcustom org-auto-align-tags t
  3155. "Non-nil keeps tags aligned when modifying headlines.
  3156. Some operations (i.e. demoting) change the length of a headline and
  3157. therefore shift the tags around. With this option turned on, after
  3158. each such operation the tags are again aligned to `org-tags-column'."
  3159. :group 'org-tags
  3160. :type 'boolean)
  3161. (defcustom org-use-tag-inheritance t
  3162. "Non-nil means tags in levels apply also for sublevels.
  3163. When nil, only the tags directly given in a specific line apply there.
  3164. This may also be a list of tags that should be inherited, or a regexp that
  3165. matches tags that should be inherited. Additional control is possible
  3166. with the variable `org-tags-exclude-from-inheritance' which gives an
  3167. explicit list of tags to be excluded from inheritance, even if the value of
  3168. `org-use-tag-inheritance' would select it for inheritance.
  3169. If this option is t, a match early-on in a tree can lead to a large
  3170. number of matches in the subtree when constructing the agenda or creating
  3171. a sparse tree. If you only want to see the first match in a tree during
  3172. a search, check out the variable `org-tags-match-list-sublevels'."
  3173. :group 'org-tags
  3174. :type '(choice
  3175. (const :tag "Not" nil)
  3176. (const :tag "Always" t)
  3177. (repeat :tag "Specific tags" (string :tag "Tag"))
  3178. (regexp :tag "Tags matched by regexp")))
  3179. (defcustom org-tags-exclude-from-inheritance nil
  3180. "List of tags that should never be inherited.
  3181. This is a way to exclude a few tags from inheritance. For way to do
  3182. the opposite, to actively allow inheritance for selected tags,
  3183. see the variable `org-use-tag-inheritance'."
  3184. :group 'org-tags
  3185. :type '(repeat (string :tag "Tag")))
  3186. (defun org-tag-inherit-p (tag)
  3187. "Check if TAG is one that should be inherited."
  3188. (cond
  3189. ((member tag org-tags-exclude-from-inheritance) nil)
  3190. ((eq org-use-tag-inheritance t) t)
  3191. ((not org-use-tag-inheritance) nil)
  3192. ((stringp org-use-tag-inheritance)
  3193. (string-match org-use-tag-inheritance tag))
  3194. ((listp org-use-tag-inheritance)
  3195. (member tag org-use-tag-inheritance))
  3196. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3197. (defcustom org-tags-match-list-sublevels t
  3198. "Non-nil means list also sublevels of headlines matching a search.
  3199. This variable applies to tags/property searches, and also to stuck
  3200. projects because this search is based on a tags match as well.
  3201. When set to the symbol `indented', sublevels are indented with
  3202. leading dots.
  3203. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3204. the sublevels of a headline matching a tag search often also match
  3205. the same search. Listing all of them can create very long lists.
  3206. Setting this variable to nil causes subtrees of a match to be skipped.
  3207. This variable is semi-obsolete and probably should always be true. It
  3208. is better to limit inheritance to certain tags using the variables
  3209. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3210. :group 'org-tags
  3211. :type '(choice
  3212. (const :tag "No, don't list them" nil)
  3213. (const :tag "Yes, do list them" t)
  3214. (const :tag "List them, indented with leading dots" indented)))
  3215. (defcustom org-tags-sort-function nil
  3216. "When set, tags are sorted using this function as a comparator."
  3217. :group 'org-tags
  3218. :type '(choice
  3219. (const :tag "No sorting" nil)
  3220. (const :tag "Alphabetical" string<)
  3221. (const :tag "Reverse alphabetical" string>)
  3222. (function :tag "Custom function" nil)))
  3223. (defvar org-tags-history nil
  3224. "History of minibuffer reads for tags.")
  3225. (defvar org-last-tags-completion-table nil
  3226. "The last used completion table for tags.")
  3227. (defvar org-after-tags-change-hook nil
  3228. "Hook that is run after the tags in a line have changed.")
  3229. (defgroup org-properties nil
  3230. "Options concerning properties in Org mode."
  3231. :tag "Org Properties"
  3232. :group 'org)
  3233. (defcustom org-property-format "%-10s %s"
  3234. "How property key/value pairs should be formatted by `indent-line'.
  3235. When `indent-line' hits a property definition, it will format the line
  3236. according to this format, mainly to make sure that the values are
  3237. lined-up with respect to each other."
  3238. :group 'org-properties
  3239. :type 'string)
  3240. (defcustom org-properties-postprocess-alist nil
  3241. "Alist of properties and functions to adjust inserted values.
  3242. Elements of this alist must be of the form
  3243. ([string] [function])
  3244. where [string] must be a property name and [function] must be a
  3245. lambda expression: this lambda expression must take one argument,
  3246. the value to adjust, and return the new value as a string.
  3247. For example, this element will allow the property \"Remaining\"
  3248. to be updated wrt the relation between the \"Effort\" property
  3249. and the clock summary:
  3250. ((\"Remaining\" (lambda(value)
  3251. (let ((clocksum (org-clock-sum-current-item))
  3252. (effort (org-duration-string-to-minutes
  3253. (org-entry-get (point) \"Effort\"))))
  3254. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3255. :group 'org-properties
  3256. :version "24.1"
  3257. :type '(alist :key-type (string :tag "Property")
  3258. :value-type (function :tag "Function")))
  3259. (defcustom org-use-property-inheritance nil
  3260. "Non-nil means properties apply also for sublevels.
  3261. This setting is chiefly used during property searches. Turning it on can
  3262. cause significant overhead when doing a search, which is why it is not
  3263. on by default.
  3264. When nil, only the properties directly given in the current entry count.
  3265. When t, every property is inherited. The value may also be a list of
  3266. properties that should have inheritance, or a regular expression matching
  3267. properties that should be inherited.
  3268. However, note that some special properties use inheritance under special
  3269. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3270. and the properties ending in \"_ALL\" when they are used as descriptor
  3271. for valid values of a property.
  3272. Note for programmers:
  3273. When querying an entry with `org-entry-get', you can control if inheritance
  3274. should be used. By default, `org-entry-get' looks only at the local
  3275. properties. You can request inheritance by setting the inherit argument
  3276. to t (to force inheritance) or to `selective' (to respect the setting
  3277. in this variable)."
  3278. :group 'org-properties
  3279. :type '(choice
  3280. (const :tag "Not" nil)
  3281. (const :tag "Always" t)
  3282. (repeat :tag "Specific properties" (string :tag "Property"))
  3283. (regexp :tag "Properties matched by regexp")))
  3284. (defun org-property-inherit-p (property)
  3285. "Check if PROPERTY is one that should be inherited."
  3286. (cond
  3287. ((eq org-use-property-inheritance t) t)
  3288. ((not org-use-property-inheritance) nil)
  3289. ((stringp org-use-property-inheritance)
  3290. (string-match org-use-property-inheritance property))
  3291. ((listp org-use-property-inheritance)
  3292. (member property org-use-property-inheritance))
  3293. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3294. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3295. "The default column format, if no other format has been defined.
  3296. This variable can be set on the per-file basis by inserting a line
  3297. #+COLUMNS: %25ITEM ....."
  3298. :group 'org-properties
  3299. :type 'string)
  3300. (defcustom org-columns-ellipses ".."
  3301. "The ellipses to be used when a field in column view is truncated.
  3302. When this is the empty string, as many characters as possible are shown,
  3303. but then there will be no visual indication that the field has been truncated.
  3304. When this is a string of length N, the last N characters of a truncated
  3305. field are replaced by this string. If the column is narrower than the
  3306. ellipses string, only part of the ellipses string will be shown."
  3307. :group 'org-properties
  3308. :type 'string)
  3309. (defconst org-global-properties-fixed
  3310. '(("VISIBILITY_ALL" . "folded children content all")
  3311. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3312. "List of property/value pairs that can be inherited by any entry.
  3313. These are fixed values, for the preset properties. The user variable
  3314. that can be used to add to this list is `org-global-properties'.
  3315. The entries in this list are cons cells where the car is a property
  3316. name and cdr is a string with the value. If the value represents
  3317. multiple items like an \"_ALL\" property, separate the items by
  3318. spaces.")
  3319. (defcustom org-global-properties nil
  3320. "List of property/value pairs that can be inherited by any entry.
  3321. This list will be combined with the constant `org-global-properties-fixed'.
  3322. The entries in this list are cons cells where the car is a property
  3323. name and cdr is a string with the value.
  3324. You can set buffer-local values for the same purpose in the variable
  3325. `org-file-properties' this by adding lines like
  3326. #+PROPERTY: NAME VALUE"
  3327. :group 'org-properties
  3328. :type '(repeat
  3329. (cons (string :tag "Property")
  3330. (string :tag "Value"))))
  3331. (defvar-local org-file-properties nil
  3332. "List of property/value pairs that can be inherited by any entry.
  3333. Valid for the current buffer.
  3334. This variable is populated from #+PROPERTY lines.")
  3335. (defgroup org-agenda nil
  3336. "Options concerning agenda views in Org mode."
  3337. :tag "Org Agenda"
  3338. :group 'org)
  3339. (defvar-local org-category nil
  3340. "Variable used by org files to set a category for agenda display.
  3341. Such files should use a file variable to set it, for example
  3342. # -*- mode: org; org-category: \"ELisp\"
  3343. or contain a special line
  3344. #+CATEGORY: ELisp
  3345. If the file does not specify a category, then file's base name
  3346. is used instead.")
  3347. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3348. (defcustom org-agenda-files nil
  3349. "The files to be used for agenda display.
  3350. If an entry is a directory, all files in that directory that are matched
  3351. by `org-agenda-file-regexp' will be part of the file list.
  3352. If the value of the variable is not a list but a single file name, then
  3353. the list of agenda files is actually stored and maintained in that file,
  3354. one agenda file per line. In this file paths can be given relative to
  3355. `org-directory'. Tilde expansion and environment variable substitution
  3356. are also made.
  3357. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3358. and removed with `\\[org-remove-file]'."
  3359. :group 'org-agenda
  3360. :type '(choice
  3361. (repeat :tag "List of files and directories" file)
  3362. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3363. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3364. "Regular expression to match files for `org-agenda-files'.
  3365. If any element in the list in that variable contains a directory instead
  3366. of a normal file, all files in that directory that are matched by this
  3367. regular expression will be included."
  3368. :group 'org-agenda
  3369. :type 'regexp)
  3370. (defcustom org-agenda-text-search-extra-files nil
  3371. "List of extra files to be searched by text search commands.
  3372. These files will be searched in addition to the agenda files by the
  3373. commands `org-search-view' (`\\[org-agenda] s') \
  3374. and `org-occur-in-agenda-files'.
  3375. Note that these files will only be searched for text search commands,
  3376. not for the other agenda views like todo lists, tag searches or the weekly
  3377. agenda. This variable is intended to list notes and possibly archive files
  3378. that should also be searched by these two commands.
  3379. In fact, if the first element in the list is the symbol `agenda-archives',
  3380. then all archive files of all agenda files will be added to the search
  3381. scope."
  3382. :group 'org-agenda
  3383. :type '(set :greedy t
  3384. (const :tag "Agenda Archives" agenda-archives)
  3385. (repeat :inline t (file))))
  3386. (defvaralias 'org-agenda-multi-occur-extra-files
  3387. 'org-agenda-text-search-extra-files)
  3388. (defcustom org-agenda-skip-unavailable-files nil
  3389. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3390. A nil value means to remove them, after a query, from the list."
  3391. :group 'org-agenda
  3392. :type 'boolean)
  3393. (defcustom org-calendar-to-agenda-key [?c]
  3394. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3395. The command `org-calendar-goto-agenda' will be bound to this key. The
  3396. default is the character `c' because then `c' can be used to switch back and
  3397. forth between agenda and calendar."
  3398. :group 'org-agenda
  3399. :type 'sexp)
  3400. (defcustom org-calendar-insert-diary-entry-key [?i]
  3401. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3402. This option is irrelevant until `org-agenda-diary-file' has been configured
  3403. to point to an Org file. When that is the case, the command
  3404. `org-agenda-diary-entry' will be bound to the key given here, by default
  3405. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3406. if you want to continue doing this, you need to change this to a different
  3407. key."
  3408. :group 'org-agenda
  3409. :type 'sexp)
  3410. (defcustom org-agenda-diary-file 'diary-file
  3411. "File to which to add new entries with the `i' key in agenda and calendar.
  3412. When this is the symbol `diary-file', the functionality in the Emacs
  3413. calendar will be used to add entries to the `diary-file'. But when this
  3414. points to a file, `org-agenda-diary-entry' will be used instead."
  3415. :group 'org-agenda
  3416. :type '(choice
  3417. (const :tag "The standard Emacs diary file" diary-file)
  3418. (file :tag "Special Org file diary entries")))
  3419. (eval-after-load "calendar"
  3420. '(progn
  3421. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3422. 'org-calendar-goto-agenda)
  3423. (add-hook 'calendar-mode-hook
  3424. (lambda ()
  3425. (unless (eq org-agenda-diary-file 'diary-file)
  3426. (define-key calendar-mode-map
  3427. org-calendar-insert-diary-entry-key
  3428. 'org-agenda-diary-entry))))))
  3429. (defgroup org-latex nil
  3430. "Options for embedding LaTeX code into Org mode."
  3431. :tag "Org LaTeX"
  3432. :group 'org)
  3433. (defcustom org-format-latex-options
  3434. '(:foreground default :background default :scale 1.0
  3435. :html-foreground "Black" :html-background "Transparent"
  3436. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3437. "Options for creating images from LaTeX fragments.
  3438. This is a property list with the following properties:
  3439. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3440. `default' means use the foreground of the default face.
  3441. `auto' means use the foreground from the text face.
  3442. :background the background color, or \"Transparent\".
  3443. `default' means use the background of the default face.
  3444. `auto' means use the background from the text face.
  3445. :scale a scaling factor for the size of the images, to get more pixels
  3446. :html-foreground, :html-background, :html-scale
  3447. the same numbers for HTML export.
  3448. :matchers a list indicating which matchers should be used to
  3449. find LaTeX fragments. Valid members of this list are:
  3450. \"begin\" find environments
  3451. \"$1\" find single characters surrounded by $.$
  3452. \"$\" find math expressions surrounded by $...$
  3453. \"$$\" find math expressions surrounded by $$....$$
  3454. \"\\(\" find math expressions surrounded by \\(...\\)
  3455. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3456. :group 'org-latex
  3457. :type 'plist)
  3458. (defcustom org-format-latex-signal-error t
  3459. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3460. When nil, just push out a message."
  3461. :group 'org-latex
  3462. :version "24.1"
  3463. :type 'boolean)
  3464. (defcustom org-latex-to-mathml-jar-file nil
  3465. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3466. Use this to specify additional executable file say a jar file.
  3467. When using MathToWeb as the converter, specify the full-path to
  3468. your mathtoweb.jar file."
  3469. :group 'org-latex
  3470. :version "24.1"
  3471. :type '(choice
  3472. (const :tag "None" nil)
  3473. (file :tag "JAR file" :must-match t)))
  3474. (defcustom org-latex-to-mathml-convert-command nil
  3475. "Command to convert LaTeX fragments to MathML.
  3476. Replace format-specifiers in the command as noted below and use
  3477. `shell-command' to convert LaTeX to MathML.
  3478. %j: Executable file in fully expanded form as specified by
  3479. `org-latex-to-mathml-jar-file'.
  3480. %I: Input LaTeX file in fully expanded form.
  3481. %i: The latex fragment to be converted.
  3482. %o: Output MathML file.
  3483. This command is used by `org-create-math-formula'.
  3484. When using MathToWeb as the converter, set this option to
  3485. \"java -jar %j -unicode -force -df %o %I\".
  3486. When using LaTeXML set this option to
  3487. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3488. :group 'org-latex
  3489. :version "24.1"
  3490. :type '(choice
  3491. (const :tag "None" nil)
  3492. (string :tag "\nShell command")))
  3493. (defcustom org-preview-latex-default-process 'dvipng
  3494. "The default process to convert LaTeX fragments to image files.
  3495. All available processes and theirs documents can be found in
  3496. `org-preview-latex-process-alist', which see."
  3497. :group 'org-latex
  3498. :version "25.2"
  3499. :package-version '(Org . "9.0")
  3500. :type 'symbol)
  3501. (defcustom org-preview-latex-process-alist
  3502. '((dvipng
  3503. :programs ("latex" "dvipng")
  3504. :description "dvi > png"
  3505. :message "you need to install the programs: latex and dvipng."
  3506. :image-input-type "dvi"
  3507. :image-output-type "png"
  3508. :image-size-adjust (1.0 . 1.0)
  3509. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3510. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3511. (dvisvgm
  3512. :programs ("latex" "dvisvgm")
  3513. :description "dvi > svg"
  3514. :message "you need to install the programs: latex and dvisvgm."
  3515. :use-xcolor t
  3516. :image-input-type "dvi"
  3517. :image-output-type "svg"
  3518. :image-size-adjust (1.7 . 1.5)
  3519. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3520. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3521. (imagemagick
  3522. :programs ("latex" "convert")
  3523. :description "pdf > png"
  3524. :message "you need to install the programs: latex and imagemagick."
  3525. :use-xcolor t
  3526. :image-input-type "pdf"
  3527. :image-output-type "png"
  3528. :image-size-adjust (1.0 . 1.0)
  3529. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3530. :image-converter
  3531. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3532. "Definitions of external processes for LaTeX previewing.
  3533. Org mode can use some external commands to generate TeX snippet's images for
  3534. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3535. `org-create-formula-image' how to call them.
  3536. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3537. PROPERTIES accepts the following attributes:
  3538. :programs list of strings, required programs.
  3539. :description string, describe the process.
  3540. :message string, message it when required programs cannot be found.
  3541. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3542. :image-output-type string, output file type of image converter (e.g., \"png\").
  3543. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3544. deal with background and foreground color of image.
  3545. Otherwise, dvipng style background and foregroud color
  3546. format are generated. You may then refer to them in
  3547. command options with \"%F\" and \"%B\".
  3548. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3549. image size showed in buffer and the cdr element is for
  3550. HTML file. This option is only useful for process
  3551. developers, users should use variable
  3552. `org-format-latex-options' instead.
  3553. :post-clean list of strings, files matched are to be cleaned up once
  3554. the image is generated. When nil, the files with \".dvi\",
  3555. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3556. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3557. be cleaned up.
  3558. :latex-header list of strings, the LaTeX header of the snippet file.
  3559. When nil, the fallback value is used instead, which is
  3560. controlled by `org-format-latex-header',
  3561. `org-latex-default-packages-alist' and
  3562. `org-latex-packages-alist', which see.
  3563. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3564. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3565. replaced with values defined below.
  3566. :image-converter list of image converter commands strings. Each of them is
  3567. given to the shell and supports any of the following
  3568. place-holders defined below.
  3569. Place-holders used by `:image-converter' and `:latex-compiler':
  3570. %f input file name
  3571. %b base name of input file
  3572. %o base directory of input file
  3573. %O absolute output file name
  3574. Place-holders only used by `:image-converter':
  3575. %F foreground of image
  3576. %B background of image
  3577. %D dpi, which is used to adjust image size by some processing commands.
  3578. %S the image size scale ratio, which is used to adjust image size by some
  3579. processing commands."
  3580. :group 'org-latex
  3581. :version "25.2"
  3582. :package-version '(Org . "9.0")
  3583. :type '(alist :tag "LaTeX to image backends"
  3584. :value-type (plist)))
  3585. (defcustom org-preview-latex-image-directory "ltximg/"
  3586. "Path to store latex preview images.
  3587. A relative path here creates many directories relative to the
  3588. processed org files paths. An absolute path puts all preview
  3589. images at the same place."
  3590. :group 'org-latex
  3591. :version "25.2"
  3592. :package-version '(Org . "9.0")
  3593. :type 'string)
  3594. (defun org-format-latex-mathml-available-p ()
  3595. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3596. (save-match-data
  3597. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3598. org-latex-to-mathml-convert-command)
  3599. (let ((executable (car (split-string
  3600. org-latex-to-mathml-convert-command))))
  3601. (when (executable-find executable)
  3602. (if (string-match
  3603. "%j" org-latex-to-mathml-convert-command)
  3604. (file-readable-p org-latex-to-mathml-jar-file)
  3605. t))))))
  3606. (defcustom org-format-latex-header "\\documentclass{article}
  3607. \\usepackage[usenames]{color}
  3608. \[PACKAGES]
  3609. \[DEFAULT-PACKAGES]
  3610. \\pagestyle{empty} % do not remove
  3611. % The settings below are copied from fullpage.sty
  3612. \\setlength{\\textwidth}{\\paperwidth}
  3613. \\addtolength{\\textwidth}{-3cm}
  3614. \\setlength{\\oddsidemargin}{1.5cm}
  3615. \\addtolength{\\oddsidemargin}{-2.54cm}
  3616. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3617. \\setlength{\\textheight}{\\paperheight}
  3618. \\addtolength{\\textheight}{-\\headheight}
  3619. \\addtolength{\\textheight}{-\\headsep}
  3620. \\addtolength{\\textheight}{-\\footskip}
  3621. \\addtolength{\\textheight}{-3cm}
  3622. \\setlength{\\topmargin}{1.5cm}
  3623. \\addtolength{\\topmargin}{-2.54cm}"
  3624. "The document header used for processing LaTeX fragments.
  3625. It is imperative that this header make sure that no page number
  3626. appears on the page. The package defined in the variables
  3627. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3628. will either replace the placeholder \"[PACKAGES]\" in this
  3629. header, or they will be appended."
  3630. :group 'org-latex
  3631. :type 'string)
  3632. (defun org-set-packages-alist (var val)
  3633. "Set the packages alist and make sure it has 3 elements per entry."
  3634. (set var (mapcar (lambda (x)
  3635. (if (and (consp x) (= (length x) 2))
  3636. (list (car x) (nth 1 x) t)
  3637. x))
  3638. val)))
  3639. (defun org-get-packages-alist (var)
  3640. "Get the packages alist and make sure it has 3 elements per entry."
  3641. (mapcar (lambda (x)
  3642. (if (and (consp x) (= (length x) 2))
  3643. (list (car x) (nth 1 x) t)
  3644. x))
  3645. (default-value var)))
  3646. (defcustom org-latex-default-packages-alist
  3647. '(("AUTO" "inputenc" t ("pdflatex"))
  3648. ("T1" "fontenc" t ("pdflatex"))
  3649. ("" "graphicx" t)
  3650. ("" "grffile" t)
  3651. ("" "longtable" nil)
  3652. ("" "wrapfig" nil)
  3653. ("" "rotating" nil)
  3654. ("normalem" "ulem" t)
  3655. ("" "amsmath" t)
  3656. ("" "textcomp" t)
  3657. ("" "amssymb" t)
  3658. ("" "capt-of" nil)
  3659. ("" "hyperref" nil))
  3660. "Alist of default packages to be inserted in the header.
  3661. Change this only if one of the packages here causes an
  3662. incompatibility with another package you are using.
  3663. The packages in this list are needed by one part or another of
  3664. Org mode to function properly:
  3665. - inputenc, fontenc: for basic font and character selection
  3666. - graphicx: for including images
  3667. - grffile: allow periods and spaces in graphics file names
  3668. - longtable: For multipage tables
  3669. - wrapfig: for figure placement
  3670. - rotating: for sideways figures and tables
  3671. - ulem: for underline and strike-through
  3672. - amsmath: for subscript and superscript and math environments
  3673. - textcomp, amssymb: for various symbols used
  3674. for interpreting the entities in `org-entities'. You can skip
  3675. some of these packages if you don't use any of their symbols.
  3676. - capt-of: for captions outside of floats
  3677. - hyperref: for cross references
  3678. Therefore you should not modify this variable unless you know
  3679. what you are doing. The one reason to change it anyway is that
  3680. you might be loading some other package that conflicts with one
  3681. of the default packages. Each element is either a cell or
  3682. a string.
  3683. A cell is of the format
  3684. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3685. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3686. when compiling LaTeX snippets into images for inclusion into
  3687. non-LaTeX output. COMPILERS is a list of compilers that should
  3688. include the package, see `org-latex-compiler'. If the document
  3689. compiler is not in the list, and the list is non-nil, the package
  3690. will not be inserted in the final document.
  3691. A string will be inserted as-is in the header of the document."
  3692. :group 'org-latex
  3693. :group 'org-export-latex
  3694. :set 'org-set-packages-alist
  3695. :get 'org-get-packages-alist
  3696. :version "25.2"
  3697. :package-version '(Org . "8.3")
  3698. :type '(repeat
  3699. (choice
  3700. (list :tag "options/package pair"
  3701. (string :tag "options")
  3702. (string :tag "package")
  3703. (boolean :tag "Snippet"))
  3704. (string :tag "A line of LaTeX"))))
  3705. (defcustom org-latex-packages-alist nil
  3706. "Alist of packages to be inserted in every LaTeX header.
  3707. These will be inserted after `org-latex-default-packages-alist'.
  3708. Each element is either a cell or a string.
  3709. A cell is of the format:
  3710. (\"options\" \"package\" SNIPPET-FLAG)
  3711. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3712. needed when turning LaTeX snippets into images for inclusion into
  3713. non-LaTeX output.
  3714. A string will be inserted as-is in the header of the document.
  3715. Make sure that you only list packages here which:
  3716. - you want in every file;
  3717. - do not conflict with the setup in `org-format-latex-header';
  3718. - do not conflict with the default packages in
  3719. `org-latex-default-packages-alist'."
  3720. :group 'org-latex
  3721. :group 'org-export-latex
  3722. :set 'org-set-packages-alist
  3723. :get 'org-get-packages-alist
  3724. :type '(repeat
  3725. (choice
  3726. (list :tag "options/package pair"
  3727. (string :tag "options")
  3728. (string :tag "package")
  3729. (boolean :tag "Snippet"))
  3730. (string :tag "A line of LaTeX"))))
  3731. (defgroup org-appearance nil
  3732. "Settings for Org mode appearance."
  3733. :tag "Org Appearance"
  3734. :group 'org)
  3735. (defcustom org-level-color-stars-only nil
  3736. "Non-nil means fontify only the stars in each headline.
  3737. When nil, the entire headline is fontified.
  3738. Changing it requires restart of `font-lock-mode' to become effective
  3739. also in regions already fontified."
  3740. :group 'org-appearance
  3741. :type 'boolean)
  3742. (defcustom org-hide-leading-stars nil
  3743. "Non-nil means hide the first N-1 stars in a headline.
  3744. This works by using the face `org-hide' for these stars. This
  3745. face is white for a light background, and black for a dark
  3746. background. You may have to customize the face `org-hide' to
  3747. make this work.
  3748. Changing it requires restart of `font-lock-mode' to become effective
  3749. also in regions already fontified.
  3750. You may also set this on a per-file basis by adding one of the following
  3751. lines to the buffer:
  3752. #+STARTUP: hidestars
  3753. #+STARTUP: showstars"
  3754. :group 'org-appearance
  3755. :type 'boolean)
  3756. (defcustom org-hidden-keywords nil
  3757. "List of symbols corresponding to keywords to be hidden the org buffer.
  3758. For example, a value \\='(title) for this list will make the document's title
  3759. appear in the buffer without the initial #+TITLE: keyword."
  3760. :group 'org-appearance
  3761. :version "24.1"
  3762. :type '(set (const :tag "#+AUTHOR" author)
  3763. (const :tag "#+DATE" date)
  3764. (const :tag "#+EMAIL" email)
  3765. (const :tag "#+TITLE" title)))
  3766. (defcustom org-custom-properties nil
  3767. "List of properties (as strings) with a special meaning.
  3768. The default use of these custom properties is to let the user
  3769. hide them with `org-toggle-custom-properties-visibility'."
  3770. :group 'org-properties
  3771. :group 'org-appearance
  3772. :version "24.3"
  3773. :type '(repeat (string :tag "Property Name")))
  3774. (defcustom org-fontify-done-headline nil
  3775. "Non-nil means change the face of a headline if it is marked DONE.
  3776. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3777. When this is non-nil, the headline after the keyword is set to the
  3778. `org-headline-done' as an additional indication."
  3779. :group 'org-appearance
  3780. :type 'boolean)
  3781. (defcustom org-fontify-emphasized-text t
  3782. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3783. Changing this variable requires a restart of Emacs to take effect."
  3784. :group 'org-appearance
  3785. :type 'boolean)
  3786. (defcustom org-fontify-whole-heading-line nil
  3787. "Non-nil means fontify the whole line for headings.
  3788. This is useful when setting a background color for the
  3789. org-level-* faces."
  3790. :group 'org-appearance
  3791. :type 'boolean)
  3792. (defcustom org-highlight-latex-and-related nil
  3793. "Non-nil means highlight LaTeX related syntax in the buffer.
  3794. When non nil, the value should be a list containing any of the
  3795. following symbols:
  3796. `latex' Highlight LaTeX snippets and environments.
  3797. `script' Highlight subscript and superscript.
  3798. `entities' Highlight entities."
  3799. :group 'org-appearance
  3800. :version "24.4"
  3801. :package-version '(Org . "8.0")
  3802. :type '(choice
  3803. (const :tag "No highlighting" nil)
  3804. (set :greedy t :tag "Highlight"
  3805. (const :tag "LaTeX snippets and environments" latex)
  3806. (const :tag "Subscript and superscript" script)
  3807. (const :tag "Entities" entities))))
  3808. (defcustom org-hide-emphasis-markers nil
  3809. "Non-nil mean font-lock should hide the emphasis marker characters."
  3810. :group 'org-appearance
  3811. :type 'boolean)
  3812. (defcustom org-hide-macro-markers nil
  3813. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3814. :group 'org-appearance
  3815. :type 'boolean)
  3816. (defcustom org-pretty-entities nil
  3817. "Non-nil means show entities as UTF8 characters.
  3818. When nil, the \\name form remains in the buffer."
  3819. :group 'org-appearance
  3820. :version "24.1"
  3821. :type 'boolean)
  3822. (defcustom org-pretty-entities-include-sub-superscripts t
  3823. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3824. :group 'org-appearance
  3825. :version "24.1"
  3826. :type 'boolean)
  3827. (defvar org-emph-re nil
  3828. "Regular expression for matching emphasis.
  3829. After a match, the match groups contain these elements:
  3830. 0 The match of the full regular expression, including the characters
  3831. before and after the proper match
  3832. 1 The character before the proper match, or empty at beginning of line
  3833. 2 The proper match, including the leading and trailing markers
  3834. 3 The leading marker like * or /, indicating the type of highlighting
  3835. 4 The text between the emphasis markers, not including the markers
  3836. 5 The character after the match, empty at the end of a line")
  3837. (defvar org-verbatim-re nil
  3838. "Regular expression for matching verbatim text.")
  3839. (defvar org-emphasis-regexp-components) ; defined just below
  3840. (defvar org-emphasis-alist) ; defined just below
  3841. (defun org-set-emph-re (var val)
  3842. "Set variable and compute the emphasis regular expression."
  3843. (set var val)
  3844. (when (and (boundp 'org-emphasis-alist)
  3845. (boundp 'org-emphasis-regexp-components)
  3846. org-emphasis-alist org-emphasis-regexp-components)
  3847. (pcase-let*
  3848. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3849. (body (if (<= nl 0) body
  3850. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3851. (template
  3852. (format (concat "\\([%s]\\|^\\)" ;before markers
  3853. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3854. "\\([%s]\\|$\\)") ;after markers
  3855. pre border border body border post)))
  3856. (setq org-emph-re (format template "*/_+"))
  3857. (setq org-verbatim-re (format template "=~")))))
  3858. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3859. ;; set this option proved cumbersome. See this message/thread:
  3860. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3861. (defvar org-emphasis-regexp-components
  3862. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3863. "Components used to build the regular expression for emphasis.
  3864. This is a list with five entries. Terminology: In an emphasis string
  3865. like \" *strong word* \", we call the initial space PREMATCH, the final
  3866. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3867. and \"trong wor\" is the body. The different components in this variable
  3868. specify what is allowed/forbidden in each part:
  3869. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3870. post Chars allowed as postmatch. End of line will be allowed too.
  3871. border The chars *forbidden* as border characters.
  3872. body-regexp A regexp like \".\" to match a body character. Don't use
  3873. non-shy groups here, and don't allow newline here.
  3874. newline The maximum number of newlines allowed in an emphasis exp.
  3875. You need to reload Org or to restart Emacs after customizing this.")
  3876. (defcustom org-emphasis-alist
  3877. '(("*" bold)
  3878. ("/" italic)
  3879. ("_" underline)
  3880. ("=" org-verbatim verbatim)
  3881. ("~" org-code verbatim)
  3882. ("+" (:strike-through t)))
  3883. "Alist of characters and faces to emphasize text.
  3884. Text starting and ending with a special character will be emphasized,
  3885. for example *bold*, _underlined_ and /italic/. This variable sets the
  3886. marker characters and the face to be used by font-lock for highlighting
  3887. in Org buffers.
  3888. You need to reload Org or to restart Emacs after customizing this."
  3889. :group 'org-appearance
  3890. :set 'org-set-emph-re
  3891. :version "24.4"
  3892. :package-version '(Org . "8.0")
  3893. :type '(repeat
  3894. (list
  3895. (string :tag "Marker character")
  3896. (choice
  3897. (face :tag "Font-lock-face")
  3898. (plist :tag "Face property list"))
  3899. (option (const verbatim)))))
  3900. (defvar org-protecting-blocks '("src" "example" "export")
  3901. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3902. This is needed for font-lock setup.")
  3903. ;;; Functions and variables from their packages
  3904. ;; Declared here to avoid compiler warnings
  3905. (defvar mark-active)
  3906. ;; Various packages
  3907. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3908. (declare-function calendar-forward-day "cal-move" (arg))
  3909. (declare-function calendar-goto-date "cal-move" (date))
  3910. (declare-function calendar-goto-today "cal-move" ())
  3911. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3912. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3913. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3914. (declare-function cdlatex-tab "ext:cdlatex" ())
  3915. (declare-function dired-get-filename
  3916. "dired"
  3917. (&optional localp no-error-if-not-filep))
  3918. (declare-function iswitchb-read-buffer
  3919. "iswitchb"
  3920. (prompt &optional
  3921. default require-match _predicate start matches-set))
  3922. (declare-function org-agenda-change-all-lines
  3923. "org-agenda"
  3924. (newhead hdmarker &optional fixface just-this))
  3925. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3926. "org-agenda"
  3927. (&optional end))
  3928. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3929. (declare-function org-agenda-format-item
  3930. "org-agenda"
  3931. (extra txt &optional level category tags dotime
  3932. remove-re habitp))
  3933. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3934. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3935. (declare-function org-agenda-save-markers-for-cut-and-paste
  3936. "org-agenda"
  3937. (beg end))
  3938. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3939. (declare-function org-agenda-skip "org-agenda" ())
  3940. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3941. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3942. (declare-function org-indent-mode "org-indent" (&optional arg))
  3943. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3944. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3945. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3946. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3947. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3948. (declare-function parse-time-string "parse-time" (string))
  3949. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3950. (defvar align-mode-rules-list)
  3951. (defvar calc-embedded-close-formula)
  3952. (defvar calc-embedded-open-formula)
  3953. (defvar calc-embedded-open-mode)
  3954. (defvar font-lock-unfontify-region-function)
  3955. (defvar iswitchb-temp-buflist)
  3956. (defvar org-agenda-tags-todo-honor-ignore-options)
  3957. (defvar remember-data-file)
  3958. (defvar texmathp-why)
  3959. ;;;###autoload
  3960. (defun turn-on-orgtbl ()
  3961. "Unconditionally turn on `orgtbl-mode'."
  3962. (require 'org-table)
  3963. (orgtbl-mode 1))
  3964. (defun org-at-table-p (&optional table-type)
  3965. "Non-nil if the cursor is inside an Org table.
  3966. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3967. If `org-enable-table-editor' is nil, return nil unconditionally."
  3968. (and
  3969. org-enable-table-editor
  3970. (save-excursion
  3971. (beginning-of-line)
  3972. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3973. (or (not (derived-mode-p 'org-mode))
  3974. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3975. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3976. (defun org-at-table.el-p ()
  3977. "Non-nil when point is at a table.el table."
  3978. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3979. (let ((element (org-element-at-point)))
  3980. (and (eq (org-element-type element) 'table)
  3981. (eq (org-element-property :type element) 'table.el)))))
  3982. (defun org-at-table-hline-p ()
  3983. "Non-nil when point is inside a hline in a table.
  3984. Assume point is already in a table. If `org-enable-table-editor'
  3985. is nil, return nil unconditionally."
  3986. (and org-enable-table-editor
  3987. (save-excursion
  3988. (beginning-of-line)
  3989. (looking-at org-table-hline-regexp))))
  3990. (defun org-table-map-tables (function &optional quietly)
  3991. "Apply FUNCTION to the start of all tables in the buffer."
  3992. (org-with-wide-buffer
  3993. (goto-char (point-min))
  3994. (while (re-search-forward org-table-any-line-regexp nil t)
  3995. (unless quietly
  3996. (message "Mapping tables: %d%%"
  3997. (floor (* 100.0 (point)) (buffer-size))))
  3998. (beginning-of-line 1)
  3999. (when (and (looking-at org-table-line-regexp)
  4000. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4001. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4002. (save-excursion (funcall function))
  4003. (or (looking-at org-table-line-regexp)
  4004. (forward-char 1)))
  4005. (re-search-forward org-table-any-border-regexp nil 1)))
  4006. (unless quietly (message "Mapping tables: done")))
  4007. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4008. (declare-function org-clock-update-mode-line "org-clock" ())
  4009. (declare-function org-resolve-clocks "org-clock"
  4010. (&optional also-non-dangling-p prompt last-valid))
  4011. (defun org-at-TBLFM-p (&optional pos)
  4012. "Non-nil when point (or POS) is in #+TBLFM line."
  4013. (save-excursion
  4014. (goto-char (or pos (point)))
  4015. (beginning-of-line)
  4016. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4017. (eq (org-element-type (org-element-at-point)) 'table))))
  4018. (defvar org-clock-start-time)
  4019. (defvar org-clock-marker (make-marker)
  4020. "Marker recording the last clock-in.")
  4021. (defvar org-clock-hd-marker (make-marker)
  4022. "Marker recording the last clock-in, but the headline position.")
  4023. (defvar org-clock-heading ""
  4024. "The heading of the current clock entry.")
  4025. (defun org-clock-is-active ()
  4026. "Return the buffer where the clock is currently running.
  4027. Return nil if no clock is running."
  4028. (marker-buffer org-clock-marker))
  4029. (defun org-check-running-clock ()
  4030. "Check if the current buffer contains the running clock.
  4031. If yes, offer to stop it and to save the buffer with the changes."
  4032. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4033. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4034. (buffer-name))))
  4035. (org-clock-out)
  4036. (when (y-or-n-p "Save changed buffer?")
  4037. (save-buffer))))
  4038. (defun org-clocktable-try-shift (dir n)
  4039. "Check if this line starts a clock table, if yes, shift the time block."
  4040. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4041. (org-clocktable-shift dir n)))
  4042. ;;;###autoload
  4043. (defun org-clock-persistence-insinuate ()
  4044. "Set up hooks for clock persistence."
  4045. (require 'org-clock)
  4046. (add-hook 'org-mode-hook 'org-clock-load)
  4047. (add-hook 'kill-emacs-hook 'org-clock-save))
  4048. (defgroup org-archive nil
  4049. "Options concerning archiving in Org mode."
  4050. :tag "Org Archive"
  4051. :group 'org-structure)
  4052. (defcustom org-archive-location "%s_archive::"
  4053. "The location where subtrees should be archived.
  4054. The value of this variable is a string, consisting of two parts,
  4055. separated by a double-colon. The first part is a filename and
  4056. the second part is a headline.
  4057. When the filename is omitted, archiving happens in the same file.
  4058. %s in the filename will be replaced by the current file
  4059. name (without the directory part). Archiving to a different file
  4060. is useful to keep archived entries from contributing to the
  4061. Org Agenda.
  4062. The archived entries will be filed as subtrees of the specified
  4063. headline. When the headline is omitted, the subtrees are simply
  4064. filed away at the end of the file, as top-level entries. Also in
  4065. the heading you can use %s to represent the file name, this can be
  4066. useful when using the same archive for a number of different files.
  4067. Here are a few examples:
  4068. \"%s_archive::\"
  4069. If the current file is Projects.org, archive in file
  4070. Projects.org_archive, as top-level trees. This is the default.
  4071. \"::* Archived Tasks\"
  4072. Archive in the current file, under the top-level headline
  4073. \"* Archived Tasks\".
  4074. \"~/org/archive.org::\"
  4075. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4076. \"~/org/archive.org::* From %s\"
  4077. Archive in file ~/org/archive.org (absolute path), under headlines
  4078. \"From FILENAME\" where file name is the current file name.
  4079. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4080. The \"datetree/\" string is special, signifying to archive
  4081. items to the datetree. Items are placed in either the CLOSED
  4082. date of the item, or the current date if there is no CLOSED date.
  4083. The heading will be a subentry to the current date. There doesn't
  4084. need to be a heading, but there always needs to be a slash after
  4085. datetree. For example, to store archived items directly in the
  4086. datetree, use \"~/org/datetree.org::datetree/\".
  4087. \"basement::** Finished Tasks\"
  4088. Archive in file ./basement (relative path), as level 3 trees
  4089. below the level 2 heading \"** Finished Tasks\".
  4090. You may set this option on a per-file basis by adding to the buffer a
  4091. line like
  4092. #+ARCHIVE: basement::** Finished Tasks
  4093. You may also define it locally for a subtree by setting an ARCHIVE property
  4094. in the entry. If such a property is found in an entry, or anywhere up
  4095. the hierarchy, it will be used."
  4096. :group 'org-archive
  4097. :type 'string)
  4098. (defcustom org-agenda-skip-archived-trees t
  4099. "Non-nil means the agenda will skip any items located in archived trees.
  4100. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4101. variable is no longer recommended, you should leave it at the value t.
  4102. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4103. :group 'org-archive
  4104. :group 'org-agenda-skip
  4105. :type 'boolean)
  4106. (defcustom org-columns-skip-archived-trees t
  4107. "Non-nil means ignore archived trees when creating column view."
  4108. :group 'org-archive
  4109. :group 'org-properties
  4110. :type 'boolean)
  4111. (defcustom org-cycle-open-archived-trees nil
  4112. "Non-nil means `org-cycle' will open archived trees.
  4113. An archived tree is a tree marked with the tag ARCHIVE.
  4114. When nil, archived trees will stay folded. You can still open them with
  4115. normal outline commands like `show-all', but not with the cycling commands."
  4116. :group 'org-archive
  4117. :group 'org-cycle
  4118. :type 'boolean)
  4119. (defcustom org-sparse-tree-open-archived-trees nil
  4120. "Non-nil means sparse tree construction shows matches in archived trees.
  4121. When nil, matches in these trees are highlighted, but the trees are kept in
  4122. collapsed state."
  4123. :group 'org-archive
  4124. :group 'org-sparse-trees
  4125. :type 'boolean)
  4126. (defcustom org-sparse-tree-default-date-type nil
  4127. "The default date type when building a sparse tree.
  4128. When this is nil, a date is a scheduled or a deadline timestamp.
  4129. Otherwise, these types are allowed:
  4130. all: all timestamps
  4131. active: only active timestamps (<...>)
  4132. inactive: only inactive timestamps ([...])
  4133. scheduled: only scheduled timestamps
  4134. deadline: only deadline timestamps"
  4135. :type '(choice (const :tag "Scheduled or deadline" nil)
  4136. (const :tag "All timestamps" all)
  4137. (const :tag "Only active timestamps" active)
  4138. (const :tag "Only inactive timestamps" inactive)
  4139. (const :tag "Only scheduled timestamps" scheduled)
  4140. (const :tag "Only deadline timestamps" deadline)
  4141. (const :tag "Only closed timestamps" closed))
  4142. :version "25.2"
  4143. :package-version '(Org . "8.3")
  4144. :group 'org-sparse-trees)
  4145. (defun org-cycle-hide-archived-subtrees (state)
  4146. "Re-hide all archived subtrees after a visibility state change."
  4147. (when (and (not org-cycle-open-archived-trees)
  4148. (not (memq state '(overview folded))))
  4149. (save-excursion
  4150. (let* ((globalp (memq state '(contents all)))
  4151. (beg (if globalp (point-min) (point)))
  4152. (end (if globalp (point-max) (org-end-of-subtree t))))
  4153. (org-hide-archived-subtrees beg end)
  4154. (goto-char beg)
  4155. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4156. (message "%s" (substitute-command-keys
  4157. "Subtree is archived and stays closed. Use \
  4158. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4159. (defun org-force-cycle-archived ()
  4160. "Cycle subtree even if it is archived."
  4161. (interactive)
  4162. (setq this-command 'org-cycle)
  4163. (let ((org-cycle-open-archived-trees t))
  4164. (call-interactively 'org-cycle)))
  4165. (defun org-hide-archived-subtrees (beg end)
  4166. "Re-hide all archived subtrees after a visibility state change."
  4167. (org-with-wide-buffer
  4168. (let ((case-fold-search nil)
  4169. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4170. (goto-char beg)
  4171. ;; Include headline point is currently on.
  4172. (beginning-of-line)
  4173. (while (and (< (point) end) (re-search-forward re end t))
  4174. (when (member org-archive-tag (org-get-tags))
  4175. (org-flag-subtree t)
  4176. (org-end-of-subtree t))))))
  4177. (declare-function outline-end-of-heading "outline" ())
  4178. (declare-function outline-flag-region "outline" (from to flag))
  4179. (defun org-flag-subtree (flag)
  4180. (save-excursion
  4181. (org-back-to-heading t)
  4182. (outline-end-of-heading)
  4183. (outline-flag-region (point)
  4184. (progn (org-end-of-subtree t) (point))
  4185. flag)))
  4186. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4187. ;; Declare Column View Code
  4188. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4189. (declare-function org-columns-compute "org-colview" (property))
  4190. ;; Declare ID code
  4191. (declare-function org-id-store-link "org-id")
  4192. (declare-function org-id-locations-load "org-id")
  4193. (declare-function org-id-locations-save "org-id")
  4194. (defvar org-id-track-globally)
  4195. ;;; Variables for pre-computed regular expressions, all buffer local
  4196. (defvar-local org-todo-regexp nil
  4197. "Matches any of the TODO state keywords.
  4198. Since TODO keywords are case-sensitive, `case-fold-search' is
  4199. expected to be bound to nil when matching against this regexp.")
  4200. (defvar-local org-not-done-regexp nil
  4201. "Matches any of the TODO state keywords except the last one.
  4202. Since TODO keywords are case-sensitive, `case-fold-search' is
  4203. expected to be bound to nil when matching against this regexp.")
  4204. (defvar-local org-not-done-heading-regexp nil
  4205. "Matches a TODO headline that is not done.
  4206. Since TODO keywords are case-sensitive, `case-fold-search' is
  4207. expected to be bound to nil when matching against this regexp.")
  4208. (defvar-local org-todo-line-regexp nil
  4209. "Matches a headline and puts TODO state into group 2 if present.
  4210. Since TODO keywords are case-sensitive, `case-fold-search' is
  4211. expected to be bound to nil when matching against this regexp.")
  4212. (defvar-local org-complex-heading-regexp nil
  4213. "Matches a headline and puts everything into groups:
  4214. group 1: Stars
  4215. group 2: The TODO keyword, maybe
  4216. group 3: Priority cookie
  4217. group 4: True headline
  4218. group 5: Tags
  4219. Since TODO keywords are case-sensitive, `case-fold-search' is
  4220. expected to be bound to nil when matching against this regexp.")
  4221. (defvar-local org-complex-heading-regexp-format nil
  4222. "Printf format to make regexp to match an exact headline.
  4223. This regexp will match the headline of any node which has the
  4224. exact headline text that is put into the format, but may have any
  4225. TODO state, priority and tags.")
  4226. (defvar-local org-todo-line-tags-regexp nil
  4227. "Matches a headline and puts TODO state into group 2 if present.
  4228. Also put tags into group 4 if tags are present.")
  4229. (defconst org-plain-time-of-day-regexp
  4230. (concat
  4231. "\\(\\<[012]?[0-9]"
  4232. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4233. "\\(--?"
  4234. "\\(\\<[012]?[0-9]"
  4235. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4236. "\\)?")
  4237. "Regular expression to match a plain time or time range.
  4238. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4239. groups carry important information:
  4240. 0 the full match
  4241. 1 the first time, range or not
  4242. 8 the second time, if it is a range.")
  4243. (defconst org-plain-time-extension-regexp
  4244. (concat
  4245. "\\(\\<[012]?[0-9]"
  4246. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4247. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4248. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4249. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4250. groups carry important information:
  4251. 0 the full match
  4252. 7 hours of duration
  4253. 9 minutes of duration")
  4254. (defconst org-stamp-time-of-day-regexp
  4255. (concat
  4256. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4257. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4258. "\\(--?"
  4259. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4260. "Regular expression to match a timestamp time or time range.
  4261. After a match, the following groups carry important information:
  4262. 0 the full match
  4263. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4264. 2 the first time, range or not
  4265. 4 the second time, if it is a range.")
  4266. (defconst org-startup-options
  4267. '(("fold" org-startup-folded t)
  4268. ("overview" org-startup-folded t)
  4269. ("nofold" org-startup-folded nil)
  4270. ("showall" org-startup-folded nil)
  4271. ("showeverything" org-startup-folded showeverything)
  4272. ("content" org-startup-folded content)
  4273. ("indent" org-startup-indented t)
  4274. ("noindent" org-startup-indented nil)
  4275. ("hidestars" org-hide-leading-stars t)
  4276. ("showstars" org-hide-leading-stars nil)
  4277. ("odd" org-odd-levels-only t)
  4278. ("oddeven" org-odd-levels-only nil)
  4279. ("align" org-startup-align-all-tables t)
  4280. ("noalign" org-startup-align-all-tables nil)
  4281. ("inlineimages" org-startup-with-inline-images t)
  4282. ("noinlineimages" org-startup-with-inline-images nil)
  4283. ("latexpreview" org-startup-with-latex-preview t)
  4284. ("nolatexpreview" org-startup-with-latex-preview nil)
  4285. ("customtime" org-display-custom-times t)
  4286. ("logdone" org-log-done time)
  4287. ("lognotedone" org-log-done note)
  4288. ("nologdone" org-log-done nil)
  4289. ("lognoteclock-out" org-log-note-clock-out t)
  4290. ("nolognoteclock-out" org-log-note-clock-out nil)
  4291. ("logrepeat" org-log-repeat state)
  4292. ("lognoterepeat" org-log-repeat note)
  4293. ("logdrawer" org-log-into-drawer t)
  4294. ("nologdrawer" org-log-into-drawer nil)
  4295. ("logstatesreversed" org-log-states-order-reversed t)
  4296. ("nologstatesreversed" org-log-states-order-reversed nil)
  4297. ("nologrepeat" org-log-repeat nil)
  4298. ("logreschedule" org-log-reschedule time)
  4299. ("lognotereschedule" org-log-reschedule note)
  4300. ("nologreschedule" org-log-reschedule nil)
  4301. ("logredeadline" org-log-redeadline time)
  4302. ("lognoteredeadline" org-log-redeadline note)
  4303. ("nologredeadline" org-log-redeadline nil)
  4304. ("logrefile" org-log-refile time)
  4305. ("lognoterefile" org-log-refile note)
  4306. ("nologrefile" org-log-refile nil)
  4307. ("fninline" org-footnote-define-inline t)
  4308. ("nofninline" org-footnote-define-inline nil)
  4309. ("fnlocal" org-footnote-section nil)
  4310. ("fnauto" org-footnote-auto-label t)
  4311. ("fnprompt" org-footnote-auto-label nil)
  4312. ("fnconfirm" org-footnote-auto-label confirm)
  4313. ("fnplain" org-footnote-auto-label plain)
  4314. ("fnadjust" org-footnote-auto-adjust t)
  4315. ("nofnadjust" org-footnote-auto-adjust nil)
  4316. ("constcgs" constants-unit-system cgs)
  4317. ("constSI" constants-unit-system SI)
  4318. ("noptag" org-tag-persistent-alist nil)
  4319. ("hideblocks" org-hide-block-startup t)
  4320. ("nohideblocks" org-hide-block-startup nil)
  4321. ("beamer" org-startup-with-beamer-mode t)
  4322. ("entitiespretty" org-pretty-entities t)
  4323. ("entitiesplain" org-pretty-entities nil))
  4324. "Variable associated with STARTUP options for org-mode.
  4325. Each element is a list of three items: the startup options (as written
  4326. in the #+STARTUP line), the corresponding variable, and the value to set
  4327. this variable to if the option is found. An optional forth element PUSH
  4328. means to push this value onto the list in the variable.")
  4329. (defcustom org-group-tags t
  4330. "When non-nil (the default), use group tags.
  4331. This can be turned on/off through `org-toggle-tags-groups'."
  4332. :group 'org-tags
  4333. :group 'org-startup
  4334. :type 'boolean)
  4335. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4336. (defun org-toggle-tags-groups ()
  4337. "Toggle support for group tags.
  4338. Support for group tags is controlled by the option
  4339. `org-group-tags', which is non-nil by default."
  4340. (interactive)
  4341. (setq org-group-tags (not org-group-tags))
  4342. (cond ((and (derived-mode-p 'org-agenda-mode)
  4343. org-group-tags)
  4344. (org-agenda-redo))
  4345. ((derived-mode-p 'org-mode)
  4346. (let ((org-inhibit-startup t)) (org-mode))))
  4347. (message "Groups tags support has been turned %s"
  4348. (if org-group-tags "on" "off")))
  4349. (defun org-set-regexps-and-options (&optional tags-only)
  4350. "Precompute regular expressions used in the current buffer.
  4351. When optional argument TAGS-ONLY is non-nil, only compute tags
  4352. related expressions."
  4353. (when (derived-mode-p 'org-mode)
  4354. (let ((alist (org--setup-collect-keywords
  4355. (org-make-options-regexp
  4356. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4357. (and (not tags-only)
  4358. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4359. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4360. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4361. ;; Startup options. Get this early since it does change
  4362. ;; behavior for other options (e.g., tags).
  4363. (let ((startup (cdr (assq 'startup alist))))
  4364. (dolist (option startup)
  4365. (let ((entry (assoc-string option org-startup-options t)))
  4366. (when entry
  4367. (let ((var (nth 1 entry))
  4368. (val (nth 2 entry)))
  4369. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4370. (unless (listp (symbol-value var))
  4371. (set (make-local-variable var) nil))
  4372. (add-to-list var val)))))))
  4373. (setq-local org-file-tags
  4374. (mapcar #'org-add-prop-inherited
  4375. (cdr (assq 'filetags alist))))
  4376. (setq org-current-tag-alist
  4377. (append org-tag-persistent-alist
  4378. (let ((tags (cdr (assq 'tags alist))))
  4379. (if tags (org-tag-string-to-alist tags)
  4380. org-tag-alist))))
  4381. (setq org-tag-groups-alist
  4382. (org-tag-alist-to-groups org-current-tag-alist))
  4383. (unless tags-only
  4384. ;; File properties.
  4385. (setq-local org-file-properties (cdr (assq 'property alist)))
  4386. ;; Archive location.
  4387. (let ((archive (cdr (assq 'archive alist))))
  4388. (when archive (setq-local org-archive-location archive)))
  4389. ;; Category.
  4390. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4391. (when cat
  4392. (setq-local org-category (intern cat))
  4393. (setq-local org-file-properties
  4394. (org--update-property-plist
  4395. "CATEGORY" cat org-file-properties))))
  4396. ;; Columns.
  4397. (let ((column (cdr (assq 'columns alist))))
  4398. (when column (setq-local org-columns-default-format column)))
  4399. ;; Constants.
  4400. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4401. ;; Link abbreviations.
  4402. (let ((links (cdr (assq 'link alist))))
  4403. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4404. ;; Priorities.
  4405. (let ((priorities (cdr (assq 'priorities alist))))
  4406. (when priorities
  4407. (setq-local org-highest-priority (nth 0 priorities))
  4408. (setq-local org-lowest-priority (nth 1 priorities))
  4409. (setq-local org-default-priority (nth 2 priorities))))
  4410. ;; Scripts.
  4411. (let ((scripts (assq 'scripts alist)))
  4412. (when scripts
  4413. (setq-local org-use-sub-superscripts (cdr scripts))))
  4414. ;; TODO keywords.
  4415. (setq-local org-todo-kwd-alist nil)
  4416. (setq-local org-todo-key-alist nil)
  4417. (setq-local org-todo-key-trigger nil)
  4418. (setq-local org-todo-keywords-1 nil)
  4419. (setq-local org-done-keywords nil)
  4420. (setq-local org-todo-heads nil)
  4421. (setq-local org-todo-sets nil)
  4422. (setq-local org-todo-log-states nil)
  4423. (let ((todo-sequences
  4424. (or (nreverse (cdr (assq 'todo alist)))
  4425. (let ((d (default-value 'org-todo-keywords)))
  4426. (if (not (stringp (car d))) d
  4427. ;; XXX: Backward compatibility code.
  4428. (list (cons org-todo-interpretation d)))))))
  4429. (dolist (sequence todo-sequences)
  4430. (let* ((sequence (or (run-hook-with-args-until-success
  4431. 'org-todo-setup-filter-hook sequence)
  4432. sequence))
  4433. (sequence-type (car sequence))
  4434. (keywords (cdr sequence))
  4435. (sep (member "|" keywords))
  4436. names alist)
  4437. (dolist (k (remove "|" keywords))
  4438. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4439. k)
  4440. (error "Invalid TODO keyword %s" k))
  4441. (let ((name (match-string 1 k))
  4442. (key (match-string 2 k))
  4443. (log (org-extract-log-state-settings k)))
  4444. (push name names)
  4445. (push (cons name (and key (string-to-char key))) alist)
  4446. (when log (push log org-todo-log-states))))
  4447. (let* ((names (nreverse names))
  4448. (done (if sep (org-remove-keyword-keys (cdr sep))
  4449. (last names)))
  4450. (head (car names))
  4451. (tail (list sequence-type head (car done) (org-last done))))
  4452. (add-to-list 'org-todo-heads head 'append)
  4453. (push names org-todo-sets)
  4454. (setq org-done-keywords (append org-done-keywords done nil))
  4455. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4456. (setq org-todo-key-alist
  4457. (append org-todo-key-alist
  4458. (and alist
  4459. (append '((:startgroup))
  4460. (nreverse alist)
  4461. '((:endgroup))))))
  4462. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4463. (setq org-todo-sets (nreverse org-todo-sets)
  4464. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4465. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4466. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4467. ;; Compute the regular expressions and other local variables.
  4468. ;; Using `org-outline-regexp-bol' would complicate them much,
  4469. ;; because of the fixed white space at the end of that string.
  4470. (unless org-done-keywords
  4471. (setq org-done-keywords
  4472. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4473. (setq org-not-done-keywords
  4474. (org-delete-all org-done-keywords
  4475. (copy-sequence org-todo-keywords-1))
  4476. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4477. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4478. org-not-done-heading-regexp
  4479. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4480. org-todo-line-regexp
  4481. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4482. org-complex-heading-regexp
  4483. (concat "^\\(\\*+\\)"
  4484. "\\(?: +" org-todo-regexp "\\)?"
  4485. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4486. "\\(?: +\\(.*?\\)\\)??"
  4487. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4488. "[ \t]*$")
  4489. org-complex-heading-regexp-format
  4490. (concat "^\\(\\*+\\)"
  4491. "\\(?: +" org-todo-regexp "\\)?"
  4492. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4493. "\\(?: +"
  4494. ;; Stats cookies can be stuck to body.
  4495. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4496. "\\(%s\\)"
  4497. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4498. "\\)"
  4499. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4500. "[ \t]*$")
  4501. org-todo-line-tags-regexp
  4502. (concat "^\\(\\*+\\)"
  4503. "\\(?: +" org-todo-regexp "\\)?"
  4504. "\\(?: +\\(.*?\\)\\)??"
  4505. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4506. "[ \t]*$"))
  4507. (org-compute-latex-and-related-regexp)))))
  4508. (defun org--setup-collect-keywords (regexp &optional files alist)
  4509. "Return setup keywords values as an alist.
  4510. REGEXP matches a subset of setup keywords. FILES is a list of
  4511. file names already visited. It is used to avoid circular setup
  4512. files. ALIST, when non-nil, is the alist computed so far.
  4513. Return value contains the following keys: `archive', `category',
  4514. `columns', `constants', `filetags', `link', `priorities',
  4515. `property', `scripts', `startup', `tags' and `todo'."
  4516. (org-with-wide-buffer
  4517. (goto-char (point-min))
  4518. (let ((case-fold-search t))
  4519. (while (re-search-forward regexp nil t)
  4520. (let ((element (org-element-at-point)))
  4521. (when (eq (org-element-type element) 'keyword)
  4522. (let ((key (org-element-property :key element))
  4523. (value (org-element-property :value element)))
  4524. (cond
  4525. ((equal key "ARCHIVE")
  4526. (when (org-string-nw-p value)
  4527. (push (cons 'archive value) alist)))
  4528. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4529. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4530. ((equal key "CONSTANTS")
  4531. (let* ((constants (assq 'constants alist))
  4532. (store (cdr constants)))
  4533. (dolist (pair (org-split-string value))
  4534. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4535. pair)
  4536. (let* ((name (match-string 1 pair))
  4537. (value (match-string 2 pair))
  4538. (old (assoc name store)))
  4539. (if old (setcdr old value)
  4540. (push (cons name value) store)))))
  4541. (if constants (setcdr constants store)
  4542. (push (cons 'constants store) alist))))
  4543. ((equal key "FILETAGS")
  4544. (when (org-string-nw-p value)
  4545. (let ((old (assq 'filetags alist))
  4546. (new (apply #'nconc
  4547. (mapcar (lambda (x) (org-split-string x ":"))
  4548. (org-split-string value)))))
  4549. (if old (setcdr old (append new (cdr old)))
  4550. (push (cons 'filetags new) alist)))))
  4551. ((equal key "LINK")
  4552. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4553. (let ((links (assq 'link alist))
  4554. (pair (cons (match-string-no-properties 1 value)
  4555. (match-string-no-properties 2 value))))
  4556. (if links (push pair (cdr links))
  4557. (push (list 'link pair) alist)))))
  4558. ((equal key "OPTIONS")
  4559. (when (and (org-string-nw-p value)
  4560. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4561. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4562. ((equal key "PRIORITIES")
  4563. (push (cons 'priorities
  4564. (let ((prio (org-split-string value)))
  4565. (if (< (length prio) 3) '(?A ?C ?B)
  4566. (mapcar #'string-to-char prio))))
  4567. alist))
  4568. ((equal key "PROPERTY")
  4569. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4570. (let* ((property (assq 'property alist))
  4571. (value (org--update-property-plist
  4572. (match-string-no-properties 1 value)
  4573. (match-string-no-properties 2 value)
  4574. (cdr property))))
  4575. (if property (setcdr property value)
  4576. (push (cons 'property value) alist)))))
  4577. ((equal key "STARTUP")
  4578. (let ((startup (assq 'startup alist)))
  4579. (if startup
  4580. (setcdr startup
  4581. (append (cdr startup) (org-split-string value)))
  4582. (push (cons 'startup (org-split-string value)) alist))))
  4583. ((equal key "TAGS")
  4584. (let ((tag-cell (assq 'tags alist)))
  4585. (if tag-cell
  4586. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4587. (push (cons 'tags value) alist))))
  4588. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4589. (let ((todo (assq 'todo alist))
  4590. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4591. (org-split-string value))))
  4592. (if todo (push value (cdr todo))
  4593. (push (list 'todo value) alist))))
  4594. ((equal key "SETUPFILE")
  4595. (unless buffer-read-only ; Do not check in Gnus messages.
  4596. (let ((f (and (org-string-nw-p value)
  4597. (expand-file-name
  4598. (org-unbracket-string "\"" "\"" value)))))
  4599. (when (and f (file-readable-p f) (not (member f files)))
  4600. (with-temp-buffer
  4601. (setq default-directory (file-name-directory f))
  4602. (insert-file-contents f)
  4603. (setq alist
  4604. ;; Fake Org mode to benefit from cache
  4605. ;; without recurring needlessly.
  4606. (let ((major-mode 'org-mode))
  4607. (org--setup-collect-keywords
  4608. regexp (cons f files) alist)))))))))))))))
  4609. alist)
  4610. (defun org-tag-string-to-alist (s)
  4611. "Return tag alist associated to string S.
  4612. S is a value for TAGS keyword or produced with
  4613. `org-tag-alist-to-string'. Return value is an alist suitable for
  4614. `org-tag-alist' or `org-tag-persistent-alist'."
  4615. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4616. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4617. "\\|{.+?}\\)" ; regular expression
  4618. "\\(?:(\\(.\\))\\)?\\'"))
  4619. alist group-flag)
  4620. (dolist (tokens lines (cdr (nreverse alist)))
  4621. (push '(:newline) alist)
  4622. (while tokens
  4623. (let ((token (pop tokens)))
  4624. (pcase token
  4625. ("{"
  4626. (push '(:startgroup) alist)
  4627. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4628. ("}"
  4629. (push '(:endgroup) alist)
  4630. (setq group-flag nil))
  4631. ("["
  4632. (push '(:startgrouptag) alist)
  4633. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4634. ("]"
  4635. (push '(:endgrouptag) alist)
  4636. (setq group-flag nil))
  4637. (":"
  4638. (push '(:grouptags) alist))
  4639. ((guard (string-match tag-re token))
  4640. (let ((tag (match-string 1 token))
  4641. (key (and (match-beginning 2)
  4642. (string-to-char (match-string 2 token)))))
  4643. ;; Push all tags in groups, no matter if they already
  4644. ;; appear somewhere else in the list.
  4645. (when (or group-flag (not (assoc tag alist)))
  4646. (push (cons tag key) alist))))))))))
  4647. (defun org-tag-alist-to-string (alist &optional skip-key)
  4648. "Return tag string associated to ALIST.
  4649. ALIST is an alist, as defined in `org-tag-alist' or
  4650. `org-tag-persistent-alist', or produced with
  4651. `org-tag-string-to-alist'.
  4652. Return value is a string suitable as a value for \"TAGS\"
  4653. keyword.
  4654. When optional argument SKIP-KEY is non-nil, skip selection keys
  4655. next to tags."
  4656. (mapconcat (lambda (token)
  4657. (pcase token
  4658. (`(:startgroup) "{")
  4659. (`(:endgroup) "}")
  4660. (`(:startgrouptag) "[")
  4661. (`(:endgrouptag) "]")
  4662. (`(:grouptags) ":")
  4663. (`(:newline) "\\n")
  4664. ((and
  4665. (guard (not skip-key))
  4666. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4667. (format "%s(%c)" tag key))
  4668. (`(,(and tag (pred stringp)) . ,_) tag)
  4669. (_ (user-error "Invalid tag token: %S" token))))
  4670. alist
  4671. " "))
  4672. (defun org-tag-alist-to-groups (alist)
  4673. "Return group alist from tag ALIST.
  4674. ALIST is an alist, as defined in `org-tag-alist' or
  4675. `org-tag-persistent-alist', or produced with
  4676. `org-tag-string-to-alist'. Return value is an alist following
  4677. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4678. a string, summarizing TAGS, as a list of strings."
  4679. (let (groups group-status current-group)
  4680. (dolist (token alist (nreverse groups))
  4681. (pcase token
  4682. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4683. (`(,(or :endgroup :endgrouptag))
  4684. (when (eq group-status 'append)
  4685. (push (nreverse current-group) groups))
  4686. (setq group-status nil))
  4687. (`(:grouptags) (setq group-status 'append))
  4688. ((and `(,tag . ,_) (guard group-status))
  4689. (if (eq group-status 'append) (push tag current-group)
  4690. (setq current-group (list tag))))
  4691. (_ nil)))))
  4692. (defun org-file-contents (file &optional noerror)
  4693. "Return the contents of FILE, as a string."
  4694. (if (and file (file-readable-p file))
  4695. (with-temp-buffer
  4696. (insert-file-contents file)
  4697. (buffer-string))
  4698. (funcall (if noerror 'message 'error)
  4699. "Cannot read file \"%s\"%s"
  4700. file
  4701. (let ((from (buffer-file-name (buffer-base-buffer))))
  4702. (if from (concat " (referenced in file \"" from "\")") "")))))
  4703. (defun org-extract-log-state-settings (x)
  4704. "Extract the log state setting from a TODO keyword string.
  4705. This will extract info from a string like \"WAIT(w@/!)\"."
  4706. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4707. (let ((kw (match-string 1 x))
  4708. (log1 (and (match-end 3) (match-string 3 x)))
  4709. (log2 (and (match-end 4) (match-string 4 x))))
  4710. (and (or log1 log2)
  4711. (list kw
  4712. (and log1 (if (equal log1 "!") 'time 'note))
  4713. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4714. (defun org-remove-keyword-keys (list)
  4715. "Remove a pair of parenthesis at the end of each string in LIST."
  4716. (mapcar (lambda (x)
  4717. (if (string-match "(.*)$" x)
  4718. (substring x 0 (match-beginning 0))
  4719. x))
  4720. list))
  4721. (defun org-assign-fast-keys (alist)
  4722. "Assign fast keys to a keyword-key alist.
  4723. Respect keys that are already there."
  4724. (let (new e (alt ?0))
  4725. (while (setq e (pop alist))
  4726. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4727. (cdr e)) ;; Key already assigned.
  4728. (push e new)
  4729. (let ((clist (string-to-list (downcase (car e))))
  4730. (used (append new alist)))
  4731. (when (= (car clist) ?@)
  4732. (pop clist))
  4733. (while (and clist (rassoc (car clist) used))
  4734. (pop clist))
  4735. (unless clist
  4736. (while (rassoc alt used)
  4737. (cl-incf alt)))
  4738. (push (cons (car e) (or (car clist) alt)) new))))
  4739. (nreverse new)))
  4740. ;;; Some variables used in various places
  4741. (defvar org-window-configuration nil
  4742. "Used in various places to store a window configuration.")
  4743. (defvar org-selected-window nil
  4744. "Used in various places to store a window configuration.")
  4745. (defvar org-finish-function nil
  4746. "Function to be called when `C-c C-c' is used.
  4747. This is for getting out of special buffers like capture.")
  4748. (defvar org-last-state)
  4749. ;; Defined somewhere in this file, but used before definition.
  4750. (defvar org-entities) ;; defined in org-entities.el
  4751. (defvar org-struct-menu)
  4752. (defvar org-org-menu)
  4753. (defvar org-tbl-menu)
  4754. ;;;; Define the Org mode
  4755. ;; We use a before-change function to check if a table might need
  4756. ;; an update.
  4757. (defvar org-table-may-need-update t
  4758. "Indicates that a table might need an update.
  4759. This variable is set by `org-before-change-function'.
  4760. `org-table-align' sets it back to nil.")
  4761. (defun org-before-change-function (_beg _end)
  4762. "Every change indicates that a table might need an update."
  4763. (setq org-table-may-need-update t))
  4764. (defvar org-mode-map)
  4765. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4766. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4767. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4768. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4769. (defvar org-table-buffer-is-an nil)
  4770. (defvar bidi-paragraph-direction)
  4771. (defvar buffer-face-mode-face)
  4772. (require 'outline)
  4773. ;; Other stuff we need.
  4774. (require 'time-date)
  4775. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4776. (require 'easymenu)
  4777. (autoload 'easy-menu-add "easymenu")
  4778. (require 'overlay)
  4779. ;; (require 'org-macs) moved higher up in the file before it is first used
  4780. (require 'org-entities)
  4781. ;; (require 'org-compat) moved higher up in the file before it is first used
  4782. (require 'org-faces)
  4783. (require 'org-list)
  4784. (require 'org-pcomplete)
  4785. (require 'org-src)
  4786. (require 'org-footnote)
  4787. (require 'org-macro)
  4788. ;; babel
  4789. (require 'ob)
  4790. ;;;###autoload
  4791. (define-derived-mode org-mode outline-mode "Org"
  4792. "Outline-based notes management and organizer, alias
  4793. \"Carsten's outline-mode for keeping track of everything.\"
  4794. Org mode develops organizational tasks around a NOTES file which
  4795. contains information about projects as plain text. Org mode is
  4796. implemented on top of Outline mode, which is ideal to keep the content
  4797. of large files well structured. It supports ToDo items, deadlines and
  4798. time stamps, which magically appear in the diary listing of the Emacs
  4799. calendar. Tables are easily created with a built-in table editor.
  4800. Plain text URL-like links connect to websites, emails (VM), Usenet
  4801. messages (Gnus), BBDB entries, and any files related to the project.
  4802. For printing and sharing of notes, an Org file (or a part of it)
  4803. can be exported as a structured ASCII or HTML file.
  4804. The following commands are available:
  4805. \\{org-mode-map}"
  4806. ;; Get rid of Outline menus, they are not needed
  4807. ;; Need to do this here because define-derived-mode sets up
  4808. ;; the keymap so late. Still, it is a waste to call this each time
  4809. ;; we switch another buffer into Org mode.
  4810. (define-key org-mode-map [menu-bar headings] 'undefined)
  4811. (define-key org-mode-map [menu-bar hide] 'undefined)
  4812. (define-key org-mode-map [menu-bar show] 'undefined)
  4813. (org-load-modules-maybe)
  4814. (org-install-agenda-files-menu)
  4815. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4816. (add-to-invisibility-spec '(org-cwidth))
  4817. (add-to-invisibility-spec '(org-hide-block . t))
  4818. (setq-local outline-regexp org-outline-regexp)
  4819. (setq-local outline-level 'org-outline-level)
  4820. (setq bidi-paragraph-direction 'left-to-right)
  4821. (when (and org-ellipsis
  4822. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4823. (fboundp 'make-glyph-code))
  4824. (unless org-display-table
  4825. (setq org-display-table (make-display-table)))
  4826. (set-display-table-slot
  4827. org-display-table 4
  4828. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4829. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4830. (setq buffer-display-table org-display-table))
  4831. (org-set-regexps-and-options)
  4832. (org-set-font-lock-defaults)
  4833. (when (and org-tag-faces (not org-tags-special-faces-re))
  4834. ;; tag faces set outside customize.... force initialization.
  4835. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4836. ;; Calc embedded
  4837. (setq-local calc-embedded-open-mode "# ")
  4838. ;; Modify a few syntax entries
  4839. (modify-syntax-entry ?@ "w")
  4840. (modify-syntax-entry ?\" "\"")
  4841. (modify-syntax-entry ?\\ "_")
  4842. (modify-syntax-entry ?~ "_")
  4843. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4844. ;; Activate before-change-function
  4845. (setq-local org-table-may-need-update t)
  4846. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4847. ;; Check for running clock before killing a buffer
  4848. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4849. ;; Initialize macros templates.
  4850. (org-macro-initialize-templates)
  4851. ;; Initialize radio targets.
  4852. (org-update-radio-target-regexp)
  4853. ;; Indentation.
  4854. (setq-local indent-line-function 'org-indent-line)
  4855. (setq-local indent-region-function 'org-indent-region)
  4856. ;; Filling and auto-filling.
  4857. (org-setup-filling)
  4858. ;; Comments.
  4859. (org-setup-comments-handling)
  4860. ;; Initialize cache.
  4861. (org-element-cache-reset)
  4862. ;; Beginning/end of defun
  4863. (setq-local beginning-of-defun-function 'org-backward-element)
  4864. (setq-local end-of-defun-function
  4865. (lambda ()
  4866. (if (not (org-at-heading-p))
  4867. (org-forward-element)
  4868. (org-forward-element)
  4869. (forward-char -1))))
  4870. ;; Next error for sparse trees
  4871. (setq-local next-error-function 'org-occur-next-match)
  4872. ;; Make sure dependence stuff works reliably, even for users who set it
  4873. ;; too late :-(
  4874. (if org-enforce-todo-dependencies
  4875. (add-hook 'org-blocker-hook
  4876. 'org-block-todo-from-children-or-siblings-or-parent)
  4877. (remove-hook 'org-blocker-hook
  4878. 'org-block-todo-from-children-or-siblings-or-parent))
  4879. (if org-enforce-todo-checkbox-dependencies
  4880. (add-hook 'org-blocker-hook
  4881. 'org-block-todo-from-checkboxes)
  4882. (remove-hook 'org-blocker-hook
  4883. 'org-block-todo-from-checkboxes))
  4884. ;; Align options lines
  4885. (setq-local
  4886. align-mode-rules-list
  4887. '((org-in-buffer-settings
  4888. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4889. (modes . '(org-mode)))))
  4890. ;; Imenu
  4891. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4892. ;; Make isearch reveal context
  4893. (setq-local outline-isearch-open-invisible-function
  4894. (lambda (&rest _) (org-show-context 'isearch)))
  4895. ;; Setup the pcomplete hooks
  4896. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4897. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4898. (setq-local pcomplete-default-completion-function 'ignore)
  4899. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4900. (setq-local pcomplete-termination-string "")
  4901. (setq-local buffer-face-mode-face 'org-default)
  4902. ;; If empty file that did not turn on Org mode automatically, make
  4903. ;; it to.
  4904. (when (and org-insert-mode-line-in-empty-file
  4905. (called-interactively-p 'any)
  4906. (= (point-min) (point-max)))
  4907. (insert "# -*- mode: org -*-\n\n"))
  4908. (unless org-inhibit-startup
  4909. (org-unmodified
  4910. (when org-startup-with-beamer-mode (org-beamer-mode))
  4911. (when org-startup-align-all-tables
  4912. (org-table-map-tables #'org-table-align t))
  4913. (when org-startup-with-inline-images (org-display-inline-images))
  4914. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4915. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4916. (when org-startup-truncated (setq truncate-lines t))
  4917. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4918. (org-refresh-effort-properties)))
  4919. ;; Try to set `org-hide' face correctly.
  4920. (let ((foreground (org-find-invisible-foreground)))
  4921. (when foreground
  4922. (set-face-foreground 'org-hide foreground))))
  4923. ;; Update `customize-package-emacs-version-alist'
  4924. (add-to-list 'customize-package-emacs-version-alist
  4925. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4926. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4927. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4928. ("9.0" . "25.2")))
  4929. (defvar org-mode-transpose-word-syntax-table
  4930. (let ((st (make-syntax-table text-mode-syntax-table)))
  4931. (dolist (c org-emphasis-alist st)
  4932. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4933. (when (fboundp 'abbrev-table-put)
  4934. (abbrev-table-put org-mode-abbrev-table
  4935. :parents (list text-mode-abbrev-table)))
  4936. (defun org-find-invisible-foreground ()
  4937. (let ((candidates (remove
  4938. "unspecified-bg"
  4939. (nconc
  4940. (list (face-background 'default)
  4941. (face-background 'org-default))
  4942. (mapcar
  4943. (lambda (alist)
  4944. (when (boundp alist)
  4945. (cdr (assq 'background-color (symbol-value alist)))))
  4946. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4947. (list (face-foreground 'org-hide))))))
  4948. (car (remove nil candidates))))
  4949. (defun org-current-time (&optional rounding-minutes past)
  4950. "Current time, possibly rounded to ROUNDING-MINUTES.
  4951. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4952. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4953. the rounding returns a past time."
  4954. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4955. (car org-time-stamp-rounding-minutes)))
  4956. (time (decode-time)) res)
  4957. (if (< r 1)
  4958. (current-time)
  4959. (setq res
  4960. (apply 'encode-time
  4961. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4962. (nthcdr 2 time))))
  4963. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4964. (seconds-to-time (- (float-time res) (* r 60)))
  4965. res))))
  4966. (defun org-today ()
  4967. "Return today date, considering `org-extend-today-until'."
  4968. (time-to-days
  4969. (time-subtract (current-time)
  4970. (list 0 (* 3600 org-extend-today-until) 0))))
  4971. ;;;; Font-Lock stuff, including the activators
  4972. (defvar org-mouse-map (make-sparse-keymap))
  4973. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4974. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4975. (when org-mouse-1-follows-link
  4976. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4977. (when org-tab-follows-link
  4978. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4979. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4980. (require 'font-lock)
  4981. (defconst org-non-link-chars "]\t\n\r<>")
  4982. (defvar org-link-types-re nil
  4983. "Matches a link that has a url-like prefix like \"http:\"")
  4984. (defvar org-link-re-with-space nil
  4985. "Matches a link with spaces, optional angular brackets around it.")
  4986. (defvar org-link-re-with-space2 nil
  4987. "Matches a link with spaces, optional angular brackets around it.")
  4988. (defvar org-link-re-with-space3 nil
  4989. "Matches a link with spaces, only for internal part in bracket links.")
  4990. (defvar org-angle-link-re nil
  4991. "Matches link with angular brackets, spaces are allowed.")
  4992. (defvar org-plain-link-re nil
  4993. "Matches plain link, without spaces.")
  4994. (defvar org-bracket-link-regexp nil
  4995. "Matches a link in double brackets.")
  4996. (defvar org-bracket-link-analytic-regexp nil
  4997. "Regular expression used to analyze links.
  4998. Here is what the match groups contain after a match:
  4999. 1: http:
  5000. 2: http
  5001. 3: path
  5002. 4: [desc]
  5003. 5: desc")
  5004. (defvar org-bracket-link-analytic-regexp++ nil
  5005. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5006. (defvar org-any-link-re nil
  5007. "Regular expression matching any link.")
  5008. (defconst org-match-sexp-depth 3
  5009. "Number of stacked braces for sub/superscript matching.")
  5010. (defun org-create-multibrace-regexp (left right n)
  5011. "Create a regular expression which will match a balanced sexp.
  5012. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5013. as single character strings.
  5014. The regexp returned will match the entire expression including the
  5015. delimiters. It will also define a single group which contains the
  5016. match except for the outermost delimiters. The maximum depth of
  5017. stacked delimiters is N. Escaping delimiters is not possible."
  5018. (let* ((nothing (concat "[^" left right "]*?"))
  5019. (or "\\|")
  5020. (re nothing)
  5021. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5022. (while (> n 1)
  5023. (setq n (1- n)
  5024. re (concat re or next)
  5025. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5026. (concat left "\\(" re "\\)" right)))
  5027. (defconst org-match-substring-regexp
  5028. (concat
  5029. "\\(\\S-\\)\\([_^]\\)\\("
  5030. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5031. "\\|"
  5032. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5033. "\\|"
  5034. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5035. "The regular expression matching a sub- or superscript.")
  5036. (defconst org-match-substring-with-braces-regexp
  5037. (concat
  5038. "\\(\\S-\\)\\([_^]\\)"
  5039. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5040. "The regular expression matching a sub- or superscript, forcing braces.")
  5041. (defun org-make-link-regexps ()
  5042. "Update the link regular expressions.
  5043. This should be called after the variable `org-link-parameters' has changed."
  5044. (let ((types-re (regexp-opt (org-link-types) t)))
  5045. (setq org-link-types-re
  5046. (concat "\\`" types-re ":")
  5047. org-link-re-with-space
  5048. (concat "<?" types-re ":"
  5049. "\\([^" org-non-link-chars " ]"
  5050. "[^" org-non-link-chars "]*"
  5051. "[^" org-non-link-chars " ]\\)>?")
  5052. org-link-re-with-space2
  5053. (concat "<?" types-re ":"
  5054. "\\([^" org-non-link-chars " ]"
  5055. "[^\t\n\r]*"
  5056. "[^" org-non-link-chars " ]\\)>?")
  5057. org-link-re-with-space3
  5058. (concat "<?" types-re ":"
  5059. "\\([^" org-non-link-chars " ]"
  5060. "[^\t\n\r]*\\)")
  5061. org-angle-link-re
  5062. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5063. types-re)
  5064. org-plain-link-re
  5065. (concat
  5066. "\\<" types-re ":"
  5067. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5068. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5069. org-bracket-link-regexp
  5070. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5071. org-bracket-link-analytic-regexp
  5072. (concat
  5073. "\\[\\["
  5074. "\\(" types-re ":\\)?"
  5075. "\\([^]]+\\)"
  5076. "\\]"
  5077. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5078. "\\]")
  5079. org-bracket-link-analytic-regexp++
  5080. (concat
  5081. "\\[\\["
  5082. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5083. "\\([^]]+\\)"
  5084. "\\]"
  5085. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5086. "\\]")
  5087. org-any-link-re
  5088. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5089. org-angle-link-re "\\)\\|\\("
  5090. org-plain-link-re "\\)"))))
  5091. (org-make-link-regexps)
  5092. (defvar org-emph-face nil)
  5093. (defun org-do-emphasis-faces (limit)
  5094. "Run through the buffer and emphasize strings."
  5095. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5096. (car org-emphasis-regexp-components))))
  5097. (catch :exit
  5098. (while (re-search-forward quick-re limit t)
  5099. (let* ((marker (match-string 2))
  5100. (verbatim? (member marker '("~" "="))))
  5101. (when (save-excursion
  5102. (goto-char (match-beginning 0))
  5103. ;; Do not match headline stars. Do not consider
  5104. ;; stars of a headline as closing marker for bold
  5105. ;; markup either.
  5106. (and (not (looking-at-p org-outline-regexp-bol))
  5107. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5108. (not (string-match-p
  5109. (concat org-outline-regexp-bol "\\'")
  5110. (match-string 0)))))
  5111. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5112. (font-lock-prepend-text-property
  5113. (match-beginning 2) (match-end 2) 'face face)
  5114. (when verbatim?
  5115. (org-remove-flyspell-overlays-in
  5116. (match-beginning 0) (match-end 0)))
  5117. (add-text-properties (match-beginning 2) (match-end 2)
  5118. '(font-lock-multiline t org-emphasis t))
  5119. (when org-hide-emphasis-markers
  5120. (add-text-properties (match-end 4) (match-beginning 5)
  5121. '(invisible org-link))
  5122. (add-text-properties (match-beginning 3) (match-end 3)
  5123. '(invisible org-link)))
  5124. (throw :exit t))))))))
  5125. (defun org-emphasize (&optional char)
  5126. "Insert or change an emphasis, i.e. a font like bold or italic.
  5127. If there is an active region, change that region to a new emphasis.
  5128. If there is no region, just insert the marker characters and position
  5129. the cursor between them.
  5130. CHAR should be the marker character. If it is a space, it means to
  5131. remove the emphasis of the selected region.
  5132. If CHAR is not given (for example in an interactive call) it will be
  5133. prompted for."
  5134. (interactive)
  5135. (let ((erc org-emphasis-regexp-components)
  5136. (string "") beg end move s)
  5137. (if (org-region-active-p)
  5138. (setq beg (region-beginning)
  5139. end (region-end)
  5140. string (buffer-substring beg end))
  5141. (setq move t))
  5142. (unless char
  5143. (message "Emphasis marker or tag: [%s]"
  5144. (mapconcat #'car org-emphasis-alist ""))
  5145. (setq char (read-char-exclusive)))
  5146. (if (equal char ?\s)
  5147. (setq s ""
  5148. move nil)
  5149. (unless (assoc (char-to-string char) org-emphasis-alist)
  5150. (user-error "No such emphasis marker: \"%c\"" char))
  5151. (setq s (char-to-string char)))
  5152. (while (and (> (length string) 1)
  5153. (equal (substring string 0 1) (substring string -1))
  5154. (assoc (substring string 0 1) org-emphasis-alist))
  5155. (setq string (substring string 1 -1)))
  5156. (setq string (concat s string s))
  5157. (when beg (delete-region beg end))
  5158. (unless (or (bolp)
  5159. (string-match (concat "[" (nth 0 erc) "\n]")
  5160. (char-to-string (char-before (point)))))
  5161. (insert " "))
  5162. (unless (or (eobp)
  5163. (string-match (concat "[" (nth 1 erc) "\n]")
  5164. (char-to-string (char-after (point)))))
  5165. (insert " ") (backward-char 1))
  5166. (insert string)
  5167. (and move (backward-char 1))))
  5168. (defconst org-nonsticky-props
  5169. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5170. (defsubst org-rear-nonsticky-at (pos)
  5171. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5172. (defun org-activate-plain-links (limit)
  5173. "Add link properties for plain links."
  5174. (when (and (re-search-forward org-plain-link-re limit t)
  5175. (not (org-in-src-block-p)))
  5176. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5177. 'face))
  5178. (link (match-string-no-properties 0))
  5179. (type (match-string-no-properties 1))
  5180. (path (match-string-no-properties 2))
  5181. (link-start (match-beginning 0))
  5182. (link-end (match-end 0))
  5183. (link-face (org-link-get-parameter type :face))
  5184. (help-echo (org-link-get-parameter type :help-echo))
  5185. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5186. (activate-func (org-link-get-parameter type :activate-func)))
  5187. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5188. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5189. (add-text-properties (match-beginning 0) (match-end 0)
  5190. (list
  5191. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5192. 'highlight)
  5193. 'face (cond
  5194. ;; A function that returns a face
  5195. ((functionp link-face)
  5196. (funcall link-face path))
  5197. ;; a face
  5198. ((facep link-face)
  5199. link-face)
  5200. ;; An anonymous face
  5201. ((consp link-face)
  5202. link-face)
  5203. ;; default
  5204. (t
  5205. 'org-link))
  5206. 'help-echo (cond
  5207. ((stringp help-echo)
  5208. help-echo)
  5209. ((functionp help-echo)
  5210. help-echo)
  5211. (t
  5212. (concat "LINK: "
  5213. (save-match-data
  5214. (org-link-unescape link)))))
  5215. 'htmlize-link (cond
  5216. ((functionp htmlize-link)
  5217. (funcall htmlize-link path))
  5218. (t
  5219. `(:uri ,link)))
  5220. 'keymap (or (org-link-get-parameter type :keymap)
  5221. org-mouse-map)
  5222. 'org-link-start (match-beginning 0)))
  5223. (org-rear-nonsticky-at (match-end 0))
  5224. (when activate-func
  5225. (funcall activate-func link-start link-end path nil))
  5226. t))))
  5227. (defun org-activate-code (limit)
  5228. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5229. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5230. (remove-text-properties (match-beginning 0) (match-end 0)
  5231. '(display t invisible t intangible t))
  5232. t))
  5233. (defcustom org-src-fontify-natively t
  5234. "When non-nil, fontify code in code blocks.
  5235. See also the `org-block' face."
  5236. :type 'boolean
  5237. :version "24.4"
  5238. :package-version '(Org . "8.3")
  5239. :group 'org-appearance
  5240. :group 'org-babel)
  5241. (defcustom org-allow-promoting-top-level-subtree nil
  5242. "When non-nil, allow promoting a top level subtree.
  5243. The leading star of the top level headline will be replaced
  5244. by a #."
  5245. :type 'boolean
  5246. :version "24.1"
  5247. :group 'org-appearance)
  5248. (defun org-fontify-meta-lines-and-blocks (limit)
  5249. (condition-case nil
  5250. (org-fontify-meta-lines-and-blocks-1 limit)
  5251. (error (message "org-mode fontification error in %S at %d"
  5252. (current-buffer)
  5253. (line-number-at-pos)))))
  5254. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5255. "Fontify #+ lines and blocks."
  5256. (let ((case-fold-search t))
  5257. (when (re-search-forward
  5258. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5259. limit t)
  5260. (let ((beg (match-beginning 0))
  5261. (block-start (match-end 0))
  5262. (block-end nil)
  5263. (lang (match-string 7))
  5264. (beg1 (line-beginning-position 2))
  5265. (dc1 (downcase (match-string 2)))
  5266. (dc3 (downcase (match-string 3)))
  5267. end end1 quoting block-type)
  5268. (cond
  5269. ((and (match-end 4) (equal dc3 "+begin"))
  5270. ;; Truly a block
  5271. (setq block-type (downcase (match-string 5))
  5272. quoting (member block-type org-protecting-blocks))
  5273. (when (re-search-forward
  5274. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5275. nil t) ;; on purpose, we look further than LIMIT
  5276. (setq end (min (point-max) (match-end 0))
  5277. end1 (min (point-max) (1- (match-beginning 0))))
  5278. (setq block-end (match-beginning 0))
  5279. (when quoting
  5280. (org-remove-flyspell-overlays-in beg1 end1)
  5281. (remove-text-properties beg end
  5282. '(display t invisible t intangible t)))
  5283. (add-text-properties
  5284. beg end '(font-lock-fontified t font-lock-multiline t))
  5285. (add-text-properties beg beg1 '(face org-meta-line))
  5286. (org-remove-flyspell-overlays-in beg beg1)
  5287. (add-text-properties ; For end_src
  5288. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5289. (org-remove-flyspell-overlays-in end1 end)
  5290. (cond
  5291. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5292. (org-src-font-lock-fontify-block lang block-start block-end)
  5293. (add-text-properties beg1 block-end '(src-block t)))
  5294. (quoting
  5295. (add-text-properties beg1 (min (point-max) (1+ end1))
  5296. (list 'face
  5297. (list :inherit
  5298. (let ((face-name
  5299. (intern (format "org-block-%s" lang))))
  5300. (append (and (facep face-name) (list face-name))
  5301. '(org-block))))))) ; end of source block
  5302. ((not org-fontify-quote-and-verse-blocks))
  5303. ((string= block-type "quote")
  5304. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5305. ((string= block-type "verse")
  5306. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5307. (add-text-properties beg beg1 '(face org-block-begin-line))
  5308. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5309. '(face org-block-end-line))
  5310. t))
  5311. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5312. (org-remove-flyspell-overlays-in
  5313. (match-beginning 0)
  5314. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5315. (add-text-properties
  5316. beg (match-end 3)
  5317. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5318. '(font-lock-fontified t invisible t)
  5319. '(font-lock-fontified t face org-document-info-keyword)))
  5320. (add-text-properties
  5321. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5322. (if (string-equal dc1 "+title:")
  5323. '(font-lock-fontified t face org-document-title)
  5324. '(font-lock-fontified t face org-document-info))))
  5325. ((string-prefix-p "+caption" dc1)
  5326. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5327. (remove-text-properties (match-beginning 0) (match-end 0)
  5328. '(display t invisible t intangible t))
  5329. ;; Handle short captions.
  5330. (save-excursion
  5331. (beginning-of-line)
  5332. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5333. (add-text-properties (line-beginning-position) (match-end 1)
  5334. '(font-lock-fontified t face org-meta-line))
  5335. (add-text-properties (match-end 0) (line-end-position)
  5336. '(font-lock-fontified t face org-block))
  5337. t)
  5338. ((member dc3 '(" " ""))
  5339. (org-remove-flyspell-overlays-in beg (match-end 0))
  5340. (add-text-properties
  5341. beg (match-end 0)
  5342. '(font-lock-fontified t face font-lock-comment-face)))
  5343. (t ;; just any other in-buffer setting, but not indented
  5344. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5345. (remove-text-properties (match-beginning 0) (match-end 0)
  5346. '(display t invisible t intangible t))
  5347. (add-text-properties beg (match-end 0)
  5348. '(font-lock-fontified t face org-meta-line))
  5349. t))))))
  5350. (defun org-fontify-drawers (limit)
  5351. "Fontify drawers."
  5352. (when (re-search-forward org-drawer-regexp limit t)
  5353. (add-text-properties
  5354. (match-beginning 0) (match-end 0)
  5355. '(font-lock-fontified t face org-special-keyword))
  5356. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5357. t))
  5358. (defun org-fontify-macros (limit)
  5359. "Fontify macros."
  5360. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5361. (add-text-properties
  5362. (match-beginning 0) (match-end 0)
  5363. '(font-lock-fontified t face org-macro))
  5364. (when org-hide-macro-markers
  5365. (add-text-properties (match-end 2) (match-beginning 2)
  5366. '(invisible t))
  5367. (add-text-properties (match-beginning 1) (match-end 1)
  5368. '(invisible t)))
  5369. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5370. t))
  5371. (defun org-activate-angle-links (limit)
  5372. "Add text properties for angle links."
  5373. (when (and (re-search-forward org-angle-link-re limit t)
  5374. (not (org-in-src-block-p)))
  5375. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5376. (add-text-properties (match-beginning 0) (match-end 0)
  5377. (list 'mouse-face 'highlight
  5378. 'keymap org-mouse-map
  5379. 'font-lock-multiline t))
  5380. (org-rear-nonsticky-at (match-end 0))
  5381. t))
  5382. (defun org-activate-footnote-links (limit)
  5383. "Add text properties for footnotes."
  5384. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5385. (when fn
  5386. (let* ((beg (nth 1 fn))
  5387. (end (nth 2 fn))
  5388. (label (car fn))
  5389. (referencep (/= (line-beginning-position) beg)))
  5390. (when (and referencep (nth 3 fn))
  5391. (save-excursion
  5392. (goto-char beg)
  5393. (search-forward (or label "fn:"))
  5394. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5395. (add-text-properties beg end
  5396. (list 'mouse-face 'highlight
  5397. 'keymap org-mouse-map
  5398. 'help-echo
  5399. (if referencep "Footnote reference"
  5400. "Footnote definition")
  5401. 'font-lock-fontified t
  5402. 'font-lock-multiline t
  5403. 'face 'org-footnote))))))
  5404. (defun org-activate-bracket-links (limit)
  5405. "Add text properties for bracketed links."
  5406. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5407. (not (org-in-src-block-p)))
  5408. (let* ((hl (save-match-data
  5409. (org-link-expand-abbrev (match-string-no-properties 1))))
  5410. (type (save-match-data
  5411. (and (string-match org-plain-link-re hl)
  5412. (match-string-no-properties 1 hl))))
  5413. (path (save-match-data
  5414. (and (string-match org-plain-link-re hl)
  5415. (match-string-no-properties 2 hl))))
  5416. (link-start (match-beginning 0))
  5417. (link-end (match-end 0))
  5418. (bracketp t)
  5419. (help-echo (org-link-get-parameter type :help-echo))
  5420. (help (cond
  5421. ((stringp help-echo)
  5422. help-echo)
  5423. ((functionp help-echo)
  5424. help-echo)
  5425. (t
  5426. (concat "LINK: "
  5427. (save-match-data
  5428. (org-link-unescape hl))))))
  5429. (link-face (org-link-get-parameter type :face))
  5430. (face (cond
  5431. ;; A function that returns a face
  5432. ((functionp link-face)
  5433. (funcall link-face path))
  5434. ;; a face
  5435. ((facep link-face)
  5436. link-face)
  5437. ;; An anonymous face
  5438. ((consp link-face)
  5439. link-face)
  5440. ;; default
  5441. (t
  5442. 'org-link)))
  5443. (keymap (or (org-link-get-parameter type :keymap)
  5444. org-mouse-map))
  5445. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5446. 'highlight))
  5447. (htmlize (org-link-get-parameter type :htmlize-link))
  5448. (htmlize-link (cond
  5449. ((functionp htmlize)
  5450. (funcall htmlize))
  5451. (t
  5452. `(:uri ,(format "%s:%s" type path)))))
  5453. (activate-func (org-link-get-parameter type :activate-func))
  5454. ;; invisible part
  5455. (ip (list 'invisible (or
  5456. (org-link-get-parameter type :display)
  5457. 'org-link)
  5458. 'face face
  5459. 'keymap keymap
  5460. 'mouse-face mouse-face
  5461. 'font-lock-multiline t
  5462. 'help-echo help
  5463. 'htmlize-link htmlize-link))
  5464. ;; visible part
  5465. (vp (list 'keymap keymap
  5466. 'face face
  5467. 'mouse-face mouse-face
  5468. 'font-lock-multiline t
  5469. 'help-echo help
  5470. 'htmlize-link htmlize-link)))
  5471. ;; We need to remove the invisible property here. Table narrowing
  5472. ;; may have made some of this invisible.
  5473. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5474. (remove-text-properties (match-beginning 0) (match-end 0)
  5475. '(invisible nil))
  5476. (if (match-end 3)
  5477. (progn
  5478. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5479. (org-rear-nonsticky-at (match-beginning 3))
  5480. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5481. (org-rear-nonsticky-at (match-end 3))
  5482. (add-text-properties (match-end 3) (match-end 0) ip)
  5483. (org-rear-nonsticky-at (match-end 0)))
  5484. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5485. (org-rear-nonsticky-at (match-beginning 1))
  5486. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5487. (org-rear-nonsticky-at (match-end 1))
  5488. (add-text-properties (match-end 1) (match-end 0) ip)
  5489. (org-rear-nonsticky-at (match-end 0)))
  5490. (when activate-func
  5491. (funcall activate-func link-start link-end path bracketp))
  5492. t)))
  5493. (defun org-activate-dates (limit)
  5494. "Add text properties for dates."
  5495. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5496. (not (equal (char-before (match-beginning 0)) 91)))
  5497. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5498. (add-text-properties (match-beginning 0) (match-end 0)
  5499. (list 'mouse-face 'highlight
  5500. 'keymap org-mouse-map))
  5501. (org-rear-nonsticky-at (match-end 0))
  5502. (when org-display-custom-times
  5503. (if (match-end 3)
  5504. (org-display-custom-time (match-beginning 3) (match-end 3))
  5505. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5506. t))
  5507. (defvar-local org-target-link-regexp nil
  5508. "Regular expression matching radio targets in plain text.")
  5509. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5510. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5511. border border border))
  5512. "Regular expression matching a link target.")
  5513. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5514. "Regular expression matching a radio target.")
  5515. (defconst org-any-target-regexp
  5516. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5517. "Regular expression matching any target.")
  5518. (defun org-activate-target-links (limit)
  5519. "Add text properties for target matches."
  5520. (when org-target-link-regexp
  5521. (let ((case-fold-search t))
  5522. (when (re-search-forward org-target-link-regexp limit t)
  5523. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5524. (add-text-properties (match-beginning 1) (match-end 1)
  5525. (list 'mouse-face 'highlight
  5526. 'keymap org-mouse-map
  5527. 'help-echo "Radio target link"
  5528. 'org-linked-text t))
  5529. (org-rear-nonsticky-at (match-end 1))
  5530. t))))
  5531. (defun org-update-radio-target-regexp ()
  5532. "Find all radio targets in this file and update the regular expression.
  5533. Also refresh fontification if needed."
  5534. (interactive)
  5535. (let ((old-regexp org-target-link-regexp)
  5536. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5537. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5538. (targets
  5539. (org-with-wide-buffer
  5540. (goto-char (point-min))
  5541. (let (rtn)
  5542. (while (re-search-forward org-radio-target-regexp nil t)
  5543. ;; Make sure point is really within the object.
  5544. (backward-char)
  5545. (let ((obj (org-element-context)))
  5546. (when (eq (org-element-type obj) 'radio-target)
  5547. (cl-pushnew (org-element-property :value obj) rtn
  5548. :test #'equal))))
  5549. rtn))))
  5550. (setq org-target-link-regexp
  5551. (and targets
  5552. (concat before-re
  5553. (mapconcat
  5554. (lambda (x)
  5555. (replace-regexp-in-string
  5556. " +" "\\s-+" (regexp-quote x) t t))
  5557. targets
  5558. "\\|")
  5559. after-re)))
  5560. (unless (equal old-regexp org-target-link-regexp)
  5561. ;; Clean-up cache.
  5562. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5563. ((not org-target-link-regexp) old-regexp)
  5564. (t
  5565. (concat before-re
  5566. (mapconcat
  5567. (lambda (re)
  5568. (substring re (length before-re)
  5569. (- (length after-re))))
  5570. (list old-regexp org-target-link-regexp)
  5571. "\\|")
  5572. after-re)))))
  5573. (org-with-wide-buffer
  5574. (goto-char (point-min))
  5575. (while (re-search-forward regexp nil t)
  5576. (org-element-cache-refresh (match-beginning 1)))))
  5577. ;; Re fontify buffer.
  5578. (when (memq 'radio org-highlight-links)
  5579. (org-restart-font-lock)))))
  5580. (defun org-hide-wide-columns (limit)
  5581. (let (s e)
  5582. (setq s (text-property-any (point) (or limit (point-max))
  5583. 'org-cwidth t))
  5584. (when s
  5585. (setq e (next-single-property-change s 'org-cwidth))
  5586. (add-text-properties s e '(invisible org-cwidth))
  5587. (goto-char e)
  5588. t)))
  5589. (defvar org-latex-and-related-regexp nil
  5590. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5591. (defun org-compute-latex-and-related-regexp ()
  5592. "Compute regular expression for LaTeX, entities and sub/superscript.
  5593. Result depends on variable `org-highlight-latex-and-related'."
  5594. (setq-local
  5595. org-latex-and-related-regexp
  5596. (let* ((re-sub
  5597. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5598. ((eq org-use-sub-superscripts '{})
  5599. (list org-match-substring-with-braces-regexp))
  5600. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5601. (re-latex
  5602. (when (memq 'latex org-highlight-latex-and-related)
  5603. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5604. (delq nil
  5605. (mapcar (lambda (x)
  5606. (and (member (car x) matchers) (nth 1 x)))
  5607. org-latex-regexps)))))
  5608. (re-entities
  5609. (when (memq 'entities org-highlight-latex-and-related)
  5610. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5611. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5612. (defun org-do-latex-and-related (limit)
  5613. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5614. LIMIT bounds the search for syntax to highlight. Stop at first
  5615. highlighted object, if any. Return t if some highlighting was
  5616. done, nil otherwise."
  5617. (when (org-string-nw-p org-latex-and-related-regexp)
  5618. (catch 'found
  5619. (while (re-search-forward org-latex-and-related-regexp limit t)
  5620. (unless
  5621. (cl-some
  5622. (lambda (f)
  5623. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5624. (save-excursion
  5625. (goto-char (1+ (match-beginning 0)))
  5626. (face-at-point nil t)))
  5627. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5628. '(?_ ?^))
  5629. 1
  5630. 0)))
  5631. (font-lock-prepend-text-property
  5632. (+ offset (match-beginning 0)) (match-end 0)
  5633. 'face 'org-latex-and-related)
  5634. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5635. '(font-lock-multiline t)))
  5636. (throw 'found t)))
  5637. nil)))
  5638. (defun org-restart-font-lock ()
  5639. "Restart `font-lock-mode', to force refontification."
  5640. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5641. (font-lock-mode -1)
  5642. (font-lock-mode 1)))
  5643. (defun org-activate-tags (limit)
  5644. (when (re-search-forward
  5645. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5646. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5647. (add-text-properties (match-beginning 1) (match-end 1)
  5648. (list 'mouse-face 'highlight
  5649. 'keymap org-mouse-map))
  5650. (org-rear-nonsticky-at (match-end 1))
  5651. t))
  5652. (defun org-outline-level ()
  5653. "Compute the outline level of the heading at point.
  5654. If this is called at a normal headline, the level is the number
  5655. of stars. Use `org-reduced-level' to remove the effect of
  5656. `org-odd-levels'. Unlike to `org-current-level', this function
  5657. takes into consideration inlinetasks."
  5658. (org-with-wide-buffer
  5659. (end-of-line)
  5660. (if (re-search-backward org-outline-regexp-bol nil t)
  5661. (1- (- (match-end 0) (match-beginning 0)))
  5662. 0)))
  5663. (defvar org-font-lock-keywords nil)
  5664. (defsubst org-re-property (property &optional literal allow-null value)
  5665. "Return a regexp matching a PROPERTY line.
  5666. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5667. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5668. non-nil, match properties even without a value.
  5669. Match group 3 is set to the value when it exists. If there is no
  5670. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5671. With optional argument VALUE, match only property lines with
  5672. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5673. unless LITERAL is non-nil."
  5674. (concat
  5675. "^\\(?4:[ \t]*\\)"
  5676. (format "\\(?1::\\(?2:%s\\):\\)"
  5677. (if literal property (regexp-quote property)))
  5678. (cond (value
  5679. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5680. (if literal value (regexp-quote value))))
  5681. (allow-null
  5682. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5683. (t
  5684. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5685. (defconst org-property-re
  5686. (org-re-property "\\S-+" 'literal t)
  5687. "Regular expression matching a property line.
  5688. There are four matching groups:
  5689. 1: :PROPKEY: including the leading and trailing colon,
  5690. 2: PROPKEY without the leading and trailing colon,
  5691. 3: PROPVAL without leading or trailing spaces,
  5692. 4: the indentation of the current line,
  5693. 5: trailing whitespace.")
  5694. (defvar org-font-lock-hook nil
  5695. "Functions to be called for special font lock stuff.")
  5696. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5697. (defvar org-font-lock-set-keywords-hook nil
  5698. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5699. This is called after `org-font-lock-extra-keywords' is defined, but before
  5700. it is installed to be used by font lock. This can be useful if something
  5701. needs to be inserted at a specific position in the font-lock sequence.")
  5702. (defun org-font-lock-hook (limit)
  5703. "Run `org-font-lock-hook' within LIMIT."
  5704. (run-hook-with-args 'org-font-lock-hook limit))
  5705. (defun org-set-font-lock-defaults ()
  5706. "Set font lock defaults for the current buffer."
  5707. (let* ((em org-fontify-emphasized-text)
  5708. (lk org-highlight-links)
  5709. (org-font-lock-extra-keywords
  5710. (list
  5711. ;; Call the hook
  5712. '(org-font-lock-hook)
  5713. ;; Headlines
  5714. `(,(if org-fontify-whole-heading-line
  5715. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5716. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5717. (1 (org-get-level-face 1))
  5718. (2 (org-get-level-face 2))
  5719. (3 (org-get-level-face 3)))
  5720. ;; Table lines
  5721. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5722. (1 'org-table t))
  5723. ;; Table internals
  5724. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5725. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5726. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5727. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5728. ;; Drawers
  5729. '(org-fontify-drawers)
  5730. ;; Properties
  5731. (list org-property-re
  5732. '(1 'org-special-keyword t)
  5733. '(3 'org-property-value t))
  5734. ;; Links
  5735. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5736. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5737. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5738. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5739. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5740. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5741. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5742. ;; Targets.
  5743. (list org-any-target-regexp '(0 'org-target t))
  5744. ;; Diary sexps.
  5745. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5746. ;; Macro
  5747. '(org-fontify-macros)
  5748. '(org-hide-wide-columns (0 nil append))
  5749. ;; TODO keyword
  5750. (list (format org-heading-keyword-regexp-format
  5751. org-todo-regexp)
  5752. '(2 (org-get-todo-face 2) t))
  5753. ;; DONE
  5754. (if org-fontify-done-headline
  5755. (list (format org-heading-keyword-regexp-format
  5756. (concat
  5757. "\\(?:"
  5758. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5759. "\\)"))
  5760. '(2 'org-headline-done t))
  5761. nil)
  5762. ;; Priorities
  5763. '(org-font-lock-add-priority-faces)
  5764. ;; Tags
  5765. '(org-font-lock-add-tag-faces)
  5766. ;; Tags groups
  5767. (when (and org-group-tags org-tag-groups-alist)
  5768. (list (concat org-outline-regexp-bol ".+\\(:"
  5769. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5770. ":\\).*$")
  5771. '(1 'org-tag-group prepend)))
  5772. ;; Special keywords
  5773. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5774. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5775. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5776. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5777. ;; Emphasis
  5778. (when em '(org-do-emphasis-faces))
  5779. ;; Checkboxes
  5780. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5781. 1 'org-checkbox prepend)
  5782. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5783. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5784. (0 (org-get-checkbox-statistics-face) t)))
  5785. ;; Description list items
  5786. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5787. 1 'org-list-dt prepend)
  5788. ;; ARCHIVEd headings
  5789. (list (concat
  5790. org-outline-regexp-bol
  5791. "\\(.*:" org-archive-tag ":.*\\)")
  5792. '(1 'org-archived prepend))
  5793. ;; Specials
  5794. '(org-do-latex-and-related)
  5795. '(org-fontify-entities)
  5796. '(org-raise-scripts)
  5797. ;; Code
  5798. '(org-activate-code (1 'org-code t))
  5799. ;; COMMENT
  5800. (list (format
  5801. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5802. org-todo-regexp
  5803. org-comment-string)
  5804. '(9 'org-special-keyword t))
  5805. ;; Blocks and meta lines
  5806. '(org-fontify-meta-lines-and-blocks))))
  5807. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5808. (run-hooks 'org-font-lock-set-keywords-hook)
  5809. ;; Now set the full font-lock-keywords
  5810. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5811. (setq-local font-lock-defaults
  5812. '(org-font-lock-keywords t nil nil backward-paragraph))
  5813. (kill-local-variable 'font-lock-keywords)
  5814. nil))
  5815. (defun org-toggle-pretty-entities ()
  5816. "Toggle the composition display of entities as UTF8 characters."
  5817. (interactive)
  5818. (setq-local org-pretty-entities (not org-pretty-entities))
  5819. (org-restart-font-lock)
  5820. (if org-pretty-entities
  5821. (message "Entities are now displayed as UTF8 characters")
  5822. (save-restriction
  5823. (widen)
  5824. (decompose-region (point-min) (point-max))
  5825. (message "Entities are now displayed as plain text"))))
  5826. (defvar-local org-custom-properties-overlays nil
  5827. "List of overlays used for custom properties.")
  5828. (defun org-toggle-custom-properties-visibility ()
  5829. "Display or hide properties in `org-custom-properties'."
  5830. (interactive)
  5831. (if org-custom-properties-overlays
  5832. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5833. (setq org-custom-properties-overlays nil))
  5834. (when org-custom-properties
  5835. (org-with-wide-buffer
  5836. (goto-char (point-min))
  5837. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5838. (while (re-search-forward regexp nil t)
  5839. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5840. (when (and end (< (point) end))
  5841. ;; Hide first custom property in current drawer.
  5842. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5843. (overlay-put o 'invisible t)
  5844. (overlay-put o 'org-custom-property t)
  5845. (push o org-custom-properties-overlays))
  5846. ;; Hide additional custom properties in the same drawer.
  5847. (while (re-search-forward regexp end t)
  5848. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5849. (overlay-put o 'invisible t)
  5850. (overlay-put o 'org-custom-property t)
  5851. (push o org-custom-properties-overlays)))))
  5852. ;; Each entry is limited to a single property drawer.
  5853. (outline-next-heading)))))))
  5854. (defun org-fontify-entities (limit)
  5855. "Find an entity to fontify."
  5856. (let (ee)
  5857. (when org-pretty-entities
  5858. (catch 'match
  5859. ;; "\_ "-family is left out on purpose. Only the first one,
  5860. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5861. ;; confusing when adding a second white space character.
  5862. (while (re-search-forward
  5863. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5864. limit t)
  5865. (when (and (not (org-at-comment-p))
  5866. (setq ee (org-entity-get (match-string 1)))
  5867. (= (length (nth 6 ee)) 1))
  5868. (let* ((end (if (equal (match-string 2) "{}")
  5869. (match-end 2)
  5870. (match-end 1))))
  5871. (add-text-properties
  5872. (match-beginning 0) end
  5873. (list 'font-lock-fontified t))
  5874. (compose-region (match-beginning 0) end
  5875. (nth 6 ee) nil)
  5876. (backward-char 1)
  5877. (throw 'match t))))
  5878. nil))))
  5879. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5880. "Fontify string S like in Org mode."
  5881. (with-temp-buffer
  5882. (insert s)
  5883. (let ((org-odd-levels-only odd-levels))
  5884. (org-mode)
  5885. (org-font-lock-ensure)
  5886. (buffer-string))))
  5887. (defvar org-m nil)
  5888. (defvar org-l nil)
  5889. (defvar org-f nil)
  5890. (defun org-get-level-face (n)
  5891. "Get the right face for match N in font-lock matching of headlines."
  5892. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5893. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5894. (if org-cycle-level-faces
  5895. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5896. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5897. (cond
  5898. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5899. ((eq n 2) org-f)
  5900. (t (unless org-level-color-stars-only org-f))))
  5901. (defun org-face-from-face-or-color (context inherit face-or-color)
  5902. "Create a face list that inherits INHERIT, but sets the foreground color.
  5903. When FACE-OR-COLOR is not a string, just return it."
  5904. (if (stringp face-or-color)
  5905. (list :inherit inherit
  5906. (cdr (assoc context org-faces-easy-properties))
  5907. face-or-color)
  5908. face-or-color))
  5909. (defun org-get-todo-face (kwd)
  5910. "Get the right face for a TODO keyword KWD.
  5911. If KWD is a number, get the corresponding match group."
  5912. (when (numberp kwd) (setq kwd (match-string kwd)))
  5913. (or (org-face-from-face-or-color
  5914. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5915. (and (member kwd org-done-keywords) 'org-done)
  5916. 'org-todo))
  5917. (defun org-get-priority-face (priority)
  5918. "Get the right face for PRIORITY.
  5919. PRIORITY is a character."
  5920. (or (org-face-from-face-or-color
  5921. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5922. 'org-priority))
  5923. (defun org-get-tag-face (tag)
  5924. "Get the right face for TAG.
  5925. If TAG is a number, get the corresponding match group."
  5926. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5927. (or (org-face-from-face-or-color
  5928. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5929. 'org-tag)))
  5930. (defun org-font-lock-add-priority-faces (limit)
  5931. "Add the special priority faces."
  5932. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5933. (add-text-properties
  5934. (match-beginning 1) (match-end 1)
  5935. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5936. 'font-lock-fontified t))))
  5937. (defun org-font-lock-add-tag-faces (limit)
  5938. "Add the special tag faces."
  5939. (when (and org-tag-faces org-tags-special-faces-re)
  5940. (while (re-search-forward org-tags-special-faces-re limit t)
  5941. (add-text-properties (match-beginning 1) (match-end 1)
  5942. (list 'face (org-get-tag-face 1)
  5943. 'font-lock-fontified t))
  5944. (backward-char 1))))
  5945. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5946. "Remove fontification and activation overlays from links."
  5947. (font-lock-default-unfontify-region beg end)
  5948. (let* ((buffer-undo-list t)
  5949. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5950. (inhibit-modification-hooks t)
  5951. deactivate-mark buffer-file-name buffer-file-truename)
  5952. (decompose-region beg end)
  5953. (remove-text-properties beg end
  5954. '(mouse-face t keymap t org-linked-text t
  5955. invisible t intangible t
  5956. org-emphasis t))
  5957. (org-remove-font-lock-display-properties beg end)))
  5958. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5959. ((raise 0.3) (height 0.7))
  5960. ((raise -0.5))
  5961. ((raise 0.5)))
  5962. "Display properties for showing superscripts and subscripts.")
  5963. (defun org-remove-font-lock-display-properties (beg end)
  5964. "Remove specific display properties that have been added by font lock.
  5965. The will remove the raise properties that are used to show superscripts
  5966. and subscripts."
  5967. (let (next prop)
  5968. (while (< beg end)
  5969. (setq next (next-single-property-change beg 'display nil end)
  5970. prop (get-text-property beg 'display))
  5971. (when (member prop org-script-display)
  5972. (put-text-property beg next 'display nil))
  5973. (setq beg next))))
  5974. (defun org-raise-scripts (limit)
  5975. "Add raise properties to sub/superscripts."
  5976. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5977. (re-search-forward
  5978. (if (eq org-use-sub-superscripts t)
  5979. org-match-substring-regexp
  5980. org-match-substring-with-braces-regexp)
  5981. limit t))
  5982. (let* ((pos (point)) table-p comment-p
  5983. (mpos (match-beginning 3))
  5984. (emph-p (get-text-property mpos 'org-emphasis))
  5985. (link-p (get-text-property mpos 'mouse-face))
  5986. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5987. (goto-char (point-at-bol))
  5988. (setq table-p (looking-at-p org-table-dataline-regexp)
  5989. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5990. (goto-char pos)
  5991. ;; Handle a_b^c
  5992. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5993. (unless (or comment-p emph-p link-p keyw-p)
  5994. (put-text-property (match-beginning 3) (match-end 0)
  5995. 'display
  5996. (if (equal (char-after (match-beginning 2)) ?^)
  5997. (nth (if table-p 3 1) org-script-display)
  5998. (nth (if table-p 2 0) org-script-display)))
  5999. (add-text-properties (match-beginning 2) (match-end 2)
  6000. (list 'invisible t
  6001. 'org-dwidth t 'org-dwidth-n 1))
  6002. (if (and (eq (char-after (match-beginning 3)) ?{)
  6003. (eq (char-before (match-end 3)) ?}))
  6004. (progn
  6005. (add-text-properties
  6006. (match-beginning 3) (1+ (match-beginning 3))
  6007. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6008. (add-text-properties
  6009. (1- (match-end 3)) (match-end 3)
  6010. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6011. t)))
  6012. ;;;; Visibility cycling, including org-goto and indirect buffer
  6013. ;;; Cycling
  6014. (defvar-local org-cycle-global-status nil)
  6015. (put 'org-cycle-global-status 'org-state t)
  6016. (defvar-local org-cycle-subtree-status nil)
  6017. (put 'org-cycle-subtree-status 'org-state t)
  6018. (defvar org-inlinetask-min-level)
  6019. (defun org-unlogged-message (&rest args)
  6020. "Display a message, but avoid logging it in the *Messages* buffer."
  6021. (let ((message-log-max nil))
  6022. (apply 'message args)))
  6023. ;;;###autoload
  6024. (defun org-cycle (&optional arg)
  6025. "TAB-action and visibility cycling for Org mode.
  6026. This is the command invoked in Org mode by the `TAB' key. Its main
  6027. purpose is outline visibility cycling, but it also invokes other actions
  6028. in special contexts.
  6029. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6030. the entire
  6031. buffer through 3 states (global cycling)
  6032. 1. OVERVIEW: Show only top-level headlines.
  6033. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6034. 3. SHOW ALL: Show everything.
  6035. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6036. switch to the startup visibility,
  6037. determined by the variable `org-startup-folded', and by any VISIBILITY
  6038. properties in the buffer.
  6039. With a `\\[universal-argument] \\[universal-argument] \
  6040. \\[universal-argument]' prefix argument, show the entire buffer, including
  6041. any drawers.
  6042. When inside a table, re-align the table and move to the next field.
  6043. When point is at the beginning of a headline, rotate the subtree started
  6044. by this line through 3 different states (local cycling)
  6045. 1. FOLDED: Only the main headline is shown.
  6046. 2. CHILDREN: The main headline and the direct children are shown.
  6047. From this state, you can move to one of the children
  6048. and zoom in further.
  6049. 3. SUBTREE: Show the entire subtree, including body text.
  6050. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6051. When point is at the beginning of an empty headline and the variable
  6052. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6053. of the headline by demoting and promoting it to likely levels. This
  6054. speeds up creation document structure by pressing `TAB' once or several
  6055. times right after creating a new headline.
  6056. When there is a numeric prefix, go up to a heading with level ARG, do
  6057. a `show-subtree' and return to the previous cursor position. If ARG
  6058. is negative, go up that many levels.
  6059. When point is not at the beginning of a headline, execute the global
  6060. binding for `TAB', which is re-indenting the line. See the option
  6061. `org-cycle-emulate-tab' for details.
  6062. As a special case, if point is at the beginning of the buffer and there is
  6063. no headline in line 1, this function will act as if called with prefix arg
  6064. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6065. prefix arg, but only
  6066. if the variable `org-cycle-global-at-bob' is t."
  6067. (interactive "P")
  6068. (org-load-modules-maybe)
  6069. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6070. (and org-cycle-level-after-item/entry-creation
  6071. (or (org-cycle-level)
  6072. (org-cycle-item-indentation))))
  6073. (let* ((limit-level
  6074. (or org-cycle-max-level
  6075. (and (boundp 'org-inlinetask-min-level)
  6076. org-inlinetask-min-level
  6077. (1- org-inlinetask-min-level))))
  6078. (nstars (and limit-level
  6079. (if org-odd-levels-only
  6080. (and limit-level (1- (* limit-level 2)))
  6081. limit-level)))
  6082. (org-outline-regexp
  6083. (if (not (derived-mode-p 'org-mode))
  6084. outline-regexp
  6085. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6086. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6087. (not (looking-at org-outline-regexp))))
  6088. (org-cycle-hook
  6089. (if bob-special
  6090. (delq 'org-optimize-window-after-visibility-change
  6091. (copy-sequence org-cycle-hook))
  6092. org-cycle-hook))
  6093. (pos (point)))
  6094. (cond
  6095. ((equal arg '(16))
  6096. (setq last-command 'dummy)
  6097. (org-set-startup-visibility)
  6098. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6099. ((equal arg '(64))
  6100. (outline-show-all)
  6101. (org-unlogged-message "Entire buffer visible, including drawers"))
  6102. ((equal arg '(4)) (org-cycle-internal-global))
  6103. ;; Try hiding block at point.
  6104. ((org-hide-block-toggle-maybe))
  6105. ;; Try cdlatex TAB completion
  6106. ((org-try-cdlatex-tab))
  6107. ;; Table: enter it or move to the next field.
  6108. ((org-at-table-p 'any)
  6109. (if (org-at-table.el-p)
  6110. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6111. Use `\\[org-edit-special]' to edit table.el tables"))
  6112. (if arg (org-table-edit-field t)
  6113. (org-table-justify-field-maybe)
  6114. (call-interactively 'org-table-next-field))))
  6115. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6116. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6117. (bob-special (org-cycle-internal-global))
  6118. ;; Drawers: delegate to `org-flag-drawer'.
  6119. ((save-excursion
  6120. (beginning-of-line 1)
  6121. (looking-at org-drawer-regexp))
  6122. (org-flag-drawer ; toggle block visibility
  6123. (not (get-char-property (match-end 0) 'invisible))))
  6124. ;; Show-subtree, ARG levels up from here.
  6125. ((integerp arg)
  6126. (save-excursion
  6127. (org-back-to-heading)
  6128. (outline-up-heading (if (< arg 0) (- arg)
  6129. (- (funcall outline-level) arg)))
  6130. (org-show-subtree)))
  6131. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6132. ((and (featurep 'org-inlinetask)
  6133. (org-inlinetask-at-task-p)
  6134. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6135. (org-inlinetask-toggle-visibility))
  6136. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6137. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6138. (save-excursion (move-beginning-of-line 1)
  6139. (looking-at org-outline-regexp)))
  6140. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6141. (org-cycle-internal-local))
  6142. ;; From there: TAB emulation and template completion.
  6143. (buffer-read-only (org-back-to-heading))
  6144. ((run-hook-with-args-until-success
  6145. 'org-tab-after-check-for-cycling-hook))
  6146. ((org-try-structure-completion))
  6147. ((run-hook-with-args-until-success
  6148. 'org-tab-before-tab-emulation-hook))
  6149. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6150. (or (not (bolp))
  6151. (not (looking-at org-outline-regexp))))
  6152. (call-interactively (global-key-binding "\t")))
  6153. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6154. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6155. (or (and (eq org-cycle-emulate-tab 'white)
  6156. (= (match-end 0) (point-at-eol)))
  6157. (and (eq org-cycle-emulate-tab 'whitestart)
  6158. (>= (match-end 0) pos))))
  6159. t
  6160. (eq org-cycle-emulate-tab t))
  6161. (call-interactively (global-key-binding "\t")))
  6162. (t (save-excursion
  6163. (org-back-to-heading)
  6164. (org-cycle)))))))
  6165. (defun org-cycle-internal-global ()
  6166. "Do the global cycling action."
  6167. ;; Hack to avoid display of messages for .org attachments in Gnus
  6168. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6169. (cond
  6170. ((and (eq last-command this-command)
  6171. (eq org-cycle-global-status 'overview))
  6172. ;; We just created the overview - now do table of contents
  6173. ;; This can be slow in very large buffers, so indicate action
  6174. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6175. (unless ga (org-unlogged-message "CONTENTS..."))
  6176. (org-content)
  6177. (unless ga (org-unlogged-message "CONTENTS...done"))
  6178. (setq org-cycle-global-status 'contents)
  6179. (run-hook-with-args 'org-cycle-hook 'contents))
  6180. ((and (eq last-command this-command)
  6181. (eq org-cycle-global-status 'contents))
  6182. ;; We just showed the table of contents - now show everything
  6183. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6184. (outline-show-all)
  6185. (unless ga (org-unlogged-message "SHOW ALL"))
  6186. (setq org-cycle-global-status 'all)
  6187. (run-hook-with-args 'org-cycle-hook 'all))
  6188. (t
  6189. ;; Default action: go to overview
  6190. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6191. (org-overview)
  6192. (unless ga (org-unlogged-message "OVERVIEW"))
  6193. (setq org-cycle-global-status 'overview)
  6194. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6195. (defvar org-called-with-limited-levels nil
  6196. "Non-nil when `org-with-limited-levels' is currently active.")
  6197. (defun org-cycle-internal-local ()
  6198. "Do the local cycling action."
  6199. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6200. ;; First, determine end of headline (EOH), end of subtree or item
  6201. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6202. (save-excursion
  6203. (if (org-at-item-p)
  6204. (progn
  6205. (beginning-of-line)
  6206. (setq struct (org-list-struct))
  6207. (setq eoh (point-at-eol))
  6208. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6209. (setq has-children (org-list-has-child-p (point) struct)))
  6210. (org-back-to-heading)
  6211. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6212. (setq eos (save-excursion (org-end-of-subtree t t)
  6213. (when (bolp) (backward-char)) (point)))
  6214. (setq has-children
  6215. (or (save-excursion
  6216. (let ((level (funcall outline-level)))
  6217. (outline-next-heading)
  6218. (and (org-at-heading-p t)
  6219. (> (funcall outline-level) level))))
  6220. (save-excursion
  6221. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6222. ;; Determine end invisible part of buffer (EOL)
  6223. (beginning-of-line 2)
  6224. (while (and (not (eobp)) ;This is like `next-line'.
  6225. (get-char-property (1- (point)) 'invisible))
  6226. (goto-char (next-single-char-property-change (point) 'invisible))
  6227. (and (eolp) (beginning-of-line 2)))
  6228. (setq eol (point)))
  6229. ;; Find out what to do next and set `this-command'
  6230. (cond
  6231. ((= eos eoh)
  6232. ;; Nothing is hidden behind this heading
  6233. (unless (org-before-first-heading-p)
  6234. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6235. (org-unlogged-message "EMPTY ENTRY")
  6236. (setq org-cycle-subtree-status nil)
  6237. (save-excursion
  6238. (goto-char eos)
  6239. (outline-next-heading)
  6240. (when (outline-invisible-p) (org-flag-heading nil))))
  6241. ((and (or (>= eol eos)
  6242. (not (string-match "\\S-" (buffer-substring eol eos))))
  6243. (or has-children
  6244. (not (setq children-skipped
  6245. org-cycle-skip-children-state-if-no-children))))
  6246. ;; Entire subtree is hidden in one line: children view
  6247. (unless (org-before-first-heading-p)
  6248. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6249. (if (org-at-item-p)
  6250. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6251. (org-show-entry)
  6252. (org-with-limited-levels (org-show-children))
  6253. ;; FIXME: This slows down the func way too much.
  6254. ;; How keep drawers hidden in subtree anyway?
  6255. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6256. ;; (org-cycle-hide-drawers 'subtree))
  6257. ;; Fold every list in subtree to top-level items.
  6258. (when (eq org-cycle-include-plain-lists 'integrate)
  6259. (save-excursion
  6260. (org-back-to-heading)
  6261. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6262. (beginning-of-line 1)
  6263. (let* ((struct (org-list-struct))
  6264. (prevs (org-list-prevs-alist struct))
  6265. (end (org-list-get-bottom-point struct)))
  6266. (dolist (e (org-list-get-all-items (point) struct prevs))
  6267. (org-list-set-item-visibility e struct 'folded))
  6268. (goto-char (if (< end eos) end eos)))))))
  6269. (org-unlogged-message "CHILDREN")
  6270. (save-excursion
  6271. (goto-char eos)
  6272. (outline-next-heading)
  6273. (when (outline-invisible-p) (org-flag-heading nil)))
  6274. (setq org-cycle-subtree-status 'children)
  6275. (unless (org-before-first-heading-p)
  6276. (run-hook-with-args 'org-cycle-hook 'children)))
  6277. ((or children-skipped
  6278. (and (eq last-command this-command)
  6279. (eq org-cycle-subtree-status 'children)))
  6280. ;; We just showed the children, or no children are there,
  6281. ;; now show everything.
  6282. (unless (org-before-first-heading-p)
  6283. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6284. (outline-flag-region eoh eos nil)
  6285. (org-unlogged-message
  6286. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6287. (setq org-cycle-subtree-status 'subtree)
  6288. (unless (org-before-first-heading-p)
  6289. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6290. (t
  6291. ;; Default action: hide the subtree.
  6292. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6293. (outline-flag-region eoh eos t)
  6294. (org-unlogged-message "FOLDED")
  6295. (setq org-cycle-subtree-status 'folded)
  6296. (unless (org-before-first-heading-p)
  6297. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6298. ;;;###autoload
  6299. (defun org-global-cycle (&optional arg)
  6300. "Cycle the global visibility. For details see `org-cycle'.
  6301. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6302. With a numeric prefix, show all headlines up to that level."
  6303. (interactive "P")
  6304. (let ((org-cycle-include-plain-lists
  6305. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6306. (cond
  6307. ((integerp arg)
  6308. (outline-show-all)
  6309. (outline-hide-sublevels arg)
  6310. (setq org-cycle-global-status 'contents))
  6311. ((equal arg '(4))
  6312. (org-set-startup-visibility)
  6313. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6314. (t
  6315. (org-cycle '(4))))))
  6316. (defun org-set-startup-visibility ()
  6317. "Set the visibility required by startup options and properties."
  6318. (cond
  6319. ((eq org-startup-folded t)
  6320. (org-overview))
  6321. ((eq org-startup-folded 'content)
  6322. (org-content))
  6323. ((or (eq org-startup-folded 'showeverything)
  6324. (eq org-startup-folded nil))
  6325. (outline-show-all)))
  6326. (unless (eq org-startup-folded 'showeverything)
  6327. (when org-hide-block-startup (org-hide-block-all))
  6328. (org-set-visibility-according-to-property 'no-cleanup)
  6329. (org-cycle-hide-archived-subtrees 'all)
  6330. (org-cycle-hide-drawers 'all)
  6331. (org-cycle-show-empty-lines t)))
  6332. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6333. "Switch subtree visibilities according to :VISIBILITY: property."
  6334. (interactive)
  6335. (org-with-wide-buffer
  6336. (goto-char (point-min))
  6337. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6338. (if (not (org-at-property-p)) (outline-next-heading)
  6339. (let ((state (match-string 3)))
  6340. (save-excursion
  6341. (org-back-to-heading t)
  6342. (outline-hide-subtree)
  6343. (org-reveal)
  6344. (cond
  6345. ((equal state "folded")
  6346. (outline-hide-subtree))
  6347. ((equal state "children")
  6348. (org-show-hidden-entry)
  6349. (org-show-children))
  6350. ((equal state "content")
  6351. (save-excursion
  6352. (save-restriction
  6353. (org-narrow-to-subtree)
  6354. (org-content))))
  6355. ((member state '("all" "showall"))
  6356. (outline-show-subtree)))))))
  6357. (unless no-cleanup
  6358. (org-cycle-hide-archived-subtrees 'all)
  6359. (org-cycle-hide-drawers 'all)
  6360. (org-cycle-show-empty-lines 'all))))
  6361. ;; This function uses outline-regexp instead of the more fundamental
  6362. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6363. ;; buffers, where outline-regexp is needed.
  6364. (defun org-overview ()
  6365. "Switch to overview mode, showing only top-level headlines.
  6366. This shows all headlines with a level equal or greater than the level
  6367. of the first headline in the buffer. This is important, because if the
  6368. first headline is not level one, then (hide-sublevels 1) gives confusing
  6369. results."
  6370. (interactive)
  6371. (save-excursion
  6372. (let ((level
  6373. (save-excursion
  6374. (goto-char (point-min))
  6375. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6376. (goto-char (match-beginning 0))
  6377. (funcall outline-level)))))
  6378. (and level (outline-hide-sublevels level)))))
  6379. (defun org-content (&optional arg)
  6380. "Show all headlines in the buffer, like a table of contents.
  6381. With numerical argument N, show content up to level N."
  6382. (interactive "P")
  6383. (org-overview)
  6384. (save-excursion
  6385. ;; Visit all headings and show their offspring
  6386. (and (integerp arg) (org-overview))
  6387. (goto-char (point-max))
  6388. (catch 'exit
  6389. (while (and (progn (condition-case nil
  6390. (outline-previous-visible-heading 1)
  6391. (error (goto-char (point-min))))
  6392. t)
  6393. (looking-at org-outline-regexp))
  6394. (if (integerp arg)
  6395. (org-show-children (1- arg))
  6396. (outline-show-branches))
  6397. (when (bobp) (throw 'exit nil))))))
  6398. (defun org-optimize-window-after-visibility-change (state)
  6399. "Adjust the window after a change in outline visibility.
  6400. This function is the default value of the hook `org-cycle-hook'."
  6401. (when (get-buffer-window (current-buffer))
  6402. (cond
  6403. ((eq state 'content) nil)
  6404. ((eq state 'all) nil)
  6405. ((eq state 'folded) nil)
  6406. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6407. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6408. (defun org-remove-empty-overlays-at (pos)
  6409. "Remove outline overlays that do not contain non-white stuff."
  6410. (dolist (o (overlays-at pos))
  6411. (and (eq 'outline (overlay-get o 'invisible))
  6412. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6413. (overlay-end o))))
  6414. (delete-overlay o))))
  6415. (defun org-clean-visibility-after-subtree-move ()
  6416. "Fix visibility issues after moving a subtree."
  6417. ;; First, find a reasonable region to look at:
  6418. ;; Start two siblings above, end three below
  6419. (let* ((beg (save-excursion
  6420. (and (org-get-last-sibling)
  6421. (org-get-last-sibling))
  6422. (point)))
  6423. (end (save-excursion
  6424. (and (org-get-next-sibling)
  6425. (org-get-next-sibling)
  6426. (org-get-next-sibling))
  6427. (if (org-at-heading-p)
  6428. (point-at-eol)
  6429. (point))))
  6430. (level (looking-at "\\*+"))
  6431. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6432. (save-excursion
  6433. (save-restriction
  6434. (narrow-to-region beg end)
  6435. (when re
  6436. ;; Properly fold already folded siblings
  6437. (goto-char (point-min))
  6438. (while (re-search-forward re nil t)
  6439. (when (and (not (outline-invisible-p))
  6440. (save-excursion
  6441. (goto-char (point-at-eol)) (outline-invisible-p)))
  6442. (outline-hide-entry))))
  6443. (org-cycle-show-empty-lines 'overview)
  6444. (org-cycle-hide-drawers 'overview)))))
  6445. (defun org-cycle-show-empty-lines (state)
  6446. "Show empty lines above all visible headlines.
  6447. The region to be covered depends on STATE when called through
  6448. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6449. entire buffer covered. Note that an empty line is only shown if there
  6450. are at least `org-cycle-separator-lines' empty lines before the headline."
  6451. (when (/= org-cycle-separator-lines 0)
  6452. (save-excursion
  6453. (let* ((n (abs org-cycle-separator-lines))
  6454. (re (cond
  6455. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6456. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6457. (t (let ((ns (number-to-string (- n 2))))
  6458. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6459. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6460. beg end)
  6461. (cond
  6462. ((memq state '(overview contents t))
  6463. (setq beg (point-min) end (point-max)))
  6464. ((memq state '(children folded))
  6465. (setq beg (point)
  6466. end (progn (org-end-of-subtree t t)
  6467. (line-beginning-position 2)))))
  6468. (when beg
  6469. (goto-char beg)
  6470. (while (re-search-forward re end t)
  6471. (unless (get-char-property (match-end 1) 'invisible)
  6472. (let ((e (match-end 1))
  6473. (b (if (>= org-cycle-separator-lines 0)
  6474. (match-beginning 1)
  6475. (save-excursion
  6476. (goto-char (match-beginning 0))
  6477. (skip-chars-backward " \t\n")
  6478. (line-end-position)))))
  6479. (outline-flag-region b e nil))))))))
  6480. ;; Never hide empty lines at the end of the file.
  6481. (save-excursion
  6482. (goto-char (point-max))
  6483. (outline-previous-heading)
  6484. (outline-end-of-heading)
  6485. (when (and (looking-at "[ \t\n]+")
  6486. (= (match-end 0) (point-max)))
  6487. (outline-flag-region (point) (match-end 0) nil))))
  6488. (defun org-show-empty-lines-in-parent ()
  6489. "Move to the parent and re-show empty lines before visible headlines."
  6490. (save-excursion
  6491. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6492. (org-cycle-show-empty-lines context))))
  6493. (defun org-files-list ()
  6494. "Return `org-agenda-files' list, plus all open Org files.
  6495. This is useful for operations that need to scan all of a user's
  6496. open and agenda-wise Org files."
  6497. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6498. (dolist (buf (buffer-list))
  6499. (with-current-buffer buf
  6500. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6501. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6502. files))
  6503. (defsubst org-entry-beginning-position ()
  6504. "Return the beginning position of the current entry."
  6505. (save-excursion (org-back-to-heading t) (point)))
  6506. (defsubst org-entry-end-position ()
  6507. "Return the end position of the current entry."
  6508. (save-excursion (outline-next-heading) (point)))
  6509. (defun org-cycle-hide-drawers (state &optional exceptions)
  6510. "Re-hide all drawers after a visibility state change.
  6511. When non-nil, optional argument EXCEPTIONS is a list of strings
  6512. specifying which drawers should not be hidden."
  6513. (when (and (derived-mode-p 'org-mode)
  6514. (not (memq state '(overview folded contents))))
  6515. (save-excursion
  6516. (let* ((globalp (memq state '(contents all)))
  6517. (beg (if globalp (point-min) (point)))
  6518. (end (if globalp (point-max)
  6519. (if (eq state 'children)
  6520. (save-excursion (outline-next-heading) (point))
  6521. (org-end-of-subtree t)))))
  6522. (goto-char beg)
  6523. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6524. (unless (member-ignore-case (match-string 1) exceptions)
  6525. (let ((drawer (org-element-at-point)))
  6526. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6527. (org-flag-drawer t drawer)
  6528. ;; Make sure to skip drawer entirely or we might flag
  6529. ;; it another time when matching its ending line with
  6530. ;; `org-drawer-regexp'.
  6531. (goto-char (org-element-property :end drawer))))))))))
  6532. (defun org-flag-drawer (flag &optional element)
  6533. "When FLAG is non-nil, hide the drawer we are at.
  6534. Otherwise make it visible. When optional argument ELEMENT is
  6535. a parsed drawer, as returned by `org-element-at-point', hide or
  6536. show that drawer instead."
  6537. (let ((drawer (or element
  6538. (and (save-excursion
  6539. (beginning-of-line)
  6540. (looking-at-p org-drawer-regexp))
  6541. (org-element-at-point)))))
  6542. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6543. (let ((post (org-element-property :post-affiliated drawer)))
  6544. (save-excursion
  6545. (outline-flag-region
  6546. (progn (goto-char post) (line-end-position))
  6547. (progn (goto-char (org-element-property :end drawer))
  6548. (skip-chars-backward " \r\t\n")
  6549. (line-end-position))
  6550. flag))
  6551. ;; When the drawer is hidden away, make sure point lies in
  6552. ;; a visible part of the buffer.
  6553. (when (and flag (> (line-beginning-position) post))
  6554. (goto-char post))))))
  6555. (defun org-subtree-end-visible-p ()
  6556. "Is the end of the current subtree visible?"
  6557. (pos-visible-in-window-p
  6558. (save-excursion (org-end-of-subtree t) (point))))
  6559. (defun org-first-headline-recenter ()
  6560. "Move cursor to the first headline and recenter the headline."
  6561. (let ((window (get-buffer-window)))
  6562. (when window
  6563. (goto-char (point-min))
  6564. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6565. (set-window-start window (line-beginning-position))))))
  6566. ;;; Saving and restoring visibility
  6567. (defun org-outline-overlay-data (&optional use-markers)
  6568. "Return a list of the locations of all outline overlays.
  6569. These are overlays with the `invisible' property value `outline'.
  6570. The return value is a list of cons cells, with start and stop
  6571. positions for each overlay.
  6572. If USE-MARKERS is set, return the positions as markers."
  6573. (let (beg end)
  6574. (org-with-wide-buffer
  6575. (delq nil
  6576. (mapcar (lambda (o)
  6577. (when (eq (overlay-get o 'invisible) 'outline)
  6578. (setq beg (overlay-start o)
  6579. end (overlay-end o))
  6580. (and beg end (> end beg)
  6581. (if use-markers
  6582. (cons (copy-marker beg)
  6583. (copy-marker end t))
  6584. (cons beg end)))))
  6585. (overlays-in (point-min) (point-max)))))))
  6586. (defun org-set-outline-overlay-data (data)
  6587. "Create visibility overlays for all positions in DATA.
  6588. DATA should have been made by `org-outline-overlay-data'."
  6589. (org-with-wide-buffer
  6590. (outline-show-all)
  6591. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6592. ;;; Folding of blocks
  6593. (defvar-local org-hide-block-overlays nil
  6594. "Overlays hiding blocks.")
  6595. (defun org-block-map (function &optional start end)
  6596. "Call FUNCTION at the head of all source blocks in the current buffer.
  6597. Optional arguments START and END can be used to limit the range."
  6598. (let ((start (or start (point-min)))
  6599. (end (or end (point-max))))
  6600. (save-excursion
  6601. (goto-char start)
  6602. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6603. (save-excursion
  6604. (save-match-data
  6605. (goto-char (match-beginning 0))
  6606. (funcall function)))))))
  6607. (defun org-hide-block-toggle-all ()
  6608. "Toggle the visibility of all blocks in the current buffer."
  6609. (org-block-map 'org-hide-block-toggle))
  6610. (defun org-hide-block-all ()
  6611. "Fold all blocks in the current buffer."
  6612. (interactive)
  6613. (org-show-block-all)
  6614. (org-block-map 'org-hide-block-toggle-maybe))
  6615. (defun org-show-block-all ()
  6616. "Unfold all blocks in the current buffer."
  6617. (interactive)
  6618. (mapc #'delete-overlay org-hide-block-overlays)
  6619. (setq org-hide-block-overlays nil))
  6620. (defun org-hide-block-toggle-maybe ()
  6621. "Toggle visibility of block at point.
  6622. Unlike to `org-hide-block-toggle', this function does not throw
  6623. an error. Return a non-nil value when toggling is successful."
  6624. (interactive)
  6625. (ignore-errors (org-hide-block-toggle)))
  6626. (defun org-hide-block-toggle (&optional force)
  6627. "Toggle the visibility of the current block.
  6628. When optional argument FORCE is `off', make block visible. If it
  6629. is non-nil, hide it unconditionally. Throw an error when not at
  6630. a block. Return a non-nil value when toggling is successful."
  6631. (interactive)
  6632. (let ((element (org-element-at-point)))
  6633. (unless (memq (org-element-type element)
  6634. '(center-block comment-block dynamic-block example-block
  6635. export-block quote-block special-block
  6636. src-block verse-block))
  6637. (user-error "Not at a block"))
  6638. (let* ((start (save-excursion
  6639. (goto-char (org-element-property :post-affiliated element))
  6640. (line-end-position)))
  6641. (end (save-excursion
  6642. (goto-char (org-element-property :end element))
  6643. (skip-chars-backward " \r\t\n")
  6644. (line-end-position)))
  6645. (overlays (overlays-at start)))
  6646. (cond
  6647. ;; Do nothing when not before or at the block opening line or
  6648. ;; at the block closing line.
  6649. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6650. ((and (not (eq force 'off))
  6651. (not (memq t (mapcar
  6652. (lambda (o)
  6653. (eq (overlay-get o 'invisible) 'org-hide-block))
  6654. overlays))))
  6655. (let ((ov (make-overlay start end)))
  6656. (overlay-put ov 'invisible 'org-hide-block)
  6657. ;; Make the block accessible to `isearch'.
  6658. (overlay-put
  6659. ov 'isearch-open-invisible
  6660. (lambda (ov)
  6661. (when (memq ov org-hide-block-overlays)
  6662. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6663. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6664. (delete-overlay ov))))
  6665. (push ov org-hide-block-overlays)
  6666. ;; When the block is hidden away, make sure point is left in
  6667. ;; a visible part of the buffer.
  6668. (when (> (line-beginning-position) start)
  6669. (goto-char start)
  6670. (beginning-of-line))
  6671. ;; Signal successful toggling.
  6672. t))
  6673. ((or (not force) (eq force 'off))
  6674. (dolist (ov overlays t)
  6675. (when (memq ov org-hide-block-overlays)
  6676. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6677. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6678. (delete-overlay ov))))))))
  6679. ;; Remove overlays when changing major mode
  6680. (add-hook 'org-mode-hook
  6681. (lambda () (add-hook 'change-major-mode-hook
  6682. 'org-show-block-all 'append 'local)))
  6683. ;;; Org-goto
  6684. (defvar org-goto-window-configuration nil)
  6685. (defvar org-goto-marker nil)
  6686. (defvar org-goto-map)
  6687. (defun org-goto-map ()
  6688. "Set the keymap `org-goto'."
  6689. (setq org-goto-map
  6690. (let ((map (make-sparse-keymap)))
  6691. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6692. mouse-drag-region universal-argument org-occur)))
  6693. (dolist (cmd cmds)
  6694. (substitute-key-definition cmd cmd map global-map)))
  6695. (suppress-keymap map)
  6696. (org-defkey map "\C-m" 'org-goto-ret)
  6697. (org-defkey map [(return)] 'org-goto-ret)
  6698. (org-defkey map [(left)] 'org-goto-left)
  6699. (org-defkey map [(right)] 'org-goto-right)
  6700. (org-defkey map [(control ?g)] 'org-goto-quit)
  6701. (org-defkey map "\C-i" 'org-cycle)
  6702. (org-defkey map [(tab)] 'org-cycle)
  6703. (org-defkey map [(down)] 'outline-next-visible-heading)
  6704. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6705. (if org-goto-auto-isearch
  6706. (if (fboundp 'define-key-after)
  6707. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6708. nil)
  6709. (org-defkey map "q" 'org-goto-quit)
  6710. (org-defkey map "n" 'outline-next-visible-heading)
  6711. (org-defkey map "p" 'outline-previous-visible-heading)
  6712. (org-defkey map "f" 'outline-forward-same-level)
  6713. (org-defkey map "b" 'outline-backward-same-level)
  6714. (org-defkey map "u" 'outline-up-heading))
  6715. (org-defkey map "/" 'org-occur)
  6716. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6717. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6718. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6719. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6720. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6721. map)))
  6722. (defconst org-goto-help
  6723. "Browse buffer copy, to find location or copy text.%s
  6724. RET=jump to location C-g=quit and return to previous location
  6725. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6726. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6727. (defun org-goto (&optional alternative-interface)
  6728. "Look up a different location in the current file, keeping current visibility.
  6729. When you want look-up or go to a different location in a
  6730. document, the fastest way is often to fold the entire buffer and
  6731. then dive into the tree. This method has the disadvantage, that
  6732. the previous location will be folded, which may not be what you
  6733. want.
  6734. This command works around this by showing a copy of the current
  6735. buffer in an indirect buffer, in overview mode. You can dive
  6736. into the tree in that copy, use org-occur and incremental search
  6737. to find a location. When pressing RET or `Q', the command
  6738. returns to the original buffer in which the visibility is still
  6739. unchanged. After RET it will also jump to the location selected
  6740. in the indirect buffer and expose the headline hierarchy above.
  6741. With a prefix argument, use the alternative interface: e.g., if
  6742. `org-goto-interface' is `outline' use `outline-path-completion'."
  6743. (interactive "P")
  6744. (org-goto-map)
  6745. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6746. (org-refile-use-outline-path t)
  6747. (org-refile-target-verify-function nil)
  6748. (interface
  6749. (if (not alternative-interface)
  6750. org-goto-interface
  6751. (if (eq org-goto-interface 'outline)
  6752. 'outline-path-completion
  6753. 'outline)))
  6754. (org-goto-start-pos (point))
  6755. (selected-point
  6756. (if (eq interface 'outline)
  6757. (car (org-get-location (current-buffer) org-goto-help))
  6758. (let ((pa (org-refile-get-location "Goto")))
  6759. (org-refile-check-position pa)
  6760. (nth 3 pa)))))
  6761. (if selected-point
  6762. (progn
  6763. (org-mark-ring-push org-goto-start-pos)
  6764. (goto-char selected-point)
  6765. (when (or (outline-invisible-p) (org-invisible-p2))
  6766. (org-show-context 'org-goto)))
  6767. (message "Quit"))))
  6768. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6769. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6770. (defvar org-goto-local-auto-isearch-map) ; defined below
  6771. (defun org-get-location (_buf help)
  6772. "Let the user select a location in current buffer.
  6773. This function uses a recursive edit. It returns the selected position
  6774. or nil."
  6775. (org-no-popups
  6776. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6777. (isearch-hide-immediately nil)
  6778. (isearch-search-fun-function
  6779. (lambda () 'org-goto-local-search-headings))
  6780. (org-goto-selected-point org-goto-exit-command))
  6781. (save-excursion
  6782. (save-window-excursion
  6783. (delete-other-windows)
  6784. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6785. (pop-to-buffer-same-window
  6786. (condition-case nil
  6787. (make-indirect-buffer (current-buffer) "*org-goto*")
  6788. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6789. (with-output-to-temp-buffer "*Org Help*"
  6790. (princ (format help (if org-goto-auto-isearch
  6791. " Just type for auto-isearch."
  6792. " n/p/f/b/u to navigate, q to quit."))))
  6793. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6794. (setq buffer-read-only nil)
  6795. (let ((org-startup-truncated t)
  6796. (org-startup-folded nil)
  6797. (org-startup-align-all-tables nil))
  6798. (org-mode)
  6799. (org-overview))
  6800. (setq buffer-read-only t)
  6801. (if (and (boundp 'org-goto-start-pos)
  6802. (integer-or-marker-p org-goto-start-pos))
  6803. (progn (goto-char org-goto-start-pos)
  6804. (when (outline-invisible-p)
  6805. (org-show-set-visibility 'lineage)))
  6806. (goto-char (point-min)))
  6807. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6808. (message "Select location and press RET")
  6809. (use-local-map org-goto-map)
  6810. (recursive-edit)))
  6811. (kill-buffer "*org-goto*")
  6812. (cons org-goto-selected-point org-goto-exit-command))))
  6813. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6814. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6815. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6816. (if (fboundp 'isearch-other-control-char)
  6817. (progn
  6818. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6819. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6820. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6821. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6822. (define-key org-goto-local-auto-isearch-map [return] nil))
  6823. (defun org-goto-local-search-headings (string bound noerror)
  6824. "Search and make sure that any matches are in headlines."
  6825. (catch 'return
  6826. (while (if isearch-forward
  6827. (search-forward string bound noerror)
  6828. (search-backward string bound noerror))
  6829. (when (save-match-data
  6830. (and (save-excursion
  6831. (beginning-of-line)
  6832. (looking-at org-complex-heading-regexp))
  6833. (or (not (match-beginning 5))
  6834. (< (point) (match-beginning 5)))))
  6835. (throw 'return (point))))))
  6836. (defun org-goto-local-auto-isearch ()
  6837. "Start isearch."
  6838. (interactive)
  6839. (goto-char (point-min))
  6840. (let ((keys (this-command-keys)))
  6841. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6842. (isearch-mode t)
  6843. (isearch-process-search-char (string-to-char keys)))))
  6844. (defun org-goto-ret (&optional _arg)
  6845. "Finish `org-goto' by going to the new location."
  6846. (interactive "P")
  6847. (setq org-goto-selected-point (point))
  6848. (setq org-goto-exit-command 'return)
  6849. (throw 'exit nil))
  6850. (defun org-goto-left ()
  6851. "Finish `org-goto' by going to the new location."
  6852. (interactive)
  6853. (if (org-at-heading-p)
  6854. (progn
  6855. (beginning-of-line 1)
  6856. (setq org-goto-selected-point (point)
  6857. org-goto-exit-command 'left)
  6858. (throw 'exit nil))
  6859. (user-error "Not on a heading")))
  6860. (defun org-goto-right ()
  6861. "Finish `org-goto' by going to the new location."
  6862. (interactive)
  6863. (if (org-at-heading-p)
  6864. (progn
  6865. (setq org-goto-selected-point (point)
  6866. org-goto-exit-command 'right)
  6867. (throw 'exit nil))
  6868. (user-error "Not on a heading")))
  6869. (defun org-goto-quit ()
  6870. "Finish `org-goto' without cursor motion."
  6871. (interactive)
  6872. (setq org-goto-selected-point nil)
  6873. (setq org-goto-exit-command 'quit)
  6874. (throw 'exit nil))
  6875. ;;; Indirect buffer display of subtrees
  6876. (defvar org-indirect-dedicated-frame nil
  6877. "This is the frame being used for indirect tree display.")
  6878. (defvar org-last-indirect-buffer nil)
  6879. (defun org-tree-to-indirect-buffer (&optional arg)
  6880. "Create indirect buffer and narrow it to current subtree.
  6881. With a numerical prefix ARG, go up to this level and then take that tree.
  6882. If ARG is negative, go up that many levels.
  6883. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6884. indirect buffer previously made with this command, to avoid proliferation of
  6885. indirect buffers. However, when you call the command with a \
  6886. `\\[universal-argument]' prefix, or
  6887. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6888. so that you can work with several indirect buffers at the same time. If
  6889. `org-indirect-buffer-display' is `dedicated-frame', the \
  6890. `\\[universal-argument]' prefix also
  6891. requests that a new frame be made for the new buffer, so that the dedicated
  6892. frame is not changed."
  6893. (interactive "P")
  6894. (let ((cbuf (current-buffer))
  6895. (cwin (selected-window))
  6896. (pos (point))
  6897. beg end level heading ibuf)
  6898. (save-excursion
  6899. (org-back-to-heading t)
  6900. (when (numberp arg)
  6901. (setq level (org-outline-level))
  6902. (when (< arg 0) (setq arg (+ level arg)))
  6903. (while (> (setq level (org-outline-level)) arg)
  6904. (org-up-heading-safe)))
  6905. (setq beg (point)
  6906. heading (org-get-heading 'no-tags))
  6907. (org-end-of-subtree t t)
  6908. (when (org-at-heading-p) (backward-char 1))
  6909. (setq end (point)))
  6910. (when (and (buffer-live-p org-last-indirect-buffer)
  6911. (not (eq org-indirect-buffer-display 'new-frame))
  6912. (not arg))
  6913. (kill-buffer org-last-indirect-buffer))
  6914. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6915. org-last-indirect-buffer ibuf)
  6916. (cond
  6917. ((or (eq org-indirect-buffer-display 'new-frame)
  6918. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6919. (select-frame (make-frame))
  6920. (delete-other-windows)
  6921. (pop-to-buffer-same-window ibuf)
  6922. (org-set-frame-title heading))
  6923. ((eq org-indirect-buffer-display 'dedicated-frame)
  6924. (raise-frame
  6925. (select-frame (or (and org-indirect-dedicated-frame
  6926. (frame-live-p org-indirect-dedicated-frame)
  6927. org-indirect-dedicated-frame)
  6928. (setq org-indirect-dedicated-frame (make-frame)))))
  6929. (delete-other-windows)
  6930. (pop-to-buffer-same-window ibuf)
  6931. (org-set-frame-title (concat "Indirect: " heading)))
  6932. ((eq org-indirect-buffer-display 'current-window)
  6933. (pop-to-buffer-same-window ibuf))
  6934. ((eq org-indirect-buffer-display 'other-window)
  6935. (pop-to-buffer ibuf))
  6936. (t (error "Invalid value")))
  6937. (narrow-to-region beg end)
  6938. (outline-show-all)
  6939. (goto-char pos)
  6940. (run-hook-with-args 'org-cycle-hook 'all)
  6941. (and (window-live-p cwin) (select-window cwin))))
  6942. (defun org-get-indirect-buffer (&optional buffer heading)
  6943. (setq buffer (or buffer (current-buffer)))
  6944. (let ((n 1) (base (buffer-name buffer)) bname)
  6945. (while (buffer-live-p
  6946. (get-buffer
  6947. (setq bname
  6948. (concat base "-"
  6949. (if heading (concat heading "-" (number-to-string n))
  6950. (number-to-string n))))))
  6951. (setq n (1+ n)))
  6952. (condition-case nil
  6953. (make-indirect-buffer buffer bname 'clone)
  6954. (error (make-indirect-buffer buffer bname)))))
  6955. (defun org-set-frame-title (title)
  6956. "Set the title of the current frame to the string TITLE."
  6957. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6958. ;;;; Structure editing
  6959. ;;; Inserting headlines
  6960. (defun org--line-empty-p (n)
  6961. "Is the Nth next line empty?
  6962. Counts the current line as N = 1 and the previous line as N = 0;
  6963. see `beginning-of-line'."
  6964. (save-excursion
  6965. (and (not (bobp))
  6966. (or (beginning-of-line n) t)
  6967. (save-match-data
  6968. (looking-at "[ \t]*$")))))
  6969. (defun org-previous-line-empty-p ()
  6970. "Is the previous line a blank line?
  6971. When NEXT is non-nil, check the next line instead."
  6972. (org--line-empty-p 0))
  6973. (defun org-next-line-empty-p ()
  6974. "Is the previous line a blank line?
  6975. When NEXT is non-nil, check the next line instead."
  6976. (org--line-empty-p 2))
  6977. (defun org--blank-before-heading-p (&optional parent)
  6978. "Non-nil when an empty line should precede a new heading here.
  6979. When optional argument PARENT is non-nil, consider parent
  6980. headline instead of current one."
  6981. (pcase (assq 'heading org-blank-before-new-entry)
  6982. (`(heading . auto)
  6983. (save-excursion
  6984. (org-with-limited-levels
  6985. (unless (and (org-before-first-heading-p)
  6986. (not (outline-next-heading)))
  6987. (org-back-to-heading t)
  6988. (when parent (org-up-heading-safe))
  6989. (cond ((not (bobp))
  6990. (org-previous-line-empty-p))
  6991. ((outline-next-heading)
  6992. (org-previous-line-empty-p))
  6993. ;; Ignore trailing spaces on last buffer line.
  6994. ((progn (skip-chars-backward " \t") (bolp))
  6995. (org-previous-line-empty-p))
  6996. (t nil))))))
  6997. (`(heading . ,value) value)
  6998. (_ nil)))
  6999. (defun org-insert-heading (&optional arg invisible-ok top)
  7000. "Insert a new heading or an item with the same depth at point.
  7001. If point is at the beginning of a heading, insert a new heading
  7002. or a new headline above the current one. When at the beginning
  7003. of a regular line of text, turn it into a heading.
  7004. If point is in the middle of a line, split it and create a new
  7005. headline with the text in the current line after point (see
  7006. `org-M-RET-may-split-line' on how to modify this behavior). As
  7007. a special case, on a headline, splitting can only happen on the
  7008. title itself. E.g., this excludes breaking stars or tags.
  7009. With a `\\[universal-argument]' prefix, set \
  7010. `org-insert-heading-respect-content' to
  7011. a non-nil value for the duration of the command. This forces the
  7012. insertion of a heading after the current subtree, independently
  7013. on the location of point.
  7014. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  7015. insert the heading at the end of the tree
  7016. above the current heading. For example, if point is within a
  7017. 2nd-level heading, then it will insert a 2nd-level heading at
  7018. the end of the 1st-level parent subtree.
  7019. When INVISIBLE-OK is set, stop at invisible headlines when going
  7020. back. This is important for non-interactive uses of the
  7021. command.
  7022. When optional argument TOP is non-nil, insert a level 1 heading,
  7023. unconditionally."
  7024. (interactive "P")
  7025. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  7026. (level (org-current-level))
  7027. (stars (make-string (if (and level (not top)) level 1) ?*)))
  7028. (cond
  7029. ((or org-insert-heading-respect-content
  7030. (member arg '((4) (16)))
  7031. (and (not invisible-ok)
  7032. (invisible-p (max (1- (point)) (point-min)))))
  7033. ;; Position point at the location of insertion.
  7034. (if (not level) ;before first headline
  7035. (org-with-limited-levels (outline-next-heading))
  7036. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  7037. ;; is nil.
  7038. (org-with-limited-levels (org-back-to-heading invisible-ok))
  7039. (cond ((equal arg '(16))
  7040. (org-up-heading-safe)
  7041. (org-end-of-subtree t t))
  7042. (t
  7043. (org-end-of-subtree t t))))
  7044. (unless (bolp) (insert "\n")) ;ensure final newline
  7045. (unless (and blank? (org-previous-line-empty-p))
  7046. (org-N-empty-lines-before-current (if blank? 1 0)))
  7047. (insert stars " \n")
  7048. (forward-char -1))
  7049. ;; At a headline...
  7050. ((org-at-heading-p)
  7051. (cond ((bolp)
  7052. (when blank? (save-excursion (insert "\n")))
  7053. (save-excursion (insert stars " \n"))
  7054. (unless (and blank? (org-previous-line-empty-p))
  7055. (org-N-empty-lines-before-current (if blank? 1 0)))
  7056. (end-of-line))
  7057. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  7058. (org-match-line org-complex-heading-regexp)
  7059. (org-pos-in-match-range (point) 4))
  7060. ;; Grab the text that should moved to the new headline.
  7061. ;; Preserve tags.
  7062. (let ((split (delete-and-extract-region (point) (match-end 4))))
  7063. (if (looking-at "[ \t]*$") (replace-match "")
  7064. (org-set-tags nil t))
  7065. (end-of-line)
  7066. (when blank? (insert "\n"))
  7067. (insert "\n" stars " ")
  7068. (when (org-string-nw-p split) (insert split))
  7069. (insert "\n")
  7070. (forward-char -1)))
  7071. (t
  7072. (end-of-line)
  7073. (when blank? (insert "\n"))
  7074. (insert "\n" stars " \n")
  7075. (forward-char -1))))
  7076. ;; On regular text, turn line into a headline or split, if
  7077. ;; appropriate.
  7078. ((bolp)
  7079. (insert stars " ")
  7080. (unless (and blank? (org-previous-line-empty-p))
  7081. (org-N-empty-lines-before-current (if blank? 1 0))))
  7082. (t
  7083. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  7084. (end-of-line))
  7085. (insert "\n" stars " ")
  7086. (unless (and blank? (org-previous-line-empty-p))
  7087. (org-N-empty-lines-before-current (if blank? 1 0))))))
  7088. (run-hooks 'org-insert-heading-hook))
  7089. (defun org-N-empty-lines-before-current (N)
  7090. "Make the number of empty lines before current exactly N.
  7091. So this will delete or add empty lines."
  7092. (save-excursion
  7093. (beginning-of-line)
  7094. (let ((p (point)))
  7095. (skip-chars-backward " \r\t\n")
  7096. (unless (bolp) (forward-line))
  7097. (delete-region (point) p))
  7098. (when (> N 0) (insert (make-string N ?\n)))))
  7099. (defun org-get-heading (&optional no-tags no-todo)
  7100. "Return the heading of the current entry, without the stars.
  7101. When NO-TAGS is non-nil, don't include tags.
  7102. When NO-TODO is non-nil, don't include TODO keywords."
  7103. (save-excursion
  7104. (org-back-to-heading t)
  7105. (let ((case-fold-search nil))
  7106. (cond
  7107. ((and no-tags no-todo)
  7108. (looking-at org-complex-heading-regexp)
  7109. ;; Return value has to be a string, but match group 4 is
  7110. ;; optional.
  7111. (or (match-string 4) ""))
  7112. (no-tags
  7113. (looking-at (concat org-outline-regexp
  7114. "\\(.*?\\)"
  7115. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7116. (match-string 1))
  7117. (no-todo
  7118. (looking-at org-todo-line-regexp)
  7119. (match-string 3))
  7120. (t (looking-at org-heading-regexp)
  7121. (match-string 2))))))
  7122. (defvar orgstruct-mode) ; defined below
  7123. (defun org-heading-components ()
  7124. "Return the components of the current heading.
  7125. This is a list with the following elements:
  7126. - the level as an integer
  7127. - the reduced level, different if `org-odd-levels-only' is set.
  7128. - the TODO keyword, or nil
  7129. - the priority character, like ?A, or nil if no priority is given
  7130. - the headline text itself, or the tags string if no headline text
  7131. - the tags string, or nil."
  7132. (save-excursion
  7133. (org-back-to-heading t)
  7134. (when (let (case-fold-search)
  7135. (looking-at
  7136. (if orgstruct-mode
  7137. org-heading-regexp
  7138. org-complex-heading-regexp)))
  7139. (if orgstruct-mode
  7140. (list (length (match-string 1))
  7141. (org-reduced-level (length (match-string 1)))
  7142. nil
  7143. nil
  7144. (match-string 2)
  7145. nil)
  7146. (list (length (match-string 1))
  7147. (org-reduced-level (length (match-string 1)))
  7148. (match-string-no-properties 2)
  7149. (and (match-end 3) (aref (match-string 3) 2))
  7150. (match-string-no-properties 4)
  7151. (match-string-no-properties 5))))))
  7152. (defun org-get-entry ()
  7153. "Get the entry text, after heading, entire subtree."
  7154. (save-excursion
  7155. (org-back-to-heading t)
  7156. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7157. (defun org-edit-headline (&optional heading)
  7158. "Edit the current headline.
  7159. Set it to HEADING when provided."
  7160. (interactive)
  7161. (org-with-wide-buffer
  7162. (org-back-to-heading t)
  7163. (let ((case-fold-search nil))
  7164. (when (looking-at org-complex-heading-regexp)
  7165. (let* ((old (match-string-no-properties 4))
  7166. (new (save-match-data
  7167. (org-trim (or heading (read-string "Edit: " old))))))
  7168. (unless (equal old new)
  7169. (if old (replace-match new t t nil 4)
  7170. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7171. (insert " " new))
  7172. (org-set-tags nil t)
  7173. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7174. (defun org-insert-heading-after-current ()
  7175. "Insert a new heading with same level as current, after current subtree."
  7176. (interactive)
  7177. (org-back-to-heading)
  7178. (org-insert-heading)
  7179. (org-move-subtree-down)
  7180. (end-of-line 1))
  7181. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7182. "Insert heading with `org-insert-heading-respect-content' set to t."
  7183. (interactive)
  7184. (org-insert-heading '(4) invisible-ok))
  7185. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7186. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7187. (interactive)
  7188. (org-insert-todo-heading force-state '(4)))
  7189. (defun org-insert-todo-heading (arg &optional force-heading)
  7190. "Insert a new heading with the same level and TODO state as current heading.
  7191. If the heading has no TODO state, or if the state is DONE, use
  7192. the first state (TODO by default). Also with one prefix arg,
  7193. force first state. With two prefix args, force inserting at the
  7194. end of the parent subtree.
  7195. When called at a plain list item, insert a new item with an
  7196. unchecked check box."
  7197. (interactive "P")
  7198. (when (or force-heading (not (org-insert-item 'checkbox)))
  7199. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7200. force-heading))
  7201. (save-excursion
  7202. (org-back-to-heading)
  7203. (outline-previous-heading)
  7204. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7205. (let* ((new-mark-x
  7206. (if (or (equal arg '(4))
  7207. (not (match-beginning 2))
  7208. (member (match-string 2) org-done-keywords))
  7209. (car org-todo-keywords-1)
  7210. (match-string 2)))
  7211. (new-mark
  7212. (or
  7213. (run-hook-with-args-until-success
  7214. 'org-todo-get-default-hook new-mark-x nil)
  7215. new-mark-x)))
  7216. (beginning-of-line 1)
  7217. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7218. (if org-treat-insert-todo-heading-as-state-change
  7219. (org-todo new-mark)
  7220. (insert new-mark " "))))
  7221. (when org-provide-todo-statistics
  7222. (org-update-parent-todo-statistics))))
  7223. (defun org-insert-subheading (arg)
  7224. "Insert a new subheading and demote it.
  7225. Works for outline headings and for plain lists alike."
  7226. (interactive "P")
  7227. (org-insert-heading arg)
  7228. (cond
  7229. ((org-at-heading-p) (org-do-demote))
  7230. ((org-at-item-p) (org-indent-item))))
  7231. (defun org-insert-todo-subheading (arg)
  7232. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7233. Works for outline headings and for plain lists alike."
  7234. (interactive "P")
  7235. (org-insert-todo-heading arg)
  7236. (cond
  7237. ((org-at-heading-p) (org-do-demote))
  7238. ((org-at-item-p) (org-indent-item))))
  7239. ;;; Promotion and Demotion
  7240. (defvar org-after-demote-entry-hook nil
  7241. "Hook run after an entry has been demoted.
  7242. The cursor will be at the beginning of the entry.
  7243. When a subtree is being demoted, the hook will be called for each node.")
  7244. (defvar org-after-promote-entry-hook nil
  7245. "Hook run after an entry has been promoted.
  7246. The cursor will be at the beginning of the entry.
  7247. When a subtree is being promoted, the hook will be called for each node.")
  7248. (defun org-promote-subtree ()
  7249. "Promote the entire subtree.
  7250. See also `org-promote'."
  7251. (interactive)
  7252. (save-excursion
  7253. (org-with-limited-levels (org-map-tree 'org-promote)))
  7254. (org-fix-position-after-promote))
  7255. (defun org-demote-subtree ()
  7256. "Demote the entire subtree.
  7257. See `org-demote' and `org-promote'."
  7258. (interactive)
  7259. (save-excursion
  7260. (org-with-limited-levels (org-map-tree 'org-demote)))
  7261. (org-fix-position-after-promote))
  7262. (defun org-do-promote ()
  7263. "Promote the current heading higher up the tree.
  7264. If the region is active in `transient-mark-mode', promote all
  7265. headings in the region."
  7266. (interactive)
  7267. (save-excursion
  7268. (if (org-region-active-p)
  7269. (org-map-region 'org-promote (region-beginning) (region-end))
  7270. (org-promote)))
  7271. (org-fix-position-after-promote))
  7272. (defun org-do-demote ()
  7273. "Demote the current heading lower down the tree.
  7274. If the region is active in `transient-mark-mode', demote all
  7275. headings in the region."
  7276. (interactive)
  7277. (save-excursion
  7278. (if (org-region-active-p)
  7279. (org-map-region 'org-demote (region-beginning) (region-end))
  7280. (org-demote)))
  7281. (org-fix-position-after-promote))
  7282. (defun org-fix-position-after-promote ()
  7283. "Fix cursor position and indentation after demoting/promoting."
  7284. (let ((pos (point)))
  7285. (when (save-excursion
  7286. (beginning-of-line)
  7287. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7288. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7289. (cond ((eobp) (insert " "))
  7290. ((eolp) (insert " "))
  7291. ((equal (char-after) ?\s) (forward-char 1))))))
  7292. (defun org-current-level ()
  7293. "Return the level of the current entry, or nil if before the first headline.
  7294. The level is the number of stars at the beginning of the
  7295. headline. Use `org-reduced-level' to remove the effect of
  7296. `org-odd-levels'. Unlike to `org-outline-level', this function
  7297. ignores inlinetasks."
  7298. (let ((level (org-with-limited-levels (org-outline-level))))
  7299. (and (> level 0) level)))
  7300. (defun org-get-previous-line-level ()
  7301. "Return the outline depth of the last headline before the current line.
  7302. Returns 0 for the first headline in the buffer, and nil if before the
  7303. first headline."
  7304. (and (org-current-level)
  7305. (or (and (/= (line-beginning-position) (point-min))
  7306. (save-excursion (beginning-of-line 0) (org-current-level)))
  7307. 0)))
  7308. (defun org-reduced-level (l)
  7309. "Compute the effective level of a heading.
  7310. This takes into account the setting of `org-odd-levels-only'."
  7311. (cond
  7312. ((zerop l) 0)
  7313. (org-odd-levels-only (1+ (floor (/ l 2))))
  7314. (t l)))
  7315. (defun org-level-increment ()
  7316. "Return the number of stars that will be added or removed at a
  7317. time to headlines when structure editing, based on the value of
  7318. `org-odd-levels-only'."
  7319. (if org-odd-levels-only 2 1))
  7320. (defun org-get-valid-level (level &optional change)
  7321. "Rectify a level change under the influence of `org-odd-levels-only'
  7322. LEVEL is a current level, CHANGE is by how much the level should be
  7323. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7324. even level numbers will become the next higher odd number."
  7325. (if org-odd-levels-only
  7326. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7327. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7328. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7329. (max 1 (+ level (or change 0)))))
  7330. (defun org-promote ()
  7331. "Promote the current heading higher up the tree."
  7332. (org-with-wide-buffer
  7333. (org-back-to-heading t)
  7334. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7335. after-change-functions))
  7336. (level (save-match-data (funcall outline-level)))
  7337. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7338. (diff (abs (- level (length up-head) -1))))
  7339. (cond
  7340. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7341. (replace-match "# " nil t))
  7342. ((= level 1)
  7343. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7344. (t (replace-match up-head nil t)))
  7345. (unless (= level 1)
  7346. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7347. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7348. (run-hooks 'org-after-promote-entry-hook))))
  7349. (defun org-demote ()
  7350. "Demote the current heading lower down the tree."
  7351. (org-with-wide-buffer
  7352. (org-back-to-heading t)
  7353. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7354. after-change-functions))
  7355. (level (save-match-data (funcall outline-level)))
  7356. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7357. (diff (abs (- level (length down-head) -1))))
  7358. (replace-match down-head nil t)
  7359. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7360. (when org-adapt-indentation (org-fixup-indentation diff))
  7361. (run-hooks 'org-after-demote-entry-hook))))
  7362. (defun org-cycle-level ()
  7363. "Cycle the level of an empty headline through possible states.
  7364. This goes first to child, then to parent, level, then up the hierarchy.
  7365. After top level, it switches back to sibling level."
  7366. (interactive)
  7367. (let ((org-adapt-indentation nil))
  7368. (when (org-point-at-end-of-empty-headline)
  7369. (setq this-command 'org-cycle-level) ; Only needed for caching
  7370. (let ((cur-level (org-current-level))
  7371. (prev-level (org-get-previous-line-level)))
  7372. (cond
  7373. ;; If first headline in file, promote to top-level.
  7374. ((= prev-level 0)
  7375. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7376. do (org-do-promote)))
  7377. ;; If same level as prev, demote one.
  7378. ((= prev-level cur-level)
  7379. (org-do-demote))
  7380. ;; If parent is top-level, promote to top level if not already.
  7381. ((= prev-level 1)
  7382. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7383. do (org-do-promote)))
  7384. ;; If top-level, return to prev-level.
  7385. ((= cur-level 1)
  7386. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7387. do (org-do-demote)))
  7388. ;; If less than prev-level, promote one.
  7389. ((< cur-level prev-level)
  7390. (org-do-promote))
  7391. ;; If deeper than prev-level, promote until higher than
  7392. ;; prev-level.
  7393. ((> cur-level prev-level)
  7394. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7395. do (org-do-promote))))
  7396. t))))
  7397. (defun org-map-tree (fun)
  7398. "Call FUN for every heading underneath the current one."
  7399. (org-back-to-heading t)
  7400. (let ((level (funcall outline-level)))
  7401. (save-excursion
  7402. (funcall fun)
  7403. (while (and (progn
  7404. (outline-next-heading)
  7405. (> (funcall outline-level) level))
  7406. (not (eobp)))
  7407. (funcall fun)))))
  7408. (defun org-map-region (fun beg end)
  7409. "Call FUN for every heading between BEG and END."
  7410. (let ((org-ignore-region t))
  7411. (save-excursion
  7412. (setq end (copy-marker end))
  7413. (goto-char beg)
  7414. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7415. (< (point) end))
  7416. (funcall fun))
  7417. (while (and (progn
  7418. (outline-next-heading)
  7419. (< (point) end))
  7420. (not (eobp)))
  7421. (funcall fun)))))
  7422. (defun org-fixup-indentation (diff)
  7423. "Change the indentation in the current entry by DIFF.
  7424. DIFF is an integer. Indentation is done according to the
  7425. following rules:
  7426. - Planning information and property drawers are always indented
  7427. according to the new level of the headline;
  7428. - Footnote definitions and their contents are ignored;
  7429. - Inlinetasks' boundaries are not shifted;
  7430. - Empty lines are ignored;
  7431. - Other lines' indentation are shifted by DIFF columns, unless
  7432. it would introduce a structural change in the document, in
  7433. which case no shifting is done at all.
  7434. Assume point is at a heading or an inlinetask beginning."
  7435. (org-with-wide-buffer
  7436. (narrow-to-region (line-beginning-position)
  7437. (save-excursion
  7438. (if (org-with-limited-levels (org-at-heading-p))
  7439. (org-with-limited-levels (outline-next-heading))
  7440. (org-inlinetask-goto-end))
  7441. (point)))
  7442. (forward-line)
  7443. ;; Indent properly planning info and property drawer.
  7444. (when (looking-at-p org-planning-line-re)
  7445. (org-indent-line)
  7446. (forward-line))
  7447. (when (looking-at org-property-drawer-re)
  7448. (goto-char (match-end 0))
  7449. (forward-line)
  7450. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7451. (catch 'no-shift
  7452. (when (zerop diff) (throw 'no-shift nil))
  7453. ;; If DIFF is negative, first check if a shift is possible at all
  7454. ;; (e.g., it doesn't break structure). This can only happen if
  7455. ;; some contents are not properly indented.
  7456. (let ((case-fold-search t))
  7457. (when (< diff 0)
  7458. (let ((diff (- diff))
  7459. (forbidden-re (concat org-outline-regexp
  7460. "\\|"
  7461. (substring org-footnote-definition-re 1))))
  7462. (save-excursion
  7463. (while (not (eobp))
  7464. (cond
  7465. ((looking-at-p "[ \t]*$") (forward-line))
  7466. ((and (looking-at-p org-footnote-definition-re)
  7467. (let ((e (org-element-at-point)))
  7468. (and (eq (org-element-type e) 'footnote-definition)
  7469. (goto-char (org-element-property :end e))))))
  7470. ((looking-at-p org-outline-regexp) (forward-line))
  7471. ;; Give up if shifting would move before column 0 or
  7472. ;; if it would introduce a headline or a footnote
  7473. ;; definition.
  7474. (t
  7475. (skip-chars-forward " \t")
  7476. (let ((ind (current-column)))
  7477. (when (or (< ind diff)
  7478. (and (= ind diff) (looking-at-p forbidden-re)))
  7479. (throw 'no-shift nil)))
  7480. ;; Ignore contents of example blocks and source
  7481. ;; blocks if their indentation is meant to be
  7482. ;; preserved. Jump to block's closing line.
  7483. (beginning-of-line)
  7484. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7485. (let ((e (org-element-at-point)))
  7486. (and (memq (org-element-type e)
  7487. '(example-block src-block))
  7488. (or org-src-preserve-indentation
  7489. (org-element-property :preserve-indent e))
  7490. (goto-char (org-element-property :end e))
  7491. (progn (skip-chars-backward " \r\t\n")
  7492. (beginning-of-line)
  7493. t))))
  7494. (forward-line))))))))
  7495. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7496. ;; by DIFF. Also skip contents of source or example blocks
  7497. ;; when indentation is meant to be preserved.
  7498. (while (not (eobp))
  7499. (cond
  7500. ((and (looking-at-p org-footnote-definition-re)
  7501. (let ((e (org-element-at-point)))
  7502. (and (eq (org-element-type e) 'footnote-definition)
  7503. (goto-char (org-element-property :end e))))))
  7504. ((looking-at-p org-outline-regexp) (forward-line))
  7505. ((looking-at-p "[ \t]*$") (forward-line))
  7506. (t
  7507. (indent-line-to (+ (org-get-indentation) diff))
  7508. (beginning-of-line)
  7509. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7510. (let ((e (org-element-at-point)))
  7511. (and (memq (org-element-type e)
  7512. '(example-block src-block))
  7513. (or org-src-preserve-indentation
  7514. (org-element-property :preserve-indent e))
  7515. (goto-char (org-element-property :end e))
  7516. (progn (skip-chars-backward " \r\t\n")
  7517. (beginning-of-line)
  7518. t))))
  7519. (forward-line)))))))))
  7520. (defun org-convert-to-odd-levels ()
  7521. "Convert an Org file with all levels allowed to one with odd levels.
  7522. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7523. level 5 etc."
  7524. (interactive)
  7525. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7526. (let ((outline-level 'org-outline-level)
  7527. (org-odd-levels-only nil) n)
  7528. (save-excursion
  7529. (goto-char (point-min))
  7530. (while (re-search-forward "^\\*\\*+ " nil t)
  7531. (setq n (- (length (match-string 0)) 2))
  7532. (while (>= (setq n (1- n)) 0)
  7533. (org-demote))
  7534. (end-of-line 1))))))
  7535. (defun org-convert-to-oddeven-levels ()
  7536. "Convert an Org file with only odd levels to one with odd/even levels.
  7537. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7538. file contains a section with an even level, conversion would
  7539. destroy the structure of the file. An error is signaled in this
  7540. case."
  7541. (interactive)
  7542. (goto-char (point-min))
  7543. ;; First check if there are no even levels
  7544. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7545. (org-show-set-visibility 'canonical)
  7546. (error "Not all levels are odd in this file. Conversion not possible"))
  7547. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7548. (let ((outline-regexp org-outline-regexp)
  7549. (outline-level 'org-outline-level)
  7550. (org-odd-levels-only nil) n)
  7551. (save-excursion
  7552. (goto-char (point-min))
  7553. (while (re-search-forward "^\\*\\*+ " nil t)
  7554. (setq n (/ (1- (length (match-string 0))) 2))
  7555. (while (>= (setq n (1- n)) 0)
  7556. (org-promote))
  7557. (end-of-line 1))))))
  7558. (defun org-tr-level (n)
  7559. "Make N odd if required."
  7560. (if org-odd-levels-only (1+ (/ n 2)) n))
  7561. ;;; Vertical tree motion, cutting and pasting of subtrees
  7562. (defun org-move-subtree-up (&optional arg)
  7563. "Move the current subtree up past ARG headlines of the same level."
  7564. (interactive "p")
  7565. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7566. (defun org-move-subtree-down (&optional arg)
  7567. "Move the current subtree down past ARG headlines of the same level."
  7568. (interactive "p")
  7569. (setq arg (prefix-numeric-value arg))
  7570. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7571. 'org-get-last-sibling))
  7572. (ins-point (make-marker))
  7573. (cnt (abs arg))
  7574. (col (current-column))
  7575. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7576. ;; Select the tree
  7577. (org-back-to-heading)
  7578. (setq beg0 (point))
  7579. (save-excursion
  7580. (setq ne-beg (org-back-over-empty-lines))
  7581. (setq beg (point)))
  7582. (save-match-data
  7583. (save-excursion (outline-end-of-heading)
  7584. (setq folded (outline-invisible-p)))
  7585. (progn (org-end-of-subtree nil t)
  7586. (unless (eobp) (backward-char))))
  7587. (outline-next-heading)
  7588. (setq ne-end (org-back-over-empty-lines))
  7589. (setq end (point))
  7590. (goto-char beg0)
  7591. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7592. ;; include less whitespace
  7593. (save-excursion
  7594. (goto-char beg)
  7595. (forward-line (- ne-beg ne-end))
  7596. (setq beg (point))))
  7597. ;; Find insertion point, with error handling
  7598. (while (> cnt 0)
  7599. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7600. (progn (goto-char beg0)
  7601. (user-error "Cannot move past superior level or buffer limit")))
  7602. (setq cnt (1- cnt)))
  7603. (when (> arg 0)
  7604. ;; Moving forward - still need to move over subtree
  7605. (org-end-of-subtree t t)
  7606. (save-excursion
  7607. (org-back-over-empty-lines)
  7608. (or (bolp) (newline))))
  7609. (setq ne-ins (org-back-over-empty-lines))
  7610. (move-marker ins-point (point))
  7611. (setq txt (buffer-substring beg end))
  7612. (org-save-markers-in-region beg end)
  7613. (delete-region beg end)
  7614. (org-remove-empty-overlays-at beg)
  7615. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7616. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7617. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7618. (let ((bbb (point)))
  7619. (insert-before-markers txt)
  7620. (org-reinstall-markers-in-region bbb)
  7621. (move-marker ins-point bbb))
  7622. (or (bolp) (insert "\n"))
  7623. (setq ins-end (point))
  7624. (goto-char ins-point)
  7625. (org-skip-whitespace)
  7626. (when (and (< arg 0)
  7627. (org-first-sibling-p)
  7628. (> ne-ins ne-beg))
  7629. ;; Move whitespace back to beginning
  7630. (save-excursion
  7631. (goto-char ins-end)
  7632. (let ((kill-whole-line t))
  7633. (kill-line (- ne-ins ne-beg)) (point)))
  7634. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7635. (move-marker ins-point nil)
  7636. (if folded
  7637. (outline-hide-subtree)
  7638. (org-show-entry)
  7639. (org-show-children)
  7640. (org-cycle-hide-drawers 'children))
  7641. (org-clean-visibility-after-subtree-move)
  7642. ;; move back to the initial column we were at
  7643. (move-to-column col)))
  7644. (defvar org-subtree-clip ""
  7645. "Clipboard for cut and paste of subtrees.
  7646. This is actually only a copy of the kill, because we use the normal kill
  7647. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7648. (defvar org-subtree-clip-folded nil
  7649. "Was the last copied subtree folded?
  7650. This is used to fold the tree back after pasting.")
  7651. (defun org-cut-subtree (&optional n)
  7652. "Cut the current subtree into the clipboard.
  7653. With prefix arg N, cut this many sequential subtrees.
  7654. This is a short-hand for marking the subtree and then cutting it."
  7655. (interactive "p")
  7656. (org-copy-subtree n 'cut))
  7657. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7658. "Copy the current subtree it in the clipboard.
  7659. With prefix arg N, copy this many sequential subtrees.
  7660. This is a short-hand for marking the subtree and then copying it.
  7661. If CUT is non-nil, actually cut the subtree.
  7662. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7663. of some markers in the region, even if CUT is non-nil. This is
  7664. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7665. (interactive "p")
  7666. (let (beg end folded (beg0 (point)))
  7667. (if (called-interactively-p 'any)
  7668. (org-back-to-heading nil) ; take what looks like a subtree
  7669. (org-back-to-heading t)) ; take what is really there
  7670. (setq beg (point))
  7671. (skip-chars-forward " \t\r\n")
  7672. (save-match-data
  7673. (if nosubtrees
  7674. (outline-next-heading)
  7675. (save-excursion (outline-end-of-heading)
  7676. (setq folded (outline-invisible-p)))
  7677. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7678. (org-end-of-subtree t t)))
  7679. ;; Include the end of an inlinetask
  7680. (when (and (featurep 'org-inlinetask)
  7681. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7682. "END[ \t]*$")))
  7683. (end-of-line))
  7684. (setq end (point))
  7685. (goto-char beg0)
  7686. (when (> end beg)
  7687. (setq org-subtree-clip-folded folded)
  7688. (when (or cut force-store-markers)
  7689. (org-save-markers-in-region beg end))
  7690. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7691. (setq org-subtree-clip (current-kill 0))
  7692. (message "%s: Subtree(s) with %d characters"
  7693. (if cut "Cut" "Copied")
  7694. (length org-subtree-clip)))))
  7695. (defun org-paste-subtree (&optional level tree for-yank remove)
  7696. "Paste the clipboard as a subtree, with modification of headline level.
  7697. The entire subtree is promoted or demoted in order to match a new headline
  7698. level.
  7699. If the cursor is at the beginning of a headline, the same level as
  7700. that headline is used to paste the tree.
  7701. If not, the new level is derived from the *visible* headings
  7702. before and after the insertion point, and taken to be the inferior headline
  7703. level of the two. So if the previous visible heading is level 3 and the
  7704. next is level 4 (or vice versa), level 4 will be used for insertion.
  7705. This makes sure that the subtree remains an independent subtree and does
  7706. not swallow low level entries.
  7707. You can also force a different level, either by using a numeric prefix
  7708. argument, or by inserting the heading marker by hand. For example, if the
  7709. cursor is after \"*****\", then the tree will be shifted to level 5.
  7710. If optional TREE is given, use this text instead of the kill ring.
  7711. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7712. move back over whitespace before inserting, and move point to the end of
  7713. the inserted text when done.
  7714. When REMOVE is non-nil, remove the subtree from the clipboard."
  7715. (interactive "P")
  7716. (setq tree (or tree (and kill-ring (current-kill 0))))
  7717. (unless (org-kill-is-subtree-p tree)
  7718. (user-error "%s"
  7719. (substitute-command-keys
  7720. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7721. (org-with-limited-levels
  7722. (let* ((visp (not (outline-invisible-p)))
  7723. (txt tree)
  7724. (^re_ "\\(\\*+\\)[ \t]*")
  7725. (old-level (if (string-match org-outline-regexp-bol txt)
  7726. (- (match-end 0) (match-beginning 0) 1)
  7727. -1))
  7728. (force-level (cond (level (prefix-numeric-value level))
  7729. ((and (looking-at "[ \t]*$")
  7730. (string-match
  7731. "^\\*+$" (buffer-substring
  7732. (point-at-bol) (point))))
  7733. (- (match-end 0) (match-beginning 0)))
  7734. ((and (bolp)
  7735. (looking-at org-outline-regexp))
  7736. (- (match-end 0) (point) 1))))
  7737. (previous-level (save-excursion
  7738. (condition-case nil
  7739. (progn
  7740. (outline-previous-visible-heading 1)
  7741. (if (looking-at ^re_)
  7742. (- (match-end 0) (match-beginning 0) 1)
  7743. 1))
  7744. (error 1))))
  7745. (next-level (save-excursion
  7746. (condition-case nil
  7747. (progn
  7748. (or (looking-at org-outline-regexp)
  7749. (outline-next-visible-heading 1))
  7750. (if (looking-at ^re_)
  7751. (- (match-end 0) (match-beginning 0) 1)
  7752. 1))
  7753. (error 1))))
  7754. (new-level (or force-level (max previous-level next-level)))
  7755. (shift (if (or (= old-level -1)
  7756. (= new-level -1)
  7757. (= old-level new-level))
  7758. 0
  7759. (- new-level old-level)))
  7760. (delta (if (> shift 0) -1 1))
  7761. (func (if (> shift 0) 'org-demote 'org-promote))
  7762. (org-odd-levels-only nil)
  7763. beg end newend)
  7764. ;; Remove the forced level indicator
  7765. (when force-level
  7766. (delete-region (point-at-bol) (point)))
  7767. ;; Paste
  7768. (beginning-of-line (if (bolp) 1 2))
  7769. (setq beg (point))
  7770. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7771. (insert-before-markers txt)
  7772. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7773. (setq newend (point))
  7774. (org-reinstall-markers-in-region beg)
  7775. (setq end (point))
  7776. (goto-char beg)
  7777. (skip-chars-forward " \t\n\r")
  7778. (setq beg (point))
  7779. (when (and (outline-invisible-p) visp)
  7780. (save-excursion (outline-show-heading)))
  7781. ;; Shift if necessary
  7782. (unless (= shift 0)
  7783. (save-restriction
  7784. (narrow-to-region beg end)
  7785. (while (not (= shift 0))
  7786. (org-map-region func (point-min) (point-max))
  7787. (setq shift (+ delta shift)))
  7788. (goto-char (point-min))
  7789. (setq newend (point-max))))
  7790. (when (or (called-interactively-p 'interactive) for-yank)
  7791. (message "Clipboard pasted as level %d subtree" new-level))
  7792. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7793. kill-ring
  7794. (eq org-subtree-clip (current-kill 0))
  7795. org-subtree-clip-folded)
  7796. ;; The tree was folded before it was killed/copied
  7797. (outline-hide-subtree))
  7798. (and for-yank (goto-char newend))
  7799. (and remove (setq kill-ring (cdr kill-ring))))))
  7800. (defun org-kill-is-subtree-p (&optional txt)
  7801. "Check if the current kill is an outline subtree, or a set of trees.
  7802. Returns nil if kill does not start with a headline, or if the first
  7803. headline level is not the largest headline level in the tree.
  7804. So this will actually accept several entries of equal levels as well,
  7805. which is OK for `org-paste-subtree'.
  7806. If optional TXT is given, check this string instead of the current kill."
  7807. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7808. (re (org-get-limited-outline-regexp))
  7809. (^re (concat "^" re))
  7810. (start-level (and kill
  7811. (string-match
  7812. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7813. kill)
  7814. (- (match-end 2) (match-beginning 2) 1)))
  7815. (start (1+ (or (match-beginning 2) -1))))
  7816. (if (not start-level)
  7817. (progn
  7818. nil) ;; does not even start with a heading
  7819. (catch 'exit
  7820. (while (setq start (string-match ^re kill (1+ start)))
  7821. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7822. (throw 'exit nil)))
  7823. t))))
  7824. (defvar org-markers-to-move nil
  7825. "Markers that should be moved with a cut-and-paste operation.
  7826. Those markers are stored together with their positions relative to
  7827. the start of the region.")
  7828. (defun org-save-markers-in-region (beg end)
  7829. "Check markers in region.
  7830. If these markers are between BEG and END, record their position relative
  7831. to BEG, so that after moving the block of text, we can put the markers back
  7832. into place.
  7833. This function gets called just before an entry or tree gets cut from the
  7834. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7835. called immediately, to move the markers with the entries."
  7836. (setq org-markers-to-move nil)
  7837. (when (featurep 'org-clock)
  7838. (org-clock-save-markers-for-cut-and-paste beg end))
  7839. (when (featurep 'org-agenda)
  7840. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7841. (defun org-check-and-save-marker (marker beg end)
  7842. "Check if MARKER is between BEG and END.
  7843. If yes, remember the marker and the distance to BEG."
  7844. (when (and (marker-buffer marker)
  7845. (equal (marker-buffer marker) (current-buffer))
  7846. (>= marker beg) (< marker end))
  7847. (push (cons marker (- marker beg)) org-markers-to-move)))
  7848. (defun org-reinstall-markers-in-region (beg)
  7849. "Move all remembered markers to their position relative to BEG."
  7850. (dolist (x org-markers-to-move)
  7851. (move-marker (car x) (+ beg (cdr x))))
  7852. (setq org-markers-to-move nil))
  7853. (defun org-narrow-to-subtree ()
  7854. "Narrow buffer to the current subtree."
  7855. (interactive)
  7856. (save-excursion
  7857. (save-match-data
  7858. (org-with-limited-levels
  7859. (narrow-to-region
  7860. (progn (org-back-to-heading t) (point))
  7861. (progn (org-end-of-subtree t t)
  7862. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7863. (point)))))))
  7864. (defun org-narrow-to-block ()
  7865. "Narrow buffer to the current block."
  7866. (interactive)
  7867. (let* ((case-fold-search t)
  7868. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7869. "^[ \t]*#\\+end_.*")))
  7870. (if blockp
  7871. (narrow-to-region (car blockp) (cdr blockp))
  7872. (user-error "Not in a block"))))
  7873. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7874. "Clone the task (subtree) at point N times.
  7875. The clones will be inserted as siblings.
  7876. In interactive use, the user will be prompted for the number of
  7877. clones to be produced. If the entry has a timestamp, the user
  7878. will also be prompted for a time shift, which may be a repeater
  7879. as used in time stamps, for example `+3d'. To disable this,
  7880. you can call the function with a universal prefix argument.
  7881. When a valid repeater is given and the entry contains any time
  7882. stamps, the clones will become a sequence in time, with time
  7883. stamps in the subtree shifted for each clone produced. If SHIFT
  7884. is nil or the empty string, time stamps will be left alone. The
  7885. ID property of the original subtree is removed.
  7886. In each clone, all the CLOCK entries will be removed. This
  7887. prevents Org from considering that the clocked times overlap.
  7888. If the original subtree did contain time stamps with a repeater,
  7889. the following will happen:
  7890. - the repeater will be removed in each clone
  7891. - an additional clone will be produced, with the current, unshifted
  7892. date(s) in the entry.
  7893. - the original entry will be placed *after* all the clones, with
  7894. repeater intact.
  7895. - the start days in the repeater in the original entry will be shifted
  7896. to past the last clone.
  7897. In this way you can spell out a number of instances of a repeating task,
  7898. and still retain the repeater to cover future instances of the task.
  7899. As described above, N+1 clones are produced when the original
  7900. subtree has a repeater. Setting N to 0, then, can be used to
  7901. remove the repeater from a subtree and create a shifted clone
  7902. with the original repeater."
  7903. (interactive "nNumber of clones to produce: ")
  7904. (let ((shift
  7905. (or shift
  7906. (if (and (not (equal current-prefix-arg '(4)))
  7907. (save-excursion
  7908. (re-search-forward org-ts-regexp-both
  7909. (save-excursion
  7910. (org-end-of-subtree t)
  7911. (point)) t)))
  7912. (read-from-minibuffer
  7913. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7914. ""))) ;; No time shift
  7915. (n-no-remove -1)
  7916. (drawer-re org-drawer-regexp)
  7917. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7918. beg end template task idprop
  7919. shift-n shift-what doshift nmin nmax)
  7920. (unless (wholenump n)
  7921. (user-error "Invalid number of replications %s" n))
  7922. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7923. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7924. shift)))
  7925. (user-error "Invalid shift specification %s" shift))
  7926. (when doshift
  7927. (setq shift-n (string-to-number (match-string 1 shift))
  7928. shift-what (cdr (assoc (match-string 2 shift)
  7929. '(("d" . day) ("w" . week)
  7930. ("m" . month) ("y" . year))))))
  7931. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7932. (setq nmin 1 nmax n)
  7933. (org-back-to-heading t)
  7934. (setq beg (point))
  7935. (setq idprop (org-entry-get nil "ID"))
  7936. (org-end-of-subtree t t)
  7937. (or (bolp) (insert "\n"))
  7938. (setq end (point))
  7939. (setq template (buffer-substring beg end))
  7940. (when (and doshift
  7941. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  7942. (delete-region beg end)
  7943. (setq end beg)
  7944. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  7945. (goto-char end)
  7946. (cl-loop for n from nmin to nmax do
  7947. ;; prepare clone
  7948. (with-temp-buffer
  7949. (insert template)
  7950. (org-mode)
  7951. (goto-char (point-min))
  7952. (org-show-subtree)
  7953. (and idprop (if org-clone-delete-id
  7954. (org-entry-delete nil "ID")
  7955. (org-id-get-create t)))
  7956. (unless (= n 0)
  7957. (while (re-search-forward org-clock-re nil t)
  7958. (kill-whole-line))
  7959. (goto-char (point-min))
  7960. (while (re-search-forward drawer-re nil t)
  7961. (org-remove-empty-drawer-at (point))))
  7962. (goto-char (point-min))
  7963. (when doshift
  7964. (while (re-search-forward org-ts-regexp-both nil t)
  7965. (org-timestamp-change (* n shift-n) shift-what))
  7966. (unless (= n n-no-remove)
  7967. (goto-char (point-min))
  7968. (while (re-search-forward org-ts-regexp nil t)
  7969. (save-excursion
  7970. (goto-char (match-beginning 0))
  7971. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7972. (delete-region (match-beginning 1) (match-end 1)))))))
  7973. (setq task (buffer-string)))
  7974. (insert task))
  7975. (goto-char beg)))
  7976. ;;; Outline Sorting
  7977. (defun org-sort (with-case)
  7978. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7979. Optional argument WITH-CASE means sort case-sensitively."
  7980. (interactive "P")
  7981. (cond
  7982. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7983. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7984. (t
  7985. (org-call-with-arg 'org-sort-entries with-case))))
  7986. (defun org-sort-remove-invisible (s)
  7987. "Remove invisible part of links and emphasis markers from string S."
  7988. (remove-text-properties 0 (length s) org-rm-props s)
  7989. (replace-regexp-in-string
  7990. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7991. (replace-regexp-in-string
  7992. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7993. (org-link-display-format s)
  7994. t t) t t))
  7995. (defvar org-priority-regexp) ; defined later in the file
  7996. (defvar org-after-sorting-entries-or-items-hook nil
  7997. "Hook that is run after a bunch of entries or items have been sorted.
  7998. When children are sorted, the cursor is in the parent line when this
  7999. hook gets called. When a region or a plain list is sorted, the cursor
  8000. will be in the first entry of the sorted region/list.")
  8001. (defun org-sort-entries
  8002. (&optional with-case sorting-type getkey-func compare-func property)
  8003. "Sort entries on a certain level of an outline tree.
  8004. If there is an active region, the entries in the region are sorted.
  8005. Else, if the cursor is before the first entry, sort the top-level items.
  8006. Else, the children of the entry at point are sorted.
  8007. Sorting can be alphabetically, numerically, by date/time as given by
  8008. a time stamp, by a property, by priority order, or by a custom function.
  8009. The command prompts for the sorting type unless it has been given to the
  8010. function through the SORTING-TYPE argument, which needs to be a character,
  8011. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8012. the precise meaning of each character:
  8013. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8014. c By creation time, which is assumed to be the first inactive time stamp
  8015. at the beginning of a line.
  8016. d By deadline date/time.
  8017. k By clocking time.
  8018. n Numerically, by converting the beginning of the entry/item to a number.
  8019. o By order of TODO keywords.
  8020. p By priority according to the cookie.
  8021. r By the value of a property.
  8022. s By scheduled date/time.
  8023. t By date/time, either the first active time stamp in the entry, or, if
  8024. none exist, by the first inactive one.
  8025. Capital letters will reverse the sort order.
  8026. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8027. called with point at the beginning of the record. It must return either
  8028. a string or a number that should serve as the sorting key for that record.
  8029. Comparing entries ignores case by default. However, with an optional argument
  8030. WITH-CASE, the sorting considers case as well.
  8031. Sorting is done against the visible part of the headlines, it ignores hidden
  8032. links.
  8033. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8034. (interactive "P")
  8035. (let ((case-func (if with-case 'identity 'downcase))
  8036. (cmstr
  8037. ;; The clock marker is lost when using `sort-subr', let's
  8038. ;; store the clocking string.
  8039. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8040. (save-excursion
  8041. (goto-char org-clock-marker)
  8042. (buffer-substring-no-properties (line-beginning-position)
  8043. (point)))))
  8044. start beg end stars re re2
  8045. txt what tmp)
  8046. ;; Find beginning and end of region to sort
  8047. (cond
  8048. ((org-region-active-p)
  8049. ;; we will sort the region
  8050. (setq end (region-end)
  8051. what "region")
  8052. (goto-char (region-beginning))
  8053. (unless (org-at-heading-p) (outline-next-heading))
  8054. (setq start (point)))
  8055. ((or (org-at-heading-p)
  8056. (ignore-errors (progn (org-back-to-heading) t)))
  8057. ;; we will sort the children of the current headline
  8058. (org-back-to-heading)
  8059. (setq start (point)
  8060. end (progn (org-end-of-subtree t t)
  8061. (or (bolp) (insert "\n"))
  8062. (when (>= (org-back-over-empty-lines) 1)
  8063. (forward-line 1))
  8064. (point))
  8065. what "children")
  8066. (goto-char start)
  8067. (outline-show-subtree)
  8068. (outline-next-heading))
  8069. (t
  8070. ;; we will sort the top-level entries in this file
  8071. (goto-char (point-min))
  8072. (or (org-at-heading-p) (outline-next-heading))
  8073. (setq start (point))
  8074. (goto-char (point-max))
  8075. (beginning-of-line 1)
  8076. (when (looking-at ".*?\\S-")
  8077. ;; File ends in a non-white line
  8078. (end-of-line 1)
  8079. (insert "\n"))
  8080. (setq end (point-max))
  8081. (setq what "top-level")
  8082. (goto-char start)
  8083. (outline-show-all)))
  8084. (setq beg (point))
  8085. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8086. (looking-at "\\(\\*+\\)")
  8087. (setq stars (match-string 1)
  8088. re (concat "^" (regexp-quote stars) " +")
  8089. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8090. txt (buffer-substring beg end))
  8091. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8092. (when (and (not (equal stars "*")) (string-match re2 txt))
  8093. (user-error "Region to sort contains a level above the first entry"))
  8094. (unless sorting-type
  8095. (message
  8096. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8097. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8098. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8099. what)
  8100. (setq sorting-type (read-char-exclusive))
  8101. (unless getkey-func
  8102. (and (= (downcase sorting-type) ?f)
  8103. (setq getkey-func
  8104. (completing-read "Sort using function: "
  8105. obarray 'fboundp t nil nil))
  8106. (setq getkey-func (intern getkey-func))))
  8107. (and (= (downcase sorting-type) ?r)
  8108. (not property)
  8109. (setq property
  8110. (completing-read "Property: "
  8111. (mapcar #'list (org-buffer-property-keys t))
  8112. nil t))))
  8113. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8114. (message "Sorting entries...")
  8115. (save-restriction
  8116. (narrow-to-region start end)
  8117. (let ((dcst (downcase sorting-type))
  8118. (case-fold-search nil)
  8119. (now (current-time)))
  8120. (sort-subr
  8121. (/= dcst sorting-type)
  8122. ;; This function moves to the beginning character of the "record" to
  8123. ;; be sorted.
  8124. (lambda nil
  8125. (if (re-search-forward re nil t)
  8126. (goto-char (match-beginning 0))
  8127. (goto-char (point-max))))
  8128. ;; This function moves to the last character of the "record" being
  8129. ;; sorted.
  8130. (lambda nil
  8131. (save-match-data
  8132. (condition-case nil
  8133. (outline-forward-same-level 1)
  8134. (error
  8135. (goto-char (point-max))))))
  8136. ;; This function returns the value that gets sorted against.
  8137. (lambda nil
  8138. (cond
  8139. ((= dcst ?n)
  8140. (if (looking-at org-complex-heading-regexp)
  8141. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8142. nil))
  8143. ((= dcst ?a)
  8144. (if (looking-at org-complex-heading-regexp)
  8145. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8146. nil))
  8147. ((= dcst ?k)
  8148. (or (get-text-property (point) :org-clock-minutes) 0))
  8149. ((= dcst ?t)
  8150. (let ((end (save-excursion (outline-next-heading) (point))))
  8151. (if (or (re-search-forward org-ts-regexp end t)
  8152. (re-search-forward org-ts-regexp-both end t))
  8153. (org-time-string-to-seconds (match-string 0))
  8154. (float-time now))))
  8155. ((= dcst ?c)
  8156. (let ((end (save-excursion (outline-next-heading) (point))))
  8157. (if (re-search-forward
  8158. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8159. end t)
  8160. (org-time-string-to-seconds (match-string 0))
  8161. (float-time now))))
  8162. ((= dcst ?s)
  8163. (let ((end (save-excursion (outline-next-heading) (point))))
  8164. (if (re-search-forward org-scheduled-time-regexp end t)
  8165. (org-time-string-to-seconds (match-string 1))
  8166. (float-time now))))
  8167. ((= dcst ?d)
  8168. (let ((end (save-excursion (outline-next-heading) (point))))
  8169. (if (re-search-forward org-deadline-time-regexp end t)
  8170. (org-time-string-to-seconds (match-string 1))
  8171. (float-time now))))
  8172. ((= dcst ?p)
  8173. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8174. (string-to-char (match-string 2))
  8175. org-default-priority))
  8176. ((= dcst ?r)
  8177. (or (org-entry-get nil property) ""))
  8178. ((= dcst ?o)
  8179. (when (looking-at org-complex-heading-regexp)
  8180. (let* ((m (match-string 2))
  8181. (s (if (member m org-done-keywords) '- '+)))
  8182. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8183. ((= dcst ?f)
  8184. (if getkey-func
  8185. (progn
  8186. (setq tmp (funcall getkey-func))
  8187. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8188. tmp)
  8189. (error "Invalid key function `%s'" getkey-func)))
  8190. (t (error "Invalid sorting type `%c'" sorting-type))))
  8191. nil
  8192. (cond
  8193. ((= dcst ?a) 'string<)
  8194. ((= dcst ?f) compare-func)
  8195. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8196. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8197. ;; Reset the clock marker if needed
  8198. (when cmstr
  8199. (save-excursion
  8200. (goto-char start)
  8201. (search-forward cmstr nil t)
  8202. (move-marker org-clock-marker (point))))
  8203. (message "Sorting entries...done")))
  8204. ;;; The orgstruct minor mode
  8205. ;; Define a minor mode which can be used in other modes in order to
  8206. ;; integrate the Org mode structure editing commands.
  8207. ;; This is really a hack, because the Org mode structure commands use
  8208. ;; keys which normally belong to the major mode. Here is how it
  8209. ;; works: The minor mode defines all the keys necessary to operate the
  8210. ;; structure commands, but wraps the commands into a function which
  8211. ;; tests if the cursor is currently at a headline or a plain list
  8212. ;; item. If that is the case, the structure command is used,
  8213. ;; temporarily setting many Org mode variables like regular
  8214. ;; expressions for filling etc. However, when any of those keys is
  8215. ;; used at a different location, function uses `key-binding' to look
  8216. ;; up if the key has an associated command in another currently active
  8217. ;; keymap (minor modes, major mode, global), and executes that
  8218. ;; command. There might be problems if any of the keys is otherwise
  8219. ;; used as a prefix key.
  8220. (defcustom orgstruct-heading-prefix-regexp ""
  8221. "Regexp that matches the custom prefix of Org headlines in
  8222. orgstruct(++)-mode."
  8223. :group 'org
  8224. :version "24.4"
  8225. :package-version '(Org . "8.3")
  8226. :type 'regexp)
  8227. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8228. (defcustom orgstruct-setup-hook nil
  8229. "Hook run after orgstruct-mode-map is filled."
  8230. :group 'org
  8231. :version "24.4"
  8232. :package-version '(Org . "8.0")
  8233. :type 'hook)
  8234. (defvar orgstruct-initialized nil)
  8235. (defvar org-local-vars nil
  8236. "List of local variables, for use by `orgstruct-mode'.")
  8237. ;;;###autoload
  8238. (define-minor-mode orgstruct-mode
  8239. "Toggle the minor mode `orgstruct-mode'.
  8240. This mode is for using Org mode structure commands in other
  8241. modes. The following keys behave as if Org mode were active, if
  8242. the cursor is on a headline, or on a plain list item (both as
  8243. defined by Org mode)."
  8244. nil " OrgStruct" (make-sparse-keymap)
  8245. (funcall (if orgstruct-mode
  8246. 'add-to-invisibility-spec
  8247. 'remove-from-invisibility-spec)
  8248. '(outline . t))
  8249. (when orgstruct-mode
  8250. (org-load-modules-maybe)
  8251. (unless orgstruct-initialized
  8252. (orgstruct-setup)
  8253. (setq orgstruct-initialized t))))
  8254. ;;;###autoload
  8255. (defun turn-on-orgstruct ()
  8256. "Unconditionally turn on `orgstruct-mode'."
  8257. (orgstruct-mode 1))
  8258. (defvar-local orgstruct-is-++ nil
  8259. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8260. (defvar-local org-fb-vars nil)
  8261. (defun orgstruct++-mode (&optional arg)
  8262. "Toggle `orgstruct-mode', the enhanced version of it.
  8263. In addition to setting orgstruct-mode, this also exports all
  8264. indentation and autofilling variables from Org mode into the
  8265. buffer. It will also recognize item context in multiline items."
  8266. (interactive "P")
  8267. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8268. (if (< arg 1)
  8269. (progn (orgstruct-mode -1)
  8270. (dolist (v org-fb-vars)
  8271. (set (make-local-variable (car v))
  8272. (if (eq (car-safe (cadr v)) 'quote)
  8273. (cl-cadadr v)
  8274. (nth 1 v)))))
  8275. (orgstruct-mode 1)
  8276. (setq org-fb-vars nil)
  8277. (unless org-local-vars
  8278. (setq org-local-vars (org-get-local-variables)))
  8279. (let (var val)
  8280. (dolist (x org-local-vars)
  8281. (when (string-match
  8282. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8283. \\|fill-prefix\\|indent-\\)"
  8284. (symbol-name (car x)))
  8285. (setq var (car x) val (nth 1 x))
  8286. (push (list var `(quote ,(eval var))) org-fb-vars)
  8287. (set (make-local-variable var)
  8288. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8289. (setq-local orgstruct-is-++ t))))
  8290. ;;;###autoload
  8291. (defun turn-on-orgstruct++ ()
  8292. "Unconditionally turn on `orgstruct++-mode'."
  8293. (orgstruct++-mode 1))
  8294. (defun orgstruct-error ()
  8295. "Error when there is no default binding for a structure key."
  8296. (interactive)
  8297. (funcall (if (fboundp 'user-error)
  8298. 'user-error
  8299. 'error)
  8300. "This key has no function outside structure elements"))
  8301. (defun orgstruct-setup ()
  8302. "Setup orgstruct keymap."
  8303. (dolist (cell '((org-demote . t)
  8304. (org-metaleft . t)
  8305. (org-metaright . t)
  8306. (org-promote . t)
  8307. (org-shiftmetaleft . t)
  8308. (org-shiftmetaright . t)
  8309. org-backward-element
  8310. org-backward-heading-same-level
  8311. org-ctrl-c-ret
  8312. org-ctrl-c-minus
  8313. org-ctrl-c-star
  8314. org-cycle
  8315. org-force-cycle-archived
  8316. org-forward-heading-same-level
  8317. org-insert-heading
  8318. org-insert-heading-respect-content
  8319. org-kill-note-or-show-branches
  8320. org-mark-subtree
  8321. org-meta-return
  8322. org-metadown
  8323. org-metaup
  8324. org-narrow-to-subtree
  8325. org-promote-subtree
  8326. org-reveal
  8327. org-shiftdown
  8328. org-shiftleft
  8329. org-shiftmetadown
  8330. org-shiftmetaup
  8331. org-shiftright
  8332. org-shifttab
  8333. org-shifttab
  8334. org-shiftup
  8335. org-show-children
  8336. org-show-subtree
  8337. org-sort
  8338. org-up-element
  8339. outline-demote
  8340. outline-next-visible-heading
  8341. outline-previous-visible-heading
  8342. outline-promote
  8343. outline-up-heading))
  8344. (let ((f (or (car-safe cell) cell))
  8345. (disable-when-heading-prefix (cdr-safe cell)))
  8346. (when (fboundp f)
  8347. (let ((new-bindings))
  8348. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8349. (where-is-internal f outline-mode-map)))
  8350. (push binding new-bindings)
  8351. ;; TODO use local-function-key-map
  8352. (dolist (rep '(("<tab>" . "TAB")
  8353. ("<return>" . "RET")
  8354. ("<escape>" . "ESC")
  8355. ("<delete>" . "DEL")))
  8356. (setq binding (read-kbd-macro
  8357. (let ((case-fold-search))
  8358. (replace-regexp-in-string
  8359. (regexp-quote (cdr rep))
  8360. (car rep)
  8361. (key-description binding)))))
  8362. (cl-pushnew binding new-bindings :test 'equal)))
  8363. (dolist (binding new-bindings)
  8364. (let ((key (lookup-key orgstruct-mode-map binding)))
  8365. (when (or (not key) (numberp key))
  8366. (ignore-errors
  8367. (org-defkey orgstruct-mode-map
  8368. binding
  8369. (orgstruct-make-binding
  8370. f binding disable-when-heading-prefix))))))))))
  8371. (run-hooks 'orgstruct-setup-hook))
  8372. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8373. "Create a function for binding in the structure minor mode.
  8374. FUN is the command to call inside a table. KEY is the key that
  8375. should be checked in for a command to execute outside of tables.
  8376. Non-nil `disable-when-heading-prefix' means to disable the command
  8377. if `orgstruct-heading-prefix-regexp' is not empty."
  8378. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8379. (let ((nname name)
  8380. (i 0))
  8381. (while (fboundp (intern nname))
  8382. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8383. (setq name (intern nname)))
  8384. (eval
  8385. (let ((bindings '((org-heading-regexp
  8386. (concat "^"
  8387. orgstruct-heading-prefix-regexp
  8388. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8389. (org-outline-regexp
  8390. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8391. (org-outline-regexp-bol
  8392. (concat "^" org-outline-regexp))
  8393. (outline-regexp org-outline-regexp)
  8394. (outline-heading-end-regexp "\n")
  8395. (outline-level 'org-outline-level)
  8396. (outline-heading-alist))))
  8397. `(defun ,name (arg)
  8398. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8399. "Outside of structure, run the binding of `"
  8400. (key-description key) "'."
  8401. (when disable-when-heading-prefix
  8402. (concat
  8403. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8404. "back to the default binding due to limitations of Org's implementation of\n"
  8405. "`" (symbol-name fun) "'.")))
  8406. (interactive "p")
  8407. (let* ((disable
  8408. ,(and disable-when-heading-prefix
  8409. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8410. (fallback
  8411. (or disable
  8412. (not
  8413. (let* ,bindings
  8414. (org-context-p 'headline 'item
  8415. ,(when (memq fun
  8416. '(org-insert-heading
  8417. org-insert-heading-respect-content
  8418. org-meta-return))
  8419. '(when orgstruct-is-++
  8420. 'item-body))))))))
  8421. (if fallback
  8422. (let* ((orgstruct-mode)
  8423. (binding
  8424. (let ((key ,key))
  8425. (catch 'exit
  8426. (dolist
  8427. (rep
  8428. '(nil
  8429. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8430. ("<\\([^>]*\\)return>" . "\\1RET")
  8431. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8432. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8433. nil)
  8434. (when rep
  8435. (setq key (read-kbd-macro
  8436. (let ((case-fold-search))
  8437. (replace-regexp-in-string
  8438. (car rep)
  8439. (cdr rep)
  8440. (key-description key))))))
  8441. (when (key-binding key)
  8442. (throw 'exit (key-binding key))))))))
  8443. (if (keymapp binding)
  8444. (org-set-transient-map binding)
  8445. (let ((func (or binding
  8446. (unless disable
  8447. 'orgstruct-error))))
  8448. (when func
  8449. (call-interactively func)))))
  8450. (org-run-like-in-org-mode
  8451. (lambda ()
  8452. (interactive)
  8453. (let* ,bindings
  8454. (call-interactively ',fun)))))))))
  8455. name))
  8456. (defun org-contextualize-keys (alist contexts)
  8457. "Return valid elements in ALIST depending on CONTEXTS.
  8458. `org-agenda-custom-commands' or `org-capture-templates' are the
  8459. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8460. or `org-capture-templates-contexts' are the associated contexts
  8461. definitions."
  8462. (let ((contexts
  8463. ;; normalize contexts
  8464. (mapcar
  8465. (lambda(c) (cond ((listp (cadr c))
  8466. (list (car c) (car c) (nth 1 c)))
  8467. ((string= "" (cadr c))
  8468. (list (car c) (car c) (nth 2 c)))
  8469. (t c)))
  8470. contexts))
  8471. (a alist) r s)
  8472. ;; loop over all commands or templates
  8473. (dolist (c a)
  8474. (let (vrules repl)
  8475. (cond
  8476. ((not (assoc (car c) contexts))
  8477. (push c r))
  8478. ((and (assoc (car c) contexts)
  8479. (setq vrules (org-contextualize-validate-key
  8480. (car c) contexts)))
  8481. (mapc (lambda (vr)
  8482. (unless (equal (car vr) (cadr vr))
  8483. (setq repl vr)))
  8484. vrules)
  8485. (if (not repl) (push c r)
  8486. (push (cadr repl) s)
  8487. (push
  8488. (cons (car c)
  8489. (cdr (or (assoc (cadr repl) alist)
  8490. (error "Undefined key `%s' as contextual replacement for `%s'"
  8491. (cadr repl) (car c)))))
  8492. r))))))
  8493. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8494. (delq
  8495. nil
  8496. (delete-dups
  8497. (mapcar (lambda (x)
  8498. (let ((tpl (car x)))
  8499. (unless (delq
  8500. nil
  8501. (mapcar (lambda (y)
  8502. (equal y tpl))
  8503. s))
  8504. x)))
  8505. (reverse r))))))
  8506. (defun org-contextualize-validate-key (key contexts)
  8507. "Check CONTEXTS for agenda or capture KEY."
  8508. (let (res)
  8509. (dolist (r contexts)
  8510. (dolist (rr (car (last r)))
  8511. (when
  8512. (and (equal key (car r))
  8513. (if (functionp rr) (funcall rr)
  8514. (or (and (eq (car rr) 'in-file)
  8515. (buffer-file-name)
  8516. (string-match (cdr rr) (buffer-file-name)))
  8517. (and (eq (car rr) 'in-mode)
  8518. (string-match (cdr rr) (symbol-name major-mode)))
  8519. (and (eq (car rr) 'in-buffer)
  8520. (string-match (cdr rr) (buffer-name)))
  8521. (when (and (eq (car rr) 'not-in-file)
  8522. (buffer-file-name))
  8523. (not (string-match (cdr rr) (buffer-file-name))))
  8524. (when (eq (car rr) 'not-in-mode)
  8525. (not (string-match (cdr rr) (symbol-name major-mode))))
  8526. (when (eq (car rr) 'not-in-buffer)
  8527. (not (string-match (cdr rr) (buffer-name)))))))
  8528. (push r res))))
  8529. (delete-dups (delq nil res))))
  8530. (defun org-context-p (&rest contexts)
  8531. "Check if local context is any of CONTEXTS.
  8532. Possible values in the list of contexts are `table', `headline', and `item'."
  8533. (let ((pos (point)))
  8534. (goto-char (point-at-bol))
  8535. (prog1 (or (and (memq 'table contexts)
  8536. (looking-at "[ \t]*|"))
  8537. (and (memq 'headline contexts)
  8538. (looking-at org-outline-regexp))
  8539. (and (memq 'item contexts)
  8540. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8541. (and (memq 'item-body contexts)
  8542. (org-in-item-p)))
  8543. (goto-char pos))))
  8544. (defconst org-unique-local-variables
  8545. '(org-element--cache
  8546. org-element--cache-objects
  8547. org-element--cache-sync-keys
  8548. org-element--cache-sync-requests
  8549. org-element--cache-sync-timer)
  8550. "List of local variables that cannot be transferred to another buffer.")
  8551. (defun org-get-local-variables ()
  8552. "Return a list of all local variables in an Org mode buffer."
  8553. (delq nil
  8554. (mapcar
  8555. (lambda (x)
  8556. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8557. (name (car binding)))
  8558. (and (not (get name 'org-state))
  8559. (not (memq name org-unique-local-variables))
  8560. (string-match-p
  8561. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8562. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8563. (symbol-name name))
  8564. binding)))
  8565. (with-temp-buffer
  8566. (org-mode)
  8567. (buffer-local-variables)))))
  8568. (defun org-clone-local-variables (from-buffer &optional regexp)
  8569. "Clone local variables from FROM-BUFFER.
  8570. Optional argument REGEXP selects variables to clone."
  8571. (dolist (pair (buffer-local-variables from-buffer))
  8572. (let ((name (car pair)))
  8573. (when (and (symbolp name)
  8574. (not (memq name org-unique-local-variables))
  8575. (or (null regexp) (string-match regexp (symbol-name name))))
  8576. (set (make-local-variable name) (cdr pair))))))
  8577. ;;;###autoload
  8578. (defun org-run-like-in-org-mode (cmd)
  8579. "Run a command, pretending that the current buffer is in Org mode.
  8580. This will temporarily bind local variables that are typically bound in
  8581. Org mode to the values they have in Org mode, and then interactively
  8582. call CMD."
  8583. (org-load-modules-maybe)
  8584. (unless org-local-vars
  8585. (setq org-local-vars (org-get-local-variables)))
  8586. (let (binds)
  8587. (dolist (var org-local-vars)
  8588. (when (or (not (boundp (car var)))
  8589. (eq (symbol-value (car var))
  8590. (default-value (car var))))
  8591. (push (list (car var) `(quote ,(cadr var))) binds)))
  8592. (eval `(let ,binds
  8593. (call-interactively (quote ,cmd))))))
  8594. (defun org-get-category (&optional pos force-refresh)
  8595. "Get the category applying to position POS."
  8596. (save-match-data
  8597. (when force-refresh (org-refresh-category-properties))
  8598. (let ((pos (or pos (point))))
  8599. (or (get-text-property pos 'org-category)
  8600. (progn (org-refresh-category-properties)
  8601. (get-text-property pos 'org-category))))))
  8602. ;;; Refresh properties
  8603. (defun org-refresh-properties (dprop tprop)
  8604. "Refresh buffer text properties.
  8605. DPROP is the drawer property and TPROP is either the
  8606. corresponding text property to set, or an alist with each element
  8607. being a text property (as a symbol) and a function to apply to
  8608. the value of the drawer property."
  8609. (let ((case-fold-search t)
  8610. (inhibit-read-only t))
  8611. (org-with-silent-modifications
  8612. (org-with-wide-buffer
  8613. (goto-char (point-min))
  8614. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8615. (org-refresh-property tprop (match-string-no-properties 1)))))))
  8616. (defun org-refresh-property (tprop p)
  8617. "Refresh the buffer text property TPROP from the drawer property P.
  8618. The refresh happens only for the current tree (not subtree)."
  8619. (unless (org-before-first-heading-p)
  8620. (save-excursion
  8621. (org-back-to-heading t)
  8622. (if (symbolp tprop)
  8623. ;; TPROP is a text property symbol
  8624. (put-text-property
  8625. (point) (or (outline-next-heading) (point-max)) tprop p)
  8626. ;; TPROP is an alist with (properties . function) elements
  8627. (dolist (al tprop)
  8628. (save-excursion
  8629. (put-text-property
  8630. (line-beginning-position) (or (outline-next-heading) (point-max))
  8631. (car al)
  8632. (funcall (cdr al) p))))))))
  8633. (defun org-refresh-category-properties ()
  8634. "Refresh category text properties in the buffer."
  8635. (let ((case-fold-search t)
  8636. (inhibit-read-only t)
  8637. (default-category
  8638. (cond ((null org-category)
  8639. (if buffer-file-name
  8640. (file-name-sans-extension
  8641. (file-name-nondirectory buffer-file-name))
  8642. "???"))
  8643. ((symbolp org-category) (symbol-name org-category))
  8644. (t org-category))))
  8645. (org-with-silent-modifications
  8646. (org-with-wide-buffer
  8647. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8648. ;; This is the default category for the buffer. If none is
  8649. ;; found, fall-back to `org-category' or buffer file name.
  8650. (put-text-property
  8651. (point-min) (point-max)
  8652. 'org-category
  8653. (catch 'buffer-category
  8654. (goto-char (point-max))
  8655. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8656. (let ((element (org-element-at-point)))
  8657. (when (eq (org-element-type element) 'keyword)
  8658. (throw 'buffer-category
  8659. (org-element-property :value element)))))
  8660. default-category))
  8661. ;; Set sub-tree specific categories.
  8662. (goto-char (point-min))
  8663. (let ((regexp (org-re-property "CATEGORY")))
  8664. (while (re-search-forward regexp nil t)
  8665. (let ((value (match-string-no-properties 3)))
  8666. (when (org-at-property-p)
  8667. (put-text-property
  8668. (save-excursion (org-back-to-heading t) (point))
  8669. (save-excursion (org-end-of-subtree t t) (point))
  8670. 'org-category
  8671. value)))))))))
  8672. (defun org-refresh-stats-properties ()
  8673. "Refresh stats text properties in the buffer."
  8674. (let (stats)
  8675. (org-with-silent-modifications
  8676. (org-with-wide-buffer
  8677. (goto-char (point-min))
  8678. (while (re-search-forward
  8679. (concat org-outline-regexp-bol ".*"
  8680. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8681. nil t)
  8682. (setq stats (cond ((equal (match-string 3) "0") 0)
  8683. ((match-string 2)
  8684. (/ (* (string-to-number (match-string 2)) 100)
  8685. (string-to-number (match-string 3))))
  8686. (t (string-to-number (match-string 1)))))
  8687. (org-back-to-heading t)
  8688. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8689. 'org-stats stats))))))
  8690. (defun org-refresh-effort-properties ()
  8691. "Refresh effort properties"
  8692. (org-refresh-properties
  8693. org-effort-property
  8694. '((effort . identity)
  8695. (effort-minutes . org-duration-string-to-minutes))))
  8696. ;;;; Link Stuff
  8697. ;;; Link abbreviations
  8698. (defun org-link-expand-abbrev (link)
  8699. "Apply replacements as defined in `org-link-abbrev-alist'."
  8700. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8701. (let* ((key (match-string 1 link))
  8702. (as (or (assoc key org-link-abbrev-alist-local)
  8703. (assoc key org-link-abbrev-alist)))
  8704. (tag (and (match-end 2) (match-string 3 link)))
  8705. rpl)
  8706. (if (not as)
  8707. link
  8708. (setq rpl (cdr as))
  8709. (cond
  8710. ((symbolp rpl) (funcall rpl tag))
  8711. ((string-match "%(\\([^)]+\\))" rpl)
  8712. (replace-match
  8713. (save-match-data
  8714. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8715. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8716. ((string-match "%h" rpl)
  8717. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8718. (t (concat rpl tag)))))
  8719. link))
  8720. ;;; Storing and inserting links
  8721. (defvar org-insert-link-history nil
  8722. "Minibuffer history for links inserted with `org-insert-link'.")
  8723. (defvar org-stored-links nil
  8724. "Contains the links stored with `org-store-link'.")
  8725. (defvar org-store-link-plist nil
  8726. "Plist with info about the most recently link created with `org-store-link'.")
  8727. (defun org-store-link-functions ()
  8728. "Return a list of functions that are called to create and store a link.
  8729. The functions defined in the :store property of
  8730. `org-link-parameters'.
  8731. Each function will be called in turn until one returns a non-nil
  8732. value. Each function should check if it is responsible for
  8733. creating this link (for example by looking at the major mode).
  8734. If not, it must exit and return nil. If yes, it should return
  8735. a non-nil value after calling `org-store-link-props' with a list
  8736. of properties and values. Special properties are:
  8737. :type The link prefix, like \"http\". This must be given.
  8738. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8739. This is obligatory as well.
  8740. :description Optional default description for the second pair
  8741. of brackets in an Org mode link. The user can still change
  8742. this when inserting this link into an Org mode buffer.
  8743. In addition to these, any additional properties can be specified
  8744. and then used in capture templates."
  8745. (cl-loop for link in org-link-parameters
  8746. with store-func
  8747. do (setq store-func (org-link-get-parameter (car link) :store))
  8748. if store-func
  8749. collect store-func))
  8750. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8751. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8752. ;;;###autoload
  8753. (defun org-store-link (arg)
  8754. "Store an org-link to the current location.
  8755. \\<org-mode-map>
  8756. This link is added to `org-stored-links' and can later be inserted
  8757. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8758. For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
  8759. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8760. For file links, ARG negates `org-context-in-file-links'.
  8761. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8762. skipping storing functions that are not
  8763. part of Org core.
  8764. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8765. prefix ARG forces storing a link for each line in the
  8766. active region."
  8767. (interactive "P")
  8768. (org-load-modules-maybe)
  8769. (if (and (equal arg '(64)) (org-region-active-p))
  8770. (save-excursion
  8771. (let ((end (region-end)))
  8772. (goto-char (region-beginning))
  8773. (set-mark (point))
  8774. (while (< (point-at-eol) end)
  8775. (move-end-of-line 1) (activate-mark)
  8776. (let (current-prefix-arg)
  8777. (call-interactively 'org-store-link))
  8778. (move-beginning-of-line 2)
  8779. (set-mark (point)))))
  8780. (setq org-store-link-plist nil)
  8781. (let (link cpltxt desc description search
  8782. txt custom-id agenda-link sfuns sfunsn)
  8783. (cond
  8784. ;; Store a link using an external link type
  8785. ((and (not (equal arg '(16)))
  8786. (setq sfuns
  8787. (delq
  8788. nil (mapcar (lambda (f)
  8789. (let (fs) (if (funcall f) (push f fs))))
  8790. (org-store-link-functions)))
  8791. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8792. (or (and (cdr sfuns)
  8793. (funcall (intern
  8794. (completing-read
  8795. "Which function for creating the link? "
  8796. sfunsn nil t (car sfunsn)))))
  8797. (funcall (caar sfuns)))
  8798. (setq link (plist-get org-store-link-plist :link)
  8799. desc (or (plist-get org-store-link-plist
  8800. :description)
  8801. link))))
  8802. ;; Store a link from a source code buffer.
  8803. ((org-src-edit-buffer-p)
  8804. (let ((coderef-format (org-src-coderef-format)))
  8805. (cond ((save-excursion
  8806. (beginning-of-line)
  8807. (looking-at (org-src-coderef-regexp coderef-format)))
  8808. (setq link (format "(%s)" (match-string-no-properties 3))))
  8809. ((called-interactively-p 'any)
  8810. (let ((label (read-string "Code line label: ")))
  8811. (end-of-line)
  8812. (setq link (format coderef-format label))
  8813. (let ((gc (- 79 (length link))))
  8814. (if (< (current-column) gc)
  8815. (org-move-to-column gc t)
  8816. (insert " ")))
  8817. (insert link)
  8818. (setq link (concat "(" label ")"))
  8819. (setq desc nil)))
  8820. (t (setq link nil)))))
  8821. ;; We are in the agenda, link to referenced location
  8822. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8823. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8824. (get-text-property (point) 'org-marker))))
  8825. (when m
  8826. (org-with-point-at m
  8827. (setq agenda-link
  8828. (if (called-interactively-p 'any)
  8829. (call-interactively 'org-store-link)
  8830. (org-store-link nil)))))))
  8831. ((eq major-mode 'calendar-mode)
  8832. (let ((cd (calendar-cursor-to-date)))
  8833. (setq link
  8834. (format-time-string
  8835. (car org-time-stamp-formats)
  8836. (apply 'encode-time
  8837. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8838. nil nil nil))))
  8839. (org-store-link-props :type "calendar" :date cd)))
  8840. ((eq major-mode 'help-mode)
  8841. (setq link (concat "help:" (save-excursion
  8842. (goto-char (point-min))
  8843. (looking-at "^[^ ]+")
  8844. (match-string 0))))
  8845. (org-store-link-props :type "help"))
  8846. ((eq major-mode 'w3-mode)
  8847. (setq cpltxt (if (and (buffer-name)
  8848. (not (string-match "Untitled" (buffer-name))))
  8849. (buffer-name)
  8850. (url-view-url t))
  8851. link (url-view-url t))
  8852. (org-store-link-props :type "w3" :url (url-view-url t)))
  8853. ((eq major-mode 'image-mode)
  8854. (setq cpltxt (concat "file:"
  8855. (abbreviate-file-name buffer-file-name))
  8856. link cpltxt)
  8857. (org-store-link-props :type "image" :file buffer-file-name))
  8858. ;; In dired, store a link to the file of the current line
  8859. ((derived-mode-p 'dired-mode)
  8860. (let ((file (dired-get-filename nil t)))
  8861. (setq file (if file
  8862. (abbreviate-file-name
  8863. (expand-file-name (dired-get-filename nil t)))
  8864. ;; otherwise, no file so use current directory.
  8865. default-directory))
  8866. (setq cpltxt (concat "file:" file)
  8867. link cpltxt)))
  8868. ((setq search (run-hook-with-args-until-success
  8869. 'org-create-file-search-functions))
  8870. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8871. "::" search))
  8872. (setq cpltxt (or description link)))
  8873. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8874. (org-with-limited-levels
  8875. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8876. (cond
  8877. ;; Store a link using the target at point
  8878. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8879. (setq cpltxt
  8880. (concat "file:"
  8881. (abbreviate-file-name
  8882. (buffer-file-name (buffer-base-buffer)))
  8883. "::" (match-string 1))
  8884. link cpltxt))
  8885. ((and (featurep 'org-id)
  8886. (or (eq org-id-link-to-org-use-id t)
  8887. (and (called-interactively-p 'any)
  8888. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8889. (and (eq org-id-link-to-org-use-id
  8890. 'create-if-interactive-and-no-custom-id)
  8891. (not custom-id))))
  8892. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8893. ;; Store a link using the ID at point
  8894. (setq link (condition-case nil
  8895. (prog1 (org-id-store-link)
  8896. (setq desc (or (plist-get org-store-link-plist
  8897. :description)
  8898. "")))
  8899. (error
  8900. ;; Probably before first headline, link only to file
  8901. (concat "file:"
  8902. (abbreviate-file-name
  8903. (buffer-file-name (buffer-base-buffer))))))))
  8904. (t
  8905. ;; Just link to current headline
  8906. (setq cpltxt (concat "file:"
  8907. (abbreviate-file-name
  8908. (buffer-file-name (buffer-base-buffer)))))
  8909. ;; Add a context search string
  8910. (when (org-xor org-context-in-file-links arg)
  8911. (let* ((element (org-element-at-point))
  8912. (name (org-element-property :name element)))
  8913. (setq txt (cond
  8914. ((org-at-heading-p) nil)
  8915. (name)
  8916. ((org-region-active-p)
  8917. (buffer-substring (region-beginning) (region-end)))))
  8918. (when (or (null txt) (string-match "\\S-" txt))
  8919. (setq cpltxt
  8920. (concat cpltxt "::"
  8921. (condition-case nil
  8922. (org-make-org-heading-search-string txt)
  8923. (error "")))
  8924. desc (or name
  8925. (nth 4 (ignore-errors (org-heading-components)))
  8926. "NONE")))))
  8927. (when (string-match "::\\'" cpltxt)
  8928. (setq cpltxt (substring cpltxt 0 -2)))
  8929. (setq link cpltxt)))))
  8930. ((buffer-file-name (buffer-base-buffer))
  8931. ;; Just link to this file here.
  8932. (setq cpltxt (concat "file:"
  8933. (abbreviate-file-name
  8934. (buffer-file-name (buffer-base-buffer)))))
  8935. ;; Add a context string.
  8936. (when (org-xor org-context-in-file-links arg)
  8937. (setq txt (if (org-region-active-p)
  8938. (buffer-substring (region-beginning) (region-end))
  8939. (buffer-substring (point-at-bol) (point-at-eol))))
  8940. ;; Only use search option if there is some text.
  8941. (when (string-match "\\S-" txt)
  8942. (setq cpltxt
  8943. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8944. desc "NONE")))
  8945. (setq link cpltxt))
  8946. ((called-interactively-p 'interactive)
  8947. (user-error "No method for storing a link from this buffer"))
  8948. (t (setq link nil)))
  8949. ;; We're done setting link and desc, clean up
  8950. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8951. (setq link (or link cpltxt)
  8952. desc (or desc cpltxt))
  8953. (cond ((not desc))
  8954. ((equal desc "NONE") (setq desc nil))
  8955. (t (setq desc
  8956. (replace-regexp-in-string
  8957. org-bracket-link-analytic-regexp
  8958. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8959. desc))))
  8960. ;; Return the link
  8961. (if (not (and (or (called-interactively-p 'any)
  8962. executing-kbd-macro)
  8963. link))
  8964. (or agenda-link (and link (org-make-link-string link desc)))
  8965. (push (list link desc) org-stored-links)
  8966. (message "Stored: %s" (or desc link))
  8967. (when custom-id
  8968. (setq link (concat "file:" (abbreviate-file-name
  8969. (buffer-file-name)) "::#" custom-id))
  8970. (push (list link desc) org-stored-links))
  8971. (car org-stored-links)))))
  8972. (defun org-store-link-props (&rest plist)
  8973. "Store link properties, extract names, addresses and dates."
  8974. (let ((x (plist-get plist :from)))
  8975. (when x
  8976. (let ((adr (mail-extract-address-components x)))
  8977. (setq plist (plist-put plist :fromname (car adr)))
  8978. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8979. (let ((x (plist-get plist :to)))
  8980. (when x
  8981. (let ((adr (mail-extract-address-components x)))
  8982. (setq plist (plist-put plist :toname (car adr)))
  8983. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8984. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8985. (when x
  8986. (setq plist (plist-put plist :date-timestamp
  8987. (format-time-string
  8988. (org-time-stamp-format t) x)))
  8989. (setq plist (plist-put plist :date-timestamp-inactive
  8990. (format-time-string
  8991. (org-time-stamp-format t t) x)))))
  8992. (let ((from (plist-get plist :from))
  8993. (to (plist-get plist :to)))
  8994. (when (and from to org-from-is-user-regexp)
  8995. (setq plist
  8996. (plist-put plist :fromto
  8997. (if (string-match org-from-is-user-regexp from)
  8998. (concat "to %t")
  8999. (concat "from %f"))))))
  9000. (setq org-store-link-plist plist))
  9001. (defun org-add-link-props (&rest plist)
  9002. "Add these properties to the link property list."
  9003. (let (key value)
  9004. (while plist
  9005. (setq key (pop plist) value (pop plist))
  9006. (setq org-store-link-plist
  9007. (plist-put org-store-link-plist key value)))))
  9008. (defun org-email-link-description (&optional fmt)
  9009. "Return the description part of an email link.
  9010. This takes information from `org-store-link-plist' and formats it
  9011. according to FMT (default from `org-email-link-description-format')."
  9012. (setq fmt (or fmt org-email-link-description-format))
  9013. (let* ((p org-store-link-plist)
  9014. (to (plist-get p :toaddress))
  9015. (from (plist-get p :fromaddress))
  9016. (table
  9017. (list
  9018. (cons "%c" (plist-get p :fromto))
  9019. (cons "%F" (plist-get p :from))
  9020. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9021. (cons "%T" (plist-get p :to))
  9022. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9023. (cons "%s" (plist-get p :subject))
  9024. (cons "%d" (plist-get p :date))
  9025. (cons "%m" (plist-get p :message-id)))))
  9026. (when (string-match "%c" fmt)
  9027. ;; Check if the user wrote this message
  9028. (if (and org-from-is-user-regexp from to
  9029. (save-match-data (string-match org-from-is-user-regexp from)))
  9030. (setq fmt (replace-match "to %t" t t fmt))
  9031. (setq fmt (replace-match "from %f" t t fmt))))
  9032. (org-replace-escapes fmt table)))
  9033. (defun org-make-org-heading-search-string (&optional string)
  9034. "Make search string for the current headline or STRING."
  9035. (let ((s (or string
  9036. (and (derived-mode-p 'org-mode)
  9037. (save-excursion
  9038. (org-back-to-heading t)
  9039. (org-element-property :raw-value (org-element-at-point))))))
  9040. (lines org-context-in-file-links))
  9041. (or string (setq s (concat "*" s))) ; Add * for headlines
  9042. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9043. (when (and string (integerp lines) (> lines 0))
  9044. (let ((slines (org-split-string s "\n")))
  9045. (when (< lines (length slines))
  9046. (setq s (mapconcat
  9047. 'identity
  9048. (reverse (nthcdr (- (length slines) lines)
  9049. (reverse slines))) "\n")))))
  9050. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9051. (defun org-make-link-string (link &optional description)
  9052. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9053. (unless (org-string-nw-p link) (error "Empty link"))
  9054. (let ((uri (cond ((string-match org-link-types-re link)
  9055. (concat (match-string 1 link)
  9056. (org-link-escape (substring link (match-end 1)))))
  9057. ;; For readability, url-encode internal links only
  9058. ;; when absolutely needed (i.e, when they contain
  9059. ;; square brackets). File links however, are
  9060. ;; encoded since, e.g., spaces are significant.
  9061. ((or (file-name-absolute-p link)
  9062. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9063. (org-link-escape link))
  9064. (t link)))
  9065. (description
  9066. (and (org-string-nw-p description)
  9067. ;; Remove brackets from description, as they are fatal.
  9068. (replace-regexp-in-string
  9069. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9070. (org-trim description)))))
  9071. (format "[[%s]%s]"
  9072. uri
  9073. (if description (format "[%s]" description) ""))))
  9074. (defconst org-link-escape-chars
  9075. ;;%20 %5B %5D %25
  9076. '(?\s ?\[ ?\] ?%)
  9077. "List of characters that should be escaped in a link when stored to Org.
  9078. This is the list that is used for internal purposes.")
  9079. (defun org-link-escape (text &optional table merge)
  9080. "Return percent escaped representation of TEXT.
  9081. TEXT is a string with the text to escape.
  9082. Optional argument TABLE is a list with characters that should be
  9083. escaped. When nil, `org-link-escape-chars' is used.
  9084. If optional argument MERGE is set, merge TABLE into
  9085. `org-link-escape-chars'."
  9086. (let ((characters-to-encode
  9087. (cond ((null table) org-link-escape-chars)
  9088. (merge (append org-link-escape-chars table))
  9089. (t table))))
  9090. (mapconcat
  9091. (lambda (c)
  9092. (if (or (memq c characters-to-encode)
  9093. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9094. (mapconcat (lambda (e) (format "%%%.2X" e))
  9095. (or (encode-coding-char c 'utf-8)
  9096. (error "Unable to percent escape character: %c" c))
  9097. "")
  9098. (char-to-string c)))
  9099. text "")))
  9100. (defun org-link-unescape (str)
  9101. "Unhex hexified Unicode parts in string STR.
  9102. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9103. reciprocal of `org-link-escape', which see."
  9104. (if (org-string-nw-p str)
  9105. (replace-regexp-in-string
  9106. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9107. str))
  9108. (defun org-link-unescape-compound (hex)
  9109. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9110. Note: this function also decodes single byte encodings like
  9111. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9112. (save-match-data
  9113. (let* ((bytes (cdr (split-string hex "%")))
  9114. (ret "")
  9115. (eat 0)
  9116. (sum 0))
  9117. (while bytes
  9118. (let* ((val (string-to-number (pop bytes) 16))
  9119. (shift-xor
  9120. (if (= 0 eat)
  9121. (cond
  9122. ((>= val 252) (cons 6 252))
  9123. ((>= val 248) (cons 5 248))
  9124. ((>= val 240) (cons 4 240))
  9125. ((>= val 224) (cons 3 224))
  9126. ((>= val 192) (cons 2 192))
  9127. (t (cons 0 0)))
  9128. (cons 6 128))))
  9129. (when (>= val 192) (setq eat (car shift-xor)))
  9130. (setq val (logxor val (cdr shift-xor)))
  9131. (setq sum (+ (lsh sum (car shift-xor)) val))
  9132. (when (> eat 0) (setq eat (- eat 1)))
  9133. (cond
  9134. ((= 0 eat) ;multi byte
  9135. (setq ret (concat ret (char-to-string sum)))
  9136. (setq sum 0))
  9137. ((not bytes) ; single byte(s)
  9138. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9139. ret)))
  9140. (defun org-link-unescape-single-byte-sequence (hex)
  9141. "Unhexify hex-encoded single byte character sequences."
  9142. (mapconcat (lambda (byte)
  9143. (char-to-string (string-to-number byte 16)))
  9144. (cdr (split-string hex "%")) ""))
  9145. (defun org-xor (a b)
  9146. "Exclusive or."
  9147. (if a (not b) b))
  9148. (defun org-fixup-message-id-for-http (s)
  9149. "Replace special characters in a message id, so it can be used in an http query."
  9150. (when (string-match "%" s)
  9151. (setq s (mapconcat (lambda (c)
  9152. (if (eq c ?%)
  9153. "%25"
  9154. (char-to-string c)))
  9155. s "")))
  9156. (while (string-match "<" s)
  9157. (setq s (replace-match "%3C" t t s)))
  9158. (while (string-match ">" s)
  9159. (setq s (replace-match "%3E" t t s)))
  9160. (while (string-match "@" s)
  9161. (setq s (replace-match "%40" t t s)))
  9162. s)
  9163. (defun org-link-prettify (link)
  9164. "Return a human-readable representation of LINK.
  9165. The car of LINK must be a raw link.
  9166. The cdr of LINK must be either a link description or nil."
  9167. (let ((desc (or (cadr link) "<no description>")))
  9168. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9169. "<" (car link) ">")))
  9170. ;;;###autoload
  9171. (defun org-insert-link-global ()
  9172. "Insert a link like Org mode does.
  9173. This command can be called in any mode to insert a link in Org syntax."
  9174. (interactive)
  9175. (org-load-modules-maybe)
  9176. (org-run-like-in-org-mode 'org-insert-link))
  9177. (defun org-insert-all-links (arg &optional pre post)
  9178. "Insert all links in `org-stored-links'.
  9179. When a universal prefix, do not delete the links from `org-stored-links'.
  9180. When `ARG' is a number, insert the last N link(s).
  9181. `PRE' and `POST' are optional arguments to define a string to
  9182. prepend or to append."
  9183. (interactive "P")
  9184. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9185. (links (copy-sequence org-stored-links))
  9186. (pr (or pre "- "))
  9187. (po (or post "\n"))
  9188. (cnt 1) l)
  9189. (if (null org-stored-links)
  9190. (message "No link to insert")
  9191. (while (and (or (listp arg) (>= arg cnt))
  9192. (setq l (if (listp arg)
  9193. (pop links)
  9194. (pop org-stored-links))))
  9195. (setq cnt (1+ cnt))
  9196. (insert pr)
  9197. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9198. (insert po)))))
  9199. (defun org-insert-last-stored-link (arg)
  9200. "Insert the last link stored in `org-stored-links'."
  9201. (interactive "p")
  9202. (org-insert-all-links arg "" "\n"))
  9203. (defun org-link-fontify-links-to-this-file ()
  9204. "Fontify links to the current file in `org-stored-links'."
  9205. (let ((f (buffer-file-name)) a b)
  9206. (setq a (mapcar (lambda(l)
  9207. (let ((ll (car l)))
  9208. (when (and (string-match "^file:\\(.+\\)::" ll)
  9209. (equal f (expand-file-name (match-string 1 ll))))
  9210. ll)))
  9211. org-stored-links))
  9212. (when (featurep 'org-id)
  9213. (setq b (mapcar (lambda(l)
  9214. (let ((ll (car l)))
  9215. (when (and (string-match "^id:\\(.+\\)$" ll)
  9216. (equal f (expand-file-name
  9217. (or (org-id-find-id-file
  9218. (match-string 1 ll)) ""))))
  9219. ll)))
  9220. org-stored-links)))
  9221. (mapcar (lambda(l)
  9222. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9223. (delq nil (append a b)))))
  9224. (defvar org--links-history nil)
  9225. (defun org-insert-link (&optional complete-file link-location default-description)
  9226. "Insert a link. At the prompt, enter the link.
  9227. Completion can be used to insert any of the link protocol prefixes in use.
  9228. The history can be used to select a link previously stored with
  9229. `org-store-link'. When the empty string is entered (i.e. if you just
  9230. press `RET' at the prompt), the link defaults to the most recently
  9231. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9232. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9233. You will also be prompted for a description, and if one is given, it will
  9234. be displayed in the buffer instead of the link.
  9235. If there is already a link at point, this command will allow you to edit
  9236. link and description parts.
  9237. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9238. file name can be
  9239. selected using completion. The path to the file will be relative to the
  9240. current directory if the file is in the current directory or a subdirectory.
  9241. Otherwise, the link will be the absolute path as completed in the minibuffer
  9242. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9243. option `org-link-file-path-type'.
  9244. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9245. absolute path even if the file is in
  9246. the current directory or below.
  9247. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9248. prefix negates `org-keep-stored-link-after-insertion'.
  9249. If `org-make-link-description-function' is non-nil, this function will be
  9250. called with the link target, and the result will be the default
  9251. link description.
  9252. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9253. the link location instead of reading one interactively.
  9254. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9255. as the default description."
  9256. (interactive "P")
  9257. (let* ((wcf (current-window-configuration))
  9258. (origbuf (current-buffer))
  9259. (region (when (org-region-active-p)
  9260. (buffer-substring (region-beginning) (region-end))))
  9261. (remove (and region (list (region-beginning) (region-end))))
  9262. (desc region)
  9263. (link link-location)
  9264. (abbrevs org-link-abbrev-alist-local)
  9265. entry all-prefixes auto-desc)
  9266. (cond
  9267. (link-location) ; specified by arg, just use it.
  9268. ((org-in-regexp org-bracket-link-regexp 1)
  9269. ;; We do have a link at point, and we are going to edit it.
  9270. (setq remove (list (match-beginning 0) (match-end 0)))
  9271. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9272. (setq link (read-string "Link: "
  9273. (org-link-unescape
  9274. (match-string-no-properties 1)))))
  9275. ((or (org-in-regexp org-angle-link-re)
  9276. (org-in-regexp org-plain-link-re))
  9277. ;; Convert to bracket link
  9278. (setq remove (list (match-beginning 0) (match-end 0))
  9279. link (read-string "Link: "
  9280. (org-unbracket-string "<" ">" (match-string 0)))))
  9281. ((member complete-file '((4) (16)))
  9282. ;; Completing read for file names.
  9283. (setq link (org-file-complete-link complete-file)))
  9284. (t
  9285. ;; Read link, with completion for stored links.
  9286. (org-link-fontify-links-to-this-file)
  9287. (org-switch-to-buffer-other-window "*Org Links*")
  9288. (with-current-buffer "*Org Links*"
  9289. (erase-buffer)
  9290. (insert "Insert a link.
  9291. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9292. (when org-stored-links
  9293. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9294. (insert (mapconcat 'org-link-prettify
  9295. (reverse org-stored-links) "\n")))
  9296. (goto-char (point-min)))
  9297. (let ((cw (selected-window)))
  9298. (select-window (get-buffer-window "*Org Links*" 'visible))
  9299. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9300. (unless (pos-visible-in-window-p (point-max))
  9301. (org-fit-window-to-buffer))
  9302. (and (window-live-p cw) (select-window cw)))
  9303. (setq all-prefixes (append (mapcar 'car abbrevs)
  9304. (mapcar 'car org-link-abbrev-alist)
  9305. (org-link-types)))
  9306. (unwind-protect
  9307. ;; Fake a link history, containing the stored links.
  9308. (let ((org--links-history
  9309. (append (mapcar #'car org-stored-links)
  9310. org-insert-link-history)))
  9311. (setq link
  9312. (org-completing-read
  9313. "Link: "
  9314. (append
  9315. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9316. (mapcar #'car org-stored-links))
  9317. nil nil nil
  9318. 'org--links-history
  9319. (caar org-stored-links)))
  9320. (unless (org-string-nw-p link) (user-error "No link selected"))
  9321. (dolist (l org-stored-links)
  9322. (when (equal link (cadr l))
  9323. (setq link (car l))
  9324. (setq auto-desc t)))
  9325. (when (or (member link all-prefixes)
  9326. (and (equal ":" (substring link -1))
  9327. (member (substring link 0 -1) all-prefixes)
  9328. (setq link (substring link 0 -1))))
  9329. (setq link (with-current-buffer origbuf
  9330. (org-link-try-special-completion link)))))
  9331. (set-window-configuration wcf)
  9332. (kill-buffer "*Org Links*"))
  9333. (setq entry (assoc link org-stored-links))
  9334. (or entry (push link org-insert-link-history))
  9335. (setq desc (or desc (nth 1 entry)))))
  9336. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9337. (not org-keep-stored-link-after-insertion))
  9338. (setq org-stored-links (delq (assoc link org-stored-links)
  9339. org-stored-links)))
  9340. (when (and (string-match org-plain-link-re link)
  9341. (not (string-match org-ts-regexp link)))
  9342. ;; URL-like link, normalize the use of angular brackets.
  9343. (setq link (org-unbracket-string "<" ">" link)))
  9344. ;; Check if we are linking to the current file with a search
  9345. ;; option If yes, simplify the link by using only the search
  9346. ;; option.
  9347. (when (and buffer-file-name
  9348. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9349. (let* ((path (match-string 1 link))
  9350. (case-fold-search nil)
  9351. (search (match-string 2 link)))
  9352. (save-match-data
  9353. (when (equal (file-truename buffer-file-name) (file-truename path))
  9354. ;; We are linking to this same file, with a search option
  9355. (setq link search)))))
  9356. ;; Check if we can/should use a relative path. If yes, simplify the link
  9357. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9358. (let* ((type (match-string 1 link))
  9359. (path (match-string 2 link))
  9360. (origpath path)
  9361. (case-fold-search nil))
  9362. (cond
  9363. ((or (eq org-link-file-path-type 'absolute)
  9364. (equal complete-file '(16)))
  9365. (setq path (abbreviate-file-name (expand-file-name path))))
  9366. ((eq org-link-file-path-type 'noabbrev)
  9367. (setq path (expand-file-name path)))
  9368. ((eq org-link-file-path-type 'relative)
  9369. (setq path (file-relative-name path)))
  9370. (t
  9371. (save-match-data
  9372. (if (string-match (concat "^" (regexp-quote
  9373. (expand-file-name
  9374. (file-name-as-directory
  9375. default-directory))))
  9376. (expand-file-name path))
  9377. ;; We are linking a file with relative path name.
  9378. (setq path (substring (expand-file-name path)
  9379. (match-end 0)))
  9380. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9381. (setq link (concat type path))
  9382. (when (equal desc origpath)
  9383. (setq desc path))))
  9384. (if org-make-link-description-function
  9385. (setq desc
  9386. (or (condition-case nil
  9387. (funcall org-make-link-description-function link desc)
  9388. (error (progn (message "Can't get link description from `%s'"
  9389. (symbol-name org-make-link-description-function))
  9390. (sit-for 2) nil)))
  9391. (read-string "Description: " default-description)))
  9392. (if default-description (setq desc default-description)
  9393. (setq desc (or (and auto-desc desc)
  9394. (read-string "Description: " desc)))))
  9395. (unless (string-match "\\S-" desc) (setq desc nil))
  9396. (when remove (apply 'delete-region remove))
  9397. (insert (org-make-link-string link desc))
  9398. ;; Redisplay so as the new link has proper invisible characters.
  9399. (sit-for 0)))
  9400. (defun org-link-try-special-completion (type)
  9401. "If there is completion support for link type TYPE, offer it."
  9402. (let ((fun (org-link-get-parameter type :complete)))
  9403. (if (functionp fun)
  9404. (funcall fun)
  9405. (read-string "Link (no completion support): " (concat type ":")))))
  9406. (defun org-file-complete-link (&optional arg)
  9407. "Create a file link using completion."
  9408. (let ((file (read-file-name "File: "))
  9409. (pwd (file-name-as-directory (expand-file-name ".")))
  9410. (pwd1 (file-name-as-directory (abbreviate-file-name
  9411. (expand-file-name ".")))))
  9412. (cond ((equal arg '(16))
  9413. (concat "file:"
  9414. (abbreviate-file-name (expand-file-name file))))
  9415. ((string-match
  9416. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9417. (concat "file:" (match-string 1 file)))
  9418. ((string-match
  9419. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9420. (expand-file-name file))
  9421. (concat "file:"
  9422. (match-string 1 (expand-file-name file))))
  9423. (t (concat "file:" file)))))
  9424. (defun org-completing-read (&rest args)
  9425. "Completing-read with SPACE being a normal character."
  9426. (let ((enable-recursive-minibuffers t)
  9427. (minibuffer-local-completion-map
  9428. (copy-keymap minibuffer-local-completion-map)))
  9429. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9430. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9431. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9432. 'org-time-stamp-inactive)
  9433. (apply #'completing-read args)))
  9434. ;;; Opening/following a link
  9435. (defvar org-link-search-failed nil)
  9436. (defvar org-open-link-functions nil
  9437. "Hook for functions finding a plain text link.
  9438. These functions must take a single argument, the link content.
  9439. They will be called for links that look like [[link text][description]]
  9440. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9441. like a filename (e.g. \"./blue.png\").
  9442. These functions will be called *before* Org attempts to resolve the
  9443. link by doing text searches in the current buffer - so if you want a
  9444. link \"[[target]]\" to still find \"<<target>>\", your function should
  9445. handle this as a special case.
  9446. When the function does handle the link, it must return a non-nil value.
  9447. If it decides that it is not responsible for this link, it must return
  9448. nil to indicate that that Org can continue with other options like
  9449. exact and fuzzy text search.")
  9450. (defun org-next-link (&optional search-backward)
  9451. "Move forward to the next link.
  9452. If the link is in hidden text, expose it."
  9453. (interactive "P")
  9454. (when (and org-link-search-failed (eq this-command last-command))
  9455. (goto-char (point-min))
  9456. (message "Link search wrapped back to beginning of buffer"))
  9457. (setq org-link-search-failed nil)
  9458. (let* ((pos (point))
  9459. (ct (org-context))
  9460. (a (assq :link ct))
  9461. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9462. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9463. ((looking-at org-any-link-re)
  9464. ;; Don't stay stuck at link without an org-link face
  9465. (forward-char (if search-backward -1 1))))
  9466. (if (funcall srch-fun org-any-link-re nil t)
  9467. (progn
  9468. (goto-char (match-beginning 0))
  9469. (when (outline-invisible-p) (org-show-context)))
  9470. (goto-char pos)
  9471. (setq org-link-search-failed t)
  9472. (message "No further link found"))))
  9473. (defun org-previous-link ()
  9474. "Move backward to the previous link.
  9475. If the link is in hidden text, expose it."
  9476. (interactive)
  9477. (funcall 'org-next-link t))
  9478. (defun org-translate-link (s)
  9479. "Translate a link string if a translation function has been defined."
  9480. (with-temp-buffer
  9481. (insert (org-trim s))
  9482. (org-trim (org-element-interpret-data (org-element-context)))))
  9483. (defun org-translate-link-from-planner (type path)
  9484. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9485. This is still an experimental function, your mileage may vary."
  9486. (cond
  9487. ((member type '("http" "https" "news" "ftp"))
  9488. ;; standard Internet links are the same.
  9489. nil)
  9490. ((and (equal type "irc") (string-match "^//" path))
  9491. ;; Planner has two / at the beginning of an irc link, we have 1.
  9492. ;; We should have zero, actually....
  9493. (setq path (substring path 1)))
  9494. ((and (equal type "lisp") (string-match "^/" path))
  9495. ;; Planner has a slash, we do not.
  9496. (setq type "elisp" path (substring path 1)))
  9497. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9498. ;; A typical message link. Planner has the id after the final slash,
  9499. ;; we separate it with a hash mark
  9500. (setq path (concat (match-string 1 path) "#"
  9501. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9502. (cons type path))
  9503. (defun org-find-file-at-mouse (ev)
  9504. "Open file link or URL at mouse."
  9505. (interactive "e")
  9506. (mouse-set-point ev)
  9507. (org-open-at-point 'in-emacs))
  9508. (defun org-open-at-mouse (ev)
  9509. "Open file link or URL at mouse.
  9510. See the docstring of `org-open-file' for details."
  9511. (interactive "e")
  9512. (mouse-set-point ev)
  9513. (when (eq major-mode 'org-agenda-mode)
  9514. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9515. (org-open-at-point))
  9516. (defvar org-window-config-before-follow-link nil
  9517. "The window configuration before following a link.
  9518. This is saved in case the need arises to restore it.")
  9519. ;;;###autoload
  9520. (defun org-open-at-point-global ()
  9521. "Follow a link or time-stamp like Org mode does.
  9522. This command can be called in any mode to follow an external link
  9523. or a time-stamp that has Org mode syntax. Its behavior is
  9524. undefined when called on internal links (e.g., fuzzy links).
  9525. Raise an error when there is nothing to follow. "
  9526. (interactive)
  9527. (cond ((org-in-regexp org-any-link-re)
  9528. (org-open-link-from-string (match-string-no-properties 0)))
  9529. ((or (org-in-regexp org-ts-regexp-both nil t)
  9530. (org-in-regexp org-tsr-regexp-both nil t))
  9531. (org-follow-timestamp-link))
  9532. (t (user-error "No link found"))))
  9533. ;;;###autoload
  9534. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9535. "Open a link in the string S, as if it was in Org mode."
  9536. (interactive "sLink: \nP")
  9537. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9538. (with-temp-buffer
  9539. (let ((org-inhibit-startup (not reference-buffer)))
  9540. (org-mode)
  9541. (insert s)
  9542. (goto-char (point-min))
  9543. (when reference-buffer
  9544. (setq org-link-abbrev-alist-local
  9545. (with-current-buffer reference-buffer
  9546. org-link-abbrev-alist-local)))
  9547. (org-open-at-point arg reference-buffer)))))
  9548. (defvar org-open-at-point-functions nil
  9549. "Hook that is run when following a link at point.
  9550. Functions in this hook must return t if they identify and follow
  9551. a link at point. If they don't find anything interesting at point,
  9552. they must return nil.")
  9553. (defvar org-link-search-inhibit-query nil)
  9554. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9555. (defun org--open-doi-link (path)
  9556. "Open a \"doi\" type link.
  9557. PATH is a the path to search for, as a string."
  9558. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9559. (defun org--open-elisp-link (path)
  9560. "Open a \"elisp\" type link.
  9561. PATH is the sexp to evaluate, as a string."
  9562. (let ((cmd path))
  9563. (if (or (and (org-string-nw-p
  9564. org-confirm-elisp-link-not-regexp)
  9565. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9566. (not org-confirm-elisp-link-function)
  9567. (funcall org-confirm-elisp-link-function
  9568. (format "Execute \"%s\" as elisp? "
  9569. (org-add-props cmd nil 'face 'org-warning))))
  9570. (message "%s => %s" cmd
  9571. (if (eq (string-to-char cmd) ?\()
  9572. (eval (read cmd))
  9573. (call-interactively (read cmd))))
  9574. (user-error "Abort"))))
  9575. (defun org--open-help-link (path)
  9576. "Open a \"help\" type link.
  9577. PATH is a symbol name, as a string."
  9578. (pcase (intern path)
  9579. ((and (pred fboundp) variable) (describe-function variable))
  9580. ((and (pred boundp) function) (describe-variable function))
  9581. (name (user-error "Unknown function or variable: %s" name))))
  9582. (defun org--open-shell-link (path)
  9583. "Open a \"shell\" type link.
  9584. PATH is the command to execute, as a string."
  9585. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9586. (cmd path))
  9587. (if (or (and (org-string-nw-p
  9588. org-confirm-shell-link-not-regexp)
  9589. (string-match
  9590. org-confirm-shell-link-not-regexp cmd))
  9591. (not org-confirm-shell-link-function)
  9592. (funcall org-confirm-shell-link-function
  9593. (format "Execute \"%s\" in shell? "
  9594. (org-add-props cmd nil
  9595. 'face 'org-warning))))
  9596. (progn
  9597. (message "Executing %s" cmd)
  9598. (shell-command cmd buf)
  9599. (when (featurep 'midnight)
  9600. (setq clean-buffer-list-kill-buffer-names
  9601. (cons (buffer-name buf)
  9602. clean-buffer-list-kill-buffer-names))))
  9603. (user-error "Abort"))))
  9604. (defun org-open-at-point (&optional arg reference-buffer)
  9605. "Open link, timestamp, footnote or tags at point.
  9606. When point is on a link, follow it. Normally, files will be
  9607. opened by an appropriate application. If the optional prefix
  9608. argument ARG is non-nil, Emacs will visit the file. With
  9609. a double prefix argument, try to open outside of Emacs, in the
  9610. application the system uses for this file type.
  9611. When point is on a timestamp, open the agenda at the day
  9612. specified.
  9613. When point is a footnote definition, move to the first reference
  9614. found. If it is on a reference, move to the associated
  9615. definition.
  9616. When point is on a headline, display a list of every link in the
  9617. entry, so it is possible to pick one, or all, of them. If point
  9618. is on a tag, call `org-tags-view' instead.
  9619. When optional argument REFERENCE-BUFFER is non-nil, it should
  9620. specify a buffer from where the link search should happen. This
  9621. is used internally by `org-open-link-from-string'.
  9622. On top of syntactically correct links, this function will open
  9623. the link at point in comments or comment blocks and the first
  9624. link in a property drawer line."
  9625. (interactive "P")
  9626. ;; On a code block, open block's results.
  9627. (unless (call-interactively 'org-babel-open-src-block-result)
  9628. (org-load-modules-maybe)
  9629. (setq org-window-config-before-follow-link (current-window-configuration))
  9630. (org-remove-occur-highlights nil nil t)
  9631. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9632. (let* ((context
  9633. ;; Only consider supported types, even if they are not
  9634. ;; the closest one.
  9635. (org-element-lineage
  9636. (org-element-context)
  9637. '(clock comment comment-block footnote-definition
  9638. footnote-reference headline inlinetask keyword link
  9639. node-property timestamp)
  9640. t))
  9641. (type (org-element-type context))
  9642. (value (org-element-property :value context)))
  9643. (cond
  9644. ((not context) (user-error "No link found"))
  9645. ;; Exception: open timestamps and links in properties
  9646. ;; drawers, keywords and comments.
  9647. ((memq type '(comment comment-block keyword node-property))
  9648. (call-interactively #'org-open-at-point-global))
  9649. ;; On a headline or an inlinetask, but not on a timestamp,
  9650. ;; a link, a footnote reference or on tags.
  9651. ((and (memq type '(headline inlinetask))
  9652. ;; Not on tags.
  9653. (let ((case-fold-search nil))
  9654. (save-excursion
  9655. (beginning-of-line)
  9656. (looking-at org-complex-heading-regexp))
  9657. (or (not (match-beginning 5))
  9658. (< (point) (match-beginning 5)))))
  9659. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9660. (links (car data))
  9661. (links-end (cdr data)))
  9662. (if links
  9663. (dolist (link (if (stringp links) (list links) links))
  9664. (search-forward link nil links-end)
  9665. (goto-char (match-beginning 0))
  9666. (org-open-at-point))
  9667. (require 'org-attach)
  9668. (org-attach-reveal 'if-exists))))
  9669. ;; On a clock line, make sure point is on the timestamp
  9670. ;; before opening it.
  9671. ((and (eq type 'clock)
  9672. value
  9673. (>= (point) (org-element-property :begin value))
  9674. (<= (point) (org-element-property :end value)))
  9675. (org-follow-timestamp-link))
  9676. ;; Do nothing on white spaces after an object.
  9677. ((>= (point)
  9678. (save-excursion
  9679. (goto-char (org-element-property :end context))
  9680. (skip-chars-backward " \t")
  9681. (point)))
  9682. (user-error "No link found"))
  9683. ((eq type 'timestamp) (org-follow-timestamp-link))
  9684. ;; On tags within a headline or an inlinetask.
  9685. ((and (memq type '(headline inlinetask))
  9686. (let ((case-fold-search nil))
  9687. (save-excursion (beginning-of-line)
  9688. (looking-at org-complex-heading-regexp))
  9689. (and (match-beginning 5)
  9690. (>= (point) (match-beginning 5)))))
  9691. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9692. ((eq type 'link)
  9693. ;; When link is located within the description of another
  9694. ;; link (e.g., an inline image), always open the parent
  9695. ;; link.
  9696. (let* ((link (let ((up (org-element-property :parent context)))
  9697. (if (eq (org-element-type up) 'link) up context)))
  9698. (type (org-element-property :type link))
  9699. (path (org-link-unescape (org-element-property :path link))))
  9700. ;; Switch back to REFERENCE-BUFFER needed when called in
  9701. ;; a temporary buffer through `org-open-link-from-string'.
  9702. (with-current-buffer (or reference-buffer (current-buffer))
  9703. (cond
  9704. ((equal type "file")
  9705. (if (string-match "[*?{]" (file-name-nondirectory path))
  9706. (dired path)
  9707. ;; Look into `org-link-parameters' in order to find
  9708. ;; a DEDICATED-FUNCTION to open file. The function
  9709. ;; will be applied on raw link instead of parsed
  9710. ;; link due to the limitation in `org-add-link-type'
  9711. ;; ("open" function called with a single argument).
  9712. ;; If no such function is found, fallback to
  9713. ;; `org-open-file'.
  9714. (let* ((option (org-element-property :search-option link))
  9715. (app (org-element-property :application link))
  9716. (dedicated-function
  9717. (org-link-get-parameter
  9718. (if app (concat type "+" app) type)
  9719. :follow)))
  9720. (if dedicated-function
  9721. (funcall dedicated-function
  9722. (concat path
  9723. (and option (concat "::" option))))
  9724. (apply #'org-open-file
  9725. path
  9726. (cond (arg)
  9727. ((equal app "emacs") 'emacs)
  9728. ((equal app "sys") 'system))
  9729. (cond ((not option) nil)
  9730. ((string-match-p "\\`[0-9]+\\'" option)
  9731. (list (string-to-number option)))
  9732. (t (list nil
  9733. (org-link-unescape option)))))))))
  9734. ((functionp (org-link-get-parameter type :follow))
  9735. (funcall (org-link-get-parameter type :follow) path))
  9736. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9737. (unless (run-hook-with-args-until-success
  9738. 'org-open-link-functions path)
  9739. (if (not arg) (org-mark-ring-push)
  9740. (switch-to-buffer-other-window
  9741. (org-get-buffer-for-internal-link (current-buffer))))
  9742. (let ((destination
  9743. (org-with-wide-buffer
  9744. (if (equal type "radio")
  9745. (org-search-radio-target
  9746. (org-element-property :path link))
  9747. (org-link-search
  9748. (if (member type '("custom-id" "coderef"))
  9749. (org-element-property :raw-link link)
  9750. path)
  9751. ;; Prevent fuzzy links from matching
  9752. ;; themselves.
  9753. (and (equal type "fuzzy")
  9754. (+ 2 (org-element-property :begin link)))))
  9755. (point))))
  9756. (unless (and (<= (point-min) destination)
  9757. (>= (point-max) destination))
  9758. (widen))
  9759. (goto-char destination))))
  9760. (t (browse-url-at-point))))))
  9761. ;; On a footnote reference or at a footnote definition's label.
  9762. ((or (eq type 'footnote-reference)
  9763. (and (eq type 'footnote-definition)
  9764. (save-excursion
  9765. ;; Do not validate action when point is on the
  9766. ;; spaces right after the footnote label, in
  9767. ;; order to be on par with behaviour on links.
  9768. (skip-chars-forward " \t")
  9769. (let ((begin
  9770. (org-element-property :contents-begin context)))
  9771. (if begin (< (point) begin)
  9772. (= (org-element-property :post-affiliated context)
  9773. (line-beginning-position)))))))
  9774. (org-footnote-action))
  9775. (t (user-error "No link found")))))
  9776. (run-hook-with-args 'org-follow-link-hook)))
  9777. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9778. "Offer links in the current entry and return the selected link.
  9779. If there is only one link, return it.
  9780. If NTH is an integer, return the NTH link found.
  9781. If ZERO is a string, check also this string for a link, and if
  9782. there is one, return it."
  9783. (with-current-buffer buffer
  9784. (org-with-wide-buffer
  9785. (goto-char marker)
  9786. (let ((cnt ?0)
  9787. have-zero end links link c)
  9788. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9789. (push (match-string 0 zero) links)
  9790. (setq cnt (1- cnt) have-zero t))
  9791. (save-excursion
  9792. (org-back-to-heading t)
  9793. (setq end (save-excursion (outline-next-heading) (point)))
  9794. (while (re-search-forward org-any-link-re end t)
  9795. (push (match-string 0) links))
  9796. (setq links (org-uniquify (reverse links))))
  9797. (cond
  9798. ((null links)
  9799. (message "No links"))
  9800. ((equal (length links) 1)
  9801. (setq link (car links)))
  9802. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9803. (setq link (nth (if have-zero nth (1- nth)) links)))
  9804. (t ; we have to select a link
  9805. (save-excursion
  9806. (save-window-excursion
  9807. (delete-other-windows)
  9808. (with-output-to-temp-buffer "*Select Link*"
  9809. (dolist (l links)
  9810. (cond
  9811. ((not (string-match org-bracket-link-regexp l))
  9812. (princ (format "[%c] %s\n" (cl-incf cnt)
  9813. (org-unbracket-string "<" ">" l))))
  9814. ((match-end 3)
  9815. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9816. (match-string 3 l) (match-string 1 l))))
  9817. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9818. (match-string 1 l)))))))
  9819. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9820. (message "Select link to open, RET to open all:")
  9821. (setq c (read-char-exclusive))
  9822. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9823. (when (equal c ?q) (user-error "Abort"))
  9824. (if (equal c ?\C-m)
  9825. (setq link links)
  9826. (setq nth (- c ?0))
  9827. (when have-zero (setq nth (1+ nth)))
  9828. (unless (and (integerp nth) (>= (length links) nth))
  9829. (user-error "Invalid link selection"))
  9830. (setq link (nth (1- nth) links)))))
  9831. (cons link end)))))
  9832. ;; TODO: These functions are deprecated since `org-open-at-point'
  9833. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9834. (defun org-open-file-with-system (path)
  9835. "Open file at PATH using the system way of opening it."
  9836. (org-open-file path 'system))
  9837. (defun org-open-file-with-emacs (path)
  9838. "Open file at PATH in Emacs."
  9839. (org-open-file path 'emacs))
  9840. ;;; File search
  9841. (defvar org-create-file-search-functions nil
  9842. "List of functions to construct the right search string for a file link.
  9843. These functions are called in turn with point at the location to
  9844. which the link should point.
  9845. A function in the hook should first test if it would like to
  9846. handle this file type, for example by checking the `major-mode'
  9847. or the file extension. If it decides not to handle this file, it
  9848. should just return nil to give other functions a chance. If it
  9849. does handle the file, it must return the search string to be used
  9850. when following the link. The search string will be part of the
  9851. file link, given after a double colon, and `org-open-at-point'
  9852. will automatically search for it. If special measures must be
  9853. taken to make the search successful, another function should be
  9854. added to the companion hook `org-execute-file-search-functions',
  9855. which see.
  9856. A function in this hook may also use `setq' to set the variable
  9857. `description' to provide a suggestion for the descriptive text to
  9858. be used for this link when it gets inserted into an Org buffer
  9859. with \\[org-insert-link].")
  9860. (defvar org-execute-file-search-functions nil
  9861. "List of functions to execute a file search triggered by a link.
  9862. Functions added to this hook must accept a single argument, the
  9863. search string that was part of the file link, the part after the
  9864. double colon. The function must first check if it would like to
  9865. handle this search, for example by checking the `major-mode' or
  9866. the file extension. If it decides not to handle this search, it
  9867. should just return nil to give other functions a chance. If it
  9868. does handle the search, it must return a non-nil value to keep
  9869. other functions from trying.
  9870. Each function can access the current prefix argument through the
  9871. variable `current-prefix-arg'. Note that a single prefix is used
  9872. to force opening a link in Emacs, so it may be good to only use a
  9873. numeric or double prefix to guide the search function.
  9874. In case this is needed, a function in this hook can also restore
  9875. the window configuration before `org-open-at-point' was called using:
  9876. (set-window-configuration org-window-config-before-follow-link)")
  9877. (defun org-search-radio-target (target)
  9878. "Search a radio target matching TARGET in current buffer.
  9879. White spaces are not significant."
  9880. (let ((re (format "<<<%s>>>"
  9881. (mapconcat #'regexp-quote
  9882. (org-split-string target "[ \t\n]+")
  9883. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9884. (origin (point)))
  9885. (goto-char (point-min))
  9886. (catch :radio-match
  9887. (while (re-search-forward re nil t)
  9888. (backward-char)
  9889. (let ((object (org-element-context)))
  9890. (when (eq (org-element-type object) 'radio-target)
  9891. (goto-char (org-element-property :begin object))
  9892. (org-show-context 'link-search)
  9893. (throw :radio-match nil))))
  9894. (goto-char origin)
  9895. (user-error "No match for radio target: %s" target))))
  9896. (defun org-link-search (s &optional avoid-pos stealth)
  9897. "Search for a search string S.
  9898. If S starts with \"#\", it triggers a custom ID search.
  9899. If S is enclosed within parenthesis, it initiates a coderef
  9900. search.
  9901. If S is surrounded by forward slashes, it is interpreted as
  9902. a regular expression. In Org mode files, this will create an
  9903. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9904. to list matches. If the current buffer is in `dired-mode', grep
  9905. will be used to search in all files.
  9906. When AVOID-POS is given, ignore matches near that position.
  9907. When optional argument STEALTH is non-nil, do not modify
  9908. visibility around point, thus ignoring `org-show-context-detail'
  9909. variable.
  9910. Search is case-insensitive and ignores white spaces. Return type
  9911. of matched result, which is either `dedicated' or `fuzzy'."
  9912. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9913. (let* ((case-fold-search t)
  9914. (origin (point))
  9915. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9916. (starred (eq (string-to-char normalized) ?*))
  9917. (words (split-string (if starred (substring s 1) s)))
  9918. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9919. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9920. type)
  9921. (cond
  9922. ;; Check if there are any special search functions.
  9923. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9924. ((eq (string-to-char s) ?#)
  9925. ;; Look for a custom ID S if S starts with "#".
  9926. (let* ((id (substring normalized 1))
  9927. (match (org-find-property "CUSTOM_ID" id)))
  9928. (if match (progn (goto-char match) (setf type 'dedicated))
  9929. (error "No match for custom ID: %s" id))))
  9930. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9931. ;; Look for coderef targets if S is enclosed within parenthesis.
  9932. (let ((coderef (match-string-no-properties 1 normalized))
  9933. (re (substring s-single-re 1 -1)))
  9934. (goto-char (point-min))
  9935. (catch :coderef-match
  9936. (while (re-search-forward re nil t)
  9937. (let ((element (org-element-at-point)))
  9938. (when (and (memq (org-element-type element)
  9939. '(example-block src-block))
  9940. ;; Build proper regexp according to current
  9941. ;; block's label format.
  9942. (let ((label-fmt
  9943. (regexp-quote
  9944. (or (org-element-property :label-fmt element)
  9945. org-coderef-label-format))))
  9946. (save-excursion
  9947. (beginning-of-line)
  9948. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9949. (format label-fmt coderef))))))
  9950. (setq type 'dedicated)
  9951. (goto-char (match-beginning 1))
  9952. (throw :coderef-match nil))))
  9953. (goto-char origin)
  9954. (error "No match for coderef: %s" coderef))))
  9955. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9956. ;; Look for a regular expression.
  9957. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9958. (match-string 1 s)))
  9959. ;; From here, we handle fuzzy links.
  9960. ;;
  9961. ;; Look for targets, only if not in a headline search.
  9962. ((and (not starred)
  9963. (let ((target (format "<<%s>>" s-multi-re)))
  9964. (catch :target-match
  9965. (goto-char (point-min))
  9966. (while (re-search-forward target nil t)
  9967. (backward-char)
  9968. (let ((context (org-element-context)))
  9969. (when (eq (org-element-type context) 'target)
  9970. (setq type 'dedicated)
  9971. (goto-char (org-element-property :begin context))
  9972. (throw :target-match t))))
  9973. nil))))
  9974. ;; Look for elements named after S, only if not in a headline
  9975. ;; search.
  9976. ((and (not starred)
  9977. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9978. (catch :name-match
  9979. (goto-char (point-min))
  9980. (while (re-search-forward name nil t)
  9981. (let ((element (org-element-at-point)))
  9982. (when (equal words
  9983. (split-string
  9984. (org-element-property :name element)))
  9985. (setq type 'dedicated)
  9986. (beginning-of-line)
  9987. (throw :name-match t))))
  9988. nil))))
  9989. ;; Regular text search. Prefer headlines in Org mode buffers.
  9990. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9991. ;; statistics cookies and tags.
  9992. ((and (derived-mode-p 'org-mode)
  9993. (let ((title-re
  9994. (format "%s[ \t]*\\(?:%s[ \t]+\\)?.*%s"
  9995. org-outline-regexp-bol
  9996. org-comment-string
  9997. (mapconcat
  9998. (lambda (w) (format "\\<%s\\>" (regexp-quote w)))
  9999. words
  10000. ".+")))
  10001. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  10002. (comment-re (format "\\`%s[ \t]+" org-comment-string)))
  10003. (goto-char (point-min))
  10004. (catch :found
  10005. (while (re-search-forward title-re nil t)
  10006. (when (equal words
  10007. (split-string
  10008. (replace-regexp-in-string
  10009. cookie-re ""
  10010. (replace-regexp-in-string
  10011. comment-re "" (org-get-heading t t)))))
  10012. (throw :found t)))
  10013. nil)))
  10014. (beginning-of-line)
  10015. (setq type 'dedicated))
  10016. ;; Offer to create non-existent headline depending on
  10017. ;; `org-link-search-must-match-exact-headline'.
  10018. ((and (derived-mode-p 'org-mode)
  10019. (not org-link-search-inhibit-query)
  10020. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10021. (yes-or-no-p "No match - create this as a new heading? "))
  10022. (goto-char (point-max))
  10023. (unless (bolp) (newline))
  10024. (org-insert-heading nil t t)
  10025. (insert s "\n")
  10026. (beginning-of-line 0))
  10027. ;; Only headlines are looked after. No need to process
  10028. ;; further: throw an error.
  10029. ((and (derived-mode-p 'org-mode)
  10030. (or starred org-link-search-must-match-exact-headline))
  10031. (goto-char origin)
  10032. (error "No match for fuzzy expression: %s" normalized))
  10033. ;; Regular text search.
  10034. ((catch :fuzzy-match
  10035. (goto-char (point-min))
  10036. (while (re-search-forward s-multi-re nil t)
  10037. ;; Skip match if it contains AVOID-POS or it is included in
  10038. ;; a link with a description but outside the description.
  10039. (unless (or (and avoid-pos
  10040. (<= (match-beginning 0) avoid-pos)
  10041. (> (match-end 0) avoid-pos))
  10042. (and (save-match-data
  10043. (org-in-regexp org-bracket-link-regexp))
  10044. (match-beginning 3)
  10045. (or (> (match-beginning 3) (point))
  10046. (<= (match-end 3) (point)))
  10047. (org-element-lineage
  10048. (save-match-data (org-element-context))
  10049. '(link) t)))
  10050. (goto-char (match-beginning 0))
  10051. (setq type 'fuzzy)
  10052. (throw :fuzzy-match t)))
  10053. nil))
  10054. ;; All failed. Throw an error.
  10055. (t (goto-char origin)
  10056. (error "No match for fuzzy expression: %s" normalized)))
  10057. ;; Disclose surroundings of match, if appropriate.
  10058. (when (and (derived-mode-p 'org-mode) (not stealth))
  10059. (org-show-context 'link-search))
  10060. type))
  10061. (defun org-get-buffer-for-internal-link (buffer)
  10062. "Return a buffer to be used for displaying the link target of internal links."
  10063. (cond
  10064. ((not org-display-internal-link-with-indirect-buffer)
  10065. buffer)
  10066. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10067. (message "Buffer is already a clone, not making another one")
  10068. ;; we also do not modify visibility in this case
  10069. buffer)
  10070. (t ; make a new indirect buffer for displaying the link
  10071. (let* ((bn (buffer-name buffer))
  10072. (ibn (concat bn "(Clone)"))
  10073. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10074. (with-current-buffer ib (org-overview))
  10075. ib))))
  10076. (defun org-do-occur (regexp &optional cleanup)
  10077. "Call the Emacs command `occur'.
  10078. If CLEANUP is non-nil, remove the printout of the regular expression
  10079. in the *Occur* buffer. This is useful if the regex is long and not useful
  10080. to read."
  10081. (occur regexp)
  10082. (when cleanup
  10083. (let ((cwin (selected-window)) win beg end)
  10084. (when (setq win (get-buffer-window "*Occur*"))
  10085. (select-window win))
  10086. (goto-char (point-min))
  10087. (when (re-search-forward "match[a-z]+" nil t)
  10088. (setq beg (match-end 0))
  10089. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10090. (setq end (1- (match-beginning 0)))))
  10091. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10092. (goto-char (point-min))
  10093. (select-window cwin))))
  10094. ;;; The mark ring for links jumps
  10095. (defvar org-mark-ring nil
  10096. "Mark ring for positions before jumps in Org mode.")
  10097. (defvar org-mark-ring-last-goto nil
  10098. "Last position in the mark ring used to go back.")
  10099. ;; Fill and close the ring
  10100. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10101. (dotimes (_ org-mark-ring-length)
  10102. (push (make-marker) org-mark-ring))
  10103. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10104. org-mark-ring)
  10105. (defun org-mark-ring-push (&optional pos buffer)
  10106. "Put the current position or POS into the mark ring and rotate it."
  10107. (interactive)
  10108. (setq pos (or pos (point)))
  10109. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10110. (move-marker (car org-mark-ring)
  10111. (or pos (point))
  10112. (or buffer (current-buffer)))
  10113. (message "%s"
  10114. (substitute-command-keys
  10115. "Position saved to mark ring, go back with \
  10116. `\\[org-mark-ring-goto]'.")))
  10117. (defun org-mark-ring-goto (&optional n)
  10118. "Jump to the previous position in the mark ring.
  10119. With prefix arg N, jump back that many stored positions. When
  10120. called several times in succession, walk through the entire ring.
  10121. Org mode commands jumping to a different position in the current file,
  10122. or to another Org file, automatically push the old position onto the ring."
  10123. (interactive "p")
  10124. (let (p m)
  10125. (if (eq last-command this-command)
  10126. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10127. (setq p org-mark-ring))
  10128. (setq org-mark-ring-last-goto p)
  10129. (setq m (car p))
  10130. (pop-to-buffer-same-window (marker-buffer m))
  10131. (goto-char m)
  10132. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10133. (defun org-add-angle-brackets (s)
  10134. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10135. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10136. s)
  10137. ;;; Following specific links
  10138. (defvar org-agenda-buffer-tmp-name)
  10139. (defvar org-agenda-start-on-weekday)
  10140. (defun org-follow-timestamp-link ()
  10141. "Open an agenda view for the time-stamp date/range at point."
  10142. (cond
  10143. ((org-at-date-range-p t)
  10144. (let ((org-agenda-start-on-weekday)
  10145. (t1 (match-string 1))
  10146. (t2 (match-string 2)) tt1 tt2)
  10147. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10148. tt2 (time-to-days (org-time-string-to-time t2)))
  10149. (let ((org-agenda-buffer-tmp-name
  10150. (format "*Org Agenda(a:%s)"
  10151. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10152. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10153. ((org-at-timestamp-p t)
  10154. (let ((org-agenda-buffer-tmp-name
  10155. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10156. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10157. (substring (match-string 1) 0 10)))
  10158. 1)))
  10159. (t (error "This should not happen"))))
  10160. ;;; Following file links
  10161. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10162. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10163. (declare-function mailcap-mime-info
  10164. "mailcap" (string &optional request no-decode))
  10165. (defvar org-wait nil)
  10166. (defun org-open-file (path &optional in-emacs line search)
  10167. "Open the file at PATH.
  10168. First, this expands any special file name abbreviations. Then the
  10169. configuration variable `org-file-apps' is checked if it contains an
  10170. entry for this file type, and if yes, the corresponding command is launched.
  10171. If no application is found, Emacs simply visits the file.
  10172. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10173. With a double \\[universal-argument] \\[universal-argument] \
  10174. prefix arg, Org tries to avoid opening in Emacs
  10175. and to use an external application to visit the file.
  10176. Optional LINE specifies a line to go to, optional SEARCH a string
  10177. to search for. If LINE or SEARCH is given, the file will be
  10178. opened in Emacs, unless an entry from org-file-apps that makes
  10179. use of groups in a regexp matches.
  10180. If you want to change the way frames are used when following a
  10181. link, please customize `org-link-frame-setup'.
  10182. If the file does not exist, an error is thrown."
  10183. (let* ((file (if (equal path "")
  10184. buffer-file-name
  10185. (substitute-in-file-name (expand-file-name path))))
  10186. (file-apps (append org-file-apps (org-default-apps)))
  10187. (apps (cl-remove-if
  10188. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10189. (apps-dlink (cl-remove-if-not
  10190. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10191. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10192. (dirp (unless remp (file-directory-p file)))
  10193. (file (if (and dirp org-open-directory-means-index-dot-org)
  10194. (concat (file-name-as-directory file) "index.org")
  10195. file))
  10196. (a-m-a-p (assq 'auto-mode apps))
  10197. (dfile (downcase file))
  10198. ;; Reconstruct the original link from the PATH, LINE and
  10199. ;; SEARCH args.
  10200. (link (cond (line (concat file "::" (number-to-string line)))
  10201. (search (concat file "::" search))
  10202. (t file)))
  10203. (dlink (downcase link))
  10204. (old-buffer (current-buffer))
  10205. (old-pos (point))
  10206. (old-mode major-mode)
  10207. (ext
  10208. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10209. (match-string 1 dfile)))
  10210. cmd link-match-data)
  10211. (cond
  10212. ((member in-emacs '((16) system))
  10213. (setq cmd (cdr (assq 'system apps))))
  10214. (in-emacs (setq cmd 'emacs))
  10215. (t
  10216. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10217. (and dirp (cdr (assq 'directory apps)))
  10218. ;; First, try matching against apps-dlink if we
  10219. ;; get a match here, store the match data for
  10220. ;; later.
  10221. (let ((match (assoc-default dlink apps-dlink
  10222. 'string-match)))
  10223. (if match
  10224. (progn (setq link-match-data (match-data))
  10225. match)
  10226. (progn (setq in-emacs (or in-emacs line search))
  10227. nil))) ; if we have no match in apps-dlink,
  10228. ; always open the file in emacs if line or search
  10229. ; is given (for backwards compatibility)
  10230. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10231. 'string-match)
  10232. (cdr (assoc ext apps))
  10233. (cdr (assq t apps))))))
  10234. (when (eq cmd 'system)
  10235. (setq cmd (cdr (assq 'system apps))))
  10236. (when (eq cmd 'default)
  10237. (setq cmd (cdr (assoc t apps))))
  10238. (when (eq cmd 'mailcap)
  10239. (require 'mailcap)
  10240. (mailcap-parse-mailcaps)
  10241. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10242. (command (mailcap-mime-info mime-type)))
  10243. (if (stringp command)
  10244. (setq cmd command)
  10245. (setq cmd 'emacs))))
  10246. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10247. (not (file-exists-p file))
  10248. (not org-open-non-existing-files))
  10249. (user-error "No such file: %s" file))
  10250. (cond
  10251. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10252. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10253. (while (string-match "['\"]%s['\"]" cmd)
  10254. (setq cmd (replace-match "%s" t t cmd)))
  10255. (setq cmd (replace-regexp-in-string
  10256. "%s"
  10257. (shell-quote-argument (convert-standard-filename file))
  10258. cmd
  10259. nil t))
  10260. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10261. (save-match-data
  10262. (let ((match-index 1)
  10263. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10264. (set-match-data link-match-data)
  10265. (while (<= match-index number-of-groups)
  10266. (let ((regex (concat "%" (number-to-string match-index)))
  10267. (replace-with (match-string match-index dlink)))
  10268. (while (string-match regex cmd)
  10269. (setq cmd (replace-match replace-with t t cmd))))
  10270. (setq match-index (+ match-index 1)))))
  10271. (save-window-excursion
  10272. (message "Running %s...done" cmd)
  10273. (start-process-shell-command cmd nil cmd)
  10274. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10275. ((or (stringp cmd)
  10276. (eq cmd 'emacs))
  10277. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10278. (widen)
  10279. (cond (line (org-goto-line line)
  10280. (when (derived-mode-p 'org-mode) (org-reveal)))
  10281. (search (org-link-search search))))
  10282. ((functionp cmd)
  10283. (save-match-data
  10284. (set-match-data link-match-data)
  10285. (condition-case nil
  10286. (funcall cmd file link)
  10287. ;; FIXME: Remove this check when most default installations
  10288. ;; of Emacs have at least Org 9.0.
  10289. ((debug wrong-number-of-arguments wrong-type-argument
  10290. invalid-function)
  10291. (user-error "Please see Org News for version 9.0 about \
  10292. `org-file-apps'--Lisp error: %S" cmd)))))
  10293. ((consp cmd)
  10294. ;; FIXME: Remove this check when most default installations of
  10295. ;; Emacs have at least Org 9.0.
  10296. ;; Heads-up instead of silently fall back to
  10297. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10298. ;; with sexp instead of a function for `cmd'.
  10299. (user-error "Please see Org News for version 9.0 about \
  10300. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10301. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10302. (and (derived-mode-p 'org-mode)
  10303. (eq old-mode 'org-mode)
  10304. (or (not (eq old-buffer (current-buffer)))
  10305. (not (eq old-pos (point))))
  10306. (org-mark-ring-push old-pos old-buffer))))
  10307. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10308. "This function returns non-nil if `entry' uses a regular
  10309. expression which should be matched against the whole link by
  10310. org-open-file.
  10311. It assumes that is the case when the entry uses a regular
  10312. expression which has at least one grouping construct and the
  10313. action is either a lisp form or a command string containing
  10314. `%1', i.e. using at least one subexpression match as a
  10315. parameter."
  10316. (let ((selector (car entry))
  10317. (action (cdr entry)))
  10318. (if (stringp selector)
  10319. (and (> (regexp-opt-depth selector) 0)
  10320. (or (and (stringp action)
  10321. (string-match "%[0-9]" action))
  10322. (consp action)))
  10323. nil)))
  10324. (defun org-default-apps ()
  10325. "Return the default applications for this operating system."
  10326. (cond
  10327. ((eq system-type 'darwin)
  10328. org-file-apps-defaults-macosx)
  10329. ((eq system-type 'windows-nt)
  10330. org-file-apps-defaults-windowsnt)
  10331. (t org-file-apps-defaults-gnu)))
  10332. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10333. "Convert extensions to regular expressions in the cars of LIST.
  10334. Also, weed out any non-string entries, because the return value is used
  10335. only for regexp matching.
  10336. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10337. point to the symbol `emacs', indicating that the file should
  10338. be opened in Emacs."
  10339. (append
  10340. (delq nil
  10341. (mapcar (lambda (x)
  10342. (unless (not (stringp (car x)))
  10343. (if (string-match "\\W" (car x))
  10344. x
  10345. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10346. list))
  10347. (when add-auto-mode
  10348. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10349. (defvar ange-ftp-name-format)
  10350. (defun org-file-remote-p (file)
  10351. "Test whether FILE specifies a location on a remote system.
  10352. Return non-nil if the location is indeed remote.
  10353. For example, the filename \"/user@host:/foo\" specifies a location
  10354. on the system \"/user@host:\"."
  10355. (cond ((fboundp 'file-remote-p)
  10356. (file-remote-p file))
  10357. ((fboundp 'tramp-handle-file-remote-p)
  10358. (tramp-handle-file-remote-p file))
  10359. ((and (boundp 'ange-ftp-name-format)
  10360. (string-match (car ange-ftp-name-format) file))
  10361. t)))
  10362. ;;;; Refiling
  10363. (defun org-get-org-file ()
  10364. "Read a filename, with default directory `org-directory'."
  10365. (let ((default (or org-default-notes-file remember-data-file)))
  10366. (read-file-name (format "File name [%s]: " default)
  10367. (file-name-as-directory org-directory)
  10368. default)))
  10369. (defun org-notes-order-reversed-p ()
  10370. "Check if the current file should receive notes in reversed order."
  10371. (cond
  10372. ((not org-reverse-note-order) nil)
  10373. ((eq t org-reverse-note-order) t)
  10374. ((not (listp org-reverse-note-order)) nil)
  10375. (t (catch 'exit
  10376. (dolist (entry org-reverse-note-order)
  10377. (when (string-match (car entry) buffer-file-name)
  10378. (throw 'exit (cdr entry))))))))
  10379. (defvar org-refile-target-table nil
  10380. "The list of refile targets, created by `org-refile'.")
  10381. (defvar org-agenda-new-buffers nil
  10382. "Buffers created to visit agenda files.")
  10383. (defvar org-refile-cache nil
  10384. "Cache for refile targets.")
  10385. (defvar org-refile-markers nil
  10386. "All the markers used for caching refile locations.")
  10387. (defun org-refile-marker (pos)
  10388. "Get a new refile marker, but only if caching is in use."
  10389. (if (not org-refile-use-cache)
  10390. pos
  10391. (let ((m (make-marker)))
  10392. (move-marker m pos)
  10393. (push m org-refile-markers)
  10394. m)))
  10395. (defun org-refile-cache-clear ()
  10396. "Clear the refile cache and disable all the markers."
  10397. (dolist (m org-refile-markers) (move-marker m nil))
  10398. (setq org-refile-markers nil)
  10399. (setq org-refile-cache nil)
  10400. (message "Refile cache has been cleared"))
  10401. (defun org-refile-cache-check-set (set)
  10402. "Check if all the markers in the cache still have live buffers."
  10403. (let (marker)
  10404. (catch 'exit
  10405. (while (and set (setq marker (nth 3 (pop set))))
  10406. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10407. (when (and marker (null (marker-buffer marker)))
  10408. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10409. (sit-for 3)
  10410. (throw 'exit nil)))
  10411. t)))
  10412. (defun org-refile-cache-put (set &rest identifiers)
  10413. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10414. (let* ((key (sha1 (prin1-to-string identifiers)))
  10415. (entry (assoc key org-refile-cache)))
  10416. (if entry
  10417. (setcdr entry set)
  10418. (push (cons key set) org-refile-cache))))
  10419. (defun org-refile-cache-get (&rest identifiers)
  10420. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10421. (cond
  10422. ((not org-refile-cache) nil)
  10423. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10424. (t
  10425. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10426. org-refile-cache))))
  10427. (and set (org-refile-cache-check-set set) set)))))
  10428. (defvar org-outline-path-cache nil
  10429. "Alist between buffer positions and outline paths.
  10430. It value is an alist (POSITION . PATH) where POSITION is the
  10431. buffer position at the beginning of an entry and PATH is a list
  10432. of strings describing the outline path for that entry, in reverse
  10433. order.")
  10434. (defun org-refile-get-targets (&optional default-buffer)
  10435. "Produce a table with refile targets."
  10436. (let ((case-fold-search nil)
  10437. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10438. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10439. targets tgs files desc descre)
  10440. (message "Getting targets...")
  10441. (with-current-buffer (or default-buffer (current-buffer))
  10442. (dolist (entry entries)
  10443. (setq files (car entry) desc (cdr entry))
  10444. (cond
  10445. ((null files) (setq files (list (current-buffer))))
  10446. ((eq files 'org-agenda-files)
  10447. (setq files (org-agenda-files 'unrestricted)))
  10448. ((and (symbolp files) (fboundp files))
  10449. (setq files (funcall files)))
  10450. ((and (symbolp files) (boundp files))
  10451. (setq files (symbol-value files))))
  10452. (when (stringp files) (setq files (list files)))
  10453. (cond
  10454. ((eq (car desc) :tag)
  10455. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10456. ((eq (car desc) :todo)
  10457. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10458. ((eq (car desc) :regexp)
  10459. (setq descre (cdr desc)))
  10460. ((eq (car desc) :level)
  10461. (setq descre (concat "^\\*\\{" (number-to-string
  10462. (if org-odd-levels-only
  10463. (1- (* 2 (cdr desc)))
  10464. (cdr desc)))
  10465. "\\}[ \t]")))
  10466. ((eq (car desc) :maxlevel)
  10467. (setq descre (concat "^\\*\\{1," (number-to-string
  10468. (if org-odd-levels-only
  10469. (1- (* 2 (cdr desc)))
  10470. (cdr desc)))
  10471. "\\}[ \t]")))
  10472. (t (error "Bad refiling target description %s" desc)))
  10473. (dolist (f files)
  10474. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10475. (or
  10476. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10477. (progn
  10478. (when (bufferp f)
  10479. (setq f (buffer-file-name (buffer-base-buffer f))))
  10480. (setq f (and f (expand-file-name f)))
  10481. (when (eq org-refile-use-outline-path 'file)
  10482. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10483. (org-with-wide-buffer
  10484. (goto-char (point-min))
  10485. (setq org-outline-path-cache nil)
  10486. (while (re-search-forward descre nil t)
  10487. (beginning-of-line)
  10488. (let ((case-fold-search nil))
  10489. (looking-at org-complex-heading-regexp))
  10490. (let ((begin (point))
  10491. (heading (match-string-no-properties 4)))
  10492. (unless (or (and
  10493. org-refile-target-verify-function
  10494. (not
  10495. (funcall org-refile-target-verify-function)))
  10496. (not heading))
  10497. (let ((re (format org-complex-heading-regexp-format
  10498. (regexp-quote heading)))
  10499. (target
  10500. (if (not org-refile-use-outline-path) heading
  10501. (mapconcat
  10502. #'org-protect-slash
  10503. (append
  10504. (pcase org-refile-use-outline-path
  10505. (`file (list (file-name-nondirectory
  10506. (buffer-file-name
  10507. (buffer-base-buffer)))))
  10508. (`full-file-path
  10509. (list (buffer-file-name
  10510. (buffer-base-buffer))))
  10511. (_ nil))
  10512. (org-get-outline-path t t))
  10513. "/"))))
  10514. (push (list target f re (org-refile-marker (point)))
  10515. tgs)))
  10516. (when (= (point) begin)
  10517. ;; Verification function has not moved point.
  10518. (end-of-line)))))))
  10519. (when org-refile-use-cache
  10520. (org-refile-cache-put tgs (buffer-file-name) descre))
  10521. (setq targets (append tgs targets))))))
  10522. (message "Getting targets...done")
  10523. (nreverse targets)))
  10524. (defun org-protect-slash (s)
  10525. (replace-regexp-in-string "/" "\\/" s nil t))
  10526. (defun org--get-outline-path-1 (&optional use-cache)
  10527. "Return outline path to current headline.
  10528. Outline path is a list of strings, in reverse order. When
  10529. optional argument USE-CACHE is non-nil, make use of a cache. See
  10530. `org-get-outline-path' for details.
  10531. Assume buffer is widened and point is on a headline."
  10532. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10533. (let ((p (point))
  10534. (heading (let ((case-fold-search nil))
  10535. (looking-at org-complex-heading-regexp)
  10536. (if (not (match-end 4)) ""
  10537. ;; Remove statistics cookies.
  10538. (org-trim
  10539. (org-link-display-format
  10540. (replace-regexp-in-string
  10541. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10542. (match-string-no-properties 4))))))))
  10543. (if (org-up-heading-safe)
  10544. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10545. (when use-cache
  10546. (push (cons p path) org-outline-path-cache))
  10547. path)
  10548. ;; This is a new root node. Since we assume we are moving
  10549. ;; forward, we can drop previous cache so as to limit number
  10550. ;; of associations there.
  10551. (let ((path (list heading)))
  10552. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10553. path)))))
  10554. (defun org-get-outline-path (&optional with-self use-cache)
  10555. "Return the outline path to the current entry.
  10556. An outline path is a list of ancestors for current headline, as
  10557. a list of strings. Statistics cookies are removed and links are
  10558. replaced with their description, if any, or their path otherwise.
  10559. When optional argument WITH-SELF is non-nil, the path also
  10560. includes the current headline.
  10561. When optional argument USE-CACHE is non-nil, cache outline paths
  10562. between calls to this function so as to avoid backtracking. This
  10563. argument is useful when planning to find more than one outline
  10564. path in the same document. In that case, there are two
  10565. conditions to satisfy:
  10566. - `org-outline-path-cache' is set to nil before starting the
  10567. process;
  10568. - outline paths are computed by increasing buffer positions."
  10569. (org-with-wide-buffer
  10570. (and (or (and with-self (org-back-to-heading t))
  10571. (org-up-heading-safe))
  10572. (reverse (org--get-outline-path-1 use-cache)))))
  10573. (defun org-format-outline-path (path &optional width prefix separator)
  10574. "Format the outline path PATH for display.
  10575. WIDTH is the maximum number of characters that is available.
  10576. PREFIX is a prefix to be included in the returned string,
  10577. such as the file name.
  10578. SEPARATOR is inserted between the different parts of the path,
  10579. the default is \"/\"."
  10580. (setq width (or width 79))
  10581. (setq path (delq nil path))
  10582. (unless (> width 0)
  10583. (user-error "Argument `width' must be positive"))
  10584. (setq separator (or separator "/"))
  10585. (let* ((org-odd-levels-only nil)
  10586. (fpath (concat
  10587. prefix (and prefix path separator)
  10588. (mapconcat
  10589. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10590. (cl-loop for head in path
  10591. for n from 0
  10592. collect (org-add-props
  10593. head nil 'face
  10594. (nth (% n org-n-level-faces) org-level-faces)))
  10595. separator))))
  10596. (when (> (length fpath) width)
  10597. (if (< width 7)
  10598. ;; It's unlikely that `width' will be this small, but don't
  10599. ;; waste characters by adding ".." if it is.
  10600. (setq fpath (substring fpath 0 width))
  10601. (setf (substring fpath (- width 2)) "..")))
  10602. fpath))
  10603. (defun org-display-outline-path (&optional file current separator just-return-string)
  10604. "Display the current outline path in the echo area.
  10605. If FILE is non-nil, prepend the output with the file name.
  10606. If CURRENT is non-nil, append the current heading to the output.
  10607. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10608. the different parts of the path and defaults to \"/\".
  10609. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10610. (interactive "P")
  10611. (let* (case-fold-search
  10612. (bfn (buffer-file-name (buffer-base-buffer)))
  10613. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10614. res)
  10615. (when current (setq path (append path
  10616. (save-excursion
  10617. (org-back-to-heading t)
  10618. (when (looking-at org-complex-heading-regexp)
  10619. (list (match-string 4)))))))
  10620. (setq res
  10621. (org-format-outline-path
  10622. path
  10623. (1- (frame-width))
  10624. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10625. separator))
  10626. (if just-return-string
  10627. (org-no-properties res)
  10628. (org-unlogged-message "%s" res))))
  10629. (defvar org-refile-history nil
  10630. "History for refiling operations.")
  10631. (defvar org-after-refile-insert-hook nil
  10632. "Hook run after `org-refile' has inserted its stuff at the new location.
  10633. Note that this is still *before* the stuff will be removed from
  10634. the *old* location.")
  10635. (defvar org-capture-last-stored-marker)
  10636. (defvar org-refile-keep nil
  10637. "Non-nil means `org-refile' will copy instead of refile.")
  10638. (defun org-copy ()
  10639. "Like `org-refile', but copy."
  10640. (interactive)
  10641. (let ((org-refile-keep t))
  10642. (funcall 'org-refile nil nil nil "Copy")))
  10643. (defun org-refile (&optional arg default-buffer rfloc msg)
  10644. "Move the entry or entries at point to another heading.
  10645. The list of target headings is compiled using the information in
  10646. `org-refile-targets', which see.
  10647. At the target location, the entry is filed as a subitem of the
  10648. target heading. Depending on `org-reverse-note-order', the new
  10649. subitem will either be the first or the last subitem.
  10650. If there is an active region, all entries in that region will be
  10651. refiled. However, the region must fulfill the requirement that
  10652. the first heading sets the top-level of the moved text.
  10653. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10654. location
  10655. and not actually move anything.
  10656. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10657. location where the last
  10658. refiling operation has put the subtree.
  10659. With a numeric prefix argument of `2', refile to the running clock.
  10660. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10661. being set to t and copy to the target location, don't move it.
  10662. Beware that keeping refiled entries may result in duplicated ID
  10663. properties.
  10664. RFLOC can be a refile location obtained in a different way.
  10665. MSG is a string to replace \"Refile\" in the default prompt with
  10666. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10667. See also `org-refile-use-outline-path'.
  10668. If you are using target caching (see `org-refile-use-cache'), you
  10669. have to clear the target cache in order to find new targets.
  10670. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10671. prefix argument (`C-u C-u C-u C-c C-w')."
  10672. (interactive "P")
  10673. (if (member arg '(0 (64)))
  10674. (org-refile-cache-clear)
  10675. (let* ((actionmsg (cond (msg msg)
  10676. ((equal arg 3) "Refile (and keep)")
  10677. (t "Refile")))
  10678. (regionp (org-region-active-p))
  10679. (region-start (and regionp (region-beginning)))
  10680. (region-end (and regionp (region-end)))
  10681. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10682. pos it nbuf file level reversed)
  10683. (setq last-command nil)
  10684. (when regionp
  10685. (goto-char region-start)
  10686. (or (bolp) (goto-char (point-at-bol)))
  10687. (setq region-start (point))
  10688. (unless (or (org-kill-is-subtree-p
  10689. (buffer-substring region-start region-end))
  10690. (prog1 org-refile-active-region-within-subtree
  10691. (let ((s (point-at-eol)))
  10692. (org-toggle-heading)
  10693. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10694. (user-error "The region is not a (sequence of) subtree(s)")))
  10695. (if (equal arg '(16))
  10696. (org-refile-goto-last-stored)
  10697. (when (or
  10698. (and (equal arg 2)
  10699. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10700. (prog1
  10701. (setq it (list (or org-clock-heading "running clock")
  10702. (buffer-file-name
  10703. (marker-buffer org-clock-hd-marker))
  10704. ""
  10705. (marker-position org-clock-hd-marker)))
  10706. (setq arg nil)))
  10707. (setq it
  10708. (or rfloc
  10709. (let (heading-text)
  10710. (save-excursion
  10711. (unless (and arg (listp arg))
  10712. (org-back-to-heading t)
  10713. (setq heading-text
  10714. (replace-regexp-in-string
  10715. org-bracket-link-regexp
  10716. "\\3"
  10717. (or (nth 4 (org-heading-components))
  10718. ""))))
  10719. (org-refile-get-location
  10720. (cond ((and arg (listp arg)) "Goto")
  10721. (regionp (concat actionmsg " region to"))
  10722. (t (concat actionmsg " subtree \""
  10723. heading-text "\" to")))
  10724. default-buffer
  10725. (and (not (equal '(4) arg))
  10726. org-refile-allow-creating-parent-nodes)))))))
  10727. (setq file (nth 1 it)
  10728. pos (nth 3 it))
  10729. (when (and (not arg)
  10730. pos
  10731. (equal (buffer-file-name) file)
  10732. (if regionp
  10733. (and (>= pos region-start)
  10734. (<= pos region-end))
  10735. (and (>= pos (point))
  10736. (< pos (save-excursion
  10737. (org-end-of-subtree t t))))))
  10738. (error "Cannot refile to position inside the tree or region"))
  10739. (setq nbuf (or (find-buffer-visiting file)
  10740. (find-file-noselect file)))
  10741. (if (and arg (not (equal arg 3)))
  10742. (progn
  10743. (pop-to-buffer-same-window nbuf)
  10744. (goto-char pos)
  10745. (org-show-context 'org-goto))
  10746. (if regionp
  10747. (progn
  10748. (org-kill-new (buffer-substring region-start region-end))
  10749. (org-save-markers-in-region region-start region-end))
  10750. (org-copy-subtree 1 nil t))
  10751. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10752. (find-file-noselect file)))
  10753. (setq reversed (org-notes-order-reversed-p))
  10754. (org-with-wide-buffer
  10755. (if pos
  10756. (progn
  10757. (goto-char pos)
  10758. (looking-at org-outline-regexp)
  10759. (setq level (org-get-valid-level (funcall outline-level) 1))
  10760. (goto-char
  10761. (if reversed
  10762. (or (outline-next-heading) (point-max))
  10763. (or (save-excursion (org-get-next-sibling))
  10764. (org-end-of-subtree t t)
  10765. (point-max)))))
  10766. (setq level 1)
  10767. (if (not reversed)
  10768. (goto-char (point-max))
  10769. (goto-char (point-min))
  10770. (or (outline-next-heading) (goto-char (point-max)))))
  10771. (unless (bolp) (newline))
  10772. (org-paste-subtree level nil nil t)
  10773. (when org-log-refile
  10774. (org-add-log-setup 'refile nil nil org-log-refile)
  10775. (unless (eq org-log-refile 'note)
  10776. (save-excursion (org-add-log-note))))
  10777. (and org-auto-align-tags
  10778. (let ((org-loop-over-headlines-in-active-region nil))
  10779. (org-set-tags nil t)))
  10780. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10781. :last-refile)))
  10782. (when bookmark-name
  10783. (with-demoted-errors
  10784. (bookmark-set bookmark-name))))
  10785. ;; If we are refiling for capture, make sure that the
  10786. ;; last-capture pointers point here
  10787. (when (bound-and-true-p org-capture-is-refiling)
  10788. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10789. :last-capture-marker)))
  10790. (when bookmark-name
  10791. (with-demoted-errors
  10792. (bookmark-set bookmark-name))))
  10793. (move-marker org-capture-last-stored-marker (point)))
  10794. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10795. (run-hooks 'org-after-refile-insert-hook)))
  10796. (unless org-refile-keep
  10797. (if regionp
  10798. (delete-region (point) (+ (point) (- region-end region-start)))
  10799. (delete-region
  10800. (and (org-back-to-heading t) (point))
  10801. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10802. (when (featurep 'org-inlinetask)
  10803. (org-inlinetask-remove-END-maybe))
  10804. (setq org-markers-to-move nil)
  10805. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10806. (defun org-refile-goto-last-stored ()
  10807. "Go to the location where the last refile was stored."
  10808. (interactive)
  10809. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10810. (message "This is the location of the last refile"))
  10811. (defun org-refile--get-location (refloc tbl)
  10812. "When user refile to REFLOC, find the associated target in TBL.
  10813. Also check `org-refile-target-table'."
  10814. (car (delq
  10815. nil
  10816. (mapcar
  10817. (lambda (r) (or (assoc r tbl)
  10818. (assoc r org-refile-target-table)))
  10819. (list (replace-regexp-in-string "/$" "" refloc)
  10820. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10821. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10822. "Prompt the user for a refile location, using PROMPT.
  10823. PROMPT should not be suffixed with a colon and a space, because
  10824. this function appends the default value from
  10825. `org-refile-history' automatically, if that is not empty."
  10826. (let ((org-refile-targets org-refile-targets)
  10827. (org-refile-use-outline-path org-refile-use-outline-path))
  10828. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10829. (unless org-refile-target-table
  10830. (user-error "No refile targets"))
  10831. (let* ((cbuf (current-buffer))
  10832. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10833. (cfunc (if (and org-refile-use-outline-path
  10834. org-outline-path-complete-in-steps)
  10835. #'org-olpath-completing-read
  10836. #'completing-read))
  10837. (extra (if org-refile-use-outline-path "/" ""))
  10838. (cbnex (concat (buffer-name) extra))
  10839. (filename (and cfn (expand-file-name cfn)))
  10840. (tbl (mapcar
  10841. (lambda (x)
  10842. (if (and (not (member org-refile-use-outline-path
  10843. '(file full-file-path)))
  10844. (not (equal filename (nth 1 x))))
  10845. (cons (concat (car x) extra " ("
  10846. (file-name-nondirectory (nth 1 x)) ")")
  10847. (cdr x))
  10848. (cons (concat (car x) extra) (cdr x))))
  10849. org-refile-target-table))
  10850. (completion-ignore-case t)
  10851. cdef
  10852. (prompt (concat prompt
  10853. (or (and (car org-refile-history)
  10854. (concat " (default " (car org-refile-history) ")"))
  10855. (and (assoc cbnex tbl) (setq cdef cbnex)
  10856. (concat " (default " cbnex ")"))) ": "))
  10857. pa answ parent-target child parent old-hist)
  10858. (setq old-hist org-refile-history)
  10859. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10860. nil 'org-refile-history (or cdef (car org-refile-history))))
  10861. (if (setq pa (org-refile--get-location answ tbl))
  10862. (progn
  10863. (org-refile-check-position pa)
  10864. (when (or (not org-refile-history)
  10865. (not (eq old-hist org-refile-history))
  10866. (not (equal (car pa) (car org-refile-history))))
  10867. (setq org-refile-history
  10868. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10869. org-refile-history
  10870. (cdr org-refile-history))))
  10871. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10872. (pop org-refile-history)))
  10873. pa)
  10874. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10875. (progn
  10876. (setq parent (match-string 1 answ)
  10877. child (match-string 2 answ))
  10878. (setq parent-target (org-refile--get-location parent tbl))
  10879. (when (and parent-target
  10880. (or (eq new-nodes t)
  10881. (and (eq new-nodes 'confirm)
  10882. (y-or-n-p (format "Create new node \"%s\"? "
  10883. child)))))
  10884. (org-refile-new-child parent-target child)))
  10885. (user-error "Invalid target location")))))
  10886. (declare-function org-string-nw-p "org-macs" (s))
  10887. (defun org-refile-check-position (refile-pointer)
  10888. "Check if the refile pointer matches the headline to which it points."
  10889. (let* ((file (nth 1 refile-pointer))
  10890. (re (nth 2 refile-pointer))
  10891. (pos (nth 3 refile-pointer))
  10892. buffer)
  10893. (if (and (not (markerp pos)) (not file))
  10894. (user-error "Please indicate a target file in the refile path")
  10895. (when (org-string-nw-p re)
  10896. (setq buffer (if (markerp pos)
  10897. (marker-buffer pos)
  10898. (or (find-buffer-visiting file)
  10899. (find-file-noselect file))))
  10900. (with-current-buffer buffer
  10901. (org-with-wide-buffer
  10902. (goto-char pos)
  10903. (beginning-of-line 1)
  10904. (unless (looking-at-p re)
  10905. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10906. (defun org-refile-new-child (parent-target child)
  10907. "Use refile target PARENT-TARGET to add new CHILD below it."
  10908. (unless parent-target
  10909. (error "Cannot find parent for new node"))
  10910. (let ((file (nth 1 parent-target))
  10911. (pos (nth 3 parent-target))
  10912. level)
  10913. (with-current-buffer (or (find-buffer-visiting file)
  10914. (find-file-noselect file))
  10915. (org-with-wide-buffer
  10916. (if pos
  10917. (goto-char pos)
  10918. (goto-char (point-max))
  10919. (unless (bolp) (newline)))
  10920. (when (looking-at org-outline-regexp)
  10921. (setq level (funcall outline-level))
  10922. (org-end-of-subtree t t))
  10923. (org-back-over-empty-lines)
  10924. (insert "\n" (make-string
  10925. (if pos (org-get-valid-level level 1) 1) ?*)
  10926. " " child "\n")
  10927. (beginning-of-line 0)
  10928. (list (concat (car parent-target) "/" child) file "" (point))))))
  10929. (defun org-olpath-completing-read (prompt collection &rest args)
  10930. "Read an outline path like a file name."
  10931. (let ((thetable collection))
  10932. (apply #'completing-read
  10933. prompt
  10934. (lambda (string predicate &optional flag)
  10935. (cond
  10936. ((eq flag nil) (try-completion string thetable))
  10937. ((eq flag t)
  10938. (let ((l (length string)))
  10939. (mapcar (lambda (x)
  10940. (let ((r (substring x l))
  10941. (f (if (string-match " ([^)]*)$" x)
  10942. (match-string 0 x)
  10943. "")))
  10944. (if (string-match "/" r)
  10945. (concat string (substring r 0 (match-end 0)) f)
  10946. x)))
  10947. (all-completions string thetable predicate))))
  10948. ;; Exact match?
  10949. ((eq flag 'lambda) (assoc string thetable))))
  10950. args)))
  10951. ;;;; Dynamic blocks
  10952. (defun org-find-dblock (name)
  10953. "Find the first dynamic block with name NAME in the buffer.
  10954. If not found, stay at current position and return nil."
  10955. (let ((case-fold-search t) pos)
  10956. (save-excursion
  10957. (goto-char (point-min))
  10958. (setq pos (and (re-search-forward
  10959. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10960. (match-beginning 0))))
  10961. (when pos (goto-char pos))
  10962. pos))
  10963. (defun org-create-dblock (plist)
  10964. "Create a dynamic block section, with parameters taken from PLIST.
  10965. PLIST must contain a :name entry which is used as the name of the block."
  10966. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10967. (end-of-line 1)
  10968. (newline))
  10969. (let ((col (current-column))
  10970. (name (plist-get plist :name)))
  10971. (insert "#+BEGIN: " name)
  10972. (while plist
  10973. (if (eq (car plist) :name)
  10974. (setq plist (cddr plist))
  10975. (insert " " (prin1-to-string (pop plist)))))
  10976. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10977. (beginning-of-line -2)))
  10978. (defun org-prepare-dblock ()
  10979. "Prepare dynamic block for refresh.
  10980. This empties the block, puts the cursor at the insert position and returns
  10981. the property list including an extra property :name with the block name."
  10982. (unless (looking-at org-dblock-start-re)
  10983. (user-error "Not at a dynamic block"))
  10984. (let* ((begdel (1+ (match-end 0)))
  10985. (name (org-no-properties (match-string 1)))
  10986. (params (append (list :name name)
  10987. (read (concat "(" (match-string 3) ")")))))
  10988. (save-excursion
  10989. (beginning-of-line 1)
  10990. (skip-chars-forward " \t")
  10991. (setq params (plist-put params :indentation-column (current-column))))
  10992. (unless (re-search-forward org-dblock-end-re nil t)
  10993. (error "Dynamic block not terminated"))
  10994. (setq params
  10995. (append params
  10996. (list :content (buffer-substring
  10997. begdel (match-beginning 0)))))
  10998. (delete-region begdel (match-beginning 0))
  10999. (goto-char begdel)
  11000. (open-line 1)
  11001. params))
  11002. (defun org-map-dblocks (&optional command)
  11003. "Apply COMMAND to all dynamic blocks in the current buffer.
  11004. If COMMAND is not given, use `org-update-dblock'."
  11005. (let ((cmd (or command 'org-update-dblock)))
  11006. (save-excursion
  11007. (goto-char (point-min))
  11008. (while (re-search-forward org-dblock-start-re nil t)
  11009. (goto-char (match-beginning 0))
  11010. (save-excursion
  11011. (condition-case nil
  11012. (funcall cmd)
  11013. (error (message "Error during update of dynamic block"))))
  11014. (unless (re-search-forward org-dblock-end-re nil t)
  11015. (error "Dynamic block not terminated"))))))
  11016. (defun org-dblock-update (&optional arg)
  11017. "User command for updating dynamic blocks.
  11018. Update the dynamic block at point. With prefix ARG, update all dynamic
  11019. blocks in the buffer."
  11020. (interactive "P")
  11021. (if arg
  11022. (org-update-all-dblocks)
  11023. (or (looking-at org-dblock-start-re)
  11024. (org-beginning-of-dblock))
  11025. (org-update-dblock)))
  11026. (defun org-update-dblock ()
  11027. "Update the dynamic block at point.
  11028. This means to empty the block, parse for parameters and then call
  11029. the correct writing function."
  11030. (interactive)
  11031. (save-excursion
  11032. (let* ((win (selected-window))
  11033. (pos (point))
  11034. (line (org-current-line))
  11035. (params (org-prepare-dblock))
  11036. (name (plist-get params :name))
  11037. (indent (plist-get params :indentation-column))
  11038. (cmd (intern (concat "org-dblock-write:" name))))
  11039. (message "Updating dynamic block `%s' at line %d..." name line)
  11040. (funcall cmd params)
  11041. (message "Updating dynamic block `%s' at line %d...done" name line)
  11042. (goto-char pos)
  11043. (when (and indent (> indent 0))
  11044. (setq indent (make-string indent ?\ ))
  11045. (save-excursion
  11046. (select-window win)
  11047. (org-beginning-of-dblock)
  11048. (forward-line 1)
  11049. (while (not (looking-at org-dblock-end-re))
  11050. (insert indent)
  11051. (beginning-of-line 2))
  11052. (when (looking-at org-dblock-end-re)
  11053. (and (looking-at "[ \t]+")
  11054. (replace-match ""))
  11055. (insert indent)))))))
  11056. (defun org-beginning-of-dblock ()
  11057. "Find the beginning of the dynamic block at point.
  11058. Error if there is no such block at point."
  11059. (let ((pos (point))
  11060. beg)
  11061. (end-of-line 1)
  11062. (if (and (re-search-backward org-dblock-start-re nil t)
  11063. (setq beg (match-beginning 0))
  11064. (re-search-forward org-dblock-end-re nil t)
  11065. (> (match-end 0) pos))
  11066. (goto-char beg)
  11067. (goto-char pos)
  11068. (error "Not in a dynamic block"))))
  11069. (defun org-update-all-dblocks ()
  11070. "Update all dynamic blocks in the buffer.
  11071. This function can be used in a hook."
  11072. (interactive)
  11073. (when (derived-mode-p 'org-mode)
  11074. (org-map-dblocks 'org-update-dblock)))
  11075. ;;;; Completion
  11076. (declare-function org-export-backend-options "ox" (cl-x) t)
  11077. (defun org-get-export-keywords ()
  11078. "Return a list of all currently understood export keywords.
  11079. Export keywords include options, block names, attributes and
  11080. keywords relative to each registered export back-end."
  11081. (let (keywords)
  11082. (dolist (backend
  11083. (bound-and-true-p org-export-registered-backends)
  11084. (delq nil keywords))
  11085. ;; Back-end name (for keywords, like #+LATEX:)
  11086. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11087. (dolist (option-entry (org-export-backend-options backend))
  11088. ;; Back-end options.
  11089. (push (nth 1 option-entry) keywords)))))
  11090. (defconst org-options-keywords
  11091. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11092. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11093. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11094. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11095. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11096. (defcustom org-structure-template-alist
  11097. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11098. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11099. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11100. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11101. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11102. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11103. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11104. ("L" "#+LaTeX: ")
  11105. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11106. ("H" "#+HTML: ")
  11107. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11108. ("A" "#+ASCII: ")
  11109. ("i" "#+INDEX: ?")
  11110. ("I" "#+INCLUDE: %file ?"))
  11111. "Structure completion elements.
  11112. This is a list of abbreviation keys and values. The value gets inserted
  11113. if you type `<' followed by the key and then press the completion key,
  11114. usually `TAB'. %file will be replaced by a file name after prompting
  11115. for the file using completion. The cursor will be placed at the position
  11116. of the `?' in the template.
  11117. There are two templates for each key, the first uses the original Org syntax,
  11118. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11119. the default when the /org-mtags.el/ module has been loaded. See also the
  11120. variable `org-mtags-prefer-muse-templates'."
  11121. :group 'org-completion
  11122. :type '(repeat
  11123. (list
  11124. (string :tag "Key")
  11125. (string :tag "Template")))
  11126. :version "25.2"
  11127. :package-version '(Org . "8.3"))
  11128. (defun org-try-structure-completion ()
  11129. "Try to complete a structure template before point.
  11130. This looks for strings like \"<e\" on an otherwise empty line and
  11131. expands them."
  11132. (let ((l (buffer-substring (point-at-bol) (point)))
  11133. a)
  11134. (when (and (looking-at "[ \t]*$")
  11135. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11136. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11137. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11138. (match-beginning 1)) a)
  11139. t)))
  11140. (defun org-complete-expand-structure-template (start cell)
  11141. "Expand a structure template."
  11142. (let ((rpl (nth 1 cell))
  11143. (ind ""))
  11144. (delete-region start (point))
  11145. (when (string-match "\\`[ \t]*#\\+" rpl)
  11146. (cond
  11147. ((bolp))
  11148. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11149. (setq ind (buffer-substring (point-at-bol) (point))))
  11150. (t (newline))))
  11151. (setq start (point))
  11152. (when (string-match "%file" rpl)
  11153. (setq rpl (replace-match
  11154. (concat
  11155. "\""
  11156. (save-match-data
  11157. (abbreviate-file-name (read-file-name "Include file: ")))
  11158. "\"")
  11159. t t rpl)))
  11160. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11161. (concat "\n" ind)))
  11162. (insert rpl)
  11163. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11164. ;;;; TODO, DEADLINE, Comments
  11165. (defun org-toggle-comment ()
  11166. "Change the COMMENT state of an entry."
  11167. (interactive)
  11168. (save-excursion
  11169. (org-back-to-heading)
  11170. (let ((case-fold-search nil))
  11171. (looking-at org-complex-heading-regexp))
  11172. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11173. (skip-chars-forward " \t")
  11174. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11175. (if (org-in-commented-heading-p t)
  11176. (delete-region (point)
  11177. (progn (search-forward " " (line-end-position) 'move)
  11178. (skip-chars-forward " \t")
  11179. (point)))
  11180. (insert org-comment-string)
  11181. (unless (eolp) (insert " ")))))
  11182. (defvar org-last-todo-state-is-todo nil
  11183. "This is non-nil when the last TODO state change led to a TODO state.
  11184. If the last change removed the TODO tag or switched to DONE, then
  11185. this is nil.")
  11186. (defvar org-setting-tags nil) ; dynamically skipped
  11187. (defvar org-todo-setup-filter-hook nil
  11188. "Hook for functions that pre-filter todo specs.
  11189. Each function takes a todo spec and returns either nil or the spec
  11190. transformed into canonical form." )
  11191. (defvar org-todo-get-default-hook nil
  11192. "Hook for functions that get a default item for todo.
  11193. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11194. nil or a string to be used for the todo mark." )
  11195. (defvar org-agenda-headline-snapshot-before-repeat)
  11196. (defun org-current-effective-time ()
  11197. "Return current time adjusted for `org-extend-today-until' variable."
  11198. (let* ((ct (org-current-time))
  11199. (dct (decode-time ct))
  11200. (ct1
  11201. (cond
  11202. (org-use-last-clock-out-time-as-effective-time
  11203. (or (org-clock-get-last-clock-out-time) ct))
  11204. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11205. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11206. (t ct))))
  11207. ct1))
  11208. (defun org-todo-yesterday (&optional arg)
  11209. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11210. (interactive "P")
  11211. (if (eq major-mode 'org-agenda-mode)
  11212. (apply 'org-agenda-todo-yesterday arg)
  11213. (let* ((org-use-effective-time t)
  11214. (hour (nth 2 (decode-time (org-current-time))))
  11215. (org-extend-today-until (1+ hour)))
  11216. (org-todo arg))))
  11217. (defvar org-block-entry-blocking ""
  11218. "First entry preventing the TODO state change.")
  11219. (defun org-cancel-repeater ()
  11220. "Cancel a repeater by setting its numeric value to zero."
  11221. (interactive)
  11222. (save-excursion
  11223. (org-back-to-heading t)
  11224. (let ((bound1 (point))
  11225. (bound0 (save-excursion (outline-next-heading) (point))))
  11226. (when (and (re-search-forward
  11227. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11228. org-deadline-time-regexp "\\)\\|\\("
  11229. org-ts-regexp "\\)")
  11230. bound0 t)
  11231. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11232. bound1 t))
  11233. (replace-match "0" t nil nil 1)))))
  11234. (defvar org-state) ;; dynamically scoped into this function
  11235. (defun org-todo (&optional arg)
  11236. "Change the TODO state of an item.
  11237. The state of an item is given by a keyword at the start of the heading,
  11238. like
  11239. *** TODO Write paper
  11240. *** DONE Call mom
  11241. The different keywords are specified in the variable `org-todo-keywords'.
  11242. By default the available states are \"TODO\" and \"DONE\". So, for this
  11243. example: when the item starts with TODO, it is changed to DONE.
  11244. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11245. DONE are present, add TODO at the beginning of the heading.
  11246. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11247. state.
  11248. With numeric prefix ARG, switch to that state.
  11249. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11250. next set of TODO \
  11251. keywords (nextset).
  11252. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11253. prefix, circumvent any state blocking.
  11254. With a numeric prefix arg of 0, inhibit note taking for the change.
  11255. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11256. When called through ELisp, arg is also interpreted in the following way:
  11257. `none' -> empty state
  11258. \"\" -> switch to empty state
  11259. `done' -> switch to DONE
  11260. `nextset' -> switch to the next set of keywords
  11261. `previousset' -> switch to the previous set of keywords
  11262. \"WAITING\" -> switch to the specified keyword, but only if it
  11263. really is a member of `org-todo-keywords'."
  11264. (interactive "P")
  11265. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11266. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11267. 'region-start-level 'region))
  11268. org-loop-over-headlines-in-active-region)
  11269. (org-map-entries
  11270. `(org-todo ,arg)
  11271. org-loop-over-headlines-in-active-region
  11272. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11273. (when (equal arg '(16)) (setq arg 'nextset))
  11274. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11275. (let ((org-blocker-hook org-blocker-hook)
  11276. commentp
  11277. case-fold-search)
  11278. (when (equal arg '(64))
  11279. (setq arg nil org-blocker-hook nil))
  11280. (when (and org-blocker-hook
  11281. (or org-inhibit-blocking
  11282. (org-entry-get nil "NOBLOCKING")))
  11283. (setq org-blocker-hook nil))
  11284. (save-excursion
  11285. (catch 'exit
  11286. (org-back-to-heading t)
  11287. (when (org-in-commented-heading-p t)
  11288. (org-toggle-comment)
  11289. (setq commentp t))
  11290. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11291. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11292. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11293. (let* ((match-data (match-data))
  11294. (startpos (point-at-bol))
  11295. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11296. (org-log-done org-log-done)
  11297. (org-log-repeat org-log-repeat)
  11298. (org-todo-log-states org-todo-log-states)
  11299. (org-inhibit-logging
  11300. (if (equal arg 0)
  11301. (progn (setq arg nil) 'note) org-inhibit-logging))
  11302. (this (match-string 1))
  11303. (hl-pos (match-beginning 0))
  11304. (head (org-get-todo-sequence-head this))
  11305. (ass (assoc head org-todo-kwd-alist))
  11306. (interpret (nth 1 ass))
  11307. (done-word (nth 3 ass))
  11308. (final-done-word (nth 4 ass))
  11309. (org-last-state (or this ""))
  11310. (completion-ignore-case t)
  11311. (member (member this org-todo-keywords-1))
  11312. (tail (cdr member))
  11313. (org-state (cond
  11314. ((and org-todo-key-trigger
  11315. (or (and (equal arg '(4))
  11316. (eq org-use-fast-todo-selection 'prefix))
  11317. (and (not arg) org-use-fast-todo-selection
  11318. (not (eq org-use-fast-todo-selection
  11319. 'prefix)))))
  11320. ;; Use fast selection
  11321. (org-fast-todo-selection))
  11322. ((and (equal arg '(4))
  11323. (or (not org-use-fast-todo-selection)
  11324. (not org-todo-key-trigger)))
  11325. ;; Read a state with completion
  11326. (completing-read
  11327. "State: " (mapcar #'list org-todo-keywords-1)
  11328. nil t))
  11329. ((eq arg 'right)
  11330. (if this
  11331. (if tail (car tail) nil)
  11332. (car org-todo-keywords-1)))
  11333. ((eq arg 'left)
  11334. (unless (equal member org-todo-keywords-1)
  11335. (if this
  11336. (nth (- (length org-todo-keywords-1)
  11337. (length tail) 2)
  11338. org-todo-keywords-1)
  11339. (org-last org-todo-keywords-1))))
  11340. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11341. (setq arg nil))) ; hack to fall back to cycling
  11342. (arg
  11343. ;; user or caller requests a specific state
  11344. (cond
  11345. ((equal arg "") nil)
  11346. ((eq arg 'none) nil)
  11347. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11348. ((eq arg 'nextset)
  11349. (or (car (cdr (member head org-todo-heads)))
  11350. (car org-todo-heads)))
  11351. ((eq arg 'previousset)
  11352. (let ((org-todo-heads (reverse org-todo-heads)))
  11353. (or (car (cdr (member head org-todo-heads)))
  11354. (car org-todo-heads))))
  11355. ((car (member arg org-todo-keywords-1)))
  11356. ((stringp arg)
  11357. (user-error "State `%s' not valid in this file" arg))
  11358. ((nth (1- (prefix-numeric-value arg))
  11359. org-todo-keywords-1))))
  11360. ((null member) (or head (car org-todo-keywords-1)))
  11361. ((equal this final-done-word) nil) ;; -> make empty
  11362. ((null tail) nil) ;; -> first entry
  11363. ((memq interpret '(type priority))
  11364. (if (eq this-command last-command)
  11365. (car tail)
  11366. (if (> (length tail) 0)
  11367. (or done-word (car org-done-keywords))
  11368. nil)))
  11369. (t
  11370. (car tail))))
  11371. (org-state (or
  11372. (run-hook-with-args-until-success
  11373. 'org-todo-get-default-hook org-state org-last-state)
  11374. org-state))
  11375. (next (if org-state (concat " " org-state " ") " "))
  11376. (change-plist (list :type 'todo-state-change :from this :to org-state
  11377. :position startpos))
  11378. dolog now-done-p)
  11379. (when org-blocker-hook
  11380. (setq org-last-todo-state-is-todo
  11381. (not (member this org-done-keywords)))
  11382. (unless (save-excursion
  11383. (save-match-data
  11384. (org-with-wide-buffer
  11385. (run-hook-with-args-until-failure
  11386. 'org-blocker-hook change-plist))))
  11387. (if (called-interactively-p 'interactive)
  11388. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11389. this org-state org-block-entry-blocking)
  11390. ;; fail silently
  11391. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11392. this org-state org-block-entry-blocking)
  11393. (throw 'exit nil))))
  11394. (store-match-data match-data)
  11395. (replace-match next t t)
  11396. (cond ((equal this org-state)
  11397. (message "TODO state was already %s" (org-trim next)))
  11398. ((pos-visible-in-window-p hl-pos)
  11399. (message "TODO state changed to %s" (org-trim next))))
  11400. (unless head
  11401. (setq head (org-get-todo-sequence-head org-state)
  11402. ass (assoc head org-todo-kwd-alist)
  11403. interpret (nth 1 ass)
  11404. done-word (nth 3 ass)
  11405. final-done-word (nth 4 ass)))
  11406. (when (memq arg '(nextset previousset))
  11407. (message "Keyword-Set %d/%d: %s"
  11408. (- (length org-todo-sets) -1
  11409. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11410. (length org-todo-sets)
  11411. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11412. (setq org-last-todo-state-is-todo
  11413. (not (member org-state org-done-keywords)))
  11414. (setq now-done-p (and (member org-state org-done-keywords)
  11415. (not (member this org-done-keywords))))
  11416. (and logging (org-local-logging logging))
  11417. (when (and (or org-todo-log-states org-log-done)
  11418. (not (eq org-inhibit-logging t))
  11419. (not (memq arg '(nextset previousset))))
  11420. ;; we need to look at recording a time and note
  11421. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11422. (nth 2 (assoc this org-todo-log-states))))
  11423. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11424. (setq dolog 'time))
  11425. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11426. (and org-state
  11427. (member org-state org-not-done-keywords)
  11428. (not (member this org-not-done-keywords))))
  11429. ;; This is now a todo state and was not one before
  11430. ;; If there was a CLOSED time stamp, get rid of it.
  11431. (org-add-planning-info nil nil 'closed))
  11432. (when (and now-done-p org-log-done)
  11433. ;; It is now done, and it was not done before
  11434. (org-add-planning-info 'closed (org-current-effective-time))
  11435. (when (and (not dolog) (eq 'note org-log-done))
  11436. (org-add-log-setup 'done org-state this 'note)))
  11437. (when (and org-state dolog)
  11438. ;; This is a non-nil state, and we need to log it
  11439. (org-add-log-setup 'state org-state this dolog)))
  11440. ;; Fixup tag positioning
  11441. (org-todo-trigger-tag-changes org-state)
  11442. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11443. (when org-provide-todo-statistics
  11444. (org-update-parent-todo-statistics))
  11445. (run-hooks 'org-after-todo-state-change-hook)
  11446. (when (and arg (not (member org-state org-done-keywords)))
  11447. (setq head (org-get-todo-sequence-head org-state)))
  11448. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11449. ;; Do we need to trigger a repeat?
  11450. (when now-done-p
  11451. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11452. ;; This is for the agenda, take a snapshot of the headline.
  11453. (save-match-data
  11454. (setq org-agenda-headline-snapshot-before-repeat
  11455. (org-get-heading))))
  11456. (org-auto-repeat-maybe org-state))
  11457. ;; Fixup cursor location if close to the keyword
  11458. (when (and (outline-on-heading-p)
  11459. (not (bolp))
  11460. (save-excursion (beginning-of-line 1)
  11461. (looking-at org-todo-line-regexp))
  11462. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11463. (goto-char (or (match-end 2) (match-end 1)))
  11464. (and (looking-at " ") (just-one-space)))
  11465. (when org-trigger-hook
  11466. (save-excursion
  11467. (run-hook-with-args 'org-trigger-hook change-plist)))
  11468. (when commentp (org-toggle-comment))))))))
  11469. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11470. "Block turning an entry into a TODO, using the hierarchy.
  11471. This checks whether the current task should be blocked from state
  11472. changes. Such blocking occurs when:
  11473. 1. The task has children which are not all in a completed state.
  11474. 2. A task has a parent with the property :ORDERED:, and there
  11475. are siblings prior to the current task with incomplete
  11476. status.
  11477. 3. The parent of the task is blocked because it has siblings that should
  11478. be done first, or is child of a block grandparent TODO entry."
  11479. (if (not org-enforce-todo-dependencies)
  11480. t ; if locally turned off don't block
  11481. (catch 'dont-block
  11482. ;; If this is not a todo state change, or if this entry is already DONE,
  11483. ;; do not block
  11484. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11485. (member (plist-get change-plist :from)
  11486. (cons 'done org-done-keywords))
  11487. (member (plist-get change-plist :to)
  11488. (cons 'todo org-not-done-keywords))
  11489. (not (plist-get change-plist :to)))
  11490. (throw 'dont-block t))
  11491. ;; If this task has children, and any are undone, it's blocked
  11492. (save-excursion
  11493. (org-back-to-heading t)
  11494. (let ((this-level (funcall outline-level)))
  11495. (outline-next-heading)
  11496. (let ((child-level (funcall outline-level)))
  11497. (while (and (not (eobp))
  11498. (> child-level this-level))
  11499. ;; this todo has children, check whether they are all
  11500. ;; completed
  11501. (when (and (not (org-entry-is-done-p))
  11502. (org-entry-is-todo-p))
  11503. (setq org-block-entry-blocking (org-get-heading))
  11504. (throw 'dont-block nil))
  11505. (outline-next-heading)
  11506. (setq child-level (funcall outline-level))))))
  11507. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11508. ;; any previous siblings are undone, it's blocked
  11509. (save-excursion
  11510. (org-back-to-heading t)
  11511. (let* ((pos (point))
  11512. (parent-pos (and (org-up-heading-safe) (point)))
  11513. (case-fold-search nil))
  11514. (unless parent-pos (throw 'dont-block t)) ; no parent
  11515. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11516. (forward-line 1)
  11517. (re-search-forward org-not-done-heading-regexp pos t))
  11518. (setq org-block-entry-blocking (match-string 0))
  11519. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11520. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11521. (while t
  11522. (goto-char parent-pos)
  11523. (unless (looking-at org-not-done-heading-regexp)
  11524. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11525. (setq pos (point))
  11526. (setq parent-pos (and (org-up-heading-safe) (point)))
  11527. (unless parent-pos (throw 'dont-block t)) ; no parent
  11528. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11529. (forward-line 1)
  11530. (re-search-forward org-not-done-heading-regexp pos t)
  11531. (setq org-block-entry-blocking (org-get-heading)))
  11532. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11533. (defcustom org-track-ordered-property-with-tag nil
  11534. "Should the ORDERED property also be shown as a tag?
  11535. The ORDERED property decides if an entry should require subtasks to be
  11536. completed in sequence. Since a property is not very visible, setting
  11537. this option means that toggling the ORDERED property with the command
  11538. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11539. not relevant for the behavior, but it makes things more visible.
  11540. Note that toggling the tag with tags commands will not change the property
  11541. and therefore not influence behavior!
  11542. This can be t, meaning the tag ORDERED should be used, It can also be a
  11543. string to select a different tag for this task."
  11544. :group 'org-todo
  11545. :type '(choice
  11546. (const :tag "No tracking" nil)
  11547. (const :tag "Track with ORDERED tag" t)
  11548. (string :tag "Use other tag")))
  11549. (defun org-toggle-ordered-property ()
  11550. "Toggle the ORDERED property of the current entry.
  11551. For better visibility, you can track the value of this property with a tag.
  11552. See variable `org-track-ordered-property-with-tag'."
  11553. (interactive)
  11554. (let* ((t1 org-track-ordered-property-with-tag)
  11555. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11556. (save-excursion
  11557. (org-back-to-heading)
  11558. (if (org-entry-get nil "ORDERED")
  11559. (progn
  11560. (org-delete-property "ORDERED")
  11561. (and tag (org-toggle-tag tag 'off))
  11562. (message "Subtasks can be completed in arbitrary order"))
  11563. (org-entry-put nil "ORDERED" "t")
  11564. (and tag (org-toggle-tag tag 'on))
  11565. (message "Subtasks must be completed in sequence")))))
  11566. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11567. (defun org-block-todo-from-checkboxes (change-plist)
  11568. "Block turning an entry into a TODO, using checkboxes.
  11569. This checks whether the current task should be blocked from state
  11570. changes because there are unchecked boxes in this entry."
  11571. (if (not org-enforce-todo-checkbox-dependencies)
  11572. t ; if locally turned off don't block
  11573. (catch 'dont-block
  11574. ;; If this is not a todo state change, or if this entry is already DONE,
  11575. ;; do not block
  11576. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11577. (member (plist-get change-plist :from)
  11578. (cons 'done org-done-keywords))
  11579. (member (plist-get change-plist :to)
  11580. (cons 'todo org-not-done-keywords))
  11581. (not (plist-get change-plist :to)))
  11582. (throw 'dont-block t))
  11583. ;; If this task has checkboxes that are not checked, it's blocked
  11584. (save-excursion
  11585. (org-back-to-heading t)
  11586. (let ((beg (point)) end)
  11587. (outline-next-heading)
  11588. (setq end (point))
  11589. (goto-char beg)
  11590. (when (org-list-search-forward
  11591. (concat (org-item-beginning-re)
  11592. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11593. "\\[[- ]\\]")
  11594. end t)
  11595. (when (boundp 'org-blocked-by-checkboxes)
  11596. (setq org-blocked-by-checkboxes t))
  11597. (throw 'dont-block nil))))
  11598. t))) ; do not block
  11599. (defun org-entry-blocked-p ()
  11600. "Non-nil if entry at point is blocked."
  11601. (and (not (org-entry-get nil "NOBLOCKING"))
  11602. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11603. (not (run-hook-with-args-until-failure
  11604. 'org-blocker-hook
  11605. (list :type 'todo-state-change
  11606. :position (point)
  11607. :from 'todo
  11608. :to 'done)))))
  11609. (defun org-update-statistics-cookies (all)
  11610. "Update the statistics cookie, either from TODO or from checkboxes.
  11611. This should be called with the cursor in a line with a statistics
  11612. cookie. When called with a \\[universal-argument] prefix, update
  11613. all statistics cookies in the buffer."
  11614. (interactive "P")
  11615. (if all
  11616. (progn
  11617. (org-update-checkbox-count 'all)
  11618. (org-map-entries 'org-update-parent-todo-statistics))
  11619. (if (not (org-at-heading-p))
  11620. (org-update-checkbox-count)
  11621. (let ((pos (point-marker))
  11622. end l1 l2)
  11623. (ignore-errors (org-back-to-heading t))
  11624. (if (not (org-at-heading-p))
  11625. (org-update-checkbox-count)
  11626. (setq l1 (org-outline-level))
  11627. (setq end (save-excursion
  11628. (outline-next-heading)
  11629. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11630. (point)))
  11631. (if (and (save-excursion
  11632. (re-search-forward
  11633. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11634. (not (save-excursion (re-search-forward
  11635. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11636. (org-update-checkbox-count)
  11637. (if (and l2 (> l2 l1))
  11638. (progn
  11639. (goto-char end)
  11640. (org-update-parent-todo-statistics))
  11641. (goto-char pos)
  11642. (beginning-of-line 1)
  11643. (while (re-search-forward
  11644. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11645. (point-at-eol) t)
  11646. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11647. (goto-char pos)
  11648. (move-marker pos nil)))))
  11649. (defvar org-entry-property-inherited-from) ;; defined below
  11650. (defun org-update-parent-todo-statistics ()
  11651. "Update any statistics cookie in the parent of the current headline.
  11652. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11653. the entire subtree and this will travel up the hierarchy and update
  11654. statistics everywhere."
  11655. (let* ((prop (save-excursion (org-up-heading-safe)
  11656. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11657. (recursive (or (not org-hierarchical-todo-statistics)
  11658. (and prop (string-match "\\<recursive\\>" prop))))
  11659. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11660. 0))
  11661. (first t)
  11662. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11663. level ltoggle l1 new ndel
  11664. (cnt-all 0) (cnt-done 0) is-percent kwd
  11665. checkbox-beg cookie-present)
  11666. (catch 'exit
  11667. (save-excursion
  11668. (beginning-of-line 1)
  11669. (setq ltoggle (funcall outline-level))
  11670. ;; Three situations are to consider:
  11671. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11672. ;; to the top-level ancestor on the headline;
  11673. ;; 2. If parent has "recursive" property, repeat up to the
  11674. ;; headline setting that property, taking inheritance into
  11675. ;; account;
  11676. ;; 3. Else, move up to direct parent and proceed only once.
  11677. (while (and (setq level (org-up-heading-safe))
  11678. (or recursive first)
  11679. (>= (point) lim))
  11680. (setq first nil cookie-present nil)
  11681. (unless (and level
  11682. (not (string-match
  11683. "\\<checkbox\\>"
  11684. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11685. "")))))
  11686. (throw 'exit nil))
  11687. (while (re-search-forward box-re (point-at-eol) t)
  11688. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11689. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11690. (save-match-data
  11691. (unless (outline-next-heading) (throw 'exit nil))
  11692. (while (and (looking-at org-complex-heading-regexp)
  11693. (> (setq l1 (length (match-string 1))) level))
  11694. (setq kwd (and (or recursive (= l1 ltoggle))
  11695. (match-string 2)))
  11696. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11697. (and (eq org-provide-todo-statistics t)
  11698. (or (member kwd org-done-keywords)))
  11699. (and (listp org-provide-todo-statistics)
  11700. (stringp (car org-provide-todo-statistics))
  11701. (or (member kwd org-provide-todo-statistics)
  11702. (member kwd org-done-keywords)))
  11703. (and (listp org-provide-todo-statistics)
  11704. (listp (car org-provide-todo-statistics))
  11705. (or (member kwd (car org-provide-todo-statistics))
  11706. (and (member kwd org-done-keywords)
  11707. (member kwd (cadr org-provide-todo-statistics))))))
  11708. (setq cnt-all (1+ cnt-all))
  11709. (and (eq org-provide-todo-statistics t)
  11710. kwd
  11711. (setq cnt-all (1+ cnt-all))))
  11712. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11713. (member kwd org-done-keywords))
  11714. (and (listp org-provide-todo-statistics)
  11715. (listp (car org-provide-todo-statistics))
  11716. (member kwd org-done-keywords)
  11717. (member kwd (cadr org-provide-todo-statistics)))
  11718. (and (listp org-provide-todo-statistics)
  11719. (stringp (car org-provide-todo-statistics))
  11720. (member kwd org-done-keywords)))
  11721. (setq cnt-done (1+ cnt-done)))
  11722. (outline-next-heading)))
  11723. (setq new
  11724. (if is-percent
  11725. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11726. (max 1 cnt-all)))
  11727. (format "[%d/%d]" cnt-done cnt-all))
  11728. ndel (- (match-end 0) checkbox-beg))
  11729. (goto-char checkbox-beg)
  11730. (insert new)
  11731. (delete-region (point) (+ (point) ndel))
  11732. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11733. (when cookie-present
  11734. (run-hook-with-args 'org-after-todo-statistics-hook
  11735. cnt-done (- cnt-all cnt-done))))))
  11736. (run-hooks 'org-todo-statistics-hook)))
  11737. (defvar org-after-todo-statistics-hook nil
  11738. "Hook that is called after a TODO statistics cookie has been updated.
  11739. Each function is called with two arguments: the number of not-done entries
  11740. and the number of done entries.
  11741. For example, the following function, when added to this hook, will switch
  11742. an entry to DONE when all children are done, and back to TODO when new
  11743. entries are set to a TODO status. Note that this hook is only called
  11744. when there is a statistics cookie in the headline!
  11745. (defun org-summary-todo (n-done n-not-done)
  11746. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11747. (let (org-log-done org-log-states) ; turn off logging
  11748. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11749. ")
  11750. (defvar org-todo-statistics-hook nil
  11751. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11752. This hook runs even if there is no statistics cookie present, in which case
  11753. `org-after-todo-statistics-hook' would not run.")
  11754. (defun org-todo-trigger-tag-changes (state)
  11755. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11756. (let ((l org-todo-state-tags-triggers)
  11757. changes)
  11758. (when (or (not state) (equal state ""))
  11759. (setq changes (append changes (cdr (assoc "" l)))))
  11760. (when (and (stringp state) (> (length state) 0))
  11761. (setq changes (append changes (cdr (assoc state l)))))
  11762. (when (member state org-not-done-keywords)
  11763. (setq changes (append changes (cdr (assq 'todo l)))))
  11764. (when (member state org-done-keywords)
  11765. (setq changes (append changes (cdr (assq 'done l)))))
  11766. (dolist (c changes)
  11767. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11768. (defun org-local-logging (value)
  11769. "Get logging settings from a property VALUE."
  11770. ;; Directly set the variables, they are already local.
  11771. (setq org-log-done nil
  11772. org-log-repeat nil
  11773. org-todo-log-states nil)
  11774. (dolist (w (org-split-string value))
  11775. (let (a)
  11776. (cond
  11777. ((setq a (assoc w org-startup-options))
  11778. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11779. (set (nth 1 a) (nth 2 a))))
  11780. ((setq a (org-extract-log-state-settings w))
  11781. (and (member (car a) org-todo-keywords-1)
  11782. (push a org-todo-log-states)))))))
  11783. (defun org-get-todo-sequence-head (kwd)
  11784. "Return the head of the TODO sequence to which KWD belongs.
  11785. If KWD is not set, check if there is a text property remembering the
  11786. right sequence."
  11787. (let (p)
  11788. (cond
  11789. ((not kwd)
  11790. (or (get-text-property (point-at-bol) 'org-todo-head)
  11791. (progn
  11792. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11793. nil (point-at-eol)))
  11794. (get-text-property p 'org-todo-head))))
  11795. ((not (member kwd org-todo-keywords-1))
  11796. (car org-todo-keywords-1))
  11797. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11798. (defun org-fast-todo-selection ()
  11799. "Fast TODO keyword selection with single keys.
  11800. Returns the new TODO keyword, or nil if no state change should occur."
  11801. (let* ((fulltable org-todo-key-alist)
  11802. (done-keywords org-done-keywords) ;; needed for the faces.
  11803. (maxlen (apply 'max (mapcar
  11804. (lambda (x)
  11805. (if (stringp (car x)) (string-width (car x)) 0))
  11806. fulltable)))
  11807. (expert nil)
  11808. (fwidth (+ maxlen 3 1 3))
  11809. (ncol (/ (- (window-width) 4) fwidth))
  11810. tg cnt e c tbl
  11811. groups ingroup)
  11812. (save-excursion
  11813. (save-window-excursion
  11814. (if expert
  11815. (set-buffer (get-buffer-create " *Org todo*"))
  11816. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11817. (erase-buffer)
  11818. (setq-local org-done-keywords done-keywords)
  11819. (setq tbl fulltable cnt 0)
  11820. (while (setq e (pop tbl))
  11821. (cond
  11822. ((equal e '(:startgroup))
  11823. (push '() groups) (setq ingroup t)
  11824. (unless (= cnt 0)
  11825. (setq cnt 0)
  11826. (insert "\n"))
  11827. (insert "{ "))
  11828. ((equal e '(:endgroup))
  11829. (setq ingroup nil cnt 0)
  11830. (insert "}\n"))
  11831. ((equal e '(:newline))
  11832. (unless (= cnt 0)
  11833. (setq cnt 0)
  11834. (insert "\n")
  11835. (setq e (car tbl))
  11836. (while (equal (car tbl) '(:newline))
  11837. (insert "\n")
  11838. (setq tbl (cdr tbl)))))
  11839. (t
  11840. (setq tg (car e) c (cdr e))
  11841. (when ingroup (push tg (car groups)))
  11842. (setq tg (org-add-props tg nil 'face
  11843. (org-get-todo-face tg)))
  11844. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11845. (insert "[" c "] " tg (make-string
  11846. (- fwidth 4 (length tg)) ?\ ))
  11847. (when (= (setq cnt (1+ cnt)) ncol)
  11848. (insert "\n")
  11849. (when ingroup (insert " "))
  11850. (setq cnt 0)))))
  11851. (insert "\n")
  11852. (goto-char (point-min))
  11853. (unless expert (org-fit-window-to-buffer))
  11854. (message "[a-z..]:Set [SPC]:clear")
  11855. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11856. (cond
  11857. ((or (= c ?\C-g)
  11858. (and (= c ?q) (not (rassoc c fulltable))))
  11859. (setq quit-flag t))
  11860. ((= c ?\ ) nil)
  11861. ((setq e (rassoc c fulltable) tg (car e))
  11862. tg)
  11863. (t (setq quit-flag t)))))))
  11864. (defun org-entry-is-todo-p ()
  11865. (member (org-get-todo-state) org-not-done-keywords))
  11866. (defun org-entry-is-done-p ()
  11867. (member (org-get-todo-state) org-done-keywords))
  11868. (defun org-get-todo-state ()
  11869. "Return the TODO keyword of the current subtree."
  11870. (save-excursion
  11871. (org-back-to-heading t)
  11872. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11873. (match-end 2)
  11874. (match-string 2))))
  11875. (defun org-at-date-range-p (&optional inactive-ok)
  11876. "Non-nil if point is inside a date range.
  11877. When optional argument INACTIVE-OK is non-nil, also consider
  11878. inactive time ranges.
  11879. When this function returns a non-nil value, match data is set
  11880. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11881. on INACTIVE-OK."
  11882. (interactive)
  11883. (save-excursion
  11884. (catch 'exit
  11885. (let ((pos (point)))
  11886. (skip-chars-backward "^[<\r\n")
  11887. (skip-chars-backward "<[")
  11888. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11889. (>= (match-end 0) pos)
  11890. (throw 'exit t))
  11891. (skip-chars-backward "^<[\r\n")
  11892. (skip-chars-backward "<[")
  11893. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11894. (>= (match-end 0) pos)
  11895. (throw 'exit t)))
  11896. nil)))
  11897. (defun org-get-repeat (&optional tagline)
  11898. "Check if there is a deadline/schedule with repeater in this entry."
  11899. (save-match-data
  11900. (save-excursion
  11901. (org-back-to-heading t)
  11902. (and (re-search-forward (if tagline
  11903. (concat tagline "\\s-*" org-repeat-re)
  11904. org-repeat-re)
  11905. (org-entry-end-position) t)
  11906. (match-string-no-properties 1)))))
  11907. (defvar org-last-changed-timestamp)
  11908. (defvar org-last-inserted-timestamp)
  11909. (defvar org-log-post-message)
  11910. (defvar org-log-note-purpose)
  11911. (defvar org-log-note-how nil)
  11912. (defvar org-log-note-extra)
  11913. (defun org-auto-repeat-maybe (done-word)
  11914. "Check if the current headline contains a repeated time-stamp.
  11915. If yes, set TODO state back to what it was and change the base date
  11916. of repeating deadline/scheduled time stamps to new date.
  11917. This function is run automatically after each state change to a DONE state."
  11918. (let* ((repeat (org-get-repeat))
  11919. (aa (assoc org-last-state org-todo-kwd-alist))
  11920. (interpret (nth 1 aa))
  11921. (head (nth 2 aa))
  11922. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11923. (msg "Entry repeats: ")
  11924. (org-log-done nil)
  11925. (org-todo-log-states nil))
  11926. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11927. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11928. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11929. org-todo-repeat-to-state)))
  11930. (unless (and to-state (member to-state org-todo-keywords-1))
  11931. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11932. (org-todo to-state))
  11933. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11934. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11935. (org-time-stamp-format t t))))
  11936. (when org-log-repeat
  11937. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11938. (memq 'org-add-log-note post-command-hook))
  11939. ;; We are already setup for some record.
  11940. (when (eq org-log-repeat 'note)
  11941. ;; Make sure we take a note, not only a time stamp.
  11942. (setq org-log-note-how 'note))
  11943. ;; Set up for taking a record.
  11944. (org-add-log-setup 'state
  11945. (or done-word (car org-done-keywords))
  11946. org-last-state
  11947. org-log-repeat)))
  11948. (org-back-to-heading t)
  11949. (org-add-planning-info nil nil 'closed)
  11950. (let ((end (save-excursion (outline-next-heading) (point)))
  11951. (planning-re (regexp-opt
  11952. (list org-scheduled-string org-deadline-string))))
  11953. (while (re-search-forward org-ts-regexp end t)
  11954. (let* ((ts (match-string 0))
  11955. (planning? (org-at-planning-p))
  11956. (type (if (not planning?) "Plain:"
  11957. (save-excursion
  11958. (re-search-backward
  11959. planning-re (line-beginning-position) t)
  11960. (match-string 0)))))
  11961. (cond
  11962. ;; Ignore fake time-stamps (e.g., within comments).
  11963. ((and (not planning?)
  11964. (not (org-at-property-p))
  11965. (not (eq 'timestamp
  11966. (org-element-type (save-excursion
  11967. (backward-char)
  11968. (org-element-context)))))))
  11969. ;; Time-stamps without a repeater are usually skipped.
  11970. ;; However, a SCHEDULED time-stamp without one is
  11971. ;; removed, as it is considered as no longer relevant.
  11972. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11973. (when (equal type org-scheduled-string)
  11974. (org-remove-timestamp-with-keyword type)))
  11975. (t
  11976. (let ((n (string-to-number (match-string 2 ts)))
  11977. (what (match-string 3 ts)))
  11978. (when (equal what "w") (setq n (* n 7) what "d"))
  11979. (when (and (equal what "h")
  11980. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11981. ts)))
  11982. (user-error
  11983. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11984. has been set"
  11985. n))
  11986. ;; Preparation, see if we need to modify the start
  11987. ;; date for the change.
  11988. (when (match-end 1)
  11989. (let ((time (save-match-data (org-time-string-to-time ts))))
  11990. (cond
  11991. ((equal (match-string 1 ts) ".")
  11992. ;; Shift starting date to today
  11993. (org-timestamp-change
  11994. (- (org-today) (time-to-days time))
  11995. 'day))
  11996. ((equal (match-string 1 ts) "+")
  11997. (let ((nshiftmax 10)
  11998. (nshift 0))
  11999. (while (or (= nshift 0)
  12000. (not (time-less-p (current-time) time)))
  12001. (when (= (cl-incf nshift) nshiftmax)
  12002. (or (y-or-n-p
  12003. (format "%d repeater intervals were not \
  12004. enough to shift date past today. Continue? "
  12005. nshift))
  12006. (user-error "Abort")))
  12007. (org-timestamp-change n (cdr (assoc what whata)))
  12008. (org-at-timestamp-p t)
  12009. (setq ts (match-string 1))
  12010. (setq time
  12011. (save-match-data
  12012. (org-time-string-to-time ts)))))
  12013. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12014. ;; Rematch, so that we have everything in place
  12015. ;; for the real shift.
  12016. (org-at-timestamp-p t)
  12017. (setq ts (match-string 1))
  12018. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12019. ts)))))
  12020. (save-excursion
  12021. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12022. (setq msg
  12023. (concat
  12024. msg type " " org-last-changed-timestamp " "))))))))
  12025. (setq org-log-post-message msg)
  12026. (message "%s" msg))))
  12027. (defun org-show-todo-tree (arg)
  12028. "Make a compact tree which shows all headlines marked with TODO.
  12029. The tree will show the lines where the regexp matches, and all higher
  12030. headlines above the match.
  12031. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12032. With a numeric prefix N, construct a sparse tree for the Nth element
  12033. of `org-todo-keywords-1'."
  12034. (interactive "P")
  12035. (let ((case-fold-search nil)
  12036. (kwd-re
  12037. (cond ((null arg) org-not-done-regexp)
  12038. ((equal arg '(4))
  12039. (let ((kwd
  12040. (completing-read "Keyword (or KWD1|KWD2|...): "
  12041. (mapcar #'list org-todo-keywords-1))))
  12042. (concat "\\("
  12043. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12044. "\\)\\>")))
  12045. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12046. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12047. org-todo-keywords-1)))
  12048. (t (user-error "Invalid prefix argument: %s" arg)))))
  12049. (message "%d TODO entries found"
  12050. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12051. (defun org-deadline (arg &optional time)
  12052. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12053. With one universal prefix argument, remove any deadline from the item.
  12054. With two universal prefix arguments, prompt for a warning delay.
  12055. With argument TIME, set the deadline at the corresponding date. TIME
  12056. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12057. (interactive "P")
  12058. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12059. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12060. 'region-start-level 'region))
  12061. org-loop-over-headlines-in-active-region)
  12062. (org-map-entries
  12063. `(org-deadline ',arg ,time)
  12064. org-loop-over-headlines-in-active-region
  12065. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12066. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12067. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12068. (repeater (and old-date
  12069. (string-match
  12070. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12071. old-date)
  12072. (match-string 1 old-date))))
  12073. (cond
  12074. ((equal arg '(4))
  12075. (when (and old-date org-log-redeadline)
  12076. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12077. (org-remove-timestamp-with-keyword org-deadline-string)
  12078. (message "Item no longer has a deadline."))
  12079. ((equal arg '(16))
  12080. (save-excursion
  12081. (org-back-to-heading t)
  12082. (if (re-search-forward
  12083. org-deadline-time-regexp
  12084. (save-excursion (outline-next-heading) (point)) t)
  12085. (let* ((rpl0 (match-string 1))
  12086. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12087. (replace-match
  12088. (concat org-deadline-string
  12089. " <" rpl
  12090. (format " -%dd"
  12091. (abs
  12092. (- (time-to-days
  12093. (save-match-data
  12094. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12095. (time-to-days old-date-time))))
  12096. ">") t t))
  12097. (user-error "No deadline information to update"))))
  12098. (t
  12099. (org-add-planning-info 'deadline time 'closed)
  12100. (when (and old-date
  12101. org-log-redeadline
  12102. (not (equal old-date org-last-inserted-timestamp)))
  12103. (org-add-log-setup
  12104. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12105. (when repeater
  12106. (save-excursion
  12107. (org-back-to-heading t)
  12108. (when (re-search-forward (concat org-deadline-string " "
  12109. org-last-inserted-timestamp)
  12110. (save-excursion
  12111. (outline-next-heading) (point)) t)
  12112. (goto-char (1- (match-end 0)))
  12113. (insert " " repeater)
  12114. (setq org-last-inserted-timestamp
  12115. (concat (substring org-last-inserted-timestamp 0 -1)
  12116. " " repeater
  12117. (substring org-last-inserted-timestamp -1))))))
  12118. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12119. (defun org-schedule (arg &optional time)
  12120. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12121. With one universal prefix argument, remove any scheduling date from the item.
  12122. With two universal prefix arguments, prompt for a delay cookie.
  12123. With argument TIME, scheduled at the corresponding date. TIME can
  12124. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12125. (interactive "P")
  12126. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12127. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12128. 'region-start-level 'region))
  12129. org-loop-over-headlines-in-active-region)
  12130. (org-map-entries
  12131. `(org-schedule ',arg ,time)
  12132. org-loop-over-headlines-in-active-region
  12133. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12134. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12135. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12136. (repeater (and old-date
  12137. (string-match
  12138. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12139. old-date)
  12140. (match-string 1 old-date))))
  12141. (cond
  12142. ((equal arg '(4))
  12143. (progn
  12144. (when (and old-date org-log-reschedule)
  12145. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12146. (org-remove-timestamp-with-keyword org-scheduled-string)
  12147. (message "Item is no longer scheduled.")))
  12148. ((equal arg '(16))
  12149. (save-excursion
  12150. (org-back-to-heading t)
  12151. (if (re-search-forward
  12152. org-scheduled-time-regexp
  12153. (save-excursion (outline-next-heading) (point)) t)
  12154. (let* ((rpl0 (match-string 1))
  12155. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12156. (replace-match
  12157. (concat org-scheduled-string
  12158. " <" rpl
  12159. (format " -%dd"
  12160. (abs
  12161. (- (time-to-days
  12162. (save-match-data
  12163. (org-read-date nil t nil "Delay until" old-date-time)))
  12164. (time-to-days old-date-time))))
  12165. ">") t t))
  12166. (user-error "No scheduled information to update"))))
  12167. (t
  12168. (org-add-planning-info 'scheduled time 'closed)
  12169. (when (and old-date
  12170. org-log-reschedule
  12171. (not (equal old-date org-last-inserted-timestamp)))
  12172. (org-add-log-setup
  12173. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12174. (when repeater
  12175. (save-excursion
  12176. (org-back-to-heading t)
  12177. (when (re-search-forward (concat org-scheduled-string " "
  12178. org-last-inserted-timestamp)
  12179. (save-excursion
  12180. (outline-next-heading) (point)) t)
  12181. (goto-char (1- (match-end 0)))
  12182. (insert " " repeater)
  12183. (setq org-last-inserted-timestamp
  12184. (concat (substring org-last-inserted-timestamp 0 -1)
  12185. " " repeater
  12186. (substring org-last-inserted-timestamp -1))))))
  12187. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12188. (defun org-get-scheduled-time (pom &optional inherit)
  12189. "Get the scheduled time as a time tuple, of a format suitable
  12190. for calling org-schedule with, or if there is no scheduling,
  12191. returns nil."
  12192. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12193. (when time
  12194. (apply 'encode-time (org-parse-time-string time)))))
  12195. (defun org-get-deadline-time (pom &optional inherit)
  12196. "Get the deadline as a time tuple, of a format suitable for
  12197. calling org-deadline with, or if there is no scheduling, returns
  12198. nil."
  12199. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12200. (when time
  12201. (apply 'encode-time (org-parse-time-string time)))))
  12202. (defun org-remove-timestamp-with-keyword (keyword)
  12203. "Remove all time stamps with KEYWORD in the current entry."
  12204. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12205. beg)
  12206. (save-excursion
  12207. (org-back-to-heading t)
  12208. (setq beg (point))
  12209. (outline-next-heading)
  12210. (while (re-search-backward re beg t)
  12211. (replace-match "")
  12212. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12213. (equal (char-before) ?\ ))
  12214. (backward-delete-char 1)
  12215. (when (string-match "^[ \t]*$" (buffer-substring
  12216. (point-at-bol) (point-at-eol)))
  12217. (delete-region (point-at-bol)
  12218. (min (point-max) (1+ (point-at-eol))))))))))
  12219. (defvar org-time-was-given) ; dynamically scoped parameter
  12220. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12221. (defun org-at-planning-p ()
  12222. "Non-nil when point is on a planning info line."
  12223. ;; This is as accurate and faster than `org-element-at-point' since
  12224. ;; planning info location is fixed in the section.
  12225. (org-with-wide-buffer
  12226. (beginning-of-line)
  12227. (and (looking-at-p org-planning-line-re)
  12228. (eq (point)
  12229. (ignore-errors
  12230. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12231. (org-back-to-heading t)
  12232. (org-with-limited-levels (org-back-to-heading t)))
  12233. (line-beginning-position 2))))))
  12234. (defun org-add-planning-info (what &optional time &rest remove)
  12235. "Insert new timestamp with keyword in the planning line.
  12236. WHAT indicates what kind of time stamp to add. It is a symbol
  12237. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12238. the time to use. If none is given, the user is prompted for
  12239. a date. REMOVE indicates what kind of entries to remove. An old
  12240. WHAT entry will also be removed."
  12241. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12242. (catch 'exit
  12243. (when (and (memq what '(scheduled deadline))
  12244. (or (not time)
  12245. (and (stringp time)
  12246. (string-match "^[-+]+[0-9]" time))))
  12247. ;; Try to get a default date/time from existing timestamp
  12248. (save-excursion
  12249. (org-back-to-heading t)
  12250. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12251. (when (re-search-forward (if (eq what 'scheduled)
  12252. org-scheduled-time-regexp
  12253. org-deadline-time-regexp)
  12254. end t)
  12255. (setq ts (match-string 1)
  12256. default-time (apply 'encode-time (org-parse-time-string ts))
  12257. default-input (and ts (org-get-compact-tod ts)))))))
  12258. (when what
  12259. (setq time
  12260. (if (stringp time)
  12261. ;; This is a string (relative or absolute), set
  12262. ;; proper date.
  12263. (apply #'encode-time
  12264. (org-read-date-analyze
  12265. time default-time (decode-time default-time)))
  12266. ;; If necessary, get the time from the user
  12267. (or time (org-read-date nil 'to-time nil nil
  12268. default-time default-input)))))
  12269. (org-with-wide-buffer
  12270. (org-back-to-heading t)
  12271. (forward-line)
  12272. (unless (bolp) (insert "\n"))
  12273. (cond ((looking-at-p org-planning-line-re)
  12274. ;; Move to current indentation.
  12275. (skip-chars-forward " \t")
  12276. ;; Check if we have to remove something.
  12277. (dolist (type (if what (cons what remove) remove))
  12278. (save-excursion
  12279. (when (re-search-forward
  12280. (cl-case type
  12281. (closed org-closed-time-regexp)
  12282. (deadline org-deadline-time-regexp)
  12283. (scheduled org-scheduled-time-regexp)
  12284. (otherwise
  12285. (error "Invalid planning type: %s" type)))
  12286. (line-end-position) t)
  12287. ;; Delete until next keyword or end of line.
  12288. (delete-region
  12289. (match-beginning 0)
  12290. (if (re-search-forward org-keyword-time-not-clock-regexp
  12291. (line-end-position)
  12292. t)
  12293. (match-beginning 0)
  12294. (line-end-position))))))
  12295. ;; If there is nothing more to add and no more keyword
  12296. ;; is left, remove the line completely.
  12297. (if (and (looking-at-p "[ \t]*$") (not what))
  12298. (delete-region (line-beginning-position)
  12299. (line-beginning-position 2))
  12300. ;; If we removed last keyword, do not leave trailing
  12301. ;; white space at the end of line.
  12302. (let ((p (point)))
  12303. (save-excursion
  12304. (end-of-line)
  12305. (unless (= (skip-chars-backward " \t" p) 0)
  12306. (delete-region (point) (line-end-position)))))))
  12307. ((not what) (throw 'exit nil)) ; Nothing to do.
  12308. (t (insert-before-markers "\n")
  12309. (backward-char 1)
  12310. (when org-adapt-indentation
  12311. (indent-to-column (1+ (org-outline-level))))))
  12312. (when what
  12313. ;; Insert planning keyword.
  12314. (insert (cl-case what
  12315. (closed org-closed-string)
  12316. (deadline org-deadline-string)
  12317. (scheduled org-scheduled-string)
  12318. (otherwise (error "Invalid planning type: %s" what)))
  12319. " ")
  12320. ;; Insert associated timestamp.
  12321. (let ((ts (org-insert-time-stamp
  12322. time
  12323. (or org-time-was-given
  12324. (and (eq what 'closed) org-log-done-with-time))
  12325. (eq what 'closed)
  12326. nil nil (list org-end-time-was-given))))
  12327. (unless (eolp) (insert " "))
  12328. ts))))))
  12329. (defvar org-log-note-marker (make-marker)
  12330. "Marker pointing at the entry where the note is to be inserted.")
  12331. (defvar org-log-note-purpose nil)
  12332. (defvar org-log-note-state nil)
  12333. (defvar org-log-note-previous-state nil)
  12334. (defvar org-log-note-extra nil)
  12335. (defvar org-log-note-window-configuration nil)
  12336. (defvar org-log-note-return-to (make-marker))
  12337. (defvar org-log-note-effective-time nil
  12338. "Remembered current time so that dynamically scoped
  12339. `org-extend-today-until' affects timestamps in state change log")
  12340. (defvar org-log-post-message nil
  12341. "Message to be displayed after a log note has been stored.
  12342. The auto-repeater uses this.")
  12343. (defun org-add-note ()
  12344. "Add a note to the current entry.
  12345. This is done in the same way as adding a state change note."
  12346. (interactive)
  12347. (org-add-log-setup 'note))
  12348. (defun org-log-beginning (&optional create)
  12349. "Return expected start of log notes in current entry.
  12350. When optional argument CREATE is non-nil, the function creates
  12351. a drawer to store notes, if necessary. Returned position ignores
  12352. narrowing."
  12353. (org-with-wide-buffer
  12354. (let ((drawer (org-log-into-drawer)))
  12355. (cond
  12356. (drawer
  12357. (org-end-of-meta-data)
  12358. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12359. (end (if (org-at-heading-p) (point)
  12360. (save-excursion (outline-next-heading) (point))))
  12361. (case-fold-search t))
  12362. (catch 'exit
  12363. ;; Try to find existing drawer.
  12364. (while (re-search-forward regexp end t)
  12365. (let ((element (org-element-at-point)))
  12366. (when (eq (org-element-type element) 'drawer)
  12367. (let ((cend (org-element-property :contents-end element)))
  12368. (when (and (not org-log-states-order-reversed) cend)
  12369. (goto-char cend)))
  12370. (throw 'exit nil))))
  12371. ;; No drawer found. Create one, if permitted.
  12372. (when create
  12373. (unless (bolp) (insert "\n"))
  12374. (let ((beg (point)))
  12375. (insert ":" drawer ":\n:END:\n")
  12376. (org-indent-region beg (point)))
  12377. (end-of-line -1)))))
  12378. (t
  12379. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12380. (skip-chars-forward " \t\n")
  12381. (beginning-of-line)
  12382. (unless org-log-states-order-reversed
  12383. (org-skip-over-state-notes)
  12384. (skip-chars-backward " \t\n")
  12385. (forward-line)))))
  12386. (if (bolp) (point) (line-beginning-position 2))))
  12387. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12388. "Set up the post command hook to take a note.
  12389. If this is about to TODO state change, the new state is expected in STATE.
  12390. HOW is an indicator what kind of note should be created.
  12391. EXTRA is additional text that will be inserted into the notes buffer."
  12392. (move-marker org-log-note-marker (point))
  12393. (setq org-log-note-purpose purpose
  12394. org-log-note-state state
  12395. org-log-note-previous-state prev-state
  12396. org-log-note-how how
  12397. org-log-note-extra extra
  12398. org-log-note-effective-time (org-current-effective-time))
  12399. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12400. (defun org-skip-over-state-notes ()
  12401. "Skip past the list of State notes in an entry."
  12402. (when (ignore-errors (goto-char (org-in-item-p)))
  12403. (let* ((struct (org-list-struct))
  12404. (prevs (org-list-prevs-alist struct))
  12405. (regexp
  12406. (concat "[ \t]*- +"
  12407. (replace-regexp-in-string
  12408. " +" " +"
  12409. (org-replace-escapes
  12410. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12411. `(("%d" . ,org-ts-regexp-inactive)
  12412. ("%D" . ,org-ts-regexp)
  12413. ("%s" . "\"\\S-+\"")
  12414. ("%S" . "\"\\S-+\"")
  12415. ("%t" . ,org-ts-regexp-inactive)
  12416. ("%T" . ,org-ts-regexp)
  12417. ("%u" . ".*?")
  12418. ("%U" . ".*?")))))))
  12419. (while (looking-at-p regexp)
  12420. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12421. (org-list-get-item-end (point) struct)))))))
  12422. (defun org-add-log-note (&optional _purpose)
  12423. "Pop up a window for taking a note, and add this note later."
  12424. (remove-hook 'post-command-hook 'org-add-log-note)
  12425. (setq org-log-note-window-configuration (current-window-configuration))
  12426. (delete-other-windows)
  12427. (move-marker org-log-note-return-to (point))
  12428. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12429. (goto-char org-log-note-marker)
  12430. (org-switch-to-buffer-other-window "*Org Note*")
  12431. (erase-buffer)
  12432. (if (memq org-log-note-how '(time state))
  12433. (let (current-prefix-arg) (org-store-log-note))
  12434. (let ((org-inhibit-startup t)) (org-mode))
  12435. (insert (format "# Insert note for %s.
  12436. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12437. (cond
  12438. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12439. ((eq org-log-note-purpose 'done) "closed todo item")
  12440. ((eq org-log-note-purpose 'state)
  12441. (format "state change from \"%s\" to \"%s\""
  12442. (or org-log-note-previous-state "")
  12443. (or org-log-note-state "")))
  12444. ((eq org-log-note-purpose 'reschedule)
  12445. "rescheduling")
  12446. ((eq org-log-note-purpose 'delschedule)
  12447. "no longer scheduled")
  12448. ((eq org-log-note-purpose 'redeadline)
  12449. "changing deadline")
  12450. ((eq org-log-note-purpose 'deldeadline)
  12451. "removing deadline")
  12452. ((eq org-log-note-purpose 'refile)
  12453. "refiling")
  12454. ((eq org-log-note-purpose 'note)
  12455. "this entry")
  12456. (t (error "This should not happen")))))
  12457. (when org-log-note-extra (insert org-log-note-extra))
  12458. (setq-local org-finish-function 'org-store-log-note)
  12459. (run-hooks 'org-log-buffer-setup-hook)))
  12460. (defvar org-note-abort nil) ; dynamically scoped
  12461. (defun org-store-log-note ()
  12462. "Finish taking a log note, and insert it to where it belongs."
  12463. (let ((txt (prog1 (buffer-string)
  12464. (kill-buffer)))
  12465. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12466. lines)
  12467. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12468. (setq txt (replace-match "" t t txt)))
  12469. (when (string-match "\\s-+\\'" txt)
  12470. (setq txt (replace-match "" t t txt)))
  12471. (setq lines (org-split-string txt "\n"))
  12472. (when (org-string-nw-p note)
  12473. (setq note
  12474. (org-replace-escapes
  12475. note
  12476. (list (cons "%u" (user-login-name))
  12477. (cons "%U" user-full-name)
  12478. (cons "%t" (format-time-string
  12479. (org-time-stamp-format 'long 'inactive)
  12480. org-log-note-effective-time))
  12481. (cons "%T" (format-time-string
  12482. (org-time-stamp-format 'long nil)
  12483. org-log-note-effective-time))
  12484. (cons "%d" (format-time-string
  12485. (org-time-stamp-format nil 'inactive)
  12486. org-log-note-effective-time))
  12487. (cons "%D" (format-time-string
  12488. (org-time-stamp-format nil nil)
  12489. org-log-note-effective-time))
  12490. (cons "%s" (cond
  12491. ((not org-log-note-state) "")
  12492. ((string-match-p org-ts-regexp
  12493. org-log-note-state)
  12494. (format "\"[%s]\""
  12495. (substring org-log-note-state 1 -1)))
  12496. (t (format "\"%s\"" org-log-note-state))))
  12497. (cons "%S"
  12498. (cond
  12499. ((not org-log-note-previous-state) "")
  12500. ((string-match-p org-ts-regexp
  12501. org-log-note-previous-state)
  12502. (format "\"[%s]\""
  12503. (substring
  12504. org-log-note-previous-state 1 -1)))
  12505. (t (format "\"%s\""
  12506. org-log-note-previous-state)))))))
  12507. (when lines (setq note (concat note " \\\\")))
  12508. (push note lines))
  12509. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12510. (with-current-buffer (marker-buffer org-log-note-marker)
  12511. (org-with-wide-buffer
  12512. ;; Find location for the new note.
  12513. (goto-char org-log-note-marker)
  12514. (set-marker org-log-note-marker nil)
  12515. (goto-char (org-log-beginning t))
  12516. ;; Make sure point is at the beginning of an empty line.
  12517. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12518. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12519. ;; In an existing list, add a new item at the top level.
  12520. ;; Otherwise, indent line like a regular one.
  12521. (let ((itemp (org-in-item-p)))
  12522. (if itemp
  12523. (indent-line-to
  12524. (let ((struct (save-excursion
  12525. (goto-char itemp) (org-list-struct))))
  12526. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12527. (org-indent-line)))
  12528. (insert (org-list-bullet-string "-") (pop lines))
  12529. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12530. (dolist (line lines)
  12531. (insert "\n")
  12532. (indent-line-to ind)
  12533. (insert line)))
  12534. (message "Note stored")
  12535. (org-back-to-heading t)
  12536. (org-cycle-hide-drawers 'children))
  12537. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12538. ;; from within `org-add-log-note' because `buffer-undo-list'
  12539. ;; is then modified outside of `org-with-remote-undo'.
  12540. (when (eq this-command 'org-agenda-todo)
  12541. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12542. ;; Don't add undo information when called from `org-agenda-todo'.
  12543. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12544. (set-window-configuration org-log-note-window-configuration)
  12545. (with-current-buffer (marker-buffer org-log-note-return-to)
  12546. (goto-char org-log-note-return-to))
  12547. (move-marker org-log-note-return-to nil)
  12548. (when org-log-post-message (message "%s" org-log-post-message))))
  12549. (defun org-remove-empty-drawer-at (pos)
  12550. "Remove an empty drawer at position POS.
  12551. POS may also be a marker."
  12552. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12553. (org-with-wide-buffer
  12554. (goto-char pos)
  12555. (let ((drawer (org-element-at-point)))
  12556. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12557. (not (org-element-property :contents-begin drawer)))
  12558. (delete-region (org-element-property :begin drawer)
  12559. (progn (goto-char (org-element-property :end drawer))
  12560. (skip-chars-backward " \r\t\n")
  12561. (forward-line)
  12562. (point))))))))
  12563. (defvar org-ts-type nil)
  12564. (defun org-sparse-tree (&optional arg type)
  12565. "Create a sparse tree, prompt for the details.
  12566. This command can create sparse trees. You first need to select the type
  12567. of match used to create the tree:
  12568. t Show all TODO entries.
  12569. T Show entries with a specific TODO keyword.
  12570. m Show entries selected by a tags/property match.
  12571. p Enter a property name and its value (both with completion on existing
  12572. names/values) and show entries with that property.
  12573. r Show entries matching a regular expression (`/' can be used as well).
  12574. b Show deadlines and scheduled items before a date.
  12575. a Show deadlines and scheduled items after a date.
  12576. d Show deadlines due within `org-deadline-warning-days'.
  12577. D Show deadlines and scheduled items between a date range."
  12578. (interactive "P")
  12579. (setq type (or type org-sparse-tree-default-date-type))
  12580. (setq org-ts-type type)
  12581. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12582. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12583. \[c]ycle through date types: %s"
  12584. (cl-case type
  12585. (all "all timestamps")
  12586. (scheduled "only scheduled")
  12587. (deadline "only deadline")
  12588. (active "only active timestamps")
  12589. (inactive "only inactive timestamps")
  12590. (closed "with a closed time-stamp")
  12591. (otherwise "scheduled/deadline")))
  12592. (let ((answer (read-char-exclusive)))
  12593. (cl-case answer
  12594. (?c
  12595. (org-sparse-tree
  12596. arg
  12597. (cadr
  12598. (memq type '(nil all scheduled deadline active inactive closed)))))
  12599. (?d (call-interactively 'org-check-deadlines))
  12600. (?b (call-interactively 'org-check-before-date))
  12601. (?a (call-interactively 'org-check-after-date))
  12602. (?D (call-interactively 'org-check-dates-range))
  12603. (?t (call-interactively 'org-show-todo-tree))
  12604. (?T (org-show-todo-tree '(4)))
  12605. (?m (call-interactively 'org-match-sparse-tree))
  12606. ((?p ?P)
  12607. (let* ((kwd (completing-read
  12608. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12609. (value (completing-read
  12610. "Value: " (mapcar #'list (org-property-values kwd)))))
  12611. (unless (string-match "\\`{.*}\\'" value)
  12612. (setq value (concat "\"" value "\"")))
  12613. (org-match-sparse-tree arg (concat kwd "=" value))))
  12614. ((?r ?R ?/) (call-interactively 'org-occur))
  12615. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12616. (defvar-local org-occur-highlights nil
  12617. "List of overlays used for occur matches.")
  12618. (defvar-local org-occur-parameters nil
  12619. "Parameters of the active org-occur calls.
  12620. This is a list, each call to org-occur pushes as cons cell,
  12621. containing the regular expression and the callback, onto the list.
  12622. The list can contain several entries if `org-occur' has been called
  12623. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12624. will only contain one set of parameters. When the highlights are
  12625. removed (for example with `C-c C-c', or with the next edit (depending
  12626. on `org-remove-highlights-with-change'), this variable is emptied
  12627. as well.")
  12628. (defun org-occur (regexp &optional keep-previous callback)
  12629. "Make a compact tree which shows all matches of REGEXP.
  12630. The tree will show the lines where the regexp matches, and any other context
  12631. defined in `org-show-context-detail', which see.
  12632. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12633. done by a previous call to `org-occur' will be kept, to allow stacking of
  12634. calls to this command.
  12635. Optional argument CALLBACK can be a function of no argument. In this case,
  12636. it is called with point at the end of the match, match data being set
  12637. accordingly. Current match is shown only if the return value is non-nil.
  12638. The function must neither move point nor alter narrowing."
  12639. (interactive "sRegexp: \nP")
  12640. (when (equal regexp "")
  12641. (user-error "Regexp cannot be empty"))
  12642. (unless keep-previous
  12643. (org-remove-occur-highlights nil nil t))
  12644. (push (cons regexp callback) org-occur-parameters)
  12645. (let ((cnt 0))
  12646. (save-excursion
  12647. (goto-char (point-min))
  12648. (when (or (not keep-previous) ; do not want to keep
  12649. (not org-occur-highlights)) ; no previous matches
  12650. ;; hide everything
  12651. (org-overview))
  12652. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12653. (isearch-no-upper-case-p regexp t)
  12654. org-occur-case-fold-search)))
  12655. (while (re-search-forward regexp nil t)
  12656. (when (or (not callback)
  12657. (save-match-data (funcall callback)))
  12658. (setq cnt (1+ cnt))
  12659. (when org-highlight-sparse-tree-matches
  12660. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12661. (org-show-context 'occur-tree)))))
  12662. (when org-remove-highlights-with-change
  12663. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12664. nil 'local))
  12665. (unless org-sparse-tree-open-archived-trees
  12666. (org-hide-archived-subtrees (point-min) (point-max)))
  12667. (run-hooks 'org-occur-hook)
  12668. (when (called-interactively-p 'interactive)
  12669. (message "%d match(es) for regexp %s" cnt regexp))
  12670. cnt))
  12671. (defun org-occur-next-match (&optional n _reset)
  12672. "Function for `next-error-function' to find sparse tree matches.
  12673. N is the number of matches to move, when negative move backwards.
  12674. This function always goes back to the starting point when no
  12675. match is found."
  12676. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12677. (search-func (if (< n 0)
  12678. 'previous-single-char-property-change
  12679. 'next-single-char-property-change))
  12680. (n (abs n))
  12681. (pos (point))
  12682. p1)
  12683. (catch 'exit
  12684. (while (setq p1 (funcall search-func (point) 'org-type))
  12685. (when (equal p1 limit)
  12686. (goto-char pos)
  12687. (user-error "No more matches"))
  12688. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12689. (setq n (1- n))
  12690. (when (= n 0)
  12691. (goto-char p1)
  12692. (throw 'exit (point))))
  12693. (goto-char p1))
  12694. (goto-char p1)
  12695. (user-error "No more matches"))))
  12696. (defun org-show-context (&optional key)
  12697. "Make sure point and context are visible.
  12698. Optional argument KEY, when non-nil, is a symbol. See
  12699. `org-show-context-detail' for allowed values and how much is to
  12700. be shown."
  12701. (org-show-set-visibility
  12702. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12703. ((cdr (assq key org-show-context-detail)))
  12704. (t (cdr (assq 'default org-show-context-detail))))))
  12705. (defun org-show-set-visibility (detail)
  12706. "Set visibility around point according to DETAIL.
  12707. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12708. `tree', `canonical' or t. See `org-show-context-detail' for more
  12709. information."
  12710. ;; Show current heading and possibly its entry, following headline
  12711. ;; or all children.
  12712. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12713. (org-flag-heading nil)
  12714. (org-show-entry)
  12715. ;; If point is hidden within a drawer or a block, make sure to
  12716. ;; expose it.
  12717. (dolist (o (overlays-at (point)))
  12718. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12719. (delete-overlay o)))
  12720. (unless (org-before-first-heading-p)
  12721. (org-with-limited-levels
  12722. (cl-case detail
  12723. ((tree canonical t) (org-show-children))
  12724. ((nil minimal ancestors))
  12725. (t (save-excursion
  12726. (outline-next-heading)
  12727. (org-flag-heading nil)))))))
  12728. ;; Show all siblings.
  12729. (when (eq detail 'lineage) (org-show-siblings))
  12730. ;; Show ancestors, possibly with their children.
  12731. (when (memq detail '(ancestors lineage tree canonical t))
  12732. (save-excursion
  12733. (while (org-up-heading-safe)
  12734. (org-flag-heading nil)
  12735. (when (memq detail '(canonical t)) (org-show-entry))
  12736. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12737. (defvar org-reveal-start-hook nil
  12738. "Hook run before revealing a location.")
  12739. (defun org-reveal (&optional siblings)
  12740. "Show current entry, hierarchy above it, and the following headline.
  12741. This can be used to show a consistent set of context around
  12742. locations exposed with `org-show-context'.
  12743. With optional argument SIBLINGS, on each level of the hierarchy all
  12744. siblings are shown. This repairs the tree structure to what it would
  12745. look like when opened with hierarchical calls to `org-cycle'.
  12746. With a \\[universal-argument] \\[universal-argument] prefix, \
  12747. go to the parent and show the entire tree."
  12748. (interactive "P")
  12749. (run-hooks 'org-reveal-start-hook)
  12750. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12751. ((equal siblings '(16))
  12752. (save-excursion
  12753. (when (org-up-heading-safe)
  12754. (org-show-subtree)
  12755. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12756. (t (org-show-set-visibility 'lineage))))
  12757. (defun org-highlight-new-match (beg end)
  12758. "Highlight from BEG to END and mark the highlight is an occur headline."
  12759. (let ((ov (make-overlay beg end)))
  12760. (overlay-put ov 'face 'secondary-selection)
  12761. (overlay-put ov 'org-type 'org-occur)
  12762. (push ov org-occur-highlights)))
  12763. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12764. "Remove the occur highlights from the buffer.
  12765. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12766. from the `before-change-functions' in the current buffer."
  12767. (interactive)
  12768. (unless org-inhibit-highlight-removal
  12769. (mapc #'delete-overlay org-occur-highlights)
  12770. (setq org-occur-highlights nil)
  12771. (setq org-occur-parameters nil)
  12772. (unless noremove
  12773. (remove-hook 'before-change-functions
  12774. 'org-remove-occur-highlights 'local))))
  12775. ;;;; Priorities
  12776. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12777. "Regular expression matching the priority indicator.")
  12778. (defvar org-remove-priority-next-time nil)
  12779. (defun org-priority-up ()
  12780. "Increase the priority of the current item."
  12781. (interactive)
  12782. (org-priority 'up))
  12783. (defun org-priority-down ()
  12784. "Decrease the priority of the current item."
  12785. (interactive)
  12786. (org-priority 'down))
  12787. (defun org-priority (&optional action _show)
  12788. "Change the priority of an item.
  12789. ACTION can be `set', `up', `down', or a character."
  12790. (interactive "P")
  12791. (if (equal action '(4))
  12792. (org-show-priority)
  12793. (unless org-enable-priority-commands
  12794. (user-error "Priority commands are disabled"))
  12795. (setq action (or action 'set))
  12796. (let (current new news have remove)
  12797. (save-excursion
  12798. (org-back-to-heading t)
  12799. (when (looking-at org-priority-regexp)
  12800. (setq current (string-to-char (match-string 2))
  12801. have t))
  12802. (cond
  12803. ((eq action 'remove)
  12804. (setq remove t new ?\ ))
  12805. ((or (eq action 'set)
  12806. (integerp action))
  12807. (if (not (eq action 'set))
  12808. (setq new action)
  12809. (message "Priority %c-%c, SPC to remove: "
  12810. org-highest-priority org-lowest-priority)
  12811. (save-match-data
  12812. (setq new (read-char-exclusive))))
  12813. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12814. (= (upcase org-lowest-priority) org-lowest-priority))
  12815. (setq new (upcase new)))
  12816. (cond ((equal new ?\ ) (setq remove t))
  12817. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12818. (user-error "Priority must be between `%c' and `%c'"
  12819. org-highest-priority org-lowest-priority))))
  12820. ((eq action 'up)
  12821. (setq new (if have
  12822. (1- current) ; normal cycling
  12823. ;; last priority was empty
  12824. (if (eq last-command this-command)
  12825. org-lowest-priority ; wrap around empty to lowest
  12826. ;; default
  12827. (if org-priority-start-cycle-with-default
  12828. org-default-priority
  12829. (1- org-default-priority))))))
  12830. ((eq action 'down)
  12831. (setq new (if have
  12832. (1+ current) ; normal cycling
  12833. ;; last priority was empty
  12834. (if (eq last-command this-command)
  12835. org-highest-priority ; wrap around empty to highest
  12836. ;; default
  12837. (if org-priority-start-cycle-with-default
  12838. org-default-priority
  12839. (1+ org-default-priority))))))
  12840. (t (user-error "Invalid action")))
  12841. (when (or (< (upcase new) org-highest-priority)
  12842. (> (upcase new) org-lowest-priority))
  12843. (if (and (memq action '(up down))
  12844. (not have) (not (eq last-command this-command)))
  12845. ;; `new' is from default priority
  12846. (error
  12847. "The default can not be set, see `org-default-priority' why")
  12848. ;; normal cycling: `new' is beyond highest/lowest priority
  12849. ;; and is wrapped around to the empty priority
  12850. (setq remove t)))
  12851. (setq news (format "%c" new))
  12852. (if have
  12853. (if remove
  12854. (replace-match "" t t nil 1)
  12855. (replace-match news t t nil 2))
  12856. (if remove
  12857. (user-error "No priority cookie found in line")
  12858. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12859. (if (match-end 2)
  12860. (progn
  12861. (goto-char (match-end 2))
  12862. (insert " [#" news "]"))
  12863. (goto-char (match-beginning 3))
  12864. (insert "[#" news "] "))))
  12865. (org-set-tags nil 'align))
  12866. (if remove
  12867. (message "Priority removed")
  12868. (message "Priority of current item set to %s" news)))))
  12869. (defun org-show-priority ()
  12870. "Show the priority of the current item.
  12871. This priority is composed of the main priority given with the [#A] cookies,
  12872. and by additional input from the age of a schedules or deadline entry."
  12873. (interactive)
  12874. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12875. (org-get-at-bol 'priority)
  12876. (save-excursion
  12877. (save-match-data
  12878. (beginning-of-line)
  12879. (and (looking-at org-heading-regexp)
  12880. (org-get-priority (match-string 0))))))))
  12881. (message "Priority is %d" (if pri pri -1000))))
  12882. (defun org-get-priority (s)
  12883. "Find priority cookie and return priority."
  12884. (save-match-data
  12885. (if (functionp org-get-priority-function)
  12886. (funcall org-get-priority-function)
  12887. (if (not (string-match org-priority-regexp s))
  12888. (* 1000 (- org-lowest-priority org-default-priority))
  12889. (* 1000 (- org-lowest-priority
  12890. (string-to-char (match-string 2 s))))))))
  12891. ;;;; Tags
  12892. (defvar org-agenda-archives-mode)
  12893. (defvar org-map-continue-from nil
  12894. "Position from where mapping should continue.
  12895. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12896. (defvar org-scanner-tags nil
  12897. "The current tag list while the tags scanner is running.")
  12898. (defvar org-trust-scanner-tags nil
  12899. "Should `org-get-tags-at' use the tags for the scanner.
  12900. This is for internal dynamical scoping only.
  12901. When this is non-nil, the function `org-get-tags-at' will return the value
  12902. of `org-scanner-tags' instead of building the list by itself. This
  12903. can lead to large speed-ups when the tags scanner is used in a file with
  12904. many entries, and when the list of tags is retrieved, for example to
  12905. obtain a list of properties. Building the tags list for each entry in such
  12906. a file becomes an N^2 operation - but with this variable set, it scales
  12907. as N.")
  12908. (defvar org--matcher-tags-todo-only nil)
  12909. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12910. "Scan headline tags with inheritance and produce output ACTION.
  12911. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12912. or `agenda' to produce an entry list for an agenda view. It can also be
  12913. a Lisp form or a function that should be called at each matched headline, in
  12914. this case the return value is a list of all return values from these calls.
  12915. MATCHER is a function accepting three arguments, returning
  12916. a non-nil value whenever a given set of tags qualifies a headline
  12917. for inclusion. See `org-make-tags-matcher' for more information.
  12918. As a special case, it can also be set to t (respectively nil) in
  12919. order to match all (respectively none) headline.
  12920. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12921. keyword are included in the output.
  12922. START-LEVEL can be a string with asterisks, reducing the scope to
  12923. headlines matching this string."
  12924. (require 'org-agenda)
  12925. (let* ((re (concat "^"
  12926. (if start-level
  12927. ;; Get the correct level to match
  12928. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12929. org-outline-regexp)
  12930. " *\\(\\<\\("
  12931. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12932. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12933. (props (list 'face 'default
  12934. 'done-face 'org-agenda-done
  12935. 'undone-face 'default
  12936. 'mouse-face 'highlight
  12937. 'org-not-done-regexp org-not-done-regexp
  12938. 'org-todo-regexp org-todo-regexp
  12939. 'org-complex-heading-regexp org-complex-heading-regexp
  12940. 'help-echo
  12941. (format "mouse-2 or RET jump to org file %s"
  12942. (abbreviate-file-name
  12943. (or (buffer-file-name (buffer-base-buffer))
  12944. (buffer-name (buffer-base-buffer)))))))
  12945. (org-map-continue-from nil)
  12946. lspos tags tags-list
  12947. (tags-alist (list (cons 0 org-file-tags)))
  12948. (llast 0) rtn rtn1 level category i txt
  12949. todo marker entry priority
  12950. ts-date ts-date-type ts-date-pair)
  12951. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12952. (setq action (list 'lambda nil action)))
  12953. (save-excursion
  12954. (goto-char (point-min))
  12955. (when (eq action 'sparse-tree)
  12956. (org-overview)
  12957. (org-remove-occur-highlights))
  12958. (while (let (case-fold-search)
  12959. (re-search-forward re nil t))
  12960. (setq org-map-continue-from nil)
  12961. (catch :skip
  12962. (setq todo
  12963. ;; TODO: is the 1-2 difference a bug?
  12964. (when (match-end 1) (match-string-no-properties 2))
  12965. tags (when (match-end 4) (match-string-no-properties 4)))
  12966. (goto-char (setq lspos (match-beginning 0)))
  12967. (setq level (org-reduced-level (org-outline-level))
  12968. category (org-get-category))
  12969. (when (eq action 'agenda)
  12970. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12971. ts-date (car ts-date-pair)
  12972. ts-date-type (cdr ts-date-pair)))
  12973. (setq i llast llast level)
  12974. ;; remove tag lists from same and sublevels
  12975. (while (>= i level)
  12976. (when (setq entry (assoc i tags-alist))
  12977. (setq tags-alist (delete entry tags-alist)))
  12978. (setq i (1- i)))
  12979. ;; add the next tags
  12980. (when tags
  12981. (setq tags (org-split-string tags ":")
  12982. tags-alist
  12983. (cons (cons level tags) tags-alist)))
  12984. ;; compile tags for current headline
  12985. (setq tags-list
  12986. (if org-use-tag-inheritance
  12987. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12988. tags)
  12989. org-scanner-tags tags-list)
  12990. (when org-use-tag-inheritance
  12991. (setcdr (car tags-alist)
  12992. (mapcar (lambda (x)
  12993. (setq x (copy-sequence x))
  12994. (org-add-prop-inherited x))
  12995. (cdar tags-alist))))
  12996. (when (and tags org-use-tag-inheritance
  12997. (or (not (eq t org-use-tag-inheritance))
  12998. org-tags-exclude-from-inheritance))
  12999. ;; Selective inheritance, remove uninherited ones.
  13000. (setcdr (car tags-alist)
  13001. (org-remove-uninherited-tags (cdar tags-alist))))
  13002. (when (and
  13003. ;; eval matcher only when the todo condition is OK
  13004. (and (or (not todo-only) (member todo org-not-done-keywords))
  13005. (if (functionp matcher)
  13006. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13007. (funcall matcher todo tags-list level))
  13008. matcher))
  13009. ;; Call the skipper, but return t if it does not
  13010. ;; skip, so that the `and' form continues evaluating.
  13011. (progn
  13012. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13013. t)
  13014. ;; Check if timestamps are deselecting this entry
  13015. (or (not todo-only)
  13016. (and (member todo org-not-done-keywords)
  13017. (or (not org-agenda-tags-todo-honor-ignore-options)
  13018. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13019. ;; select this headline
  13020. (cond
  13021. ((eq action 'sparse-tree)
  13022. (and org-highlight-sparse-tree-matches
  13023. (org-get-heading) (match-end 0)
  13024. (org-highlight-new-match
  13025. (match-beginning 1) (match-end 1)))
  13026. (org-show-context 'tags-tree))
  13027. ((eq action 'agenda)
  13028. (setq txt (org-agenda-format-item
  13029. ""
  13030. (concat
  13031. (if (eq org-tags-match-list-sublevels 'indented)
  13032. (make-string (1- level) ?.) "")
  13033. (org-get-heading))
  13034. (make-string level ?\s)
  13035. category
  13036. tags-list)
  13037. priority (org-get-priority txt))
  13038. (goto-char lspos)
  13039. (setq marker (org-agenda-new-marker))
  13040. (org-add-props txt props
  13041. 'org-marker marker 'org-hd-marker marker 'org-category category
  13042. 'todo-state todo
  13043. 'ts-date ts-date
  13044. 'priority priority
  13045. 'type (concat "tagsmatch" ts-date-type))
  13046. (push txt rtn))
  13047. ((functionp action)
  13048. (setq org-map-continue-from nil)
  13049. (save-excursion
  13050. (setq rtn1 (funcall action))
  13051. (push rtn1 rtn)))
  13052. (t (user-error "Invalid action")))
  13053. ;; if we are to skip sublevels, jump to end of subtree
  13054. (unless org-tags-match-list-sublevels
  13055. (org-end-of-subtree t)
  13056. (backward-char 1))))
  13057. ;; Get the correct position from where to continue
  13058. (if org-map-continue-from
  13059. (goto-char org-map-continue-from)
  13060. (and (= (point) lspos) (end-of-line 1)))))
  13061. (when (and (eq action 'sparse-tree)
  13062. (not org-sparse-tree-open-archived-trees))
  13063. (org-hide-archived-subtrees (point-min) (point-max)))
  13064. (nreverse rtn)))
  13065. (defun org-remove-uninherited-tags (tags)
  13066. "Remove all tags that are not inherited from the list TAGS."
  13067. (cond
  13068. ((eq org-use-tag-inheritance t)
  13069. (if org-tags-exclude-from-inheritance
  13070. (org-delete-all org-tags-exclude-from-inheritance tags)
  13071. tags))
  13072. ((not org-use-tag-inheritance) nil)
  13073. ((stringp org-use-tag-inheritance)
  13074. (delq nil (mapcar
  13075. (lambda (x)
  13076. (if (and (string-match org-use-tag-inheritance x)
  13077. (not (member x org-tags-exclude-from-inheritance)))
  13078. x nil))
  13079. tags)))
  13080. ((listp org-use-tag-inheritance)
  13081. (delq nil (mapcar
  13082. (lambda (x)
  13083. (if (member x org-use-tag-inheritance) x nil))
  13084. tags)))))
  13085. (defun org-match-sparse-tree (&optional todo-only match)
  13086. "Create a sparse tree according to tags string MATCH.
  13087. MATCH is a string with match syntax. It can contain a selection
  13088. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13089. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13090. those. See the manual for details.
  13091. If optional argument TODO-ONLY is non-nil, only select lines that
  13092. are also TODO tasks."
  13093. (interactive "P")
  13094. (org-agenda-prepare-buffers (list (current-buffer)))
  13095. (let ((org--matcher-tags-todo-only todo-only))
  13096. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13097. org--matcher-tags-todo-only)))
  13098. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13099. (defvar org-cached-props nil)
  13100. (defun org-cached-entry-get (pom property)
  13101. (if (or (eq t org-use-property-inheritance)
  13102. (and (stringp org-use-property-inheritance)
  13103. (let ((case-fold-search t))
  13104. (string-match-p org-use-property-inheritance property)))
  13105. (and (listp org-use-property-inheritance)
  13106. (member-ignore-case property org-use-property-inheritance)))
  13107. ;; Caching is not possible, check it directly.
  13108. (org-entry-get pom property 'inherit)
  13109. ;; Get all properties, so we can do complicated checks easily.
  13110. (cdr (assoc-string property
  13111. (or org-cached-props
  13112. (setq org-cached-props (org-entry-properties pom)))
  13113. t))))
  13114. (defun org-global-tags-completion-table (&optional files)
  13115. "Return the list of all tags in all agenda buffer/files.
  13116. Optional FILES argument is a list of files which can be used
  13117. instead of the agenda files."
  13118. (save-excursion
  13119. (org-uniquify
  13120. (delq nil
  13121. (apply #'append
  13122. (mapcar
  13123. (lambda (file)
  13124. (set-buffer (find-file-noselect file))
  13125. (mapcar (lambda (x)
  13126. (and (stringp (car-safe x))
  13127. (list (car-safe x))))
  13128. (or org-current-tag-alist (org-get-buffer-tags))))
  13129. (if (car-safe files) files
  13130. (org-agenda-files))))))))
  13131. (defun org-make-tags-matcher (match)
  13132. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13133. Returns a cons of the selection string MATCH and a function
  13134. implementing the matcher.
  13135. The matcher is to be called at an Org entry, with point on the
  13136. headline, and returns non-nil if the entry matches the selection
  13137. string MATCH. It must be called with three arguments: the TODO
  13138. keyword at the entry (or nil if none), the list of all tags at
  13139. the entry including inherited ones and the reduced level of the
  13140. headline. Additionally, the category of the entry, if any, must
  13141. be specified as the text property `org-category' on the headline.
  13142. This function sets the variable `org--matcher-tags-todo-only' to
  13143. a non-nil value if the matcher restricts matching to TODO
  13144. entries, otherwise it is not touched.
  13145. See also `org-scan-tags'."
  13146. (unless match
  13147. ;; Get a new match request, with completion against the global
  13148. ;; tags table and the local tags in current buffer.
  13149. (let ((org-last-tags-completion-table
  13150. (org-uniquify
  13151. (delq nil (append (org-get-buffer-tags)
  13152. (org-global-tags-completion-table))))))
  13153. (setq match
  13154. (completing-read
  13155. "Match: "
  13156. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13157. (let ((match0 match)
  13158. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13159. (start 0)
  13160. tagsmatch todomatch tagsmatcher todomatcher)
  13161. ;; Expand group tags.
  13162. (setq match (org-tags-expand match))
  13163. ;; Check if there is a TODO part of this match, which would be the
  13164. ;; part after a "/". To make sure that this slash is not part of
  13165. ;; a property value to be matched against, we also check that
  13166. ;; there is no / after that slash. First, find the last slash.
  13167. (let ((s 0))
  13168. (while (string-match "/+" match s)
  13169. (setq start (match-beginning 0))
  13170. (setq s (match-end 0))))
  13171. (if (and (string-match "/+" match start)
  13172. (not (string-match-p "\"" match start)))
  13173. ;; Match contains also a TODO-matching request.
  13174. (progn
  13175. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13176. (setq todomatch (substring match (match-end 0)))
  13177. (when (string-prefix-p "!" todomatch)
  13178. (setq org--matcher-tags-todo-only t)
  13179. (setq todomatch (substring todomatch 1)))
  13180. (when (string-match "\\`\\s-*\\'" todomatch)
  13181. (setq todomatch nil)))
  13182. ;; Only matching tags.
  13183. (setq tagsmatch match)
  13184. (setq todomatch nil))
  13185. ;; Make the tags matcher.
  13186. (when (org-string-nw-p tagsmatch)
  13187. (let ((orlist nil)
  13188. (orterms (org-split-string tagsmatch "|"))
  13189. term)
  13190. (while (setq term (pop orterms))
  13191. (while (and (equal (substring term -1) "\\") orterms)
  13192. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13193. (while (string-match re term)
  13194. (let* ((rest (substring term (match-end 0)))
  13195. (minus (and (match-end 1)
  13196. (equal (match-string 1 term) "-")))
  13197. (tag (save-match-data
  13198. (replace-regexp-in-string
  13199. "\\\\-" "-" (match-string 2 term))))
  13200. (regexp (eq (string-to-char tag) ?{))
  13201. (levelp (match-end 4))
  13202. (propp (match-end 5))
  13203. (mm
  13204. (cond
  13205. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13206. (levelp
  13207. `(,(org-op-to-function (match-string 3 term))
  13208. level
  13209. ,(string-to-number (match-string 4 term))))
  13210. (propp
  13211. (let* ((gv (pcase (upcase (match-string 5 term))
  13212. ("CATEGORY"
  13213. '(get-text-property (point) 'org-category))
  13214. ("TODO" 'todo)
  13215. (p `(org-cached-entry-get nil ,p))))
  13216. (pv (match-string 7 term))
  13217. (regexp (eq (string-to-char pv) ?{))
  13218. (strp (eq (string-to-char pv) ?\"))
  13219. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13220. (po (org-op-to-function (match-string 6 term)
  13221. (if timep 'time strp))))
  13222. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13223. (when timep (setq pv (org-matcher-time pv)))
  13224. (cond ((and regexp (eq po 'org<>))
  13225. `(not (string-match ,pv (or ,gv ""))))
  13226. (regexp `(string-match ,pv (or ,gv "")))
  13227. (strp `(,po (or ,gv "") ,pv))
  13228. (t
  13229. `(,po
  13230. (string-to-number (or ,gv ""))
  13231. ,(string-to-number pv))))))
  13232. (t `(member ,tag tags-list)))))
  13233. (push (if minus `(not ,mm) mm) tagsmatcher)
  13234. (setq term rest)))
  13235. (push `(and ,@tagsmatcher) orlist)
  13236. (setq tagsmatcher nil))
  13237. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13238. ;; Make the TODO matcher.
  13239. (when (org-string-nw-p todomatch)
  13240. (let ((orlist nil))
  13241. (dolist (term (org-split-string todomatch "|"))
  13242. (while (string-match re term)
  13243. (let* ((minus (and (match-end 1)
  13244. (equal (match-string 1 term) "-")))
  13245. (kwd (match-string 2 term))
  13246. (regexp (eq (string-to-char kwd) ?{))
  13247. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13248. `(equal todo ,kwd))))
  13249. (push (if minus `(not ,mm) mm) todomatcher))
  13250. (setq term (substring term (match-end 0))))
  13251. (push (if (> (length todomatcher) 1)
  13252. (cons 'and todomatcher)
  13253. (car todomatcher))
  13254. orlist)
  13255. (setq todomatcher nil))
  13256. (setq todomatcher (cons 'or orlist))))
  13257. ;; Return the string and function of the matcher. If no
  13258. ;; tags-specific or todo-specific matcher exists, match
  13259. ;; everything.
  13260. (let ((matcher (if (and tagsmatcher todomatcher)
  13261. `(and ,tagsmatcher ,todomatcher)
  13262. (or tagsmatcher todomatcher t))))
  13263. (when org--matcher-tags-todo-only
  13264. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13265. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13266. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13267. "Expand group tags in MATCH.
  13268. This replaces every group tag in MATCH with a regexp tag search.
  13269. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13270. will be replaced like this:
  13271. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13272. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13273. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13274. Replacing by a regexp preserves the structure of the match.
  13275. E.g., this expansion
  13276. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13277. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13278. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13279. A group tag in MATCH can contain regular expressions of its own.
  13280. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13281. will be replaced like this:
  13282. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13283. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13284. assumed to be a single group tag, and the function will return
  13285. the list of tags in this group.
  13286. When DOWNCASE is non-nil, expand downcased TAGS."
  13287. (if org-group-tags
  13288. (let* ((case-fold-search t)
  13289. (stable org-mode-syntax-table)
  13290. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13291. (taggroups (if downcased
  13292. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13293. taggroups)
  13294. taggroups))
  13295. (taggroups-keys (mapcar #'car taggroups))
  13296. (return-match (if downcased (downcase match) match))
  13297. (count 0)
  13298. (work-already-expanded tags-already-expanded)
  13299. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13300. ;; @ and _ are allowed as word-components in tags.
  13301. (modify-syntax-entry ?@ "w" stable)
  13302. (modify-syntax-entry ?_ "w" stable)
  13303. ;; Temporarily replace regexp-expressions in the match-expression.
  13304. (while (string-match "{.+?}" return-match)
  13305. (cl-incf count)
  13306. (push (match-string 0 return-match) regexps-in-match)
  13307. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13308. (while (and taggroups-keys
  13309. (with-syntax-table stable
  13310. (string-match
  13311. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13312. (regexp-opt taggroups-keys) "\\>\\)")
  13313. return-match)))
  13314. (let* ((dir (match-string 1 return-match))
  13315. (tag (match-string 2 return-match))
  13316. (tag (if downcased (downcase tag) tag)))
  13317. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13318. (member tag work-already-expanded))
  13319. (setq tags-in-group (assoc tag taggroups))
  13320. (push tag work-already-expanded)
  13321. ;; Recursively expand each tag in the group, if the tag hasn't
  13322. ;; already been expanded. Restore the match-data after all recursive calls.
  13323. (save-match-data
  13324. (let (tags-expanded)
  13325. (dolist (x (cdr tags-in-group))
  13326. (if (and (member x taggroups-keys)
  13327. (not (member x work-already-expanded)))
  13328. (setq tags-expanded
  13329. (delete-dups
  13330. (append
  13331. (org-tags-expand x t downcased
  13332. work-already-expanded)
  13333. tags-expanded)))
  13334. (setq tags-expanded
  13335. (append (list x) tags-expanded)))
  13336. (setq work-already-expanded
  13337. (delete-dups
  13338. (append tags-expanded
  13339. work-already-expanded))))
  13340. (setq tags-in-group
  13341. (delete-dups (cons (car tags-in-group)
  13342. tags-expanded)))))
  13343. ;; Filter tag-regexps from tags.
  13344. (setq regexp-in-group-escaped
  13345. (delq nil (mapcar (lambda (x)
  13346. (if (stringp x)
  13347. (and (equal "{" (substring x 0 1))
  13348. (equal "}" (substring x -1))
  13349. x)
  13350. x))
  13351. tags-in-group))
  13352. regexp-in-group
  13353. (mapcar (lambda (x)
  13354. (substring x 1 -1))
  13355. regexp-in-group-escaped)
  13356. tags-in-group
  13357. (delq nil (mapcar (lambda (x)
  13358. (if (stringp x)
  13359. (and (not (equal "{" (substring x 0 1)))
  13360. (not (equal "}" (substring x -1)))
  13361. x)
  13362. x))
  13363. tags-in-group)))
  13364. ;; If single-as-list, do no more in the while-loop.
  13365. (if (not single-as-list)
  13366. (progn
  13367. (when regexp-in-group
  13368. (setq regexp-in-group
  13369. (concat "\\|"
  13370. (mapconcat 'identity regexp-in-group
  13371. "\\|"))))
  13372. (setq tags-in-group
  13373. (concat dir
  13374. "{\\<"
  13375. (regexp-opt tags-in-group)
  13376. "\\>"
  13377. regexp-in-group
  13378. "}"))
  13379. (when (stringp tags-in-group)
  13380. (org-add-props tags-in-group '(grouptag t)))
  13381. (setq return-match
  13382. (replace-match tags-in-group t t return-match)))
  13383. (setq tags-in-group
  13384. (append regexp-in-group-escaped tags-in-group))))
  13385. (setq taggroups-keys (delete tag taggroups-keys))))
  13386. ;; Add the regular expressions back into the match-expression again.
  13387. (while regexps-in-match
  13388. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13389. (pop regexps-in-match)
  13390. return-match t t))
  13391. (cl-decf count))
  13392. (if single-as-list
  13393. (if tags-in-group tags-in-group (list return-match))
  13394. return-match))
  13395. (if single-as-list
  13396. (list (if downcased (downcase match) match))
  13397. match)))
  13398. (defun org-op-to-function (op &optional stringp)
  13399. "Turn an operator into the appropriate function."
  13400. (setq op
  13401. (cond
  13402. ((equal op "<" ) '(< string< org-time<))
  13403. ((equal op ">" ) '(> org-string> org-time>))
  13404. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13405. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13406. ((member op '("=" "==")) '(= string= org-time=))
  13407. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13408. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13409. (defun org<> (a b) (not (= a b)))
  13410. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13411. (defun org-string>= (a b) (not (string< a b)))
  13412. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13413. (defun org-string<> (a b) (not (string= a b)))
  13414. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13415. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
  13420. (defun org-2ft (s)
  13421. "Convert S to a floating point time.
  13422. If S is already a number, just return it. If it is a string, parse
  13423. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13424. (cond
  13425. ((numberp s) s)
  13426. ((stringp s)
  13427. (condition-case nil
  13428. (float-time (apply 'encode-time (org-parse-time-string s)))
  13429. (error 0.)))
  13430. (t 0.)))
  13431. (defun org-time-today ()
  13432. "Time in seconds today at 0:00.
  13433. Returns the float number of seconds since the beginning of the
  13434. epoch to the beginning of today (00:00)."
  13435. (float-time (apply 'encode-time
  13436. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13437. (defun org-matcher-time (s)
  13438. "Interpret a time comparison value."
  13439. (save-match-data
  13440. (cond
  13441. ((string= s "<now>") (float-time))
  13442. ((string= s "<today>") (org-time-today))
  13443. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13444. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13445. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13446. (+ (org-time-today)
  13447. (* (string-to-number (match-string 1 s))
  13448. (cdr (assoc (match-string 2 s)
  13449. '(("d" . 86400.0) ("w" . 604800.0)
  13450. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13451. (t (org-2ft s)))))
  13452. (defun org-match-any-p (re list)
  13453. "Does re match any element of list?"
  13454. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13455. (delq nil list))
  13456. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13457. (defvar org-tags-overlay (make-overlay 1 1))
  13458. (delete-overlay org-tags-overlay)
  13459. (defun org-get-local-tags-at (&optional pos)
  13460. "Get a list of tags defined in the current headline."
  13461. (org-get-tags-at pos 'local))
  13462. (defun org-get-local-tags ()
  13463. "Get a list of tags defined in the current headline."
  13464. (org-get-tags-at nil 'local))
  13465. (defun org-get-tags-at (&optional pos local)
  13466. "Get a list of all headline tags applicable at POS.
  13467. POS defaults to point. If tags are inherited, the list contains
  13468. the targets in the same sequence as the headlines appear, i.e.
  13469. the tags of the current headline come last.
  13470. When LOCAL is non-nil, only return tags from the current headline,
  13471. ignore inherited ones."
  13472. (interactive)
  13473. (if (and org-trust-scanner-tags
  13474. (or (not pos) (equal pos (point)))
  13475. (not local))
  13476. org-scanner-tags
  13477. (let (tags ltags lastpos parent)
  13478. (save-excursion
  13479. (save-restriction
  13480. (widen)
  13481. (goto-char (or pos (point)))
  13482. (save-match-data
  13483. (catch 'done
  13484. (condition-case nil
  13485. (progn
  13486. (org-back-to-heading t)
  13487. (while (not (equal lastpos (point)))
  13488. (setq lastpos (point))
  13489. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13490. (setq ltags (org-split-string
  13491. (match-string-no-properties 1) ":"))
  13492. (when parent
  13493. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13494. (setq tags (append
  13495. (if parent
  13496. (org-remove-uninherited-tags ltags)
  13497. ltags)
  13498. tags)))
  13499. (or org-use-tag-inheritance (throw 'done t))
  13500. (when local (throw 'done t))
  13501. (or (org-up-heading-safe) (error nil))
  13502. (setq parent t)))
  13503. (error nil)))))
  13504. (if local
  13505. tags
  13506. (reverse (delete-dups
  13507. (reverse (append
  13508. (org-remove-uninherited-tags
  13509. org-file-tags)
  13510. tags)))))))))
  13511. (defun org-add-prop-inherited (s)
  13512. (add-text-properties 0 (length s) '(inherited t) s)
  13513. s)
  13514. (defun org-toggle-tag (tag &optional onoff)
  13515. "Toggle the tag TAG for the current line.
  13516. If ONOFF is `on' or `off', don't toggle but set to this state."
  13517. (let (res current)
  13518. (save-excursion
  13519. (org-back-to-heading t)
  13520. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13521. (point-at-eol) t)
  13522. (progn
  13523. (setq current (match-string 1))
  13524. (replace-match ""))
  13525. (setq current ""))
  13526. (setq current (nreverse (org-split-string current ":")))
  13527. (cond
  13528. ((eq onoff 'on)
  13529. (setq res t)
  13530. (or (member tag current) (push tag current)))
  13531. ((eq onoff 'off)
  13532. (or (not (member tag current)) (setq current (delete tag current))))
  13533. (t (if (member tag current)
  13534. (setq current (delete tag current))
  13535. (setq res t)
  13536. (push tag current))))
  13537. (end-of-line 1)
  13538. (if current
  13539. (progn
  13540. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13541. (org-set-tags nil t))
  13542. (delete-horizontal-space))
  13543. (run-hooks 'org-after-tags-change-hook))
  13544. res))
  13545. (defun org--align-tags-here (to-col)
  13546. "Align tags on the current headline to TO-COL.
  13547. Assume point is on a headline."
  13548. (let ((pos (point)))
  13549. (beginning-of-line)
  13550. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13551. (>= pos (match-beginning 2)))
  13552. ;; No tags or point within tags: do not align.
  13553. (goto-char pos)
  13554. (goto-char (match-beginning 1))
  13555. (let ((shift (max (- (if (>= to-col 0) to-col
  13556. (- (abs to-col) (string-width (match-string 2))))
  13557. (current-column))
  13558. 1)))
  13559. (replace-match (make-string shift ?\s) nil nil nil 1)
  13560. ;; Preserve initial position, if possible. In any case, stop
  13561. ;; before tags.
  13562. (when (< pos (point)) (goto-char pos))))))
  13563. (defun org-set-tags-command (&optional arg just-align)
  13564. "Call the set-tags command for the current entry."
  13565. (interactive "P")
  13566. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13567. (org-set-tags arg just-align)
  13568. (save-excursion
  13569. (unless (and (org-region-active-p)
  13570. org-loop-over-headlines-in-active-region)
  13571. (org-back-to-heading t))
  13572. (org-set-tags arg just-align))))
  13573. (defun org-set-tags-to (data)
  13574. "Set the tags of the current entry to DATA, replacing the current tags.
  13575. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13576. If DATA is nil or the empty string, any tags will be removed."
  13577. (interactive "sTags: ")
  13578. (setq data
  13579. (cond
  13580. ((eq data nil) "")
  13581. ((equal data "") "")
  13582. ((stringp data)
  13583. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13584. ":"))
  13585. ((listp data)
  13586. (concat ":" (mapconcat 'identity data ":") ":"))))
  13587. (when data
  13588. (save-excursion
  13589. (org-back-to-heading t)
  13590. (when (let ((case-fold-search nil))
  13591. (looking-at org-complex-heading-regexp))
  13592. (if (match-end 5)
  13593. (progn
  13594. (goto-char (match-beginning 5))
  13595. (insert data)
  13596. (delete-region (point) (point-at-eol))
  13597. (org-set-tags nil 'align))
  13598. (goto-char (point-at-eol))
  13599. (insert " " data)
  13600. (org-set-tags nil 'align)))
  13601. (beginning-of-line 1)
  13602. (when (looking-at ".*?\\([ \t]+\\)$")
  13603. (delete-region (match-beginning 1) (match-end 1))))))
  13604. (defun org-align-all-tags ()
  13605. "Align the tags in all headings."
  13606. (interactive)
  13607. (save-excursion
  13608. (or (ignore-errors (org-back-to-heading t))
  13609. (outline-next-heading))
  13610. (if (org-at-heading-p)
  13611. (org-set-tags t)
  13612. (message "No headings"))))
  13613. (defvar org-indent-indentation-per-level)
  13614. (defun org-set-tags (&optional arg just-align)
  13615. "Set the tags for the current headline.
  13616. With prefix ARG, realign all tags in headings in the current buffer.
  13617. When JUST-ALIGN is non-nil, only align tags."
  13618. (interactive "P")
  13619. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13620. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13621. 'region-start-level
  13622. 'region))
  13623. org-loop-over-headlines-in-active-region)
  13624. (org-map-entries
  13625. ;; We don't use ARG and JUST-ALIGN here because these args
  13626. ;; are not useful when looping over headlines.
  13627. #'org-set-tags
  13628. org-loop-over-headlines-in-active-region
  13629. cl
  13630. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13631. (let ((org-setting-tags t))
  13632. (if arg
  13633. (save-excursion
  13634. (goto-char (point-min))
  13635. (while (re-search-forward org-outline-regexp-bol nil t)
  13636. (org-set-tags nil t)
  13637. (end-of-line))
  13638. (message "All tags realigned to column %d" org-tags-column))
  13639. (let* ((current (org-get-tags-string))
  13640. (tags
  13641. (if just-align current
  13642. ;; Get a new set of tags from the user.
  13643. (save-excursion
  13644. (let* ((seen)
  13645. (table
  13646. (setq
  13647. org-last-tags-completion-table
  13648. ;; Uniquify tags in alists, yet preserve
  13649. ;; structure (i.e., keywords).
  13650. (delq nil
  13651. (mapcar
  13652. (lambda (pair)
  13653. (let ((head (car pair)))
  13654. (cond ((symbolp head) pair)
  13655. ((member head seen) nil)
  13656. (t (push head seen)
  13657. pair))))
  13658. (append
  13659. (or org-current-tag-alist
  13660. (org-get-buffer-tags))
  13661. (and
  13662. org-complete-tags-always-offer-all-agenda-tags
  13663. (org-global-tags-completion-table
  13664. (org-agenda-files))))))))
  13665. (current-tags (org-split-string current ":"))
  13666. (inherited-tags
  13667. (nreverse (nthcdr (length current-tags)
  13668. (nreverse (org-get-tags-at))))))
  13669. (replace-regexp-in-string
  13670. "\\([-+&]+\\|,\\)"
  13671. ":"
  13672. (if (or (eq t org-use-fast-tag-selection)
  13673. (and org-use-fast-tag-selection
  13674. (delq nil (mapcar #'cdr table))))
  13675. (org-fast-tag-selection
  13676. current-tags inherited-tags table
  13677. (and org-fast-tag-selection-include-todo
  13678. org-todo-key-alist))
  13679. (let ((org-add-colon-after-tag-completion
  13680. (< 1 (length table))))
  13681. (org-trim
  13682. (completing-read
  13683. "Tags: "
  13684. #'org-tags-completion-function
  13685. nil nil current 'org-tags-history))))))))))
  13686. (when org-tags-sort-function
  13687. (setq tags
  13688. (mapconcat
  13689. #'identity
  13690. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13691. org-tags-sort-function)
  13692. ":")))
  13693. (if (not (org-string-nw-p tags)) (setq tags "")
  13694. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13695. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13696. ;; Insert new tags at the correct column.
  13697. (unless (equal current tags)
  13698. (save-excursion
  13699. (beginning-of-line)
  13700. (let ((case-fold-search nil))
  13701. (looking-at org-complex-heading-regexp))
  13702. ;; Remove current tags, if any.
  13703. (when (match-end 5) (replace-match "" nil nil nil 5))
  13704. ;; Insert new tags, if any. Otherwise, remove trailing
  13705. ;; white spaces.
  13706. (end-of-line)
  13707. (if (not (equal tags ""))
  13708. (insert " " tags)
  13709. (skip-chars-backward " \t")
  13710. (delete-region (point) (line-end-position)))))
  13711. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13712. ;; is on.
  13713. (unless (equal tags "")
  13714. (let* ((level (save-excursion
  13715. (beginning-of-line)
  13716. (skip-chars-forward "\\*")))
  13717. (offset (if (bound-and-true-p org-indent-mode)
  13718. (* (1- org-indent-indentation-per-level)
  13719. (1- level))
  13720. 0))
  13721. (tags-column
  13722. (+ org-tags-column
  13723. (if (> org-tags-column 0) (- offset) offset))))
  13724. (org--align-tags-here tags-column))))
  13725. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13726. (defun org-change-tag-in-region (beg end tag off)
  13727. "Add or remove TAG for each entry in the region.
  13728. This works in the agenda, and also in an Org buffer."
  13729. (interactive
  13730. (list (region-beginning) (region-end)
  13731. (let ((org-last-tags-completion-table
  13732. (if (derived-mode-p 'org-mode)
  13733. (org-uniquify
  13734. (delq nil (append (org-get-buffer-tags)
  13735. (org-global-tags-completion-table))))
  13736. (org-global-tags-completion-table))))
  13737. (completing-read
  13738. "Tag: " 'org-tags-completion-function nil nil nil
  13739. 'org-tags-history))
  13740. (progn
  13741. (message "[s]et or [r]emove? ")
  13742. (equal (read-char-exclusive) ?r))))
  13743. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13744. (let ((agendap (equal major-mode 'org-agenda-mode))
  13745. l1 l2 m buf pos newhead (cnt 0))
  13746. (goto-char end)
  13747. (setq l2 (1- (org-current-line)))
  13748. (goto-char beg)
  13749. (setq l1 (org-current-line))
  13750. (cl-loop for l from l1 to l2 do
  13751. (org-goto-line l)
  13752. (setq m (get-text-property (point) 'org-hd-marker))
  13753. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13754. (and agendap m))
  13755. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13756. pos (if agendap m (point)))
  13757. (with-current-buffer buf
  13758. (save-excursion
  13759. (save-restriction
  13760. (goto-char pos)
  13761. (setq cnt (1+ cnt))
  13762. (org-toggle-tag tag (if off 'off 'on))
  13763. (setq newhead (org-get-heading)))))
  13764. (and agendap (org-agenda-change-all-lines newhead m))))
  13765. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13766. (defun org-tags-completion-function (string _predicate &optional flag)
  13767. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13768. (confirm (lambda (x) (stringp (car x)))))
  13769. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13770. (setq s1 (match-string 1 string)
  13771. s2 (match-string 2 string))
  13772. (setq s1 "" s2 string))
  13773. (cond
  13774. ((eq flag nil)
  13775. ;; try completion
  13776. (setq rtn (try-completion s2 ctable confirm))
  13777. (when (stringp rtn)
  13778. (setq rtn
  13779. (concat s1 s2 (substring rtn (length s2))
  13780. (if (and org-add-colon-after-tag-completion
  13781. (assoc rtn ctable))
  13782. ":" ""))))
  13783. rtn)
  13784. ((eq flag t)
  13785. ;; all-completions
  13786. (all-completions s2 ctable confirm))
  13787. ((eq flag 'lambda)
  13788. ;; exact match?
  13789. (assoc s2 ctable)))))
  13790. (defun org-fast-tag-insert (kwd tags face &optional end)
  13791. "Insert KDW, and the TAGS, the latter with face FACE.
  13792. Also insert END."
  13793. (insert (format "%-12s" (concat kwd ":"))
  13794. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13795. (or end "")))
  13796. (defun org-fast-tag-show-exit (flag)
  13797. (save-excursion
  13798. (org-goto-line 3)
  13799. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13800. (replace-match ""))
  13801. (when flag
  13802. (end-of-line 1)
  13803. (org-move-to-column (- (window-width) 19) t)
  13804. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13805. (defun org-set-current-tags-overlay (current prefix)
  13806. "Add an overlay to CURRENT tag with PREFIX."
  13807. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13808. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13809. (org-overlay-display org-tags-overlay (concat prefix s))))
  13810. (defvar org-last-tag-selection-key nil)
  13811. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13812. "Fast tag selection with single keys.
  13813. CURRENT is the current list of tags in the headline, INHERITED is the
  13814. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13815. possibly with grouping information. TODO-TABLE is a similar table with
  13816. TODO keywords, should these have keys assigned to them.
  13817. If the keys are nil, a-z are automatically assigned.
  13818. Returns the new tags string, or nil to not change the current settings."
  13819. (let* ((fulltable (append table todo-table))
  13820. (maxlen (apply 'max (mapcar
  13821. (lambda (x)
  13822. (if (stringp (car x)) (string-width (car x)) 0))
  13823. fulltable)))
  13824. (buf (current-buffer))
  13825. (expert (eq org-fast-tag-selection-single-key 'expert))
  13826. (buffer-tags nil)
  13827. (fwidth (+ maxlen 3 1 3))
  13828. (ncol (/ (- (window-width) 4) fwidth))
  13829. (i-face 'org-done)
  13830. (c-face 'org-todo)
  13831. tg cnt e c char c1 c2 ntable tbl rtn
  13832. ov-start ov-end ov-prefix
  13833. (exit-after-next org-fast-tag-selection-single-key)
  13834. (done-keywords org-done-keywords)
  13835. groups ingroup intaggroup)
  13836. (save-excursion
  13837. (beginning-of-line 1)
  13838. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13839. (setq ov-start (match-beginning 1)
  13840. ov-end (match-end 1)
  13841. ov-prefix "")
  13842. (setq ov-start (1- (point-at-eol))
  13843. ov-end (1+ ov-start))
  13844. (skip-chars-forward "^\n\r")
  13845. (setq ov-prefix
  13846. (concat
  13847. (buffer-substring (1- (point)) (point))
  13848. (if (> (current-column) org-tags-column)
  13849. " "
  13850. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13851. (move-overlay org-tags-overlay ov-start ov-end)
  13852. (save-window-excursion
  13853. (if expert
  13854. (set-buffer (get-buffer-create " *Org tags*"))
  13855. (delete-other-windows)
  13856. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13857. (org-switch-to-buffer-other-window " *Org tags*"))
  13858. (erase-buffer)
  13859. (setq-local org-done-keywords done-keywords)
  13860. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13861. (org-fast-tag-insert "Current" current c-face "\n\n")
  13862. (org-fast-tag-show-exit exit-after-next)
  13863. (org-set-current-tags-overlay current ov-prefix)
  13864. (setq tbl fulltable char ?a cnt 0)
  13865. (while (setq e (pop tbl))
  13866. (cond
  13867. ((eq (car e) :startgroup)
  13868. (push '() groups) (setq ingroup t)
  13869. (unless (zerop cnt)
  13870. (setq cnt 0)
  13871. (insert "\n"))
  13872. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13873. ((eq (car e) :endgroup)
  13874. (setq ingroup nil cnt 0)
  13875. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13876. ((eq (car e) :startgrouptag)
  13877. (setq intaggroup t)
  13878. (unless (zerop cnt)
  13879. (setq cnt 0)
  13880. (insert "\n"))
  13881. (insert "[ "))
  13882. ((eq (car e) :endgrouptag)
  13883. (setq intaggroup nil cnt 0)
  13884. (insert "]\n"))
  13885. ((equal e '(:newline))
  13886. (unless (zerop cnt)
  13887. (setq cnt 0)
  13888. (insert "\n")
  13889. (setq e (car tbl))
  13890. (while (equal (car tbl) '(:newline))
  13891. (insert "\n")
  13892. (setq tbl (cdr tbl)))))
  13893. ((equal e '(:grouptags)) (insert " : "))
  13894. (t
  13895. (setq tg (copy-sequence (car e)) c2 nil)
  13896. (if (cdr e)
  13897. (setq c (cdr e))
  13898. ;; automatically assign a character.
  13899. (setq c1 (string-to-char
  13900. (downcase (substring
  13901. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13902. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13903. (while (or (rassoc char ntable) (rassoc char table))
  13904. (setq char (1+ char)))
  13905. (setq c2 c1))
  13906. (setq c (or c2 char)))
  13907. (when ingroup (push tg (car groups)))
  13908. (setq tg (org-add-props tg nil 'face
  13909. (cond
  13910. ((not (assoc tg table))
  13911. (org-get-todo-face tg))
  13912. ((member tg current) c-face)
  13913. ((member tg inherited) i-face))))
  13914. (when (equal (caar tbl) :grouptags)
  13915. (org-add-props tg nil 'face 'org-tag-group))
  13916. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13917. (insert "[" c "] " tg (make-string
  13918. (- fwidth 4 (length tg)) ?\ ))
  13919. (push (cons tg c) ntable)
  13920. (when (= (cl-incf cnt) ncol)
  13921. (insert "\n")
  13922. (when (or ingroup intaggroup) (insert " "))
  13923. (setq cnt 0)))))
  13924. (setq ntable (nreverse ntable))
  13925. (insert "\n")
  13926. (goto-char (point-min))
  13927. (unless expert (org-fit-window-to-buffer))
  13928. (setq rtn
  13929. (catch 'exit
  13930. (while t
  13931. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13932. (if (not groups) "no " "")
  13933. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13934. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13935. (setq org-last-tag-selection-key c)
  13936. (cond
  13937. ((= c ?\r) (throw 'exit t))
  13938. ((= c ?!)
  13939. (setq groups (not groups))
  13940. (goto-char (point-min))
  13941. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13942. ((= c ?\C-c)
  13943. (if (not expert)
  13944. (org-fast-tag-show-exit
  13945. (setq exit-after-next (not exit-after-next)))
  13946. (setq expert nil)
  13947. (delete-other-windows)
  13948. (set-window-buffer (split-window-vertically) " *Org tags*")
  13949. (org-switch-to-buffer-other-window " *Org tags*")
  13950. (org-fit-window-to-buffer)))
  13951. ((or (= c ?\C-g)
  13952. (and (= c ?q) (not (rassoc c ntable))))
  13953. (delete-overlay org-tags-overlay)
  13954. (setq quit-flag t))
  13955. ((= c ?\ )
  13956. (setq current nil)
  13957. (when exit-after-next (setq exit-after-next 'now)))
  13958. ((= c ?\t)
  13959. (condition-case nil
  13960. (setq tg (completing-read
  13961. "Tag: "
  13962. (or buffer-tags
  13963. (with-current-buffer buf
  13964. (setq buffer-tags
  13965. (org-get-buffer-tags))))))
  13966. (quit (setq tg "")))
  13967. (when (string-match "\\S-" tg)
  13968. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13969. (if (member tg current)
  13970. (setq current (delete tg current))
  13971. (push tg current)))
  13972. (when exit-after-next (setq exit-after-next 'now)))
  13973. ((setq e (rassoc c todo-table) tg (car e))
  13974. (with-current-buffer buf
  13975. (save-excursion (org-todo tg)))
  13976. (when exit-after-next (setq exit-after-next 'now)))
  13977. ((setq e (rassoc c ntable) tg (car e))
  13978. (if (member tg current)
  13979. (setq current (delete tg current))
  13980. (cl-loop for g in groups do
  13981. (when (member tg g)
  13982. (dolist (x g) (setq current (delete x current)))))
  13983. (push tg current))
  13984. (when exit-after-next (setq exit-after-next 'now))))
  13985. ;; Create a sorted list
  13986. (setq current
  13987. (sort current
  13988. (lambda (a b)
  13989. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13990. (when (eq exit-after-next 'now) (throw 'exit t))
  13991. (goto-char (point-min))
  13992. (beginning-of-line 2)
  13993. (delete-region (point) (point-at-eol))
  13994. (org-fast-tag-insert "Current" current c-face)
  13995. (org-set-current-tags-overlay current ov-prefix)
  13996. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13997. (setq tg (match-string 1))
  13998. (add-text-properties
  13999. (match-beginning 1) (match-end 1)
  14000. (list 'face
  14001. (cond
  14002. ((member tg current) c-face)
  14003. ((member tg inherited) i-face)
  14004. (t (get-text-property (match-beginning 1) 'face))))))
  14005. (goto-char (point-min)))))
  14006. (delete-overlay org-tags-overlay)
  14007. (if rtn
  14008. (mapconcat 'identity current ":")
  14009. nil))))
  14010. (defun org-get-tags-string ()
  14011. "Get the TAGS string in the current headline."
  14012. (unless (org-at-heading-p t)
  14013. (user-error "Not on a heading"))
  14014. (save-excursion
  14015. (beginning-of-line 1)
  14016. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14017. (match-string-no-properties 1)
  14018. "")))
  14019. (defun org-get-tags ()
  14020. "Get the list of tags specified in the current headline."
  14021. (org-split-string (org-get-tags-string) ":"))
  14022. (defun org-get-buffer-tags ()
  14023. "Get a table of all tags used in the buffer, for completion."
  14024. (org-with-wide-buffer
  14025. (goto-char (point-min))
  14026. (let ((tag-re (concat org-outline-regexp-bol
  14027. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14028. tags)
  14029. (while (re-search-forward tag-re nil t)
  14030. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14031. (push tag tags)))
  14032. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14033. ;;;; The mapping API
  14034. (defvar org-agenda-skip-comment-trees)
  14035. (defvar org-agenda-skip-function)
  14036. (defun org-map-entries (func &optional match scope &rest skip)
  14037. "Call FUNC at each headline selected by MATCH in SCOPE.
  14038. FUNC is a function or a lisp form. The function will be called without
  14039. arguments, with the cursor positioned at the beginning of the headline.
  14040. The return values of all calls to the function will be collected and
  14041. returned as a list.
  14042. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14043. does not need to preserve point. After evaluation, the cursor will be
  14044. moved to the end of the line (presumably of the headline of the
  14045. processed entry) and search continues from there. Under some
  14046. circumstances, this may not produce the wanted results. For example,
  14047. if you have removed (e.g. archived) the current (sub)tree it could
  14048. mean that the next entry will be skipped entirely. In such cases, you
  14049. can specify the position from where search should continue by making
  14050. FUNC set the variable `org-map-continue-from' to the desired buffer
  14051. position.
  14052. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14053. Only headlines that are matched by this query will be considered during
  14054. the iteration. When MATCH is nil or t, all headlines will be
  14055. visited by the iteration.
  14056. SCOPE determines the scope of this command. It can be any of:
  14057. nil The current buffer, respecting the restriction if any
  14058. tree The subtree started with the entry at point
  14059. region The entries within the active region, if any
  14060. region-start-level
  14061. The entries within the active region, but only those at
  14062. the same level than the first one.
  14063. file The current buffer, without restriction
  14064. file-with-archives
  14065. The current buffer, and any archives associated with it
  14066. agenda All agenda files
  14067. agenda-with-archives
  14068. All agenda files with any archive files associated with them
  14069. \(file1 file2 ...)
  14070. If this is a list, all files in the list will be scanned
  14071. The remaining args are treated as settings for the skipping facilities of
  14072. the scanner. The following items can be given here:
  14073. archive skip trees with the archive tag
  14074. comment skip trees with the COMMENT keyword
  14075. function or Emacs Lisp form:
  14076. will be used as value for `org-agenda-skip-function', so
  14077. whenever the function returns a position, FUNC will not be
  14078. called for that entry and search will continue from the
  14079. position returned
  14080. If your function needs to retrieve the tags including inherited tags
  14081. at the *current* entry, you can use the value of the variable
  14082. `org-scanner-tags' which will be much faster than getting the value
  14083. with `org-get-tags-at'. If your function gets properties with
  14084. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14085. to t around the call to `org-entry-properties' to get the same speedup.
  14086. Note that if your function moves around to retrieve tags and properties at
  14087. a *different* entry, you cannot use these techniques."
  14088. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14089. (not (org-region-active-p)))
  14090. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14091. (org-agenda-skip-archived-trees (memq 'archive skip))
  14092. (org-agenda-skip-comment-trees (memq 'comment skip))
  14093. (org-agenda-skip-function
  14094. (car (org-delete-all '(comment archive) skip)))
  14095. (org-tags-match-list-sublevels t)
  14096. (start-level (eq scope 'region-start-level))
  14097. matcher res
  14098. org-todo-keywords-for-agenda
  14099. org-done-keywords-for-agenda
  14100. org-todo-keyword-alist-for-agenda
  14101. org-tag-alist-for-agenda
  14102. org--matcher-tags-todo-only)
  14103. (cond
  14104. ((eq match t) (setq matcher t))
  14105. ((eq match nil) (setq matcher t))
  14106. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14107. (save-excursion
  14108. (save-restriction
  14109. (cond ((eq scope 'tree)
  14110. (org-back-to-heading t)
  14111. (org-narrow-to-subtree)
  14112. (setq scope nil))
  14113. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14114. (org-region-active-p))
  14115. ;; If needed, set start-level to a string like "2"
  14116. (when start-level
  14117. (save-excursion
  14118. (goto-char (region-beginning))
  14119. (unless (org-at-heading-p) (outline-next-heading))
  14120. (setq start-level (org-current-level))))
  14121. (narrow-to-region (region-beginning)
  14122. (save-excursion
  14123. (goto-char (region-end))
  14124. (unless (and (bolp) (org-at-heading-p))
  14125. (outline-next-heading))
  14126. (point)))
  14127. (setq scope nil)))
  14128. (if (not scope)
  14129. (progn
  14130. (org-agenda-prepare-buffers
  14131. (and buffer-file-name (list buffer-file-name)))
  14132. (setq res
  14133. (org-scan-tags
  14134. func matcher org--matcher-tags-todo-only start-level)))
  14135. ;; Get the right scope
  14136. (cond
  14137. ((and scope (listp scope) (symbolp (car scope)))
  14138. (setq scope (eval scope)))
  14139. ((eq scope 'agenda)
  14140. (setq scope (org-agenda-files t)))
  14141. ((eq scope 'agenda-with-archives)
  14142. (setq scope (org-agenda-files t))
  14143. (setq scope (org-add-archive-files scope)))
  14144. ((eq scope 'file)
  14145. (setq scope (and buffer-file-name (list buffer-file-name))))
  14146. ((eq scope 'file-with-archives)
  14147. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14148. (org-agenda-prepare-buffers scope)
  14149. (dolist (file scope)
  14150. (with-current-buffer (org-find-base-buffer-visiting file)
  14151. (org-with-wide-buffer
  14152. (goto-char (point-min))
  14153. (setq res
  14154. (append
  14155. res
  14156. (org-scan-tags
  14157. func matcher org--matcher-tags-todo-only)))))))))
  14158. res)))
  14159. ;;; Properties API
  14160. (defconst org-special-properties
  14161. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14162. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14163. "The special properties valid in Org mode.
  14164. These are properties that are not defined in the property drawer,
  14165. but in some other way.")
  14166. (defconst org-default-properties
  14167. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14168. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14169. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14170. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14171. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14172. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14173. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14174. "Some properties that are used by Org mode for various purposes.
  14175. Being in this list makes sure that they are offered for completion.")
  14176. (defun org--valid-property-p (property)
  14177. "Non nil when string PROPERTY is a valid property name."
  14178. (not
  14179. (or (equal property "")
  14180. (string-match-p "\\s-" property))))
  14181. (defun org--update-property-plist (key val props)
  14182. "Associate KEY to VAL in alist PROPS.
  14183. Modifications are made by side-effect. Return new alist."
  14184. (let* ((appending (string= (substring key -1) "+"))
  14185. (key (if appending (substring key 0 -1) key))
  14186. (old (assoc-string key props t)))
  14187. (if (not old) (cons (cons key val) props)
  14188. (setcdr old (if appending (concat (cdr old) " " val) val))
  14189. props)))
  14190. (defun org-get-property-block (&optional beg force)
  14191. "Return the (beg . end) range of the body of the property drawer.
  14192. BEG is the beginning of the current subtree, or of the part
  14193. before the first headline. If it is not given, it will be found.
  14194. If the drawer does not exist, create it if FORCE is non-nil, or
  14195. return nil."
  14196. (org-with-wide-buffer
  14197. (when beg (goto-char beg))
  14198. (unless (org-before-first-heading-p)
  14199. (let ((beg (cond (beg)
  14200. ((or (not (featurep 'org-inlinetask))
  14201. (org-inlinetask-in-task-p))
  14202. (org-back-to-heading t))
  14203. (t (org-with-limited-levels (org-back-to-heading t))))))
  14204. (forward-line)
  14205. (when (looking-at-p org-planning-line-re) (forward-line))
  14206. (cond ((looking-at org-property-drawer-re)
  14207. (forward-line)
  14208. (cons (point) (progn (goto-char (match-end 0))
  14209. (line-beginning-position))))
  14210. (force
  14211. (goto-char beg)
  14212. (org-insert-property-drawer)
  14213. (let ((pos (save-excursion (search-forward ":END:")
  14214. (line-beginning-position))))
  14215. (cons pos pos))))))))
  14216. (defun org-at-property-p ()
  14217. "Non-nil when point is inside a property drawer.
  14218. See `org-property-re' for match data, if applicable."
  14219. (save-excursion
  14220. (beginning-of-line)
  14221. (and (looking-at org-property-re)
  14222. (let ((property-drawer (save-match-data (org-get-property-block))))
  14223. (and property-drawer
  14224. (>= (point) (car property-drawer))
  14225. (< (point) (cdr property-drawer)))))))
  14226. (defun org-property-action ()
  14227. "Do an action on properties."
  14228. (interactive)
  14229. (unless (org-at-property-p) (user-error "Not at a property"))
  14230. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14231. (let ((c (read-char-exclusive)))
  14232. (cl-case c
  14233. (?s (call-interactively #'org-set-property))
  14234. (?d (call-interactively #'org-delete-property))
  14235. (?D (call-interactively #'org-delete-property-globally))
  14236. (?c (call-interactively #'org-compute-property-at-point))
  14237. (otherwise (user-error "No such property action %c" c)))))
  14238. (defun org-inc-effort ()
  14239. "Increment the value of the effort property in the current entry."
  14240. (interactive)
  14241. (org-set-effort nil t))
  14242. (defvar org-clock-effort) ; Defined in org-clock.el.
  14243. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14244. (defun org-set-effort (&optional value increment)
  14245. "Set the effort property of the current entry.
  14246. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14247. 10th allowed value.
  14248. When INCREMENT is non-nil, set the property to the next allowed value."
  14249. (interactive "P")
  14250. (when (equal value 0) (setq value 10))
  14251. (let* ((completion-ignore-case t)
  14252. (prop org-effort-property)
  14253. (cur (org-entry-get nil prop))
  14254. (allowed (org-property-get-allowed-values nil prop 'table))
  14255. (existing (mapcar 'list (org-property-values prop)))
  14256. (heading (nth 4 (org-heading-components)))
  14257. rpl
  14258. (val (cond
  14259. ((stringp value) value)
  14260. ((and allowed (integerp value))
  14261. (or (car (nth (1- value) allowed))
  14262. (car (org-last allowed))))
  14263. ((and allowed increment)
  14264. (or (cl-caadr (member (list cur) allowed))
  14265. (user-error "Allowed effort values are not set")))
  14266. (allowed
  14267. (message "Select 1-9,0, [RET%s]: %s"
  14268. (if cur (concat "=" cur) "")
  14269. (mapconcat 'car allowed " "))
  14270. (setq rpl (read-char-exclusive))
  14271. (if (equal rpl ?\r)
  14272. cur
  14273. (setq rpl (- rpl ?0))
  14274. (when (equal rpl 0) (setq rpl 10))
  14275. (if (and (> rpl 0) (<= rpl (length allowed)))
  14276. (car (nth (1- rpl) allowed))
  14277. (org-completing-read "Effort: " allowed nil))))
  14278. (t
  14279. (org-completing-read
  14280. (concat "Effort" (and cur (string-match "\\S-" cur)
  14281. (concat " [" cur "]"))
  14282. ": ")
  14283. existing nil nil "" nil cur)))))
  14284. (unless (equal (org-entry-get nil prop) val)
  14285. (org-entry-put nil prop val))
  14286. (org-refresh-property
  14287. '((effort . identity)
  14288. (effort-minutes . org-duration-string-to-minutes))
  14289. val)
  14290. (when (equal heading (bound-and-true-p org-clock-current-task))
  14291. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14292. (org-clock-update-mode-line))
  14293. (message "%s is now %s" prop val)))
  14294. (defun org-entry-properties (&optional pom which)
  14295. "Get all properties of the current entry.
  14296. When POM is a buffer position, get all properties from the entry
  14297. there instead.
  14298. This includes the TODO keyword, the tags, time strings for
  14299. deadline, scheduled, and clocking, and any additional properties
  14300. defined in the entry.
  14301. If WHICH is nil or `all', get all properties. If WHICH is
  14302. `special' or `standard', only get that subclass. If WHICH is
  14303. a string, only get that property.
  14304. Return value is an alist. Keys are properties, as upcased
  14305. strings."
  14306. (org-with-point-at pom
  14307. (when (and (derived-mode-p 'org-mode)
  14308. (ignore-errors (org-back-to-heading t)))
  14309. (catch 'exit
  14310. (let* ((beg (point))
  14311. (specific (and (stringp which) (upcase which)))
  14312. (which (cond ((not specific) which)
  14313. ((member specific org-special-properties) 'special)
  14314. (t 'standard)))
  14315. props)
  14316. ;; Get the special properties, like TODO and TAGS.
  14317. (when (memq which '(nil all special))
  14318. (when (or (not specific) (string= specific "CLOCKSUM"))
  14319. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14320. (when clocksum
  14321. (push (cons "CLOCKSUM"
  14322. (org-minutes-to-clocksum-string clocksum))
  14323. props)))
  14324. (when specific (throw 'exit props)))
  14325. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14326. (let ((clocksumt (get-text-property (point)
  14327. :org-clock-minutes-today)))
  14328. (when clocksumt
  14329. (push (cons "CLOCKSUM_T"
  14330. (org-minutes-to-clocksum-string clocksumt))
  14331. props)))
  14332. (when specific (throw 'exit props)))
  14333. (when (or (not specific) (string= specific "ITEM"))
  14334. (let ((case-fold-search nil))
  14335. (when (looking-at org-complex-heading-regexp)
  14336. (push (cons "ITEM"
  14337. (let ((title (match-string-no-properties 4)))
  14338. (if (org-string-nw-p title)
  14339. (org-remove-tabs title)
  14340. "")))
  14341. props)))
  14342. (when specific (throw 'exit props)))
  14343. (when (or (not specific) (string= specific "TODO"))
  14344. (let ((case-fold-search nil))
  14345. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14346. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14347. (when specific (throw 'exit props)))
  14348. (when (or (not specific) (string= specific "PRIORITY"))
  14349. (push (cons "PRIORITY"
  14350. (if (looking-at org-priority-regexp)
  14351. (match-string-no-properties 2)
  14352. (char-to-string org-default-priority)))
  14353. props)
  14354. (when specific (throw 'exit props)))
  14355. (when (or (not specific) (string= specific "FILE"))
  14356. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14357. props)
  14358. (when specific (throw 'exit props)))
  14359. (when (or (not specific) (string= specific "TAGS"))
  14360. (let ((value (org-string-nw-p (org-get-tags-string))))
  14361. (when value (push (cons "TAGS" value) props)))
  14362. (when specific (throw 'exit props)))
  14363. (when (or (not specific) (string= specific "ALLTAGS"))
  14364. (let ((value (org-get-tags-at)))
  14365. (when value
  14366. (push (cons "ALLTAGS"
  14367. (format ":%s:" (mapconcat #'identity value ":")))
  14368. props)))
  14369. (when specific (throw 'exit props)))
  14370. (when (or (not specific) (string= specific "BLOCKED"))
  14371. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14372. (when specific (throw 'exit props)))
  14373. (when (or (not specific)
  14374. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14375. (forward-line)
  14376. (when (looking-at-p org-planning-line-re)
  14377. (end-of-line)
  14378. (let ((bol (line-beginning-position))
  14379. ;; Backward compatibility: time keywords used to
  14380. ;; be configurable (before 8.3). Make sure we
  14381. ;; get the correct keyword.
  14382. (key-assoc `(("CLOSED" . ,org-closed-string)
  14383. ("DEADLINE" . ,org-deadline-string)
  14384. ("SCHEDULED" . ,org-scheduled-string))))
  14385. (dolist (pair (if specific (list (assoc specific key-assoc))
  14386. key-assoc))
  14387. (save-excursion
  14388. (when (search-backward (cdr pair) bol t)
  14389. (goto-char (match-end 0))
  14390. (skip-chars-forward " \t")
  14391. (and (looking-at org-ts-regexp-both)
  14392. (push (cons (car pair)
  14393. (match-string-no-properties 0))
  14394. props)))))))
  14395. (when specific (throw 'exit props)))
  14396. (when (or (not specific)
  14397. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14398. (let ((find-ts
  14399. (lambda (end ts)
  14400. ;; Fix next time-stamp before END. TS is the
  14401. ;; list of time-stamps found so far.
  14402. (let ((ts ts)
  14403. (regexp (cond
  14404. ((string= specific "TIMESTAMP")
  14405. org-ts-regexp)
  14406. ((string= specific "TIMESTAMP_IA")
  14407. org-ts-regexp-inactive)
  14408. ((assoc "TIMESTAMP_IA" ts)
  14409. org-ts-regexp)
  14410. ((assoc "TIMESTAMP" ts)
  14411. org-ts-regexp-inactive)
  14412. (t org-ts-regexp-both))))
  14413. (catch 'next
  14414. (while (re-search-forward regexp end t)
  14415. (backward-char)
  14416. (let ((object (org-element-context)))
  14417. ;; Accept to match timestamps in node
  14418. ;; properties, too.
  14419. (when (memq (org-element-type object)
  14420. '(node-property timestamp))
  14421. (let ((type
  14422. (org-element-property :type object)))
  14423. (cond
  14424. ((and (memq type '(active active-range))
  14425. (not (equal specific "TIMESTAMP_IA")))
  14426. (unless (assoc "TIMESTAMP" ts)
  14427. (push (cons "TIMESTAMP"
  14428. (org-element-property
  14429. :raw-value object))
  14430. ts)
  14431. (when specific (throw 'exit ts))))
  14432. ((and (memq type '(inactive inactive-range))
  14433. (not (string= specific "TIMESTAMP")))
  14434. (unless (assoc "TIMESTAMP_IA" ts)
  14435. (push (cons "TIMESTAMP_IA"
  14436. (org-element-property
  14437. :raw-value object))
  14438. ts)
  14439. (when specific (throw 'exit ts))))))
  14440. ;; Both timestamp types are found,
  14441. ;; move to next part.
  14442. (when (= (length ts) 2) (throw 'next ts)))))
  14443. ts)))))
  14444. (goto-char beg)
  14445. ;; First look for timestamps within headline.
  14446. (let ((ts (funcall find-ts (line-end-position) nil)))
  14447. (if (= (length ts) 2) (setq props (nconc ts props))
  14448. (forward-line)
  14449. ;; Then find timestamps in the section, skipping
  14450. ;; planning line.
  14451. (when (looking-at-p org-planning-line-re)
  14452. (forward-line))
  14453. (let ((end (save-excursion (outline-next-heading))))
  14454. (setq props (nconc (funcall find-ts end ts) props))))))))
  14455. ;; Get the standard properties, like :PROP:.
  14456. (when (memq which '(nil all standard))
  14457. ;; If we are looking after a specific property, delegate
  14458. ;; to `org-entry-get', which is faster. However, make an
  14459. ;; exception for "CATEGORY", since it can be also set
  14460. ;; through keywords (i.e. #+CATEGORY).
  14461. (if (and specific (not (equal specific "CATEGORY")))
  14462. (let ((value (org-entry-get beg specific nil t)))
  14463. (throw 'exit (and value (list (cons specific value)))))
  14464. (let ((range (org-get-property-block beg)))
  14465. (when range
  14466. (let ((end (cdr range)) seen-base)
  14467. (goto-char (car range))
  14468. ;; Unlike to `org--update-property-plist', we
  14469. ;; handle the case where base values is found
  14470. ;; after its extension. We also forbid standard
  14471. ;; properties to be named as special properties.
  14472. (while (re-search-forward org-property-re end t)
  14473. (let* ((key (upcase (match-string-no-properties 2)))
  14474. (extendp (string-match-p "\\+\\'" key))
  14475. (key-base (if extendp (substring key 0 -1) key))
  14476. (value (match-string-no-properties 3)))
  14477. (cond
  14478. ((member-ignore-case key-base org-special-properties))
  14479. (extendp
  14480. (setq props
  14481. (org--update-property-plist key value props)))
  14482. ((member key seen-base))
  14483. (t (push key seen-base)
  14484. (let ((p (assoc-string key props t)))
  14485. (if p (setcdr p (concat value " " (cdr p)))
  14486. (push (cons key value) props))))))))))))
  14487. (unless (assoc "CATEGORY" props)
  14488. (push (cons "CATEGORY" (org-get-category beg)) props)
  14489. (when (string= specific "CATEGORY") (throw 'exit props)))
  14490. ;; Return value.
  14491. props)))))
  14492. (defun org-property--local-values (property literal-nil)
  14493. "Return value for PROPERTY in current entry.
  14494. Value is a list whose car is the base value for PROPERTY and cdr
  14495. a list of accumulated values. Return nil if neither is found in
  14496. the entry. Also return nil when PROPERTY is set to \"nil\",
  14497. unless LITERAL-NIL is non-nil."
  14498. (let ((range (org-get-property-block)))
  14499. (when range
  14500. (goto-char (car range))
  14501. (let* ((case-fold-search t)
  14502. (end (cdr range))
  14503. (value
  14504. ;; Base value.
  14505. (save-excursion
  14506. (let ((v (and (re-search-forward
  14507. (org-re-property property nil t) end t)
  14508. (match-string-no-properties 3))))
  14509. (list (if literal-nil v (org-not-nil v)))))))
  14510. ;; Find additional values.
  14511. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14512. (while (re-search-forward property+ end t)
  14513. (push (match-string-no-properties 3) value)))
  14514. ;; Return final values.
  14515. (and (not (equal value '(nil))) (nreverse value))))))
  14516. (defun org-entry-get (pom property &optional inherit literal-nil)
  14517. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14518. If INHERIT is non-nil and the entry does not have the property,
  14519. then also check higher levels of the hierarchy. If INHERIT is
  14520. the symbol `selective', use inheritance only if the setting in
  14521. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14522. If the property is present but empty, the return value is the
  14523. empty string. If the property is not present at all, nil is
  14524. returned. In any other case, return the value as a string.
  14525. Search is case-insensitive.
  14526. If LITERAL-NIL is set, return the string value \"nil\" as
  14527. a string, do not interpret it as the list atom nil. This is used
  14528. for inheritance when a \"nil\" value can supersede a non-nil
  14529. value higher up the hierarchy."
  14530. (org-with-point-at pom
  14531. (cond
  14532. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14533. ;; We need a special property. Use `org-entry-properties' to
  14534. ;; retrieve it, but specify the wanted property.
  14535. (cdr (assoc-string property (org-entry-properties nil property))))
  14536. ((and inherit
  14537. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14538. (org-entry-get-with-inheritance property literal-nil))
  14539. (t
  14540. (let* ((local (org-property--local-values property literal-nil))
  14541. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14542. (if literal-nil value (org-not-nil value)))))))
  14543. (defun org-property-or-variable-value (var &optional inherit)
  14544. "Check if there is a property fixing the value of VAR.
  14545. If yes, return this value. If not, return the current value of the variable."
  14546. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14547. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14548. (read prop)
  14549. (symbol-value var))))
  14550. (defun org-entry-delete (pom property)
  14551. "Delete PROPERTY from entry at point-or-marker POM.
  14552. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14553. non-nil when a property was removed."
  14554. (unless (member property org-special-properties)
  14555. (org-with-point-at pom
  14556. (let ((range (org-get-property-block)))
  14557. (when range
  14558. (let* ((begin (car range))
  14559. (origin (cdr range))
  14560. (end (copy-marker origin))
  14561. (re (org-re-property
  14562. (concat (regexp-quote property) "\\+?") t t)))
  14563. (goto-char begin)
  14564. (while (re-search-forward re end t)
  14565. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14566. ;; If drawer is empty, remove it altogether.
  14567. (when (= begin end)
  14568. (delete-region (line-beginning-position 0)
  14569. (line-beginning-position 2)))
  14570. ;; Return non-nil if some property was removed.
  14571. (prog1 (/= end origin) (set-marker end nil))))))))
  14572. ;; Multi-values properties are properties that contain multiple values
  14573. ;; These values are assumed to be single words, separated by whitespace.
  14574. (defun org-entry-add-to-multivalued-property (pom property value)
  14575. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14576. (let* ((old (org-entry-get pom property))
  14577. (values (and old (org-split-string old "[ \t]"))))
  14578. (setq value (org-entry-protect-space value))
  14579. (unless (member value values)
  14580. (setq values (append values (list value)))
  14581. (org-entry-put pom property
  14582. (mapconcat 'identity values " ")))))
  14583. (defun org-entry-remove-from-multivalued-property (pom property value)
  14584. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14585. (let* ((old (org-entry-get pom property))
  14586. (values (and old (org-split-string old "[ \t]"))))
  14587. (setq value (org-entry-protect-space value))
  14588. (when (member value values)
  14589. (setq values (delete value values))
  14590. (org-entry-put pom property
  14591. (mapconcat 'identity values " ")))))
  14592. (defun org-entry-member-in-multivalued-property (pom property value)
  14593. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14594. (let* ((old (org-entry-get pom property))
  14595. (values (and old (org-split-string old "[ \t]"))))
  14596. (setq value (org-entry-protect-space value))
  14597. (member value values)))
  14598. (defun org-entry-get-multivalued-property (pom property)
  14599. "Return a list of values in a multivalued property."
  14600. (let* ((value (org-entry-get pom property))
  14601. (values (and value (org-split-string value "[ \t]"))))
  14602. (mapcar 'org-entry-restore-space values)))
  14603. (defun org-entry-put-multivalued-property (pom property &rest values)
  14604. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14605. VALUES should be a list of strings. Spaces will be protected."
  14606. (org-entry-put pom property
  14607. (mapconcat 'org-entry-protect-space values " "))
  14608. (let* ((value (org-entry-get pom property))
  14609. (values (and value (org-split-string value "[ \t]"))))
  14610. (mapcar 'org-entry-restore-space values)))
  14611. (defun org-entry-protect-space (s)
  14612. "Protect spaces and newline in string S."
  14613. (while (string-match " " s)
  14614. (setq s (replace-match "%20" t t s)))
  14615. (while (string-match "\n" s)
  14616. (setq s (replace-match "%0A" t t s)))
  14617. s)
  14618. (defun org-entry-restore-space (s)
  14619. "Restore spaces and newline in string S."
  14620. (while (string-match "%20" s)
  14621. (setq s (replace-match " " t t s)))
  14622. (while (string-match "%0A" s)
  14623. (setq s (replace-match "\n" t t s)))
  14624. s)
  14625. (defvar org-entry-property-inherited-from (make-marker)
  14626. "Marker pointing to the entry from where a property was inherited.
  14627. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14628. location of the entry where the inheritance search matched. If there was
  14629. no match, the marker will point nowhere.
  14630. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14631. is set.")
  14632. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14633. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14634. The search will stop at the first ancestor which has the property defined.
  14635. If the value found is \"nil\", return nil to show that the property
  14636. should be considered as undefined (this is the meaning of nil here).
  14637. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14638. (move-marker org-entry-property-inherited-from nil)
  14639. (org-with-wide-buffer
  14640. (let (value)
  14641. (catch 'exit
  14642. (while t
  14643. (let ((v (org-property--local-values property literal-nil)))
  14644. (when v
  14645. (setq value
  14646. (concat (mapconcat #'identity (delq nil v) " ")
  14647. (and value " ")
  14648. value)))
  14649. (cond
  14650. ((car v)
  14651. (org-back-to-heading t)
  14652. (move-marker org-entry-property-inherited-from (point))
  14653. (throw 'exit nil))
  14654. ((org-up-heading-safe))
  14655. (t
  14656. (let ((global
  14657. (cdr (or (assoc-string property org-file-properties t)
  14658. (assoc-string property org-global-properties t)
  14659. (assoc-string property org-global-properties-fixed t)))))
  14660. (cond ((not global))
  14661. (value (setq value (concat global " " value)))
  14662. (t (setq value global))))
  14663. (throw 'exit nil))))))
  14664. (if literal-nil value (org-not-nil value)))))
  14665. (defvar org-property-changed-functions nil
  14666. "Hook called when the value of a property has changed.
  14667. Each hook function should accept two arguments, the name of the property
  14668. and the new value.")
  14669. (defun org-entry-put (pom property value)
  14670. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14671. If the value is nil, it is converted to the empty string. If it
  14672. is not a string, an error is raised. Also raise an error on
  14673. invalid property names.
  14674. PROPERTY can be any regular property (see
  14675. `org-special-properties'). It can also be \"TODO\",
  14676. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14677. For the last two properties, VALUE may have any of the special
  14678. values \"earlier\" and \"later\". The function then increases or
  14679. decreases scheduled or deadline date by one day."
  14680. (cond ((null value) (setq value ""))
  14681. ((not (stringp value)) (error "Properties values should be strings"))
  14682. ((not (org--valid-property-p property))
  14683. (user-error "Invalid property name: \"%s\"" property)))
  14684. (org-with-point-at pom
  14685. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14686. (org-back-to-heading t)
  14687. (org-with-limited-levels (org-back-to-heading t)))
  14688. (let ((beg (point)))
  14689. (cond
  14690. ((equal property "TODO")
  14691. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14692. ((not (member value org-todo-keywords-1))
  14693. (user-error "\"%s\" is not a valid TODO state" value)))
  14694. (org-todo value)
  14695. (org-set-tags nil 'align))
  14696. ((equal property "PRIORITY")
  14697. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14698. (org-set-tags nil 'align))
  14699. ((equal property "SCHEDULED")
  14700. (forward-line)
  14701. (if (and (looking-at-p org-planning-line-re)
  14702. (re-search-forward
  14703. org-scheduled-time-regexp (line-end-position) t))
  14704. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14705. ((string= value "later") (org-timestamp-change 1 'day))
  14706. ((string= value "") (org-schedule '(4)))
  14707. (t (org-schedule nil value)))
  14708. (if (member value '("earlier" "later" ""))
  14709. (call-interactively #'org-schedule)
  14710. (org-schedule nil value))))
  14711. ((equal property "DEADLINE")
  14712. (forward-line)
  14713. (if (and (looking-at-p org-planning-line-re)
  14714. (re-search-forward
  14715. org-deadline-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-deadline '(4)))
  14719. (t (org-deadline nil value)))
  14720. (if (member value '("earlier" "later" ""))
  14721. (call-interactively #'org-deadline)
  14722. (org-deadline nil value))))
  14723. ((member property org-special-properties)
  14724. (error "The %s property cannot be set with `org-entry-put'" property))
  14725. (t
  14726. (let* ((range (org-get-property-block beg 'force))
  14727. (end (cdr range))
  14728. (case-fold-search t))
  14729. (goto-char (car range))
  14730. (if (re-search-forward (org-re-property property nil t) end t)
  14731. (progn (delete-region (match-beginning 0) (match-end 0))
  14732. (goto-char (match-beginning 0)))
  14733. (goto-char end)
  14734. (insert "\n")
  14735. (backward-char))
  14736. (insert ":" property ":")
  14737. (when value (insert " " value))
  14738. (org-indent-line)))))
  14739. (run-hook-with-args 'org-property-changed-functions property value)))
  14740. (defun org-buffer-property-keys
  14741. (&optional specials defaults columns ignore-malformed)
  14742. "Get all property keys in the current buffer.
  14743. When SPECIALS is non-nil, also list the special properties that
  14744. reflect things like tags and TODO state.
  14745. When DEFAULTS is non-nil, also include properties that has
  14746. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14747. DESCRIPTION, LOCATION, and LOGGING and others.
  14748. When COLUMNS in non-nil, also include property names given in
  14749. COLUMN formats in the current buffer.
  14750. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14751. automatically performed, such drawers will be silently ignored."
  14752. (let ((case-fold-search t)
  14753. (props (append
  14754. (and specials org-special-properties)
  14755. (and defaults (cons org-effort-property org-default-properties))
  14756. nil)))
  14757. (org-with-wide-buffer
  14758. (goto-char (point-min))
  14759. (while (re-search-forward org-property-start-re nil t)
  14760. (let ((range (org-get-property-block)))
  14761. (catch 'skip
  14762. (unless range
  14763. (when (and (not ignore-malformed)
  14764. (not (org-before-first-heading-p))
  14765. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14766. (line-beginning-position))))
  14767. (org-get-property-block nil t))
  14768. (throw 'skip nil))
  14769. (goto-char (car range))
  14770. (let ((begin (car range))
  14771. (end (cdr range)))
  14772. ;; Make sure that found property block is not located
  14773. ;; before current point, as it would generate an infloop.
  14774. ;; It can happen, for example, in the following
  14775. ;; situation:
  14776. ;;
  14777. ;; * Headline
  14778. ;; :PROPERTIES:
  14779. ;; ...
  14780. ;; :END:
  14781. ;; *************** Inlinetask
  14782. ;; #+BEGIN_EXAMPLE
  14783. ;; :PROPERTIES:
  14784. ;; #+END_EXAMPLE
  14785. ;;
  14786. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14787. (while (< (point) end)
  14788. (let ((p (progn (looking-at org-property-re)
  14789. (match-string-no-properties 2))))
  14790. ;; Only add true property name, not extension symbol.
  14791. (push (if (not (string-match-p "\\+\\'" p)) p
  14792. (substring p 0 -1))
  14793. props))
  14794. (forward-line))))
  14795. (outline-next-heading)))
  14796. (when columns
  14797. (goto-char (point-min))
  14798. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14799. (let ((element (org-element-at-point)))
  14800. (when (memq (org-element-type element) '(keyword node-property))
  14801. (let ((value (org-element-property :value element))
  14802. (start 0))
  14803. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14804. (setq start (match-end 0))
  14805. (let ((p (match-string-no-properties 1 value)))
  14806. (unless (member-ignore-case p org-special-properties)
  14807. (push p props))))))))))
  14808. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14809. (defun org-property-values (key)
  14810. "List all non-nil values of property KEY in current buffer."
  14811. (org-with-wide-buffer
  14812. (goto-char (point-min))
  14813. (let ((case-fold-search t)
  14814. (re (org-re-property key))
  14815. values)
  14816. (while (re-search-forward re nil t)
  14817. (push (org-entry-get (point) key) values))
  14818. (delete-dups values))))
  14819. (defun org-insert-property-drawer ()
  14820. "Insert a property drawer into the current entry."
  14821. (org-with-wide-buffer
  14822. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14823. (org-back-to-heading t)
  14824. (org-with-limited-levels (org-back-to-heading t)))
  14825. (forward-line)
  14826. (when (looking-at-p org-planning-line-re) (forward-line))
  14827. (unless (looking-at-p org-property-drawer-re)
  14828. ;; Make sure we start editing a line from current entry, not from
  14829. ;; next one. It prevents extending text properties or overlays
  14830. ;; belonging to the latter.
  14831. (when (bolp) (backward-char))
  14832. (let ((begin (1+ (point)))
  14833. (inhibit-read-only t))
  14834. (insert "\n:PROPERTIES:\n:END:")
  14835. (when (eobp) (insert "\n"))
  14836. (org-indent-region begin (point))))))
  14837. (defun org-insert-drawer (&optional arg drawer)
  14838. "Insert a drawer at point.
  14839. When optional argument ARG is non-nil, insert a property drawer.
  14840. Optional argument DRAWER, when non-nil, is a string representing
  14841. drawer's name. Otherwise, the user is prompted for a name.
  14842. If a region is active, insert the drawer around that region
  14843. instead.
  14844. Point is left between drawer's boundaries."
  14845. (interactive "P")
  14846. (let* ((drawer (if arg "PROPERTIES"
  14847. (or drawer (read-from-minibuffer "Drawer: ")))))
  14848. (cond
  14849. ;; With C-u, fall back on `org-insert-property-drawer'
  14850. (arg (org-insert-property-drawer))
  14851. ;; Check validity of suggested drawer's name.
  14852. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14853. (user-error "Invalid drawer name"))
  14854. ;; With an active region, insert a drawer at point.
  14855. ((not (org-region-active-p))
  14856. (progn
  14857. (unless (bolp) (insert "\n"))
  14858. (insert (format ":%s:\n\n:END:\n" drawer))
  14859. (forward-line -2)))
  14860. ;; Otherwise, insert the drawer at point
  14861. (t
  14862. (let ((rbeg (region-beginning))
  14863. (rend (copy-marker (region-end))))
  14864. (unwind-protect
  14865. (progn
  14866. (goto-char rbeg)
  14867. (beginning-of-line)
  14868. (when (save-excursion
  14869. (re-search-forward org-outline-regexp-bol rend t))
  14870. (user-error "Drawers cannot contain headlines"))
  14871. ;; Position point at the beginning of the first
  14872. ;; non-blank line in region. Insert drawer's opening
  14873. ;; there, then indent it.
  14874. (org-skip-whitespace)
  14875. (beginning-of-line)
  14876. (insert ":" drawer ":\n")
  14877. (forward-line -1)
  14878. (indent-for-tab-command)
  14879. ;; Move point to the beginning of the first blank line
  14880. ;; after the last non-blank line in region. Insert
  14881. ;; drawer's closing, then indent it.
  14882. (goto-char rend)
  14883. (skip-chars-backward " \r\t\n")
  14884. (insert "\n:END:")
  14885. (deactivate-mark t)
  14886. (indent-for-tab-command)
  14887. (unless (eolp) (insert "\n")))
  14888. ;; Clear marker, whatever the outcome of insertion is.
  14889. (set-marker rend nil)))))))
  14890. (defvar org-property-set-functions-alist nil
  14891. "Property set function alist.
  14892. Each entry should have the following format:
  14893. (PROPERTY . READ-FUNCTION)
  14894. The read function will be called with the same argument as
  14895. `org-completing-read'.")
  14896. (defun org-set-property-function (property)
  14897. "Get the function that should be used to set PROPERTY.
  14898. This is computed according to `org-property-set-functions-alist'."
  14899. (or (cdr (assoc property org-property-set-functions-alist))
  14900. 'org-completing-read))
  14901. (defun org-read-property-value (property)
  14902. "Read PROPERTY value from user."
  14903. (let* ((completion-ignore-case t)
  14904. (allowed (org-property-get-allowed-values nil property 'table))
  14905. (cur (org-entry-get nil property))
  14906. (prompt (concat property " value"
  14907. (if (and cur (string-match "\\S-" cur))
  14908. (concat " [" cur "]") "") ": "))
  14909. (set-function (org-set-property-function property))
  14910. (val (if allowed
  14911. (funcall set-function prompt allowed nil
  14912. (not (get-text-property 0 'org-unrestricted
  14913. (caar allowed))))
  14914. (funcall set-function prompt
  14915. (mapcar 'list (org-property-values property))
  14916. nil nil "" nil cur))))
  14917. (org-trim val)))
  14918. (defvar org-last-set-property nil)
  14919. (defvar org-last-set-property-value nil)
  14920. (defun org-read-property-name ()
  14921. "Read a property name."
  14922. (let ((completion-ignore-case t)
  14923. (default-prop (or (and (org-at-property-p)
  14924. (match-string-no-properties 2))
  14925. org-last-set-property)))
  14926. (org-completing-read
  14927. (concat "Property"
  14928. (if default-prop (concat " [" default-prop "]") "")
  14929. ": ")
  14930. (mapcar #'list (org-buffer-property-keys nil t t))
  14931. nil nil nil nil default-prop)))
  14932. (defun org-set-property-and-value (use-last)
  14933. "Allow to set [PROPERTY]: [value] direction from prompt.
  14934. When use-default, don't even ask, just use the last
  14935. \"[PROPERTY]: [value]\" string from the history."
  14936. (interactive "P")
  14937. (let* ((completion-ignore-case t)
  14938. (pv (or (and use-last org-last-set-property-value)
  14939. (org-completing-read
  14940. "Enter a \"[Property]: [value]\" pair: "
  14941. nil nil nil nil nil
  14942. org-last-set-property-value)))
  14943. prop val)
  14944. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14945. (setq prop (match-string 1 pv)
  14946. val (match-string 2 pv))
  14947. (org-set-property prop val))))
  14948. (defun org-set-property (property value)
  14949. "In the current entry, set PROPERTY to VALUE.
  14950. When called interactively, this will prompt for a property name, offering
  14951. completion on existing and default properties. And then it will prompt
  14952. for a value, offering completion either on allowed values (via an inherited
  14953. xxx_ALL property) or on existing values in other instances of this property
  14954. in the current file.
  14955. Throw an error when trying to set a property with an invalid name."
  14956. (interactive (list nil nil))
  14957. (let ((property (or property (org-read-property-name))))
  14958. ;; `org-entry-put' also makes the following check, but this one
  14959. ;; avoids polluting `org-last-set-property' and
  14960. ;; `org-last-set-property-value' needlessly.
  14961. (unless (org--valid-property-p property)
  14962. (user-error "Invalid property name: \"%s\"" property))
  14963. (let ((value (or value (org-read-property-value property)))
  14964. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14965. (setq org-last-set-property property)
  14966. (setq org-last-set-property-value (concat property ": " value))
  14967. ;; Possibly postprocess the inserted value:
  14968. (when fn (setq value (funcall fn value)))
  14969. (unless (equal (org-entry-get nil property) value)
  14970. (org-entry-put nil property value)))))
  14971. (defun org-find-property (property &optional value)
  14972. "Find first entry in buffer that sets PROPERTY.
  14973. When optional argument VALUE is non-nil, only consider an entry
  14974. if it contains PROPERTY set to this value. If PROPERTY should be
  14975. explicitly set to nil, use string \"nil\" for VALUE.
  14976. Return position where the entry begins, or nil if there is no
  14977. such entry. If narrowing is in effect, only search the visible
  14978. part of the buffer."
  14979. (save-excursion
  14980. (goto-char (point-min))
  14981. (let ((case-fold-search t)
  14982. (re (org-re-property property nil (not value) value)))
  14983. (catch 'exit
  14984. (while (re-search-forward re nil t)
  14985. (when (if value (org-at-property-p)
  14986. (org-entry-get (point) property nil t))
  14987. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14988. (defun org-delete-property (property)
  14989. "In the current entry, delete PROPERTY."
  14990. (interactive
  14991. (let* ((completion-ignore-case t)
  14992. (cat (org-entry-get (point) "CATEGORY"))
  14993. (props0 (org-entry-properties nil 'standard))
  14994. (props (if cat props0
  14995. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14996. (prop (if (< 1 (length props))
  14997. (completing-read "Property: " props nil t)
  14998. (caar props))))
  14999. (list prop)))
  15000. (if (not property)
  15001. (message "No property to delete in this entry")
  15002. (org-entry-delete nil property)
  15003. (message "Property \"%s\" deleted" property)))
  15004. (defun org-delete-property-globally (property)
  15005. "Remove PROPERTY globally, from all entries.
  15006. This function ignores narrowing, if any."
  15007. (interactive
  15008. (let* ((completion-ignore-case t)
  15009. (prop (completing-read
  15010. "Globally remove property: "
  15011. (mapcar #'list (org-buffer-property-keys)))))
  15012. (list prop)))
  15013. (org-with-wide-buffer
  15014. (goto-char (point-min))
  15015. (let ((count 0)
  15016. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15017. (while (re-search-forward re nil t)
  15018. (when (org-entry-delete (point) property) (cl-incf count)))
  15019. (message "Property \"%s\" removed from %d entries" property count))))
  15020. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15021. (defun org-compute-property-at-point ()
  15022. "Compute the property at point.
  15023. This looks for an enclosing column format, extracts the operator and
  15024. then applies it to the property in the column format's scope."
  15025. (interactive)
  15026. (unless (org-at-property-p)
  15027. (user-error "Not at a property"))
  15028. (let ((prop (match-string-no-properties 2)))
  15029. (org-columns-get-format-and-top-level)
  15030. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15031. (user-error "No operator defined for property %s" prop))
  15032. (org-columns-compute prop)))
  15033. (defvar org-property-allowed-value-functions nil
  15034. "Hook for functions supplying allowed values for a specific property.
  15035. The functions must take a single argument, the name of the property, and
  15036. return a flat list of allowed values. If \":ETC\" is one of
  15037. the values, this means that these values are intended as defaults for
  15038. completion, but that other values should be allowed too.
  15039. The functions must return nil if they are not responsible for this
  15040. property.")
  15041. (defun org-property-get-allowed-values (pom property &optional table)
  15042. "Get allowed values for the property PROPERTY.
  15043. When TABLE is non-nil, return an alist that can directly be used for
  15044. completion."
  15045. (let (vals)
  15046. (cond
  15047. ((equal property "TODO")
  15048. (setq vals (org-with-point-at pom
  15049. (append org-todo-keywords-1 '("")))))
  15050. ((equal property "PRIORITY")
  15051. (let ((n org-lowest-priority))
  15052. (while (>= n org-highest-priority)
  15053. (push (char-to-string n) vals)
  15054. (setq n (1- n)))))
  15055. ((equal property "CATEGORY"))
  15056. ((member property org-special-properties))
  15057. ((setq vals (run-hook-with-args-until-success
  15058. 'org-property-allowed-value-functions property)))
  15059. (t
  15060. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15061. (when (and vals (string-match "\\S-" vals))
  15062. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15063. (setq vals (mapcar (lambda (x)
  15064. (cond ((stringp x) x)
  15065. ((numberp x) (number-to-string x))
  15066. ((symbolp x) (symbol-name x))
  15067. (t "???")))
  15068. vals)))))
  15069. (when (member ":ETC" vals)
  15070. (setq vals (remove ":ETC" vals))
  15071. (org-add-props (car vals) '(org-unrestricted t)))
  15072. (if table (mapcar 'list vals) vals)))
  15073. (defun org-property-previous-allowed-value (&optional _previous)
  15074. "Switch to the next allowed value for this property."
  15075. (interactive)
  15076. (org-property-next-allowed-value t))
  15077. (defun org-property-next-allowed-value (&optional previous)
  15078. "Switch to the next allowed value for this property."
  15079. (interactive)
  15080. (unless (org-at-property-p)
  15081. (user-error "Not at a property"))
  15082. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15083. (key (match-string 2))
  15084. (value (match-string 3))
  15085. (allowed (or (org-property-get-allowed-values (point) key)
  15086. (and (member value '("[ ]" "[-]" "[X]"))
  15087. '("[ ]" "[X]"))))
  15088. (heading (save-match-data (nth 4 (org-heading-components))))
  15089. nval)
  15090. (unless allowed
  15091. (user-error "Allowed values for this property have not been defined"))
  15092. (when previous (setq allowed (reverse allowed)))
  15093. (when (member value allowed)
  15094. (setq nval (car (cdr (member value allowed)))))
  15095. (setq nval (or nval (car allowed)))
  15096. (when (equal nval value)
  15097. (user-error "Only one allowed value for this property"))
  15098. (org-at-property-p)
  15099. (replace-match (concat " :" key ": " nval) t t)
  15100. (org-indent-line)
  15101. (beginning-of-line 1)
  15102. (skip-chars-forward " \t")
  15103. (when (equal prop org-effort-property)
  15104. (org-refresh-property
  15105. '((effort . identity)
  15106. (effort-minutes . org-duration-string-to-minutes))
  15107. nval)
  15108. (when (string= org-clock-current-task heading)
  15109. (setq org-clock-effort nval)
  15110. (org-clock-update-mode-line)))
  15111. (run-hook-with-args 'org-property-changed-functions key nval)))
  15112. (defun org-find-olp (path &optional this-buffer)
  15113. "Return a marker pointing to the entry at outline path OLP.
  15114. If anything goes wrong, throw an error.
  15115. You can wrap this call to catch the error like this:
  15116. (condition-case msg
  15117. (org-mobile-locate-entry (match-string 4))
  15118. (error (nth 1 msg)))
  15119. The return value will then be either a string with the error message,
  15120. or a marker if everything is OK.
  15121. If THIS-BUFFER is set, the outline path does not contain a file,
  15122. only headings."
  15123. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15124. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15125. (level 1)
  15126. (lmin 1)
  15127. (lmax 1)
  15128. end found flevel)
  15129. (unless buffer (error "File not found :%s" file))
  15130. (with-current-buffer buffer
  15131. (org-with-wide-buffer
  15132. (goto-char (point-min))
  15133. (dolist (heading path)
  15134. (let ((re (format org-complex-heading-regexp-format
  15135. (regexp-quote heading)))
  15136. (cnt 0))
  15137. (while (re-search-forward re end t)
  15138. (setq level (- (match-end 1) (match-beginning 1)))
  15139. (when (and (>= level lmin) (<= level lmax))
  15140. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15141. (when (= cnt 0)
  15142. (error "Heading not found on level %d: %s" lmax heading))
  15143. (when (> cnt 1)
  15144. (error "Heading not unique on level %d: %s" lmax heading))
  15145. (goto-char found)
  15146. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15147. (setq end (save-excursion (org-end-of-subtree t t)))))
  15148. (when (org-at-heading-p)
  15149. (point-marker))))))
  15150. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15151. "Find node HEADING in BUFFER.
  15152. Return a marker to the heading if it was found, or nil if not.
  15153. If POS-ONLY is set, return just the position instead of a marker.
  15154. The heading text must match exact, but it may have a TODO keyword,
  15155. a priority cookie and tags in the standard locations."
  15156. (with-current-buffer (or buffer (current-buffer))
  15157. (org-with-wide-buffer
  15158. (goto-char (point-min))
  15159. (let (case-fold-search)
  15160. (when (re-search-forward
  15161. (format org-complex-heading-regexp-format
  15162. (regexp-quote heading)) nil t)
  15163. (if pos-only
  15164. (match-beginning 0)
  15165. (move-marker (make-marker) (match-beginning 0))))))))
  15166. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15167. "Find Org node headline HEADING in all .org files in directory DIR.
  15168. When the target headline is found, return a marker to this location."
  15169. (let ((files (directory-files (or dir default-directory)
  15170. t "\\`[^.#].*\\.org\\'"))
  15171. visiting m buffer)
  15172. (catch 'found
  15173. (dolist (file files)
  15174. (message "trying %s" file)
  15175. (setq visiting (org-find-base-buffer-visiting file))
  15176. (setq buffer (or visiting (find-file-noselect file)))
  15177. (setq m (org-find-exact-headline-in-buffer
  15178. heading buffer))
  15179. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15180. (and m (throw 'found m))))))
  15181. (defun org-find-entry-with-id (ident)
  15182. "Locate the entry that contains the ID property with exact value IDENT.
  15183. IDENT can be a string, a symbol or a number, this function will search for
  15184. the string representation of it.
  15185. Return the position where this entry starts, or nil if there is no such entry."
  15186. (interactive "sID: ")
  15187. (let ((id (cond
  15188. ((stringp ident) ident)
  15189. ((symbolp ident) (symbol-name ident))
  15190. ((numberp ident) (number-to-string ident))
  15191. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15192. (org-with-wide-buffer (org-find-property "ID" id))))
  15193. ;;;; Timestamps
  15194. (defvar org-last-changed-timestamp nil)
  15195. (defvar org-last-inserted-timestamp nil
  15196. "The last time stamp inserted with `org-insert-time-stamp'.")
  15197. (defvar org-ts-what) ; dynamically scoped parameter
  15198. (defun org-time-stamp (arg &optional inactive)
  15199. "Prompt for a date/time and insert a time stamp.
  15200. If the user specifies a time like HH:MM or if this command is
  15201. called with at least one prefix argument, the time stamp contains
  15202. the date and the time. Otherwise, only the date is included.
  15203. All parts of a date not specified by the user are filled in from
  15204. the timestamp at point, if any, or the current date/time
  15205. otherwise.
  15206. If there is already a timestamp at the cursor, it is replaced.
  15207. With two universal prefix arguments, insert an active timestamp
  15208. with the current time without prompting the user.
  15209. When called from lisp, the timestamp is inactive if INACTIVE is
  15210. non-nil."
  15211. (interactive "P")
  15212. (let* ((ts (cond
  15213. ((org-at-date-range-p t)
  15214. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15215. ((org-at-timestamp-p t) (match-string 0))))
  15216. ;; Default time is either the timestamp at point or today.
  15217. ;; When entering a range, only the range start is considered.
  15218. (default-time (if (not ts) (current-time)
  15219. (apply #'encode-time (org-parse-time-string ts))))
  15220. (default-input (and ts (org-get-compact-tod ts)))
  15221. (repeater (and ts
  15222. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15223. (match-string 0 ts)))
  15224. org-time-was-given
  15225. org-end-time-was-given
  15226. (time
  15227. (and (if (equal arg '(16)) (current-time)
  15228. ;; Preserve `this-command' and `last-command'.
  15229. (let ((this-command this-command)
  15230. (last-command last-command))
  15231. (org-read-date
  15232. arg 'totime nil nil default-time default-input
  15233. inactive))))))
  15234. (cond
  15235. ((and ts
  15236. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15237. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15238. (insert "--")
  15239. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15240. (ts
  15241. ;; Make sure we're on a timestamp. When in the middle of a date
  15242. ;; range, move arbitrarily to range end.
  15243. (unless (org-at-timestamp-p t)
  15244. (skip-chars-forward "-")
  15245. (org-at-timestamp-p t))
  15246. (replace-match "")
  15247. (setq org-last-changed-timestamp
  15248. (org-insert-time-stamp
  15249. time (or org-time-was-given arg)
  15250. inactive nil nil (list org-end-time-was-given)))
  15251. (when repeater
  15252. (backward-char)
  15253. (insert " " repeater)
  15254. (setq org-last-changed-timestamp
  15255. (concat (substring org-last-inserted-timestamp 0 -1)
  15256. " " repeater ">")))
  15257. (message "Timestamp updated"))
  15258. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15259. (t (org-insert-time-stamp
  15260. time (or org-time-was-given arg) inactive nil nil
  15261. (list org-end-time-was-given))))))
  15262. ;; FIXME: can we use this for something else, like computing time differences?
  15263. (defun org-get-compact-tod (s)
  15264. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15265. (let* ((t1 (match-string 1 s))
  15266. (h1 (string-to-number (match-string 2 s)))
  15267. (m1 (string-to-number (match-string 3 s)))
  15268. (t2 (and (match-end 4) (match-string 5 s)))
  15269. (h2 (and t2 (string-to-number (match-string 6 s))))
  15270. (m2 (and t2 (string-to-number (match-string 7 s))))
  15271. dh dm)
  15272. (if (not t2)
  15273. t1
  15274. (setq dh (- h2 h1) dm (- m2 m1))
  15275. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15276. (concat t1 "+" (number-to-string dh)
  15277. (and (/= 0 dm) (format ":%02d" dm)))))))
  15278. (defun org-time-stamp-inactive (&optional arg)
  15279. "Insert an inactive time stamp.
  15280. An inactive time stamp is enclosed in square brackets instead of angle
  15281. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15282. does not link to the calendar and cannot be changed with the S-cursor keys.
  15283. So these are more for recording a certain time/date."
  15284. (interactive "P")
  15285. (org-time-stamp arg 'inactive))
  15286. (defvar org-date-ovl (make-overlay 1 1))
  15287. (overlay-put org-date-ovl 'face 'org-date-selected)
  15288. (delete-overlay org-date-ovl)
  15289. (defvar org-ans1) ; dynamically scoped parameter
  15290. (defvar org-ans2) ; dynamically scoped parameter
  15291. (defvar org-plain-time-of-day-regexp) ; defined below
  15292. (defvar org-overriding-default-time nil) ; dynamically scoped
  15293. (defvar org-read-date-overlay nil)
  15294. (defvar org-dcst nil) ; dynamically scoped
  15295. (defvar org-read-date-history nil)
  15296. (defvar org-read-date-final-answer nil)
  15297. (defvar org-read-date-analyze-futurep nil)
  15298. (defvar org-read-date-analyze-forced-year nil)
  15299. (defvar org-read-date-inactive)
  15300. (defvar org-read-date-minibuffer-local-map
  15301. (let* ((map (make-sparse-keymap)))
  15302. (set-keymap-parent map minibuffer-local-map)
  15303. (org-defkey map (kbd ".")
  15304. (lambda () (interactive)
  15305. ;; Are we at the beginning of the prompt?
  15306. (if (looking-back "^[^:]+: "
  15307. (let ((inhibit-field-text-motion t))
  15308. (line-beginning-position)))
  15309. (org-eval-in-calendar '(calendar-goto-today))
  15310. (insert "."))))
  15311. (org-defkey map (kbd "C-.")
  15312. (lambda () (interactive)
  15313. (org-eval-in-calendar '(calendar-goto-today))))
  15314. (org-defkey map [(meta shift left)]
  15315. (lambda () (interactive)
  15316. (org-eval-in-calendar '(calendar-backward-month 1))))
  15317. (org-defkey map [(meta shift right)]
  15318. (lambda () (interactive)
  15319. (org-eval-in-calendar '(calendar-forward-month 1))))
  15320. (org-defkey map [(meta shift up)]
  15321. (lambda () (interactive)
  15322. (org-eval-in-calendar '(calendar-backward-year 1))))
  15323. (org-defkey map [(meta shift down)]
  15324. (lambda () (interactive)
  15325. (org-eval-in-calendar '(calendar-forward-year 1))))
  15326. (org-defkey map [?\e (shift left)]
  15327. (lambda () (interactive)
  15328. (org-eval-in-calendar '(calendar-backward-month 1))))
  15329. (org-defkey map [?\e (shift right)]
  15330. (lambda () (interactive)
  15331. (org-eval-in-calendar '(calendar-forward-month 1))))
  15332. (org-defkey map [?\e (shift up)]
  15333. (lambda () (interactive)
  15334. (org-eval-in-calendar '(calendar-backward-year 1))))
  15335. (org-defkey map [?\e (shift down)]
  15336. (lambda () (interactive)
  15337. (org-eval-in-calendar '(calendar-forward-year 1))))
  15338. (org-defkey map [(shift up)]
  15339. (lambda () (interactive)
  15340. (org-eval-in-calendar '(calendar-backward-week 1))))
  15341. (org-defkey map [(shift down)]
  15342. (lambda () (interactive)
  15343. (org-eval-in-calendar '(calendar-forward-week 1))))
  15344. (org-defkey map [(shift left)]
  15345. (lambda () (interactive)
  15346. (org-eval-in-calendar '(calendar-backward-day 1))))
  15347. (org-defkey map [(shift right)]
  15348. (lambda () (interactive)
  15349. (org-eval-in-calendar '(calendar-forward-day 1))))
  15350. (org-defkey map "!"
  15351. (lambda () (interactive)
  15352. (org-eval-in-calendar '(diary-view-entries))
  15353. (message "")))
  15354. (org-defkey map ">"
  15355. (lambda () (interactive)
  15356. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15357. (org-defkey map "<"
  15358. (lambda () (interactive)
  15359. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15360. (org-defkey map "\C-v"
  15361. (lambda () (interactive)
  15362. (org-eval-in-calendar
  15363. '(calendar-scroll-left-three-months 1))))
  15364. (org-defkey map "\M-v"
  15365. (lambda () (interactive)
  15366. (org-eval-in-calendar
  15367. '(calendar-scroll-right-three-months 1))))
  15368. map)
  15369. "Keymap for minibuffer commands when using `org-read-date'.")
  15370. (defvar org-def)
  15371. (defvar org-defdecode)
  15372. (defvar org-with-time)
  15373. (defvar calendar-setup) ; Dynamically scoped.
  15374. (defun org-read-date (&optional with-time to-time from-string prompt
  15375. default-time default-input inactive)
  15376. "Read a date, possibly a time, and make things smooth for the user.
  15377. The prompt will suggest to enter an ISO date, but you can also enter anything
  15378. which will at least partially be understood by `parse-time-string'.
  15379. Unrecognized parts of the date will default to the current day, month, year,
  15380. hour and minute. If this command is called to replace a timestamp at point,
  15381. or to enter the second timestamp of a range, the default time is taken
  15382. from the existing stamp. Furthermore, the command prefers the future,
  15383. so if you are giving a date where the year is not given, and the day-month
  15384. combination is already past in the current year, it will assume you
  15385. mean next year. For details, see the manual. A few examples:
  15386. 3-2-5 --> 2003-02-05
  15387. feb 15 --> currentyear-02-15
  15388. 2/15 --> currentyear-02-15
  15389. sep 12 9 --> 2009-09-12
  15390. 12:45 --> today 12:45
  15391. 22 sept 0:34 --> currentyear-09-22 0:34
  15392. 12 --> currentyear-currentmonth-12
  15393. Fri --> nearest Friday after today
  15394. -Tue --> last Tuesday
  15395. etc.
  15396. Furthermore you can specify a relative date by giving, as the *first* thing
  15397. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15398. change in days weeks, months, years.
  15399. With a single plus or minus, the date is relative to today. With a double
  15400. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15401. +4d --> four days from today
  15402. +4 --> same as above
  15403. +2w --> two weeks from today
  15404. ++5 --> five days from default date
  15405. The function understands only English month and weekday abbreviations.
  15406. While prompting, a calendar is popped up - you can also select the
  15407. date with the mouse (button 1). The calendar shows a period of three
  15408. months. To scroll it to other months, use the keys `>' and `<'.
  15409. If you don't like the calendar, turn it off with
  15410. (setq org-read-date-popup-calendar nil)
  15411. With optional argument TO-TIME, the date will immediately be converted
  15412. to an internal time.
  15413. With an optional argument WITH-TIME, the prompt will suggest to
  15414. also insert a time. Note that when WITH-TIME is not set, you can
  15415. still enter a time, and this function will inform the calling routine
  15416. about this change. The calling routine may then choose to change the
  15417. format used to insert the time stamp into the buffer to include the time.
  15418. With optional argument FROM-STRING, read from this string instead from
  15419. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15420. the time/date that is used for everything that is not specified by the
  15421. user."
  15422. (require 'parse-time)
  15423. (let* ((org-with-time with-time)
  15424. (org-time-stamp-rounding-minutes
  15425. (if (equal org-with-time '(16))
  15426. '(0 0)
  15427. org-time-stamp-rounding-minutes))
  15428. (org-dcst org-display-custom-times)
  15429. (ct (org-current-time))
  15430. (org-def (or org-overriding-default-time default-time ct))
  15431. (org-defdecode (decode-time org-def))
  15432. (cur-frame (selected-frame))
  15433. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15434. (calendar-setup
  15435. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15436. (calendar-move-hook nil)
  15437. (calendar-view-diary-initially-flag nil)
  15438. (calendar-view-holidays-initially-flag nil)
  15439. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15440. ;; Rationalize `org-def' and `org-defdecode', if required.
  15441. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15442. (setf (nth 2 org-defdecode) -1)
  15443. (setf (nth 1 org-defdecode) 59)
  15444. (setq org-def (apply #'encode-time org-defdecode))
  15445. (setq org-defdecode (decode-time org-def)))
  15446. (let* ((timestr (format-time-string
  15447. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15448. org-def))
  15449. (prompt (concat (if prompt (concat prompt " ") "")
  15450. (format "Date+time [%s]: " timestr))))
  15451. (cond
  15452. (from-string (setq ans from-string))
  15453. (org-read-date-popup-calendar
  15454. (save-excursion
  15455. (save-window-excursion
  15456. (calendar)
  15457. (when (eq calendar-setup 'calendar-only)
  15458. (setq cal-frame
  15459. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15460. (select-frame cal-frame))
  15461. (org-eval-in-calendar '(setq cursor-type nil) t)
  15462. (unwind-protect
  15463. (progn
  15464. (calendar-forward-day (- (time-to-days org-def)
  15465. (calendar-absolute-from-gregorian
  15466. (calendar-current-date))))
  15467. (org-eval-in-calendar nil t)
  15468. (let* ((old-map (current-local-map))
  15469. (map (copy-keymap calendar-mode-map))
  15470. (minibuffer-local-map
  15471. (copy-keymap org-read-date-minibuffer-local-map)))
  15472. (org-defkey map (kbd "RET") 'org-calendar-select)
  15473. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15474. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15475. (unwind-protect
  15476. (progn
  15477. (use-local-map map)
  15478. (setq org-read-date-inactive inactive)
  15479. (add-hook 'post-command-hook 'org-read-date-display)
  15480. (setq org-ans0
  15481. (read-string prompt
  15482. default-input
  15483. 'org-read-date-history
  15484. nil))
  15485. ;; org-ans0: from prompt
  15486. ;; org-ans1: from mouse click
  15487. ;; org-ans2: from calendar motion
  15488. (setq ans
  15489. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15490. (remove-hook 'post-command-hook 'org-read-date-display)
  15491. (use-local-map old-map)
  15492. (when org-read-date-overlay
  15493. (delete-overlay org-read-date-overlay)
  15494. (setq org-read-date-overlay nil)))))
  15495. (bury-buffer "*Calendar*")
  15496. (when cal-frame
  15497. (delete-frame cal-frame)
  15498. (select-frame-set-input-focus cur-frame))))))
  15499. (t ; Naked prompt only
  15500. (unwind-protect
  15501. (setq ans (read-string prompt default-input
  15502. 'org-read-date-history timestr))
  15503. (when org-read-date-overlay
  15504. (delete-overlay org-read-date-overlay)
  15505. (setq org-read-date-overlay nil))))))
  15506. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15507. (when org-read-date-analyze-forced-year
  15508. (message "Year was forced into %s"
  15509. (if org-read-date-force-compatible-dates
  15510. "compatible range (1970-2037)"
  15511. "range representable on this machine"))
  15512. (ding))
  15513. ;; One round trip to get rid of 34th of August and stuff like that....
  15514. (setq final (decode-time (apply 'encode-time final)))
  15515. (setq org-read-date-final-answer ans)
  15516. (if to-time
  15517. (apply 'encode-time final)
  15518. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15519. (format "%04d-%02d-%02d %02d:%02d"
  15520. (nth 5 final) (nth 4 final) (nth 3 final)
  15521. (nth 2 final) (nth 1 final))
  15522. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15523. (defun org-read-date-display ()
  15524. "Display the current date prompt interpretation in the minibuffer."
  15525. (when org-read-date-display-live
  15526. (when org-read-date-overlay
  15527. (delete-overlay org-read-date-overlay))
  15528. (when (minibufferp (current-buffer))
  15529. (save-excursion
  15530. (end-of-line 1)
  15531. (while (not (equal (buffer-substring
  15532. (max (point-min) (- (point) 4)) (point))
  15533. " "))
  15534. (insert " ")))
  15535. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15536. " " (or org-ans1 org-ans2)))
  15537. (org-end-time-was-given nil)
  15538. (f (org-read-date-analyze ans org-def org-defdecode))
  15539. (fmts (if org-dcst
  15540. org-time-stamp-custom-formats
  15541. org-time-stamp-formats))
  15542. (fmt (if (or org-with-time
  15543. (and (boundp 'org-time-was-given) org-time-was-given))
  15544. (cdr fmts)
  15545. (car fmts)))
  15546. (txt (format-time-string fmt (apply 'encode-time f)))
  15547. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15548. (txt (concat "=> " txt)))
  15549. (when (and org-end-time-was-given
  15550. (string-match org-plain-time-of-day-regexp txt))
  15551. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15552. org-end-time-was-given
  15553. (substring txt (match-end 0)))))
  15554. (when org-read-date-analyze-futurep
  15555. (setq txt (concat txt " (=>F)")))
  15556. (setq org-read-date-overlay
  15557. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15558. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15559. (defun org-read-date-analyze (ans def defdecode)
  15560. "Analyze the combined answer of the date prompt."
  15561. ;; FIXME: cleanup and comment
  15562. ;; Pass `current-time' result to `decode-time' (instead of calling
  15563. ;; without arguments) so that only `current-time' has to be
  15564. ;; overriden in tests.
  15565. (let ((org-def def)
  15566. (org-defdecode defdecode)
  15567. (nowdecode (decode-time (current-time)))
  15568. delta deltan deltaw deltadef year month day
  15569. hour minute second wday pm h2 m2 tl wday1
  15570. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15571. (setq org-read-date-analyze-futurep nil
  15572. org-read-date-analyze-forced-year nil)
  15573. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15574. (setq ans "+0"))
  15575. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15576. (setq ans (replace-match "" t t ans)
  15577. deltan (car delta)
  15578. deltaw (nth 1 delta)
  15579. deltadef (nth 2 delta)))
  15580. ;; Check if there is an iso week date in there. If yes, store the
  15581. ;; info and postpone interpreting it until the rest of the parsing
  15582. ;; is done.
  15583. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15584. (setq iso-year (when (match-end 1)
  15585. (org-small-year-to-year
  15586. (string-to-number (match-string 1 ans))))
  15587. iso-weekday (when (match-end 3)
  15588. (string-to-number (match-string 3 ans)))
  15589. iso-week (string-to-number (match-string 2 ans)))
  15590. (setq ans (replace-match "" t t ans)))
  15591. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15592. (when (string-match
  15593. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15594. (setq year (if (match-end 2)
  15595. (string-to-number (match-string 2 ans))
  15596. (progn (setq kill-year t)
  15597. (string-to-number (format-time-string "%Y"))))
  15598. month (string-to-number (match-string 3 ans))
  15599. day (string-to-number (match-string 4 ans)))
  15600. (setq year (org-small-year-to-year year))
  15601. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15602. t nil ans)))
  15603. ;; Help matching dotted european dates
  15604. (when (string-match
  15605. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15606. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15607. (setq kill-year t)
  15608. (string-to-number (format-time-string "%Y")))
  15609. day (string-to-number (match-string 1 ans))
  15610. month (string-to-number (match-string 2 ans))
  15611. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15612. t nil ans)))
  15613. ;; Help matching american dates, like 5/30 or 5/30/7
  15614. (when (string-match
  15615. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15616. (setq year (if (match-end 4)
  15617. (string-to-number (match-string 4 ans))
  15618. (progn (setq kill-year t)
  15619. (string-to-number (format-time-string "%Y"))))
  15620. month (string-to-number (match-string 1 ans))
  15621. day (string-to-number (match-string 2 ans)))
  15622. (setq year (org-small-year-to-year year))
  15623. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15624. t nil ans)))
  15625. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15626. ;; If there is a time with am/pm, and *no* time without it, we convert
  15627. ;; so that matching will be successful.
  15628. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15629. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15630. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15631. (setq hour (string-to-number (match-string 1 ans))
  15632. minute (if (match-end 3)
  15633. (string-to-number (match-string 3 ans))
  15634. 0)
  15635. pm (equal ?p
  15636. (string-to-char (downcase (match-string 4 ans)))))
  15637. (if (and (= hour 12) (not pm))
  15638. (setq hour 0)
  15639. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15640. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15641. t t ans))))
  15642. ;; Check if a time range is given as a duration
  15643. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15644. (setq hour (string-to-number (match-string 1 ans))
  15645. h2 (+ hour (string-to-number (match-string 3 ans)))
  15646. minute (string-to-number (match-string 2 ans))
  15647. m2 (+ minute (if (match-end 5) (string-to-number
  15648. (match-string 5 ans))0)))
  15649. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15650. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15651. t t ans)))
  15652. ;; Check if there is a time range
  15653. (when (boundp 'org-end-time-was-given)
  15654. (setq org-time-was-given nil)
  15655. (when (and (string-match org-plain-time-of-day-regexp ans)
  15656. (match-end 8))
  15657. (setq org-end-time-was-given (match-string 8 ans))
  15658. (setq ans (concat (substring ans 0 (match-beginning 7))
  15659. (substring ans (match-end 7))))))
  15660. (setq tl (parse-time-string ans)
  15661. day (or (nth 3 tl) (nth 3 org-defdecode))
  15662. month
  15663. (cond ((nth 4 tl))
  15664. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15665. ;; Day was specified. Make sure DAY+MONTH
  15666. ;; combination happens in the future.
  15667. ((nth 3 tl)
  15668. (setq futurep t)
  15669. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15670. (nth 4 nowdecode)))
  15671. (t (nth 4 org-defdecode)))
  15672. year
  15673. (cond ((and (not kill-year) (nth 5 tl)))
  15674. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15675. ;; Month was guessed in the future and is at least
  15676. ;; equal to NOWDECODE's. Fix year accordingly.
  15677. (futurep
  15678. (if (or (> month (nth 4 nowdecode))
  15679. (>= day (nth 3 nowdecode)))
  15680. (nth 5 nowdecode)
  15681. (1+ (nth 5 nowdecode))))
  15682. ;; Month was specified. Make sure MONTH+YEAR
  15683. ;; combination happens in the future.
  15684. ((nth 4 tl)
  15685. (setq futurep t)
  15686. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15687. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15688. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15689. (t (nth 5 nowdecode))))
  15690. (t (nth 5 org-defdecode)))
  15691. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15692. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15693. second (or (nth 0 tl) 0)
  15694. wday (nth 6 tl))
  15695. (when (and (eq org-read-date-prefer-future 'time)
  15696. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15697. (equal day (nth 3 nowdecode))
  15698. (equal month (nth 4 nowdecode))
  15699. (equal year (nth 5 nowdecode))
  15700. (nth 2 tl)
  15701. (or (< (nth 2 tl) (nth 2 nowdecode))
  15702. (and (= (nth 2 tl) (nth 2 nowdecode))
  15703. (nth 1 tl)
  15704. (< (nth 1 tl) (nth 1 nowdecode)))))
  15705. (setq day (1+ day)
  15706. futurep t))
  15707. ;; Special date definitions below
  15708. (cond
  15709. (iso-week
  15710. ;; There was an iso week
  15711. (require 'cal-iso)
  15712. (setq futurep nil)
  15713. (setq year (or iso-year year)
  15714. day (or iso-weekday wday 1)
  15715. wday nil ; to make sure that the trigger below does not match
  15716. iso-date (calendar-gregorian-from-absolute
  15717. (calendar-iso-to-absolute
  15718. (list iso-week day year))))
  15719. ; FIXME: Should we also push ISO weeks into the future?
  15720. ; (when (and org-read-date-prefer-future
  15721. ; (not iso-year)
  15722. ; (< (calendar-absolute-from-gregorian iso-date)
  15723. ; (time-to-days (current-time))))
  15724. ; (setq year (1+ year)
  15725. ; iso-date (calendar-gregorian-from-absolute
  15726. ; (calendar-iso-to-absolute
  15727. ; (list iso-week day year)))))
  15728. (setq month (car iso-date)
  15729. year (nth 2 iso-date)
  15730. day (nth 1 iso-date)))
  15731. (deltan
  15732. (setq futurep nil)
  15733. (unless deltadef
  15734. ;; Pass `current-time' result to `decode-time' (instead of
  15735. ;; calling without arguments) so that only `current-time' has
  15736. ;; to be overriden in tests.
  15737. (let ((now (decode-time (current-time))))
  15738. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15739. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15740. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15741. ((equal deltaw "m") (setq month (+ month deltan)))
  15742. ((equal deltaw "y") (setq year (+ year deltan)))))
  15743. ((and wday (not (nth 3 tl)))
  15744. ;; Weekday was given, but no day, so pick that day in the week
  15745. ;; on or after the derived date.
  15746. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15747. (unless (equal wday wday1)
  15748. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15749. (when (and (boundp 'org-time-was-given)
  15750. (nth 2 tl))
  15751. (setq org-time-was-given t))
  15752. (when (< year 100) (setq year (+ 2000 year)))
  15753. ;; Check of the date is representable
  15754. (if org-read-date-force-compatible-dates
  15755. (progn
  15756. (when (< year 1970)
  15757. (setq year 1970 org-read-date-analyze-forced-year t))
  15758. (when (> year 2037)
  15759. (setq year 2037 org-read-date-analyze-forced-year t)))
  15760. (condition-case nil
  15761. (ignore (encode-time second minute hour day month year))
  15762. (error
  15763. (setq year (nth 5 org-defdecode))
  15764. (setq org-read-date-analyze-forced-year t))))
  15765. (setq org-read-date-analyze-futurep futurep)
  15766. (list second minute hour day month year)))
  15767. (defvar parse-time-weekdays)
  15768. (defun org-read-date-get-relative (s today default)
  15769. "Check string S for special relative date string.
  15770. TODAY and DEFAULT are internal times, for today and for a default.
  15771. Return shift list (N what def-flag)
  15772. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15773. N is the number of WHATs to shift.
  15774. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15775. the DEFAULT date rather than TODAY."
  15776. (require 'parse-time)
  15777. (when (and
  15778. (string-match
  15779. (concat
  15780. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15781. "\\([0-9]+\\)?"
  15782. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15783. "\\([ \t]\\|$\\)") s)
  15784. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15785. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15786. (string-to-char (substring (match-string 1 s) -1))
  15787. ?+))
  15788. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15789. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15790. (what (if (match-end 3) (match-string 3 s) "d"))
  15791. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15792. (date (if rel default today))
  15793. (wday (nth 6 (decode-time date)))
  15794. delta)
  15795. (if wday1
  15796. (progn
  15797. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15798. (when (= delta 0) (setq delta 7))
  15799. (when (= dir ?-)
  15800. (setq delta (- delta 7))
  15801. (when (= delta 0) (setq delta -7)))
  15802. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15803. (list delta "d" rel))
  15804. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15805. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15806. "Turn a user-specified date into the internal representation.
  15807. The internal representation needed by the calendar is (month day year).
  15808. This is a wrapper to handle the brain-dead convention in calendar that
  15809. user function argument order change dependent on argument order."
  15810. (pcase calendar-date-style
  15811. (`american (list arg1 arg2 arg3))
  15812. (`european (list arg2 arg1 arg3))
  15813. (`iso (list arg2 arg3 arg1))))
  15814. (defun org-eval-in-calendar (form &optional keepdate)
  15815. "Eval FORM in the calendar window and return to current window.
  15816. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15817. (let ((sf (selected-frame))
  15818. (sw (selected-window)))
  15819. (select-window (get-buffer-window "*Calendar*" t))
  15820. (eval form)
  15821. (when (and (not keepdate) (calendar-cursor-to-date))
  15822. (let* ((date (calendar-cursor-to-date))
  15823. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15824. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15825. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15826. (select-window sw)
  15827. (select-frame-set-input-focus sf)))
  15828. (defun org-calendar-select ()
  15829. "Return to `org-read-date' with the date currently selected.
  15830. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15831. (interactive)
  15832. (when (calendar-cursor-to-date)
  15833. (let* ((date (calendar-cursor-to-date))
  15834. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15835. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15836. (when (active-minibuffer-window) (exit-minibuffer))))
  15837. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15838. "Insert a date stamp for the date given by the internal TIME.
  15839. See `format-time-string' for the format of TIME.
  15840. WITH-HM means use the stamp format that includes the time of the day.
  15841. INACTIVE means use square brackets instead of angular ones, so that the
  15842. stamp will not contribute to the agenda.
  15843. PRE and POST are optional strings to be inserted before and after the
  15844. stamp.
  15845. The command returns the inserted time stamp."
  15846. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15847. stamp)
  15848. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15849. (insert-before-markers (or pre ""))
  15850. (when (listp extra)
  15851. (setq extra (car extra))
  15852. (if (and (stringp extra)
  15853. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15854. (setq extra (format "-%02d:%02d"
  15855. (string-to-number (match-string 1 extra))
  15856. (string-to-number (match-string 2 extra))))
  15857. (setq extra nil)))
  15858. (when extra
  15859. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15860. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15861. (insert-before-markers (or post ""))
  15862. (setq org-last-inserted-timestamp stamp)))
  15863. (defun org-toggle-time-stamp-overlays ()
  15864. "Toggle the use of custom time stamp formats."
  15865. (interactive)
  15866. (setq org-display-custom-times (not org-display-custom-times))
  15867. (unless org-display-custom-times
  15868. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15869. (while (setq p (next-single-property-change p 'display))
  15870. (when (and (get-text-property p 'display)
  15871. (eq (get-text-property p 'face) 'org-date))
  15872. (remove-text-properties
  15873. p (setq p (next-single-property-change p 'display))
  15874. '(display t))))
  15875. (set-buffer-modified-p bmp)))
  15876. (org-restart-font-lock)
  15877. (setq org-table-may-need-update t)
  15878. (if org-display-custom-times
  15879. (message "Time stamps are overlaid with custom format")
  15880. (message "Time stamp overlays removed")))
  15881. (defun org-display-custom-time (beg end)
  15882. "Overlay modified time stamp format over timestamp between BEG and END."
  15883. (let* ((ts (buffer-substring beg end))
  15884. t1 w1 with-hm tf time str w2 (off 0))
  15885. (save-match-data
  15886. (setq t1 (org-parse-time-string ts t))
  15887. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15888. (setq off (- (match-end 0) (match-beginning 0)))))
  15889. (setq end (- end off))
  15890. (setq w1 (- end beg)
  15891. with-hm (and (nth 1 t1) (nth 2 t1))
  15892. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15893. time (org-fix-decoded-time t1)
  15894. str (org-add-props
  15895. (format-time-string
  15896. (substring tf 1 -1) (apply 'encode-time time))
  15897. nil 'mouse-face 'highlight)
  15898. w2 (length str))
  15899. (unless (= w2 w1)
  15900. (add-text-properties (1+ beg) (+ 2 beg)
  15901. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15902. (put-text-property beg end 'display str)))
  15903. (defun org-fix-decoded-time (time)
  15904. "Set 0 instead of nil for the first 6 elements of time.
  15905. Don't touch the rest."
  15906. (let ((n 0))
  15907. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15908. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15909. "Difference between TIMESTAMP-STRING and now in days.
  15910. If SECONDS is non-nil, return the difference in seconds."
  15911. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15912. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15913. (funcall fdiff (current-time)))))
  15914. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15915. "Is the time in TIMESTAMP-STRING close to the current date?"
  15916. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15917. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15918. (not (org-entry-is-done-p))))
  15919. (defun org-get-wdays (ts &optional delay zero-delay)
  15920. "Get the deadline lead time appropriate for timestring TS.
  15921. When DELAY is non-nil, get the delay time for scheduled items
  15922. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15923. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15924. don't try to find the delay cookie in the scheduled timestamp."
  15925. (let ((tv (if delay org-scheduled-delay-days
  15926. org-deadline-warning-days)))
  15927. (cond
  15928. ((or (and delay (< tv 0))
  15929. (and delay zero-delay (<= tv 0))
  15930. (and (not delay) (<= tv 0)))
  15931. ;; Enforce this value no matter what
  15932. (- tv))
  15933. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15934. ;; lead time is specified.
  15935. (floor (* (string-to-number (match-string 1 ts))
  15936. (cdr (assoc (match-string 2 ts)
  15937. '(("d" . 1) ("w" . 7)
  15938. ("m" . 30.4) ("y" . 365.25)
  15939. ("h" . 0.041667)))))))
  15940. ;; go for the default.
  15941. (t tv))))
  15942. (defun org-calendar-select-mouse (ev)
  15943. "Return to `org-read-date' with the date currently selected.
  15944. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15945. (interactive "e")
  15946. (mouse-set-point ev)
  15947. (when (calendar-cursor-to-date)
  15948. (let* ((date (calendar-cursor-to-date))
  15949. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15950. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15951. (when (active-minibuffer-window) (exit-minibuffer))))
  15952. (defun org-check-deadlines (ndays)
  15953. "Check if there are any deadlines due or past due.
  15954. A deadline is considered due if it happens within `org-deadline-warning-days'
  15955. days from today's date. If the deadline appears in an entry marked DONE,
  15956. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15957. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15958. are shown."
  15959. (interactive "P")
  15960. (let* ((org-warn-days
  15961. (cond
  15962. ((equal ndays '(4)) 100000)
  15963. (ndays (prefix-numeric-value ndays))
  15964. (t (abs org-deadline-warning-days))))
  15965. (case-fold-search nil)
  15966. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15967. (callback
  15968. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15969. (message "%d deadlines past-due or due within %d days"
  15970. (org-occur regexp nil callback)
  15971. org-warn-days)))
  15972. (defsubst org-re-timestamp (type)
  15973. "Return a regexp for timestamp TYPE.
  15974. Allowed values for TYPE are:
  15975. all: all timestamps
  15976. active: only active timestamps (<...>)
  15977. inactive: only inactive timestamps ([...])
  15978. scheduled: only scheduled timestamps
  15979. deadline: only deadline timestamps
  15980. closed: only closed time-stamps
  15981. When TYPE is nil, fall back on returning a regexp that matches
  15982. both scheduled and deadline timestamps."
  15983. (cl-case type
  15984. (all org-ts-regexp-both)
  15985. (active org-ts-regexp)
  15986. (inactive org-ts-regexp-inactive)
  15987. (scheduled org-scheduled-time-regexp)
  15988. (deadline org-deadline-time-regexp)
  15989. (closed org-closed-time-regexp)
  15990. (otherwise
  15991. (concat "\\<"
  15992. (regexp-opt (list org-deadline-string org-scheduled-string))
  15993. " *<\\([^>]+\\)>"))))
  15994. (defun org-check-before-date (d)
  15995. "Check if there are deadlines or scheduled entries before date D."
  15996. (interactive (list (org-read-date)))
  15997. (let* ((case-fold-search nil)
  15998. (regexp (org-re-timestamp org-ts-type))
  15999. (ts-type org-ts-type)
  16000. (callback
  16001. (lambda ()
  16002. (let ((match (match-string 1)))
  16003. (and (if (memq ts-type '(active inactive all))
  16004. (eq (org-element-type (save-excursion
  16005. (backward-char)
  16006. (org-element-context)))
  16007. 'timestamp)
  16008. (org-at-planning-p))
  16009. (time-less-p
  16010. (org-time-string-to-time match)
  16011. (org-time-string-to-time d)))))))
  16012. (message "%d entries before %s"
  16013. (org-occur regexp nil callback)
  16014. d)))
  16015. (defun org-check-after-date (d)
  16016. "Check if there are deadlines or scheduled entries after date D."
  16017. (interactive (list (org-read-date)))
  16018. (let* ((case-fold-search nil)
  16019. (regexp (org-re-timestamp org-ts-type))
  16020. (ts-type org-ts-type)
  16021. (callback
  16022. (lambda ()
  16023. (let ((match (match-string 1)))
  16024. (and (if (memq ts-type '(active inactive all))
  16025. (eq (org-element-type (save-excursion
  16026. (backward-char)
  16027. (org-element-context)))
  16028. 'timestamp)
  16029. (org-at-planning-p))
  16030. (not (time-less-p
  16031. (org-time-string-to-time match)
  16032. (org-time-string-to-time d))))))))
  16033. (message "%d entries after %s"
  16034. (org-occur regexp nil callback)
  16035. d)))
  16036. (defun org-check-dates-range (start-date end-date)
  16037. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16038. (interactive (list (org-read-date nil nil nil "Range starts")
  16039. (org-read-date nil nil nil "Range end")))
  16040. (let ((case-fold-search nil)
  16041. (regexp (org-re-timestamp org-ts-type))
  16042. (callback
  16043. (let ((type org-ts-type))
  16044. (lambda ()
  16045. (let ((match (match-string 1)))
  16046. (and
  16047. (if (memq type '(active inactive all))
  16048. (eq (org-element-type (save-excursion
  16049. (backward-char)
  16050. (org-element-context)))
  16051. 'timestamp)
  16052. (org-at-planning-p))
  16053. (not (time-less-p
  16054. (org-time-string-to-time match)
  16055. (org-time-string-to-time start-date)))
  16056. (time-less-p
  16057. (org-time-string-to-time match)
  16058. (org-time-string-to-time end-date))))))))
  16059. (message "%d entries between %s and %s"
  16060. (org-occur regexp nil callback) start-date end-date)))
  16061. (defun org-evaluate-time-range (&optional to-buffer)
  16062. "Evaluate a time range by computing the difference between start and end.
  16063. Normally the result is just printed in the echo area, but with prefix arg
  16064. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16065. If the time range is actually in a table, the result is inserted into the
  16066. next column.
  16067. For time difference computation, a year is assumed to be exactly 365
  16068. days in order to avoid rounding problems."
  16069. (interactive "P")
  16070. (or
  16071. (org-clock-update-time-maybe)
  16072. (save-excursion
  16073. (unless (org-at-date-range-p t)
  16074. (goto-char (point-at-bol))
  16075. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16076. (unless (org-at-date-range-p t)
  16077. (user-error "Not at a time-stamp range, and none found in current line")))
  16078. (let* ((ts1 (match-string 1))
  16079. (ts2 (match-string 2))
  16080. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16081. (match-end (match-end 0))
  16082. (time1 (org-time-string-to-time ts1))
  16083. (time2 (org-time-string-to-time ts2))
  16084. (t1 (float-time time1))
  16085. (t2 (float-time time2))
  16086. (diff (abs (- t2 t1)))
  16087. (negative (< (- t2 t1) 0))
  16088. ;; (ys (floor (* 365 24 60 60)))
  16089. (ds (* 24 60 60))
  16090. (hs (* 60 60))
  16091. (fy "%dy %dd %02d:%02d")
  16092. (fy1 "%dy %dd")
  16093. (fd "%dd %02d:%02d")
  16094. (fd1 "%dd")
  16095. (fh "%02d:%02d")
  16096. y d h m align)
  16097. (if havetime
  16098. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16099. y 0
  16100. d (floor (/ diff ds)) diff (mod diff ds)
  16101. h (floor (/ diff hs)) diff (mod diff hs)
  16102. m (floor (/ diff 60)))
  16103. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16104. y 0
  16105. d (floor (+ (/ diff ds) 0.5))
  16106. h 0 m 0))
  16107. (if (not to-buffer)
  16108. (message "%s" (org-make-tdiff-string y d h m))
  16109. (if (org-at-table-p)
  16110. (progn
  16111. (goto-char match-end)
  16112. (setq align t)
  16113. (and (looking-at " *|") (goto-char (match-end 0))))
  16114. (goto-char match-end))
  16115. (when (looking-at
  16116. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16117. (replace-match ""))
  16118. (when negative (insert " -"))
  16119. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16120. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16121. (insert " " (format fh h m))))
  16122. (when align (org-table-align))
  16123. (message "Time difference inserted")))))
  16124. (defun org-make-tdiff-string (y d h m)
  16125. (let ((fmt "")
  16126. (l nil))
  16127. (when (> y 0)
  16128. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16129. (push y l))
  16130. (when (> d 0)
  16131. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16132. (push d l))
  16133. (when (> h 0)
  16134. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16135. (push h l))
  16136. (when (> m 0)
  16137. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16138. (push m l))
  16139. (apply 'format fmt (nreverse l))))
  16140. (defun org-time-string-to-time (s &optional buffer pos)
  16141. "Convert a timestamp string into internal time."
  16142. (condition-case errdata
  16143. (apply 'encode-time (org-parse-time-string s))
  16144. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16145. s (if (not (and buffer pos))
  16146. ""
  16147. (format-message " at %d in buffer `%s'" pos buffer))
  16148. (cdr errdata)))))
  16149. (defun org-time-string-to-seconds (s)
  16150. "Convert a timestamp string to a number of seconds."
  16151. (float-time (org-time-string-to-time s)))
  16152. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16153. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16154. "Convert time stamp S to an absolute day number.
  16155. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16156. stamp, get the closest date to DAYNR. If PREFER is
  16157. `past' (respectively `future') return a date past (respectively
  16158. after) or equal to DAYNR.
  16159. POS is the location of time stamp S, as a buffer position in
  16160. BUFFER.
  16161. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16162. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16163. signalled."
  16164. (cond
  16165. ((string-match "\\`%%\\((.*)\\)" s)
  16166. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16167. ;; only able to match individual dates. If it fails, raise an
  16168. ;; error.
  16169. (if (and daynr
  16170. (org-diary-sexp-entry
  16171. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16172. daynr
  16173. (signal 'org-diary-sexp-no-match (list s))))
  16174. (daynr (org-closest-date s daynr prefer))
  16175. (t (time-to-days
  16176. (condition-case errdata
  16177. (apply #'encode-time (org-parse-time-string s))
  16178. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16179. s
  16180. (if (not (and buffer pos)) ""
  16181. (format-message " at %d in buffer `%s'" pos buffer))
  16182. (cdr errdata))))))))
  16183. (defun org-days-to-iso-week (days)
  16184. "Return the iso week number."
  16185. (require 'cal-iso)
  16186. (car (calendar-iso-from-absolute days)))
  16187. (defun org-small-year-to-year (year)
  16188. "Convert 2-digit years into 4-digit years.
  16189. YEAR is expanded into one of the 30 next years, if possible, or
  16190. into a past one. Any year larger than 99 is returned unchanged."
  16191. (if (>= year 100) year
  16192. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16193. (century (/ current 100))
  16194. (offset (- year (% current 100))))
  16195. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16196. ((> offset -70) (+ (* century 100) year))
  16197. (t (+ (* (1+ century) 100) year))))))
  16198. (defun org-time-from-absolute (d)
  16199. "Return the time corresponding to date D.
  16200. D may be an absolute day number, or a calendar-type list (month day year)."
  16201. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16202. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16203. (defvar org-agenda-current-date)
  16204. (defun org-calendar-holiday ()
  16205. "List of holidays, for Diary display in Org mode."
  16206. (require 'holidays)
  16207. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16208. (and hl (mapconcat #'identity hl "; "))))
  16209. (defun org-diary-sexp-entry (sexp entry d)
  16210. "Process a SEXP diary ENTRY for date D."
  16211. (require 'diary-lib)
  16212. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16213. ;; dynamically.
  16214. (let* ((sexp `(let ((entry ,entry)
  16215. (date ',d))
  16216. ,(car (read-from-string sexp))))
  16217. (result (if calendar-debug-sexp (eval sexp)
  16218. (condition-case nil
  16219. (eval sexp)
  16220. (error
  16221. (beep)
  16222. (message "Bad sexp at line %d in %s: %s"
  16223. (org-current-line)
  16224. (buffer-file-name) sexp)
  16225. (sleep-for 2))))))
  16226. (cond ((stringp result) (split-string result "; "))
  16227. ((and (consp result)
  16228. (not (consp (cdr result)))
  16229. (stringp (cdr result))) (cdr result))
  16230. ((and (consp result)
  16231. (stringp (car result))) result)
  16232. (result entry))))
  16233. (defun org-diary-to-ical-string (frombuf)
  16234. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16235. This uses the icalendar.el library."
  16236. (let* ((tmpdir temporary-file-directory)
  16237. (tmpfile (make-temp-name
  16238. (expand-file-name "orgics" tmpdir)))
  16239. buf rtn b e)
  16240. (with-current-buffer frombuf
  16241. (icalendar-export-region (point-min) (point-max) tmpfile)
  16242. (setq buf (find-buffer-visiting tmpfile))
  16243. (set-buffer buf)
  16244. (goto-char (point-min))
  16245. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16246. (setq b (match-beginning 0)))
  16247. (goto-char (point-max))
  16248. (when (re-search-backward "^END:VEVENT" nil t)
  16249. (setq e (match-end 0)))
  16250. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16251. (kill-buffer buf)
  16252. (delete-file tmpfile)
  16253. rtn))
  16254. (defun org-closest-date (start current prefer)
  16255. "Return closest date to CURRENT starting from START.
  16256. CURRENT and START are both time stamps.
  16257. When PREFER is `past', return a date that is either CURRENT or
  16258. past. When PREFER is `future', return a date that is either
  16259. CURRENT or future.
  16260. Only time stamps with a repeater are modified. Any other time
  16261. stamp stay unchanged. In any case, return value is an absolute
  16262. day number."
  16263. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16264. ;; No repeater. Do not shift time stamp.
  16265. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16266. (let ((value (string-to-number (match-string 1 start)))
  16267. (type (match-string 2 start)))
  16268. (if (= 0 value)
  16269. ;; Repeater with a 0-value is considered as void.
  16270. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16271. (let* ((base (org-date-to-gregorian start))
  16272. (target (org-date-to-gregorian current))
  16273. (sday (calendar-absolute-from-gregorian base))
  16274. (cday (calendar-absolute-from-gregorian target))
  16275. n1 n2)
  16276. ;; If START is already past CURRENT, just return START.
  16277. (if (<= cday sday) sday
  16278. ;; Compute closest date before (N1) and closest date past
  16279. ;; (N2) CURRENT.
  16280. (pcase type
  16281. ("h"
  16282. (let ((missing-hours
  16283. (mod (+ (- (* 24 (- cday sday))
  16284. (nth 2 (org-parse-time-string start)))
  16285. org-extend-today-until)
  16286. value)))
  16287. (setf n1 (if (= missing-hours 0) cday
  16288. (- cday (1+ (/ missing-hours 24)))))
  16289. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16290. ((or "d" "w")
  16291. (let ((value (if (equal type "w") (* 7 value) value)))
  16292. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16293. (setf n2 (+ n1 value))))
  16294. ("m"
  16295. (let* ((add-months
  16296. (lambda (d n)
  16297. ;; Add N months to gregorian date D, i.e.,
  16298. ;; a list (MONTH DAY YEAR). Return a valid
  16299. ;; gregorian date.
  16300. (let ((m (+ (nth 0 d) n)))
  16301. (list (mod m 12)
  16302. (nth 1 d)
  16303. (+ (/ m 12) (nth 2 d))))))
  16304. (months ; Complete months to TARGET.
  16305. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16306. (- (nth 0 target) (nth 0 base))
  16307. ;; If START's day is greater than
  16308. ;; TARGET's, remove incomplete month.
  16309. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16310. value)
  16311. value))
  16312. (before (funcall add-months base months)))
  16313. (setf n1 (calendar-absolute-from-gregorian before))
  16314. (setf n2
  16315. (calendar-absolute-from-gregorian
  16316. (funcall add-months before value)))))
  16317. (_
  16318. (let* ((d (nth 1 base))
  16319. (m (nth 0 base))
  16320. (y (nth 2 base))
  16321. (years ; Complete years to TARGET.
  16322. (* (/ (- (nth 2 target)
  16323. y
  16324. ;; If START's month and day are
  16325. ;; greater than TARGET's, remove
  16326. ;; incomplete year.
  16327. (if (or (> (nth 0 target) m)
  16328. (and (= (nth 0 target) m)
  16329. (> (nth 1 target) d)))
  16330. 0
  16331. 1))
  16332. value)
  16333. value))
  16334. (before (list m d (+ y years))))
  16335. (setf n1 (calendar-absolute-from-gregorian before))
  16336. (setf n2 (calendar-absolute-from-gregorian
  16337. (list m d (+ (nth 2 before) value)))))))
  16338. ;; Handle PREFER parameter, if any.
  16339. (cond
  16340. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16341. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16342. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16343. (defun org-date-to-gregorian (d)
  16344. "Turn any specification of date D into a Gregorian date for the calendar."
  16345. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16346. ((and (listp d) (= (length d) 3)) d)
  16347. ((stringp d)
  16348. (let ((d (org-parse-time-string d)))
  16349. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16350. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16351. (defun org-parse-time-string (s &optional nodefault)
  16352. "Parse the standard Org time string.
  16353. This should be a lot faster than the normal `parse-time-string'.
  16354. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16355. hour and minute fields will be nil if not given."
  16356. (cond ((string-match org-ts-regexp0 s)
  16357. (list 0
  16358. (when (or (match-beginning 8) (not nodefault))
  16359. (string-to-number (or (match-string 8 s) "0")))
  16360. (when (or (match-beginning 7) (not nodefault))
  16361. (string-to-number (or (match-string 7 s) "0")))
  16362. (string-to-number (match-string 4 s))
  16363. (string-to-number (match-string 3 s))
  16364. (string-to-number (match-string 2 s))
  16365. nil nil nil))
  16366. ((string-match "^<[^>]+>$" s)
  16367. (decode-time (seconds-to-time (org-matcher-time s))))
  16368. (t (error "Not a standard Org time string: %s" s))))
  16369. (defun org-timestamp-up (&optional arg)
  16370. "Increase the date item at the cursor by one.
  16371. If the cursor is on the year, change the year. If it is on the month,
  16372. the day or the time, change that.
  16373. With prefix ARG, change by that many units."
  16374. (interactive "p")
  16375. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16376. (defun org-timestamp-down (&optional arg)
  16377. "Decrease the date item at the cursor by one.
  16378. If the cursor is on the year, change the year. If it is on the month,
  16379. the day or the time, change that.
  16380. With prefix ARG, change by that many units."
  16381. (interactive "p")
  16382. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16383. (defun org-timestamp-up-day (&optional arg)
  16384. "Increase the date in the time stamp by one day.
  16385. With prefix ARG, change that many days."
  16386. (interactive "p")
  16387. (if (and (not (org-at-timestamp-p t))
  16388. (org-at-heading-p))
  16389. (org-todo 'up)
  16390. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16391. (defun org-timestamp-down-day (&optional arg)
  16392. "Decrease the date in the time stamp by one day.
  16393. With prefix ARG, change that many days."
  16394. (interactive "p")
  16395. (if (and (not (org-at-timestamp-p t))
  16396. (org-at-heading-p))
  16397. (org-todo 'down)
  16398. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16399. (defun org-at-timestamp-p (&optional inactive-ok)
  16400. "Non-nil if point is inside a timestamp.
  16401. When optional argument INACTIVE-OK is non-nil, also consider
  16402. inactive timestamps.
  16403. When this function returns a non-nil value, match data is set
  16404. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16405. INACTIVE-OK."
  16406. (interactive)
  16407. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16408. (pos (point))
  16409. (ans (or (looking-at tsr)
  16410. (save-excursion
  16411. (skip-chars-backward "^[<\n\r\t")
  16412. (when (> (point) (point-min)) (backward-char 1))
  16413. (and (looking-at tsr)
  16414. (> (- (match-end 0) pos) -1))))))
  16415. (and ans
  16416. (boundp 'org-ts-what)
  16417. (setq org-ts-what
  16418. (cond
  16419. ((= pos (match-beginning 0)) 'bracket)
  16420. ;; Point is considered to be "on the bracket" whether
  16421. ;; it's really on it or right after it.
  16422. ((= pos (1- (match-end 0))) 'bracket)
  16423. ((= pos (match-end 0)) 'after)
  16424. ((org-pos-in-match-range pos 2) 'year)
  16425. ((org-pos-in-match-range pos 3) 'month)
  16426. ((org-pos-in-match-range pos 7) 'hour)
  16427. ((org-pos-in-match-range pos 8) 'minute)
  16428. ((or (org-pos-in-match-range pos 4)
  16429. (org-pos-in-match-range pos 5)) 'day)
  16430. ((and (> pos (or (match-end 8) (match-end 5)))
  16431. (< pos (match-end 0)))
  16432. (- pos (or (match-end 8) (match-end 5))))
  16433. (t 'day))))
  16434. ans))
  16435. (defun org-toggle-timestamp-type ()
  16436. "Toggle the type (<active> or [inactive]) of a time stamp."
  16437. (interactive)
  16438. (when (org-at-timestamp-p t)
  16439. (let ((beg (match-beginning 0)) (end (match-end 0))
  16440. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16441. (save-excursion
  16442. (goto-char beg)
  16443. (while (re-search-forward "[][<>]" end t)
  16444. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16445. t t)))
  16446. (message "Timestamp is now %sactive"
  16447. (if (equal (char-after beg) ?<) "" "in")))))
  16448. (defun org-at-clock-log-p nil
  16449. "Is the cursor on the clock log line?"
  16450. (save-excursion
  16451. (beginning-of-line)
  16452. (looking-at org-clock-line-re)))
  16453. (defvar org-clock-history) ; defined in org-clock.el
  16454. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16455. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16456. "Change the date in the time stamp at point.
  16457. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16458. `year', `minute', `second'. If WHAT is not given, the cursor position
  16459. in the timestamp determines what will be changed.
  16460. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16461. (let ((origin (point)) origin-cat
  16462. with-hm inactive
  16463. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16464. org-ts-what
  16465. extra rem
  16466. ts time time0 fixnext clrgx)
  16467. (unless (org-at-timestamp-p t)
  16468. (user-error "Not at a timestamp"))
  16469. (if (and (not what) (eq org-ts-what 'bracket))
  16470. (org-toggle-timestamp-type)
  16471. ;; Point isn't on brackets. Remember the part of the time-stamp
  16472. ;; the point was in. Indeed, size of time-stamps may change,
  16473. ;; but point must be kept in the same category nonetheless.
  16474. (setq origin-cat org-ts-what)
  16475. (when (and (not what) (not (eq org-ts-what 'day))
  16476. org-display-custom-times
  16477. (get-text-property (point) 'display)
  16478. (not (get-text-property (1- (point)) 'display)))
  16479. (setq org-ts-what 'day))
  16480. (setq org-ts-what (or what org-ts-what)
  16481. inactive (= (char-after (match-beginning 0)) ?\[)
  16482. ts (match-string 0))
  16483. (replace-match "")
  16484. (when (string-match
  16485. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16486. ts)
  16487. (setq extra (match-string 1 ts))
  16488. (when suppress-tmp-delay
  16489. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16490. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16491. (setq with-hm t))
  16492. (setq time0 (org-parse-time-string ts))
  16493. (when (and updown
  16494. (eq org-ts-what 'minute)
  16495. (not current-prefix-arg))
  16496. ;; This looks like s-up and s-down. Change by one rounding step.
  16497. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16498. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16499. (setcar (cdr time0) (+ (nth 1 time0)
  16500. (if (> n 0) (- rem) (- dm rem))))))
  16501. (setq time
  16502. (apply #'encode-time
  16503. (or (car time0) 0)
  16504. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16505. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16506. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16507. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16508. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16509. (nthcdr 6 time0)))
  16510. (when (and (member org-ts-what '(hour minute))
  16511. extra
  16512. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16513. (setq extra (org-modify-ts-extra
  16514. extra
  16515. (if (eq org-ts-what 'hour) 2 5)
  16516. n dm)))
  16517. (when (integerp org-ts-what)
  16518. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16519. (when (eq what 'calendar)
  16520. (let ((cal-date (org-get-date-from-calendar)))
  16521. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16522. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16523. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16524. (setcar time0 (or (car time0) 0))
  16525. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16526. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16527. (setq time (apply 'encode-time time0))))
  16528. ;; Insert the new time-stamp, and ensure point stays in the same
  16529. ;; category as before (i.e. not after the last position in that
  16530. ;; category).
  16531. (let ((pos (point)))
  16532. ;; Stay before inserted string. `save-excursion' is of no use.
  16533. (setq org-last-changed-timestamp
  16534. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16535. (goto-char pos))
  16536. (save-match-data
  16537. (looking-at org-ts-regexp3)
  16538. (goto-char
  16539. (pcase origin-cat
  16540. ;; `day' category ends before `hour' if any, or at the end
  16541. ;; of the day name.
  16542. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16543. (`hour (min (match-end 7) origin))
  16544. (`minute (min (1- (match-end 8)) origin))
  16545. ((pred integerp) (min (1- (match-end 0)) origin))
  16546. ;; Point was right after the time-stamp. However, the
  16547. ;; time-stamp length might have changed, so refer to
  16548. ;; (match-end 0) instead.
  16549. (`after (match-end 0))
  16550. ;; `year' and `month' have both fixed size: point couldn't
  16551. ;; have moved into another part.
  16552. (_ origin))))
  16553. ;; Update clock if on a CLOCK line.
  16554. (org-clock-update-time-maybe)
  16555. ;; Maybe adjust the closest clock in `org-clock-history'
  16556. (when org-clock-adjust-closest
  16557. (if (not (and (org-at-clock-log-p)
  16558. (< 1 (length (delq nil (mapcar 'marker-position
  16559. org-clock-history))))))
  16560. (message "No clock to adjust")
  16561. (cond ((save-excursion ; fix previous clock?
  16562. (re-search-backward org-ts-regexp0 nil t)
  16563. (looking-back (concat org-clock-string " \\[")
  16564. (line-beginning-position)))
  16565. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16566. ((save-excursion ; fix next clock?
  16567. (re-search-backward org-ts-regexp0 nil t)
  16568. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16569. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16570. (save-window-excursion
  16571. ;; Find closest clock to point, adjust the previous/next one in history
  16572. (let* ((p (save-excursion (org-back-to-heading t)))
  16573. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16574. (clfixnth
  16575. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16576. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16577. (if (not clfixpos)
  16578. (message "No clock to adjust")
  16579. (save-excursion
  16580. (org-goto-marker-or-bmk clfixpos)
  16581. (org-show-subtree)
  16582. (when (re-search-forward clrgx nil t)
  16583. (goto-char (match-beginning 1))
  16584. (let (org-clock-adjust-closest)
  16585. (org-timestamp-change n org-ts-what updown))
  16586. (message "Clock adjusted in %s for heading: %s"
  16587. (file-name-nondirectory (buffer-file-name))
  16588. (org-get-heading t t)))))))))
  16589. ;; Try to recenter the calendar window, if any.
  16590. (when (and org-calendar-follow-timestamp-change
  16591. (get-buffer-window "*Calendar*" t)
  16592. (memq org-ts-what '(day month year)))
  16593. (org-recenter-calendar (time-to-days time))))))
  16594. (defun org-modify-ts-extra (s pos n dm)
  16595. "Change the different parts of the lead-time and repeat fields in timestamp."
  16596. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16597. ng h m new rem)
  16598. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16599. (cond
  16600. ((or (org-pos-in-match-range pos 2)
  16601. (org-pos-in-match-range pos 3))
  16602. (setq m (string-to-number (match-string 3 s))
  16603. h (string-to-number (match-string 2 s)))
  16604. (if (org-pos-in-match-range pos 2)
  16605. (setq h (+ h n))
  16606. (setq n (* dm (with-no-warnings (signum n))))
  16607. (unless (= 0 (setq rem (% m dm)))
  16608. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16609. (setq m (+ m n)))
  16610. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16611. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16612. (setq h (mod h 24))
  16613. (setq ng 1 new (format "-%02d:%02d" h m)))
  16614. ((org-pos-in-match-range pos 6)
  16615. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16616. ((org-pos-in-match-range pos 5)
  16617. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16618. ((org-pos-in-match-range pos 9)
  16619. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16620. ((org-pos-in-match-range pos 8)
  16621. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16622. (when ng
  16623. (setq s (concat
  16624. (substring s 0 (match-beginning ng))
  16625. new
  16626. (substring s (match-end ng))))))
  16627. s))
  16628. (defun org-recenter-calendar (d)
  16629. "If the calendar is visible, recenter it to date D."
  16630. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16631. (when cwin
  16632. (let ((calendar-move-hook nil))
  16633. (with-selected-window cwin
  16634. (calendar-goto-date
  16635. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16636. (defun org-goto-calendar (&optional arg)
  16637. "Go to the Emacs calendar at the current date.
  16638. If there is a time stamp in the current line, go to that date.
  16639. A prefix ARG can be used to force the current date."
  16640. (interactive "P")
  16641. (let ((tsr org-ts-regexp) diff
  16642. (calendar-move-hook nil)
  16643. (calendar-view-holidays-initially-flag nil)
  16644. (calendar-view-diary-initially-flag nil))
  16645. (when (or (org-at-timestamp-p)
  16646. (save-excursion
  16647. (beginning-of-line 1)
  16648. (looking-at (concat ".*" tsr))))
  16649. (let ((d1 (time-to-days (current-time)))
  16650. (d2 (time-to-days
  16651. (org-time-string-to-time (match-string 1)))))
  16652. (setq diff (- d2 d1))))
  16653. (calendar)
  16654. (calendar-goto-today)
  16655. (when (and diff (not arg)) (calendar-forward-day diff))))
  16656. (defun org-get-date-from-calendar ()
  16657. "Return a list (month day year) of date at point in calendar."
  16658. (with-current-buffer "*Calendar*"
  16659. (save-match-data
  16660. (calendar-cursor-to-date))))
  16661. (defun org-date-from-calendar ()
  16662. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16663. If there is already a time stamp at the cursor position, update it."
  16664. (interactive)
  16665. (if (org-at-timestamp-p t)
  16666. (org-timestamp-change 0 'calendar)
  16667. (let ((cal-date (org-get-date-from-calendar)))
  16668. (org-insert-time-stamp
  16669. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16670. (defcustom org-effort-durations
  16671. `(("min" . 1)
  16672. ("h" . 60)
  16673. ("d" . ,(* 60 8))
  16674. ("w" . ,(* 60 8 5))
  16675. ("m" . ,(* 60 8 5 4))
  16676. ("y" . ,(* 60 8 5 40)))
  16677. "Conversion factor to minutes for an effort modifier.
  16678. Each entry has the form (MODIFIER . MINUTES).
  16679. In an effort string, a number followed by MODIFIER is multiplied
  16680. by the specified number of MINUTES to obtain an effort in
  16681. minutes.
  16682. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16683. effort string \"2hours\" is equivalent to 120 minutes."
  16684. :group 'org-agenda
  16685. :version "25.2"
  16686. :package-version '(Org . "8.3")
  16687. :type '(alist :key-type (string :tag "Modifier")
  16688. :value-type (number :tag "Minutes")))
  16689. (defun org-minutes-to-clocksum-string (m)
  16690. "Format number of minutes as a clocksum string.
  16691. The format is determined by `org-time-clocksum-format',
  16692. `org-time-clocksum-use-fractional' and
  16693. `org-time-clocksum-fractional-format' and
  16694. `org-time-clocksum-use-effort-durations'."
  16695. (let ((clocksum "")
  16696. (m (round m)) ; Don't allow fractions of minutes
  16697. h d w mo y fmt n)
  16698. (setq h (if org-time-clocksum-use-effort-durations
  16699. (cdr (assoc "h" org-effort-durations)) 60)
  16700. d (if org-time-clocksum-use-effort-durations
  16701. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16702. w (if org-time-clocksum-use-effort-durations
  16703. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16704. mo (if org-time-clocksum-use-effort-durations
  16705. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16706. y (if org-time-clocksum-use-effort-durations
  16707. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16708. ;; fractional format
  16709. (if org-time-clocksum-use-fractional
  16710. (cond
  16711. ;; single format string
  16712. ((stringp org-time-clocksum-fractional-format)
  16713. (format org-time-clocksum-fractional-format (/ m (float h))))
  16714. ;; choice of fractional formats for different time units
  16715. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16716. (> (/ (truncate m) (* y d h)) 0))
  16717. (format fmt (/ m (* y d (float h)))))
  16718. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16719. (> (/ (truncate m) (* mo d h)) 0))
  16720. (format fmt (/ m (* mo d (float h)))))
  16721. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16722. (> (/ (truncate m) (* w d h)) 0))
  16723. (format fmt (/ m (* w d (float h)))))
  16724. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16725. (> (/ (truncate m) (* d h)) 0))
  16726. (format fmt (/ m (* d (float h)))))
  16727. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16728. (> (/ (truncate m) h) 0))
  16729. (format fmt (/ m (float h))))
  16730. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16731. (format fmt m))
  16732. ;; fall back to smallest time unit with a format
  16733. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16734. (format fmt (/ m (float h))))
  16735. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16736. (format fmt (/ m (* d (float h)))))
  16737. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16738. (format fmt (/ m (* w d (float h)))))
  16739. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16740. (format fmt (/ m (* mo d (float h)))))
  16741. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16742. (format fmt (/ m (* y d (float h))))))
  16743. ;; standard (non-fractional) format, with single format string
  16744. (if (stringp org-time-clocksum-format)
  16745. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16746. ;; separate formats components
  16747. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16748. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16749. (plist-get org-time-clocksum-format :require-years))
  16750. (setq clocksum (concat clocksum (format fmt n))
  16751. m (- m (* n y d h))))
  16752. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16753. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16754. (plist-get org-time-clocksum-format :require-months))
  16755. (setq clocksum (concat clocksum (format fmt n))
  16756. m (- m (* n mo d h))))
  16757. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16758. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16759. (plist-get org-time-clocksum-format :require-weeks))
  16760. (setq clocksum (concat clocksum (format fmt n))
  16761. m (- m (* n w d h))))
  16762. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16763. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16764. (plist-get org-time-clocksum-format :require-days))
  16765. (setq clocksum (concat clocksum (format fmt n))
  16766. m (- m (* n d h))))
  16767. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16768. (or (> (setq n (/ (truncate m) h)) 0)
  16769. (plist-get org-time-clocksum-format :require-hours))
  16770. (setq clocksum (concat clocksum (format fmt n))
  16771. m (- m (* n h))))
  16772. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16773. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16774. (setq clocksum (concat clocksum (format fmt m))))
  16775. ;; return formatted time duration
  16776. clocksum))))
  16777. (defun org-hours-to-clocksum-string (n)
  16778. (org-minutes-to-clocksum-string (* n 60)))
  16779. (defun org-hh:mm-string-to-minutes (s)
  16780. "Convert a string H:MM to a number of minutes.
  16781. If the string is just a number, interpret it as minutes.
  16782. In fact, the first hh:mm or number in the string will be taken,
  16783. there can be extra stuff in the string.
  16784. If no number is found, the return value is 0."
  16785. (cond
  16786. ((integerp s) s)
  16787. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16788. (+ (* (string-to-number (match-string 1 s)) 60)
  16789. (string-to-number (match-string 2 s))))
  16790. ((string-match "\\([0-9]+\\)" s)
  16791. (string-to-number (match-string 1 s)))
  16792. (t 0)))
  16793. (defcustom org-image-actual-width t
  16794. "Should we use the actual width of images when inlining them?
  16795. When set to t, always use the image width.
  16796. When set to a number, use imagemagick (when available) to set
  16797. the image's width to this value.
  16798. When set to a number in a list, try to get the width from any
  16799. #+ATTR.* keyword if it matches a width specification like
  16800. #+ATTR_HTML: :width 300px
  16801. and fall back on that number if none is found.
  16802. When set to nil, try to get the width from an #+ATTR.* keyword
  16803. and fall back on the original width if none is found.
  16804. This requires Emacs >= 24.1, build with imagemagick support."
  16805. :group 'org-appearance
  16806. :version "24.4"
  16807. :package-version '(Org . "8.0")
  16808. :type '(choice
  16809. (const :tag "Use the image width" t)
  16810. (integer :tag "Use a number of pixels")
  16811. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16812. (const :tag "Use #+ATTR* or don't resize" nil)))
  16813. (defcustom org-agenda-inhibit-startup nil
  16814. "Inhibit startup when preparing agenda buffers.
  16815. When this variable is t, the initialization of the Org agenda
  16816. buffers is inhibited: e.g. the visibility state is not set, the
  16817. tables are not re-aligned, etc."
  16818. :type 'boolean
  16819. :version "24.3"
  16820. :group 'org-agenda)
  16821. (defcustom org-agenda-ignore-properties nil
  16822. "Avoid updating text properties when building the agenda.
  16823. Properties are used to prepare buffers for effort estimates,
  16824. appointments, statistics and subtree-local categories.
  16825. If you don't use these in the agenda, you can add them to this
  16826. list and agenda building will be a bit faster.
  16827. The value is a list, with zero or more of the symbols `effort', `appt',
  16828. `stats' or `category'."
  16829. :type '(set :greedy t
  16830. (const effort)
  16831. (const appt)
  16832. (const stats)
  16833. (const category))
  16834. :version "25.2"
  16835. :package-version '(Org . "8.3")
  16836. :group 'org-agenda)
  16837. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16838. "Convert a duration string S to minutes.
  16839. A bare number is interpreted as minutes, modifiers can be set by
  16840. customizing `org-effort-durations' (which see).
  16841. Entries containing a colon are interpreted as H:MM by
  16842. `org-hh:mm-string-to-minutes'."
  16843. (let ((result 0)
  16844. (re (concat "\\([0-9.]+\\) *\\("
  16845. (regexp-opt (mapcar 'car org-effort-durations))
  16846. "\\)")))
  16847. (while (string-match re s)
  16848. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16849. (string-to-number (match-string 1 s))))
  16850. (setq s (replace-match "" nil t s)))
  16851. (setq result (floor result))
  16852. (cl-incf result (org-hh:mm-string-to-minutes s))
  16853. (if output-to-string (number-to-string result) result)))
  16854. ;;;; Files
  16855. (defun org-save-all-org-buffers ()
  16856. "Save all Org buffers without user confirmation."
  16857. (interactive)
  16858. (message "Saving all Org buffers...")
  16859. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16860. (when (featurep 'org-id) (org-id-locations-save))
  16861. (message "Saving all Org buffers... done"))
  16862. (defun org-revert-all-org-buffers ()
  16863. "Revert all Org buffers.
  16864. Prompt for confirmation when there are unsaved changes.
  16865. Be sure you know what you are doing before letting this function
  16866. overwrite your changes.
  16867. This function is useful in a setup where one tracks org files
  16868. with a version control system, to revert on one machine after pulling
  16869. changes from another. I believe the procedure must be like this:
  16870. 1. M-x org-save-all-org-buffers
  16871. 2. Pull changes from the other machine, resolve conflicts
  16872. 3. M-x org-revert-all-org-buffers"
  16873. (interactive)
  16874. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16875. (user-error "Abort"))
  16876. (save-excursion
  16877. (save-window-excursion
  16878. (dolist (b (buffer-list))
  16879. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16880. (with-current-buffer b buffer-file-name))
  16881. (pop-to-buffer-same-window b)
  16882. (revert-buffer t 'no-confirm)))
  16883. (when (and (featurep 'org-id) org-id-track-globally)
  16884. (org-id-locations-load)))))
  16885. ;;;; Agenda files
  16886. ;;;###autoload
  16887. (defun org-switchb (&optional arg)
  16888. "Switch between Org buffers.
  16889. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16890. With `\\[universal-argument] \\[universal-argument]' \
  16891. prefix, restrict available buffers to agenda files."
  16892. (interactive "P")
  16893. (let ((blist (org-buffer-list
  16894. (cond ((equal arg '(4)) 'files)
  16895. ((equal arg '(16)) 'agenda)))))
  16896. (pop-to-buffer-same-window
  16897. (completing-read "Org buffer: "
  16898. (mapcar #'list (mapcar #'buffer-name blist))
  16899. nil t))))
  16900. (defun org-buffer-list (&optional predicate exclude-tmp)
  16901. "Return a list of Org buffers.
  16902. PREDICATE can be `export', `files' or `agenda'.
  16903. export restrict the list to Export buffers.
  16904. files restrict the list to buffers visiting Org files.
  16905. agenda restrict the list to buffers visiting agenda files.
  16906. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16907. (let* ((bfn nil)
  16908. (agenda-files (and (eq predicate 'agenda)
  16909. (mapcar 'file-truename (org-agenda-files t))))
  16910. (filter
  16911. (cond
  16912. ((eq predicate 'files)
  16913. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16914. ((eq predicate 'export)
  16915. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16916. ((eq predicate 'agenda)
  16917. (lambda (b)
  16918. (with-current-buffer b
  16919. (and (derived-mode-p 'org-mode)
  16920. (setq bfn (buffer-file-name b))
  16921. (member (file-truename bfn) agenda-files)))))
  16922. (t (lambda (b) (with-current-buffer b
  16923. (or (derived-mode-p 'org-mode)
  16924. (string-match "\\*Org .*Export"
  16925. (buffer-name b)))))))))
  16926. (delq nil
  16927. (mapcar
  16928. (lambda(b)
  16929. (if (and (funcall filter b)
  16930. (or (not exclude-tmp)
  16931. (not (string-match "tmp" (buffer-name b)))))
  16932. b
  16933. nil))
  16934. (buffer-list)))))
  16935. (defun org-agenda-files (&optional unrestricted archives)
  16936. "Get the list of agenda files.
  16937. Optional UNRESTRICTED means return the full list even if a restriction
  16938. is currently in place.
  16939. When ARCHIVES is t, include all archive files that are really being
  16940. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16941. `org-agenda-archives-mode' is t."
  16942. (let ((files
  16943. (cond
  16944. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16945. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16946. ((listp org-agenda-files) org-agenda-files)
  16947. (t (error "Invalid value of `org-agenda-files'")))))
  16948. (setq files (apply 'append
  16949. (mapcar (lambda (f)
  16950. (if (file-directory-p f)
  16951. (directory-files
  16952. f t org-agenda-file-regexp)
  16953. (list f)))
  16954. files)))
  16955. (when org-agenda-skip-unavailable-files
  16956. (setq files (delq nil
  16957. (mapcar (function
  16958. (lambda (file)
  16959. (and (file-readable-p file) file)))
  16960. files))))
  16961. (when (or (eq archives t)
  16962. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16963. (setq files (org-add-archive-files files)))
  16964. files))
  16965. (defun org-agenda-file-p (&optional file)
  16966. "Return non-nil, if FILE is an agenda file.
  16967. If FILE is omitted, use the file associated with the current
  16968. buffer."
  16969. (let ((fname (or file (buffer-file-name))))
  16970. (and fname
  16971. (member (file-truename fname)
  16972. (mapcar #'file-truename (org-agenda-files t))))))
  16973. (defun org-edit-agenda-file-list ()
  16974. "Edit the list of agenda files.
  16975. Depending on setup, this either uses customize to edit the variable
  16976. `org-agenda-files', or it visits the file that is holding the list. In the
  16977. latter case, the buffer is set up in a way that saving it automatically kills
  16978. the buffer and restores the previous window configuration."
  16979. (interactive)
  16980. (if (stringp org-agenda-files)
  16981. (let ((cw (current-window-configuration)))
  16982. (find-file org-agenda-files)
  16983. (setq-local org-window-configuration cw)
  16984. (add-hook 'after-save-hook
  16985. (lambda ()
  16986. (set-window-configuration
  16987. (prog1 org-window-configuration
  16988. (kill-buffer (current-buffer))))
  16989. (org-install-agenda-files-menu)
  16990. (message "New agenda file list installed"))
  16991. nil 'local)
  16992. (message "%s" (substitute-command-keys
  16993. "Edit list and finish with \\[save-buffer]")))
  16994. (customize-variable 'org-agenda-files)))
  16995. (defun org-store-new-agenda-file-list (list)
  16996. "Set new value for the agenda file list and save it correctly."
  16997. (if (stringp org-agenda-files)
  16998. (let ((fe (org-read-agenda-file-list t)) b u)
  16999. (while (setq b (find-buffer-visiting org-agenda-files))
  17000. (kill-buffer b))
  17001. (with-temp-file org-agenda-files
  17002. (insert
  17003. (mapconcat
  17004. (lambda (f) ;; Keep un-expanded entries.
  17005. (if (setq u (assoc f fe))
  17006. (cdr u)
  17007. f))
  17008. list "\n")
  17009. "\n")))
  17010. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17011. (org-insert-mode-line-in-empty-file nil))
  17012. (setq org-agenda-files list)
  17013. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17014. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17015. "Read the list of agenda files from a file.
  17016. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17017. filenames, used by `org-store-new-agenda-file-list' to write back
  17018. un-expanded file names."
  17019. (when (file-directory-p org-agenda-files)
  17020. (error "`org-agenda-files' cannot be a single directory"))
  17021. (when (stringp org-agenda-files)
  17022. (with-temp-buffer
  17023. (insert-file-contents org-agenda-files)
  17024. (mapcar
  17025. (lambda (f)
  17026. (let ((e (expand-file-name (substitute-in-file-name f)
  17027. org-directory)))
  17028. (if pair-with-expansion
  17029. (cons e f)
  17030. e)))
  17031. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17032. ;;;###autoload
  17033. (defun org-cycle-agenda-files ()
  17034. "Cycle through the files in `org-agenda-files'.
  17035. If the current buffer visits an agenda file, find the next one in the list.
  17036. If the current buffer does not, find the first agenda file."
  17037. (interactive)
  17038. (let* ((fs (or (org-agenda-files t)
  17039. (user-error "No agenda files")))
  17040. (files (copy-sequence fs))
  17041. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17042. file)
  17043. (when tcf
  17044. (while (and (setq file (pop files))
  17045. (not (equal (file-truename file) tcf)))))
  17046. (find-file (car (or files fs)))
  17047. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17048. (defun org-agenda-file-to-front (&optional to-end)
  17049. "Move/add the current file to the top of the agenda file list.
  17050. If the file is not present in the list, it is added to the front. If it is
  17051. present, it is moved there. With optional argument TO-END, add/move to the
  17052. end of the list."
  17053. (interactive "P")
  17054. (let ((org-agenda-skip-unavailable-files nil)
  17055. (file-alist (mapcar (lambda (x)
  17056. (cons (file-truename x) x))
  17057. (org-agenda-files t)))
  17058. (ctf (file-truename
  17059. (or buffer-file-name
  17060. (user-error "Please save the current buffer to a file"))))
  17061. x had)
  17062. (setq x (assoc ctf file-alist) had x)
  17063. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17064. (if to-end
  17065. (setq file-alist (append (delq x file-alist) (list x)))
  17066. (setq file-alist (cons x (delq x file-alist))))
  17067. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17068. (org-install-agenda-files-menu)
  17069. (message "File %s to %s of agenda file list"
  17070. (if had "moved" "added") (if to-end "end" "front"))))
  17071. (defun org-remove-file (&optional file)
  17072. "Remove current file from the list of files in variable `org-agenda-files'.
  17073. These are the files which are being checked for agenda entries.
  17074. Optional argument FILE means use this file instead of the current."
  17075. (interactive)
  17076. (let* ((org-agenda-skip-unavailable-files nil)
  17077. (file (or file buffer-file-name
  17078. (user-error "Current buffer does not visit a file")))
  17079. (true-file (file-truename file))
  17080. (afile (abbreviate-file-name file))
  17081. (files (delq nil (mapcar
  17082. (lambda (x)
  17083. (unless (equal true-file
  17084. (file-truename x))
  17085. x))
  17086. (org-agenda-files t)))))
  17087. (if (not (= (length files) (length (org-agenda-files t))))
  17088. (progn
  17089. (org-store-new-agenda-file-list files)
  17090. (org-install-agenda-files-menu)
  17091. (message "Removed from Org Agenda list: %s" afile))
  17092. (message "File was not in list: %s (not removed)" afile))))
  17093. (defun org-file-menu-entry (file)
  17094. (vector file (list 'find-file file) t))
  17095. (defun org-check-agenda-file (file)
  17096. "Make sure FILE exists. If not, ask user what to do."
  17097. (unless (file-exists-p file)
  17098. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17099. (abbreviate-file-name file))
  17100. (let ((r (downcase (read-char-exclusive))))
  17101. (cond
  17102. ((equal r ?r)
  17103. (org-remove-file file)
  17104. (throw 'nextfile t))
  17105. (t (user-error "Abort"))))))
  17106. (defun org-get-agenda-file-buffer (file)
  17107. "Get an agenda buffer visiting FILE.
  17108. If the buffer needs to be created, add it to the list of buffers
  17109. which might be released later."
  17110. (let ((buf (org-find-base-buffer-visiting file)))
  17111. (if buf
  17112. buf ; just return it
  17113. ;; Make a new buffer and remember it
  17114. (setq buf (find-file-noselect file))
  17115. (when buf (push buf org-agenda-new-buffers))
  17116. buf)))
  17117. (defun org-release-buffers (blist)
  17118. "Release all buffers in list, asking the user for confirmation when needed.
  17119. When a buffer is unmodified, it is just killed. When modified, it is saved
  17120. \(if the user agrees) and then killed."
  17121. (let (file)
  17122. (dolist (buf blist)
  17123. (setq file (buffer-file-name buf))
  17124. (when (and (buffer-modified-p buf)
  17125. file
  17126. (y-or-n-p (format "Save file %s? " file)))
  17127. (with-current-buffer buf (save-buffer)))
  17128. (kill-buffer buf))))
  17129. (defun org-agenda-prepare-buffers (files)
  17130. "Create buffers for all agenda files, protect archived trees and comments."
  17131. (interactive)
  17132. (let ((pa '(:org-archived t))
  17133. (pc '(:org-comment t))
  17134. (pall '(:org-archived t :org-comment t))
  17135. (inhibit-read-only t)
  17136. (org-inhibit-startup org-agenda-inhibit-startup)
  17137. (rea (concat ":" org-archive-tag ":"))
  17138. re pos)
  17139. (setq org-tag-alist-for-agenda nil
  17140. org-tag-groups-alist-for-agenda nil)
  17141. (save-excursion
  17142. (save-restriction
  17143. (dolist (file files)
  17144. (catch 'nextfile
  17145. (if (bufferp file)
  17146. (set-buffer file)
  17147. (org-check-agenda-file file)
  17148. (set-buffer (org-get-agenda-file-buffer file)))
  17149. (widen)
  17150. (org-set-regexps-and-options 'tags-only)
  17151. (setq pos (point))
  17152. (or (memq 'category org-agenda-ignore-properties)
  17153. (org-refresh-category-properties))
  17154. (or (memq 'stats org-agenda-ignore-properties)
  17155. (org-refresh-stats-properties))
  17156. (or (memq 'effort org-agenda-ignore-properties)
  17157. (org-refresh-effort-properties))
  17158. (or (memq 'appt org-agenda-ignore-properties)
  17159. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17160. (setq org-todo-keywords-for-agenda
  17161. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17162. (setq org-done-keywords-for-agenda
  17163. (append org-done-keywords-for-agenda org-done-keywords))
  17164. (setq org-todo-keyword-alist-for-agenda
  17165. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17166. (setq org-tag-alist-for-agenda
  17167. (org-uniquify
  17168. (append org-tag-alist-for-agenda
  17169. org-current-tag-alist)))
  17170. ;; Merge current file's tag groups into global
  17171. ;; `org-tag-groups-alist-for-agenda'.
  17172. (when org-group-tags
  17173. (dolist (alist org-tag-groups-alist)
  17174. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17175. (if old
  17176. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17177. (push alist org-tag-groups-alist-for-agenda)))))
  17178. (org-with-silent-modifications
  17179. (save-excursion
  17180. (remove-text-properties (point-min) (point-max) pall)
  17181. (when org-agenda-skip-archived-trees
  17182. (goto-char (point-min))
  17183. (while (re-search-forward rea nil t)
  17184. (when (org-at-heading-p t)
  17185. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17186. (goto-char (point-min))
  17187. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17188. (while (re-search-forward re nil t)
  17189. (when (save-match-data (org-in-commented-heading-p t))
  17190. (add-text-properties
  17191. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17192. (goto-char pos)))))
  17193. (setq org-todo-keywords-for-agenda
  17194. (org-uniquify org-todo-keywords-for-agenda))
  17195. (setq org-todo-keyword-alist-for-agenda
  17196. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17197. ;;;; CDLaTeX minor mode
  17198. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17199. "Keymap for the minor `org-cdlatex-mode'.")
  17200. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17201. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17202. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17203. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17204. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17205. (defvar org-cdlatex-texmathp-advice-is-done nil
  17206. "Flag remembering if we have applied the advice to texmathp already.")
  17207. (define-minor-mode org-cdlatex-mode
  17208. "Toggle the minor `org-cdlatex-mode'.
  17209. This mode supports entering LaTeX environment and math in LaTeX fragments
  17210. in Org mode.
  17211. \\{org-cdlatex-mode-map}"
  17212. nil " OCDL" nil
  17213. (when org-cdlatex-mode
  17214. (require 'cdlatex)
  17215. (run-hooks 'cdlatex-mode-hook)
  17216. (cdlatex-compute-tables))
  17217. (unless org-cdlatex-texmathp-advice-is-done
  17218. (setq org-cdlatex-texmathp-advice-is-done t)
  17219. (defadvice texmathp (around org-math-always-on activate)
  17220. "Always return t in Org buffers.
  17221. This is because we want to insert math symbols without dollars even outside
  17222. the LaTeX math segments. If Org mode thinks that point is actually inside
  17223. an embedded LaTeX fragment, let `texmathp' do its job.
  17224. `\\[org-cdlatex-mode-map]'"
  17225. (interactive)
  17226. (let (p)
  17227. (cond
  17228. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17229. ((eq this-command 'cdlatex-math-symbol)
  17230. (setq ad-return-value t
  17231. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17232. (t
  17233. (let ((p (org-inside-LaTeX-fragment-p)))
  17234. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17235. (setq ad-return-value t
  17236. texmathp-why '("Org mode embedded math" . 0))
  17237. (when p ad-do-it)))))))))
  17238. (defun turn-on-org-cdlatex ()
  17239. "Unconditionally turn on `org-cdlatex-mode'."
  17240. (org-cdlatex-mode 1))
  17241. (defun org-try-cdlatex-tab ()
  17242. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17243. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17244. - inside a LaTeX fragment, or
  17245. - after the first word in a line, where an abbreviation expansion could
  17246. insert a LaTeX environment."
  17247. (when org-cdlatex-mode
  17248. (cond
  17249. ;; Before any word on the line: No expansion possible.
  17250. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17251. ;; Just after first word on the line: Expand it. Make sure it
  17252. ;; cannot happen on headlines, though.
  17253. ((save-excursion
  17254. (skip-chars-backward "a-zA-Z0-9*")
  17255. (skip-chars-backward " \t")
  17256. (and (bolp) (not (org-at-heading-p))))
  17257. (cdlatex-tab) t)
  17258. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17259. (defun org-cdlatex-underscore-caret (&optional _arg)
  17260. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17261. Revert to the normal definition outside of these fragments."
  17262. (interactive "P")
  17263. (if (org-inside-LaTeX-fragment-p)
  17264. (call-interactively 'cdlatex-sub-superscript)
  17265. (let (org-cdlatex-mode)
  17266. (call-interactively (key-binding (vector last-input-event))))))
  17267. (defun org-cdlatex-math-modify (&optional _arg)
  17268. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17269. Revert to the normal definition outside of these fragments."
  17270. (interactive "P")
  17271. (if (org-inside-LaTeX-fragment-p)
  17272. (call-interactively 'cdlatex-math-modify)
  17273. (let (org-cdlatex-mode)
  17274. (call-interactively (key-binding (vector last-input-event))))))
  17275. (defun org-cdlatex-environment-indent (&optional environment item)
  17276. "Execute `cdlatex-environment' and indent the inserted environment.
  17277. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17278. The inserted environment is indented to current indentation
  17279. unless point is at the beginning of the line, in which the
  17280. environment remains unintended."
  17281. (interactive)
  17282. ;; cdlatex-environment always return nil. Therefore, capture output
  17283. ;; first and determine if an environment was selected.
  17284. (let* ((beg (point-marker))
  17285. (end (copy-marker (point) t))
  17286. (inserted (progn
  17287. (ignore-errors (cdlatex-environment environment item))
  17288. (< beg end)))
  17289. ;; Figure out how many lines to move forward after the
  17290. ;; environment has been inserted.
  17291. (lines (when inserted
  17292. (save-excursion
  17293. (- (cl-loop while (< beg (point))
  17294. with x = 0
  17295. do (forward-line -1)
  17296. (cl-incf x)
  17297. finally return x)
  17298. (if (progn (goto-char beg)
  17299. (and (progn (skip-chars-forward " \t") (eolp))
  17300. (progn (skip-chars-backward " \t") (bolp))))
  17301. 1 0)))))
  17302. (env (org-trim (delete-and-extract-region beg end))))
  17303. (when inserted
  17304. ;; Get indentation of next line unless at column 0.
  17305. (let ((ind (if (bolp) 0
  17306. (save-excursion
  17307. (org-return-indent)
  17308. (prog1 (org-get-indentation)
  17309. (when (progn (skip-chars-forward " \t") (eolp))
  17310. (delete-region beg (point)))))))
  17311. (bol (progn (skip-chars-backward " \t") (bolp))))
  17312. ;; Insert a newline before environment unless at column zero
  17313. ;; to "escape" the current line. Insert a newline if
  17314. ;; something is one the same line as \end{ENVIRONMENT}.
  17315. (insert
  17316. (concat (unless bol "\n") env
  17317. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17318. (unless (zerop ind)
  17319. (save-excursion
  17320. (goto-char beg)
  17321. (while (< (point) end)
  17322. (unless (eolp) (indent-line-to ind))
  17323. (forward-line))))
  17324. (goto-char beg)
  17325. (forward-line lines)
  17326. (indent-line-to ind)))
  17327. (set-marker beg nil)
  17328. (set-marker end nil)))
  17329. ;;;; LaTeX fragments
  17330. (defun org-inside-LaTeX-fragment-p ()
  17331. "Test if point is inside a LaTeX fragment.
  17332. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17333. sequence appearing also before point.
  17334. Even though the matchers for math are configurable, this function assumes
  17335. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17336. delimiters are skipped when they have been removed by customization.
  17337. The return value is nil, or a cons cell with the delimiter and the
  17338. position of this delimiter.
  17339. This function does a reasonably good job, but can locally be fooled by
  17340. for example currency specifications. For example it will assume being in
  17341. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17342. fragments that are properly closed, but during editing, we have to live
  17343. with the uncertainty caused by missing closing delimiters. This function
  17344. looks only before point, not after."
  17345. (catch 'exit
  17346. (let ((pos (point))
  17347. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17348. (lim (progn
  17349. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17350. (point)))
  17351. dd-on str (start 0) m re)
  17352. (goto-char pos)
  17353. (when dodollar
  17354. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17355. re (nth 1 (assoc "$" org-latex-regexps)))
  17356. (while (string-match re str start)
  17357. (cond
  17358. ((= (match-end 0) (length str))
  17359. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17360. ((= (match-end 0) (- (length str) 5))
  17361. (throw 'exit nil))
  17362. (t (setq start (match-end 0))))))
  17363. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17364. (goto-char pos)
  17365. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17366. (and (match-beginning 2) (throw 'exit nil))
  17367. ;; count $$
  17368. (while (re-search-backward "\\$\\$" lim t)
  17369. (setq dd-on (not dd-on)))
  17370. (goto-char pos)
  17371. (when dd-on (cons "$$" m))))))
  17372. (defun org-inside-latex-macro-p ()
  17373. "Is point inside a LaTeX macro or its arguments?"
  17374. (save-match-data
  17375. (org-in-regexp
  17376. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17377. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17378. "Build an overlay between BEG and END using IMAGE file.
  17379. Argument IMAGETYPE is the extension of the displayed image,
  17380. as a string. It defaults to \"png\"."
  17381. (let ((ov (make-overlay beg end))
  17382. (imagetype (or (intern imagetype) 'png)))
  17383. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17384. (overlay-put ov 'evaporate t)
  17385. (overlay-put ov
  17386. 'modification-hooks
  17387. (list (lambda (o _flag _beg _end &optional _l)
  17388. (delete-overlay o))))
  17389. (overlay-put ov
  17390. 'display
  17391. (list 'image :type imagetype :file image :ascent 'center))))
  17392. (defun org--list-latex-overlays (&optional beg end)
  17393. "List all Org LaTeX overlays in current buffer.
  17394. Limit to overlays between BEG and END when those are provided."
  17395. (cl-remove-if-not
  17396. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17397. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17398. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17399. "Remove all overlays with LaTeX fragment images in current buffer.
  17400. When optional arguments BEG and END are non-nil, remove all
  17401. overlays between them instead. Return a non-nil value when some
  17402. overlays were removed, nil otherwise."
  17403. (let ((overlays (org--list-latex-overlays beg end)))
  17404. (mapc #'delete-overlay overlays)
  17405. overlays))
  17406. (defun org-toggle-latex-fragment (&optional arg)
  17407. "Preview the LaTeX fragment at point, or all locally or globally.
  17408. If the cursor is on a LaTeX fragment, create the image and overlay
  17409. it over the source code, if there is none. Remove it otherwise.
  17410. If there is no fragment at point, display all fragments in the
  17411. current section.
  17412. With prefix ARG, preview or clear image for all fragments in the
  17413. current subtree or in the whole buffer when used before the first
  17414. headline. With a prefix ARG `\\[universal-argument] \
  17415. \\[universal-argument]' preview or clear images
  17416. for all fragments in the buffer."
  17417. (interactive "P")
  17418. (when (display-graphic-p)
  17419. (catch 'exit
  17420. (save-excursion
  17421. (let (beg end msg)
  17422. (cond
  17423. ((or (equal arg '(16))
  17424. (and (equal arg '(4))
  17425. (org-with-limited-levels (org-before-first-heading-p))))
  17426. (if (org-remove-latex-fragment-image-overlays)
  17427. (progn (message "LaTeX fragments images removed from buffer")
  17428. (throw 'exit nil))
  17429. (setq msg "Creating images for buffer...")))
  17430. ((equal arg '(4))
  17431. (org-with-limited-levels (org-back-to-heading t))
  17432. (setq beg (point))
  17433. (setq end (progn (org-end-of-subtree t) (point)))
  17434. (if (org-remove-latex-fragment-image-overlays beg end)
  17435. (progn
  17436. (message "LaTeX fragment images removed from subtree")
  17437. (throw 'exit nil))
  17438. (setq msg "Creating images for subtree...")))
  17439. ((let ((datum (org-element-context)))
  17440. (when (memq (org-element-type datum)
  17441. '(latex-environment latex-fragment))
  17442. (setq beg (org-element-property :begin datum))
  17443. (setq end (org-element-property :end datum))
  17444. (if (org-remove-latex-fragment-image-overlays beg end)
  17445. (progn (message "LaTeX fragment image removed")
  17446. (throw 'exit nil))
  17447. (setq msg "Creating image...")))))
  17448. (t
  17449. (org-with-limited-levels
  17450. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17451. (outline-previous-heading)
  17452. (point)))
  17453. (setq end (progn (outline-next-heading) (point)))
  17454. (if (org-remove-latex-fragment-image-overlays beg end)
  17455. (progn
  17456. (message "LaTeX fragment images removed from section")
  17457. (throw 'exit nil))
  17458. (setq msg "Creating images for section...")))))
  17459. (let ((file (buffer-file-name (buffer-base-buffer))))
  17460. (org-format-latex
  17461. (concat org-preview-latex-image-directory "org-ltximg")
  17462. beg end
  17463. ;; Emacs cannot overlay images from remote hosts. Create
  17464. ;; it in `temporary-file-directory' instead.
  17465. (if (or (not file) (file-remote-p file))
  17466. temporary-file-directory
  17467. default-directory)
  17468. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17469. (message (concat msg "done")))))))
  17470. (defun org-format-latex
  17471. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17472. "Replace LaTeX fragments with links to an image.
  17473. The function takes care of creating the replacement image.
  17474. Only consider fragments between BEG and END when those are
  17475. provided.
  17476. When optional argument OVERLAYS is non-nil, display the image on
  17477. top of the fragment instead of replacing it.
  17478. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17479. Some of the options can be changed using the variable
  17480. `org-format-latex-options', which see."
  17481. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17482. (unless (eq processing-type 'verbatim)
  17483. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17484. (cnt 0)
  17485. checkdir-flag)
  17486. (goto-char (or beg (point-min)))
  17487. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17488. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17489. (overlay-recenter (or end (point-max))))
  17490. (while (re-search-forward math-regexp end t)
  17491. (unless (and overlays
  17492. (eq (get-char-property (point) 'org-overlay-type)
  17493. 'org-latex-overlay))
  17494. (let* ((context (org-element-context))
  17495. (type (org-element-type context)))
  17496. (when (memq type '(latex-environment latex-fragment))
  17497. (let ((block-type (eq type 'latex-environment))
  17498. (value (org-element-property :value context))
  17499. (beg (org-element-property :begin context))
  17500. (end (save-excursion
  17501. (goto-char (org-element-property :end context))
  17502. (skip-chars-backward " \r\t\n")
  17503. (point))))
  17504. (cond
  17505. ((eq processing-type 'mathjax)
  17506. ;; Prepare for MathJax processing.
  17507. (if (not (string-match "\\`\\$\\$?" value))
  17508. (goto-char end)
  17509. (delete-region beg end)
  17510. (if (string= (match-string 0 value) "$$")
  17511. (insert "\\[" (substring value 2 -2) "\\]")
  17512. (insert "\\(" (substring value 1 -1) "\\)"))))
  17513. ((assq processing-type org-preview-latex-process-alist)
  17514. ;; Process to an image.
  17515. (cl-incf cnt)
  17516. (goto-char beg)
  17517. (let* ((processing-info
  17518. (cdr (assq processing-type org-preview-latex-process-alist)))
  17519. (face (face-at-point))
  17520. ;; Get the colors from the face at point.
  17521. (fg
  17522. (let ((color (plist-get org-format-latex-options
  17523. :foreground)))
  17524. (if (and forbuffer (eq color 'auto))
  17525. (face-attribute face :foreground nil 'default)
  17526. color)))
  17527. (bg
  17528. (let ((color (plist-get org-format-latex-options
  17529. :background)))
  17530. (if (and forbuffer (eq color 'auto))
  17531. (face-attribute face :background nil 'default)
  17532. color)))
  17533. (hash (sha1 (prin1-to-string
  17534. (list org-format-latex-header
  17535. org-latex-default-packages-alist
  17536. org-latex-packages-alist
  17537. org-format-latex-options
  17538. forbuffer value fg bg))))
  17539. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17540. (absprefix (expand-file-name prefix dir))
  17541. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17542. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17543. (sep (and block-type "\n\n"))
  17544. (link (concat sep "[[file:" linkfile "]]" sep))
  17545. (options
  17546. (org-combine-plists
  17547. org-format-latex-options
  17548. `(:foreground ,fg :background ,bg))))
  17549. (when msg (message msg cnt))
  17550. (unless checkdir-flag ; Ensure the directory exists.
  17551. (setq checkdir-flag t)
  17552. (let ((todir (file-name-directory absprefix)))
  17553. (unless (file-directory-p todir)
  17554. (make-directory todir t))))
  17555. (unless (file-exists-p movefile)
  17556. (org-create-formula-image
  17557. value movefile options forbuffer processing-type))
  17558. (if overlays
  17559. (progn
  17560. (dolist (o (overlays-in beg end))
  17561. (when (eq (overlay-get o 'org-overlay-type)
  17562. 'org-latex-overlay)
  17563. (delete-overlay o)))
  17564. (org--format-latex-make-overlay beg end movefile imagetype)
  17565. (goto-char end))
  17566. (delete-region beg end)
  17567. (insert
  17568. (org-add-props link
  17569. (list 'org-latex-src
  17570. (replace-regexp-in-string "\"" "" value)
  17571. 'org-latex-src-embed-type
  17572. (if block-type 'paragraph 'character)))))))
  17573. ((eq processing-type 'mathml)
  17574. ;; Process to MathML.
  17575. (unless (org-format-latex-mathml-available-p)
  17576. (user-error "LaTeX to MathML converter not configured"))
  17577. (cl-incf cnt)
  17578. (when msg (message msg cnt))
  17579. (goto-char beg)
  17580. (delete-region beg end)
  17581. (insert (org-format-latex-as-mathml
  17582. value block-type prefix dir)))
  17583. (t
  17584. (error "Unknown conversion process %s for LaTeX fragments"
  17585. processing-type)))))))))))
  17586. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17587. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17588. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17589. sucessful, return the portion between \"<math...> </math>\"
  17590. elements otherwise return nil. When MATHML-FILE is specified,
  17591. write the results in to that file. When invoked as an
  17592. interactive command, prompt for LATEX-FRAG, with initial value
  17593. set to the current active region and echo the results for user
  17594. inspection."
  17595. (interactive (list (let ((frag (when (org-region-active-p)
  17596. (buffer-substring-no-properties
  17597. (region-beginning) (region-end)))))
  17598. (read-string "LaTeX Fragment: " frag nil frag))))
  17599. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17600. (let* ((tmp-in-file
  17601. (let ((file (file-relative-name
  17602. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17603. (write-region latex-frag nil file)
  17604. file))
  17605. (tmp-out-file (file-relative-name
  17606. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17607. (cmd (format-spec
  17608. org-latex-to-mathml-convert-command
  17609. `((?j . ,(and org-latex-to-mathml-jar-file
  17610. (shell-quote-argument
  17611. (expand-file-name
  17612. org-latex-to-mathml-jar-file))))
  17613. (?I . ,(shell-quote-argument tmp-in-file))
  17614. (?i . ,latex-frag)
  17615. (?o . ,(shell-quote-argument tmp-out-file)))))
  17616. mathml shell-command-output)
  17617. (when (called-interactively-p 'any)
  17618. (unless (org-format-latex-mathml-available-p)
  17619. (user-error "LaTeX to MathML converter not configured")))
  17620. (message "Running %s" cmd)
  17621. (setq shell-command-output (shell-command-to-string cmd))
  17622. (setq mathml
  17623. (when (file-readable-p tmp-out-file)
  17624. (with-current-buffer (find-file-noselect tmp-out-file t)
  17625. (goto-char (point-min))
  17626. (when (re-search-forward
  17627. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17628. (regexp-quote
  17629. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17630. nil t)
  17631. (prog1 (match-string 0) (kill-buffer))))))
  17632. (cond
  17633. (mathml
  17634. (setq mathml
  17635. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17636. (when mathml-file
  17637. (write-region mathml nil mathml-file))
  17638. (when (called-interactively-p 'any)
  17639. (message mathml)))
  17640. ((message "LaTeX to MathML conversion failed")
  17641. (message shell-command-output)))
  17642. (delete-file tmp-in-file)
  17643. (when (file-exists-p tmp-out-file)
  17644. (delete-file tmp-out-file))
  17645. mathml))
  17646. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17647. prefix &optional dir)
  17648. "Use `org-create-math-formula' but check local cache first."
  17649. (let* ((absprefix (expand-file-name prefix dir))
  17650. (print-length nil) (print-level nil)
  17651. (formula-id (concat
  17652. "formula-"
  17653. (sha1
  17654. (prin1-to-string
  17655. (list latex-frag
  17656. org-latex-to-mathml-convert-command)))))
  17657. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17658. (formula-cache-dir (file-name-directory formula-cache)))
  17659. (unless (file-directory-p formula-cache-dir)
  17660. (make-directory formula-cache-dir t))
  17661. (unless (file-exists-p formula-cache)
  17662. (org-create-math-formula latex-frag formula-cache))
  17663. (if (file-exists-p formula-cache)
  17664. ;; Successful conversion. Return the link to MathML file.
  17665. (org-add-props
  17666. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17667. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17668. 'org-latex-src-embed-type (if latex-frag-type
  17669. 'paragraph 'character)))
  17670. ;; Failed conversion. Return the LaTeX fragment verbatim
  17671. latex-frag)))
  17672. (declare-function org-export-get-backend "ox" (name))
  17673. (declare-function org-export--get-global-options "ox" (&optional backend))
  17674. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17675. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17676. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17677. (defun org-create-formula--latex-header ()
  17678. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17679. (let ((info (org-combine-plists (org-export--get-global-options
  17680. (org-export-get-backend 'latex))
  17681. (org-export--get-inbuffer-options
  17682. (org-export-get-backend 'latex)))))
  17683. (org-latex-guess-babel-language
  17684. (org-latex-guess-inputenc
  17685. (org-splice-latex-header
  17686. org-format-latex-header
  17687. org-latex-default-packages-alist
  17688. org-latex-packages-alist t
  17689. (plist-get info :latex-header)))
  17690. info)))
  17691. (defun org--get-display-dpi ()
  17692. "Get the DPI of the display.
  17693. The function assumes that the display has the same pixel width in
  17694. the horizontal and vertical directions."
  17695. (if (display-graphic-p)
  17696. (round (/ (display-pixel-height)
  17697. (/ (display-mm-height) 25.4)))
  17698. (error "Attempt to calculate the dpi of a non-graphic display")))
  17699. (defun org-create-formula-image
  17700. (string tofile options buffer &optional processing-type)
  17701. "Create an image from LaTeX source using external processes.
  17702. The LaTeX STRING is saved to a temporary LaTeX file, then
  17703. converted to an image file by process PROCESSING-TYPE defined in
  17704. `org-preview-latex-process-alist'. A nil value defaults to
  17705. `org-preview-latex-default-process'.
  17706. The generated image file is eventually moved to TOFILE.
  17707. The OPTIONS argument controls the size, foreground color and
  17708. background color of the generated image.
  17709. When BUFFER non-nil, this function is used for LaTeX previewing.
  17710. Otherwise, it is used to deal with LaTeX snippets showed in
  17711. a HTML file."
  17712. (let* ((processing-type (or processing-type
  17713. org-preview-latex-default-process))
  17714. (processing-info
  17715. (cdr (assq processing-type org-preview-latex-process-alist)))
  17716. (programs (plist-get processing-info :programs))
  17717. (error-message (or (plist-get processing-info :message) ""))
  17718. (use-xcolor (plist-get processing-info :use-xcolor))
  17719. (image-input-type (plist-get processing-info :image-input-type))
  17720. (image-output-type (plist-get processing-info :image-output-type))
  17721. (post-clean (or (plist-get processing-info :post-clean)
  17722. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17723. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17724. (latex-header (or (plist-get processing-info :latex-header)
  17725. (org-create-formula--latex-header)))
  17726. (latex-compiler (plist-get processing-info :latex-compiler))
  17727. (image-converter (plist-get processing-info :image-converter))
  17728. (tmpdir temporary-file-directory)
  17729. (texfilebase (make-temp-name
  17730. (expand-file-name "orgtex" tmpdir)))
  17731. (texfile (concat texfilebase ".tex"))
  17732. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17733. '(1.0 . 1.0)))
  17734. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17735. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17736. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17737. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17738. "Black"))
  17739. (bg (or (plist-get options (if buffer :background :html-background))
  17740. "Transparent"))
  17741. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17742. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17743. (dolist (program programs)
  17744. (org-check-external-command program error-message))
  17745. (if use-xcolor
  17746. (progn (if (eq fg 'default)
  17747. (setq fg (org-latex-color :foreground))
  17748. (setq fg (org-latex-color-format fg)))
  17749. (if (eq bg 'default)
  17750. (setq bg (org-latex-color :background))
  17751. (setq bg (org-latex-color-format
  17752. (if (string= bg "Transparent") "white" bg))))
  17753. (with-temp-file texfile
  17754. (insert latex-header)
  17755. (insert "\n\\begin{document}\n"
  17756. "\\definecolor{fg}{rgb}{" fg "}\n"
  17757. "\\definecolor{bg}{rgb}{" bg "}\n"
  17758. "\n\\pagecolor{bg}\n"
  17759. "\n{\\color{fg}\n"
  17760. string
  17761. "\n}\n"
  17762. "\n\\end{document}\n")))
  17763. (if (eq fg 'default)
  17764. (setq fg (org-dvipng-color :foreground))
  17765. (unless (string= fg "Transparent")
  17766. (setq fg (org-dvipng-color-format fg))))
  17767. (if (eq bg 'default)
  17768. (setq bg (org-dvipng-color :background))
  17769. (unless (string= bg "Transparent")
  17770. (setq bg (org-dvipng-color-format bg))))
  17771. (with-temp-file texfile
  17772. (insert latex-header)
  17773. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17774. (let* ((err-msg (format "Please adjust '%s' part of \
  17775. `org-preview-latex-process-alist'."
  17776. processing-type))
  17777. (image-input-file
  17778. (org-compile-file
  17779. texfile latex-compiler image-input-type err-msg log-buf))
  17780. (image-output-file
  17781. (org-compile-file
  17782. image-input-file image-converter image-output-type err-msg log-buf
  17783. `((?F . ,(shell-quote-argument fg))
  17784. (?B . ,(shell-quote-argument bg))
  17785. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17786. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17787. (copy-file image-output-file tofile 'replace)
  17788. (dolist (e post-clean)
  17789. (when (file-exists-p (concat texfilebase e))
  17790. (delete-file (concat texfilebase e))))
  17791. image-output-file)))
  17792. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17793. "Fill a LaTeX header template TPL.
  17794. In the template, the following place holders will be recognized:
  17795. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17796. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17797. [PACKAGES] \\usepackage statements for PKG
  17798. [NO-PACKAGES] do not include PKG
  17799. [EXTRA] the string EXTRA
  17800. [NO-EXTRA] do not include EXTRA
  17801. For backward compatibility, if both the positive and the negative place
  17802. holder is missing, the positive one (without the \"NO-\") will be
  17803. assumed to be present at the end of the template.
  17804. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17805. EXTRA is a string.
  17806. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17807. (let (rpl (end ""))
  17808. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17809. (setq rpl (if (or (match-end 1) (not def-pkg))
  17810. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17811. tpl (replace-match rpl t t tpl))
  17812. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17813. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17814. (setq rpl (if (or (match-end 1) (not pkg))
  17815. "" (org-latex-packages-to-string pkg snippets-p t))
  17816. tpl (replace-match rpl t t tpl))
  17817. (when pkg (setq end
  17818. (concat end "\n"
  17819. (org-latex-packages-to-string pkg snippets-p)))))
  17820. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17821. (setq rpl (if (or (match-end 1) (not extra))
  17822. "" (concat extra "\n"))
  17823. tpl (replace-match rpl t t tpl))
  17824. (when (and extra (string-match "\\S-" extra))
  17825. (setq end (concat end "\n" extra))))
  17826. (if (string-match "\\S-" end)
  17827. (concat tpl "\n" end)
  17828. tpl)))
  17829. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17830. "Turn an alist of packages into a string with the \\usepackage macros."
  17831. (setq pkg (mapconcat (lambda(p)
  17832. (cond
  17833. ((stringp p) p)
  17834. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17835. (format "%% Package %s omitted" (cadr p)))
  17836. ((equal "" (car p))
  17837. (format "\\usepackage{%s}" (cadr p)))
  17838. (t
  17839. (format "\\usepackage[%s]{%s}"
  17840. (car p) (cadr p)))))
  17841. pkg
  17842. "\n"))
  17843. (if newline (concat pkg "\n") pkg))
  17844. (defun org-dvipng-color (attr)
  17845. "Return a RGB color specification for dvipng."
  17846. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17847. (defun org-dvipng-color-format (color-name)
  17848. "Convert COLOR-NAME to a RGB color value for dvipng."
  17849. (apply #'format "rgb %s %s %s"
  17850. (mapcar 'org-normalize-color
  17851. (color-values color-name))))
  17852. (defun org-latex-color (attr)
  17853. "Return a RGB color for the LaTeX color package."
  17854. (org-latex-color-format (face-attribute 'default attr nil)))
  17855. (defun org-latex-color-format (color-name)
  17856. "Convert COLOR-NAME to a RGB color value."
  17857. (apply #'format "%s,%s,%s"
  17858. (mapcar 'org-normalize-color
  17859. (color-values color-name))))
  17860. (defun org-normalize-color (value)
  17861. "Return string to be used as color value for an RGB component."
  17862. (format "%g" (/ value 65535.0)))
  17863. ;; Image display
  17864. (defvar-local org-inline-image-overlays nil)
  17865. (defun org-toggle-inline-images (&optional include-linked)
  17866. "Toggle the display of inline images.
  17867. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17868. (interactive "P")
  17869. (if org-inline-image-overlays
  17870. (progn
  17871. (org-remove-inline-images)
  17872. (when (called-interactively-p 'interactive)
  17873. (message "Inline image display turned off")))
  17874. (org-display-inline-images include-linked)
  17875. (when (called-interactively-p 'interactive)
  17876. (message (if org-inline-image-overlays
  17877. (format "%d images displayed inline"
  17878. (length org-inline-image-overlays))
  17879. "No images to display inline")))))
  17880. (defun org-redisplay-inline-images ()
  17881. "Refresh the display of inline images."
  17882. (interactive)
  17883. (if (not org-inline-image-overlays)
  17884. (org-toggle-inline-images)
  17885. (org-toggle-inline-images)
  17886. (org-toggle-inline-images)))
  17887. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17888. "Display inline images.
  17889. An inline image is a link which follows either of these
  17890. conventions:
  17891. 1. Its path is a file with an extension matching return value
  17892. from `image-file-name-regexp' and it has no contents.
  17893. 2. Its description consists in a single link of the previous
  17894. type.
  17895. When optional argument INCLUDE-LINKED is non-nil, also links with
  17896. a text description part will be inlined. This can be nice for
  17897. a quick look at those images, but it does not reflect what
  17898. exported files will look like.
  17899. When optional argument REFRESH is non-nil, refresh existing
  17900. images between BEG and END. This will create new image displays
  17901. only if necessary. BEG and END default to the buffer
  17902. boundaries."
  17903. (interactive "P")
  17904. (when (display-graphic-p)
  17905. (unless refresh
  17906. (org-remove-inline-images)
  17907. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17908. (org-with-wide-buffer
  17909. (goto-char (or beg (point-min)))
  17910. (let ((case-fold-search t)
  17911. (file-extension-re (image-file-name-regexp)))
  17912. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17913. (let ((link (save-match-data (org-element-context))))
  17914. ;; Check if we're at an inline image.
  17915. (when (and (equal (org-element-property :type link) "file")
  17916. (or include-linked
  17917. (not (org-element-property :contents-begin link)))
  17918. (let ((parent (org-element-property :parent link)))
  17919. (or (not (eq (org-element-type parent) 'link))
  17920. (not (cdr (org-element-contents parent)))))
  17921. (string-match-p file-extension-re
  17922. (org-element-property :path link)))
  17923. (let ((file (expand-file-name
  17924. (org-link-unescape
  17925. (org-element-property :path link)))))
  17926. (when (file-exists-p file)
  17927. (let ((width
  17928. ;; Apply `org-image-actual-width' specifications.
  17929. (cond
  17930. ((not (image-type-available-p 'imagemagick)) nil)
  17931. ((eq org-image-actual-width t) nil)
  17932. ((listp org-image-actual-width)
  17933. (or
  17934. ;; First try to find a width among
  17935. ;; attributes associated to the paragraph
  17936. ;; containing link.
  17937. (let ((paragraph
  17938. (let ((e link))
  17939. (while (and (setq e (org-element-property
  17940. :parent e))
  17941. (not (eq (org-element-type e)
  17942. 'paragraph))))
  17943. e)))
  17944. (when paragraph
  17945. (save-excursion
  17946. (goto-char (org-element-property :begin paragraph))
  17947. (when
  17948. (re-search-forward
  17949. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17950. (org-element-property
  17951. :post-affiliated paragraph)
  17952. t)
  17953. (string-to-number (match-string 1))))))
  17954. ;; Otherwise, fall-back to provided number.
  17955. (car org-image-actual-width)))
  17956. ((numberp org-image-actual-width)
  17957. org-image-actual-width)))
  17958. (old (get-char-property-and-overlay
  17959. (org-element-property :begin link)
  17960. 'org-image-overlay)))
  17961. (if (and (car-safe old) refresh)
  17962. (image-refresh (overlay-get (cdr old) 'display))
  17963. (let ((image (create-image file
  17964. (and width 'imagemagick)
  17965. nil
  17966. :width width)))
  17967. (when image
  17968. (let* ((link
  17969. ;; If inline image is the description
  17970. ;; of another link, be sure to
  17971. ;; consider the latter as the one to
  17972. ;; apply the overlay on.
  17973. (let ((parent
  17974. (org-element-property :parent link)))
  17975. (if (eq (org-element-type parent) 'link)
  17976. parent
  17977. link)))
  17978. (ov (make-overlay
  17979. (org-element-property :begin link)
  17980. (progn
  17981. (goto-char
  17982. (org-element-property :end link))
  17983. (skip-chars-backward " \t")
  17984. (point)))))
  17985. (overlay-put ov 'display image)
  17986. (overlay-put ov 'face 'default)
  17987. (overlay-put ov 'org-image-overlay t)
  17988. (overlay-put
  17989. ov 'modification-hooks
  17990. (list 'org-display-inline-remove-overlay))
  17991. (push ov org-inline-image-overlays)))))))))))))))
  17992. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17993. "Remove inline-display overlay if a corresponding region is modified."
  17994. (let ((inhibit-modification-hooks t))
  17995. (when (and ov after)
  17996. (delete ov org-inline-image-overlays)
  17997. (delete-overlay ov))))
  17998. (defun org-remove-inline-images ()
  17999. "Remove inline display of images."
  18000. (interactive)
  18001. (mapc #'delete-overlay org-inline-image-overlays)
  18002. (setq org-inline-image-overlays nil))
  18003. ;;;; Key bindings
  18004. ;; Outline functions from `outline-mode-prefix-map'
  18005. ;; that can be remapped in Org:
  18006. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18007. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18008. (define-key org-mode-map [remap outline-forward-same-level]
  18009. 'org-forward-heading-same-level)
  18010. (define-key org-mode-map [remap outline-backward-same-level]
  18011. 'org-backward-heading-same-level)
  18012. (define-key org-mode-map [remap outline-show-branches]
  18013. 'org-kill-note-or-show-branches)
  18014. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18015. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18016. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18017. (define-key org-mode-map [remap outline-next-visible-heading]
  18018. 'org-next-visible-heading)
  18019. (define-key org-mode-map [remap outline-previous-visible-heading]
  18020. 'org-previous-visible-heading)
  18021. (define-key org-mode-map [remap show-children] 'org-show-children)
  18022. ;; Outline functions from `outline-mode-prefix-map' that can not
  18023. ;; be remapped in Org:
  18024. ;; - the column "key binding" shows whether the Outline function is still
  18025. ;; available in Org mode on the same key that it has been bound to in
  18026. ;; Outline mode:
  18027. ;; - "overridden": key used for a different functionality in Org mode
  18028. ;; - else: key still bound to the same Outline function in Org mode
  18029. ;; | Outline function | key binding | Org replacement |
  18030. ;; |------------------------------------+-------------+--------------------------|
  18031. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18032. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18033. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18034. ;; | `show-entry' | overridden | no replacement |
  18035. ;; | `show-branches' | `C-c C-k' | still same function |
  18036. ;; | `show-subtree' | overridden | visibility cycling |
  18037. ;; | `show-all' | overridden | no replacement |
  18038. ;; | `hide-subtree' | overridden | visibility cycling |
  18039. ;; | `hide-body' | overridden | no replacement |
  18040. ;; | `hide-entry' | overridden | visibility cycling |
  18041. ;; | `hide-leaves' | overridden | no replacement |
  18042. ;; | `hide-sublevels' | overridden | no replacement |
  18043. ;; | `hide-other' | overridden | no replacement |
  18044. ;; Make `C-c C-x' a prefix key
  18045. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18046. ;; TAB key with modifiers
  18047. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18048. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18049. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18050. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18051. ;; The following line is necessary under Suse GNU/Linux
  18052. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18053. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18054. (define-key org-mode-map [backtab] 'org-shifttab)
  18055. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18056. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18057. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18058. ;; Cursor keys with modifiers
  18059. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18060. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18061. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18062. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18063. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18064. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18065. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18066. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18067. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18068. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18069. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18070. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18071. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18072. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18073. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18074. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18075. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18076. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18077. ;; Babel keys
  18078. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18079. (dolist (pair org-babel-key-bindings)
  18080. (define-key org-babel-map (car pair) (cdr pair)))
  18081. ;;; Extra keys for tty access.
  18082. ;; We only set them when really needed because otherwise the
  18083. ;; menus don't show the simple keys
  18084. (when (or org-use-extra-keys (not window-system))
  18085. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18086. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18087. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18088. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18089. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18090. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18091. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18092. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18093. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18094. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18095. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18096. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18097. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18098. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18099. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18100. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18101. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18102. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18103. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18104. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18105. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18106. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18107. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18108. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18109. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18110. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18111. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18112. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18113. ;; All the other keys
  18114. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18115. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18116. (if (boundp 'narrow-map)
  18117. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18118. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18119. (if (boundp 'narrow-map)
  18120. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18121. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18122. (if (boundp 'narrow-map)
  18123. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18124. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18125. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18126. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18127. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18128. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18129. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18130. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18131. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18132. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18133. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18134. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18135. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18136. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18137. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18138. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18139. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18140. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18141. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18142. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18143. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18144. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18145. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18146. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18147. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18148. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18149. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18150. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18151. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18152. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18153. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18154. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18155. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18156. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18157. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18158. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18159. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18160. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18161. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18162. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18163. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18164. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18165. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18166. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18167. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18168. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18169. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18170. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18171. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18172. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18173. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18174. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18175. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18176. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18177. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18178. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18179. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18180. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18181. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18182. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18183. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18184. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18185. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18186. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18187. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18188. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18189. (org-defkey org-mode-map "\C-m" 'org-return)
  18190. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18191. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18192. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18193. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18194. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18195. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18196. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18197. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18198. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18199. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18200. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18201. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18202. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18203. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18204. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18205. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18206. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18207. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18208. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18209. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18210. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18211. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18212. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18213. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18214. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18215. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18216. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18217. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18218. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18219. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18220. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18221. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18222. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18223. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18224. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18225. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18226. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18227. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18228. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18229. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18230. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18231. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18232. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18233. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18234. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18235. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18236. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18237. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18238. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18239. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18240. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18241. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18242. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18243. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18244. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18245. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18246. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18247. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18248. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18249. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18250. (defconst org-speed-commands-default
  18251. '(
  18252. ("Outline Navigation")
  18253. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18254. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18255. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18256. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18257. ("F" . org-next-block)
  18258. ("B" . org-previous-block)
  18259. ("u" . (org-speed-move-safe 'outline-up-heading))
  18260. ("j" . org-goto)
  18261. ("g" . (org-refile t))
  18262. ("Outline Visibility")
  18263. ("c" . org-cycle)
  18264. ("C" . org-shifttab)
  18265. (" " . org-display-outline-path)
  18266. ("s" . org-narrow-to-subtree)
  18267. ("=" . org-columns)
  18268. ("Outline Structure Editing")
  18269. ("U" . org-metaup)
  18270. ("D" . org-metadown)
  18271. ("r" . org-metaright)
  18272. ("l" . org-metaleft)
  18273. ("R" . org-shiftmetaright)
  18274. ("L" . org-shiftmetaleft)
  18275. ("i" . (progn (forward-char 1) (call-interactively
  18276. 'org-insert-heading-respect-content)))
  18277. ("^" . org-sort)
  18278. ("w" . org-refile)
  18279. ("a" . org-archive-subtree-default-with-confirmation)
  18280. ("@" . org-mark-subtree)
  18281. ("#" . org-toggle-comment)
  18282. ("Clock Commands")
  18283. ("I" . org-clock-in)
  18284. ("O" . org-clock-out)
  18285. ("Meta Data Editing")
  18286. ("t" . org-todo)
  18287. ("," . (org-priority))
  18288. ("0" . (org-priority ?\ ))
  18289. ("1" . (org-priority ?A))
  18290. ("2" . (org-priority ?B))
  18291. ("3" . (org-priority ?C))
  18292. (":" . org-set-tags-command)
  18293. ("e" . org-set-effort)
  18294. ("E" . org-inc-effort)
  18295. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18296. (org-entry-put (point) "APPT_WARNTIME" m)))
  18297. ("Agenda Views etc")
  18298. ("v" . org-agenda)
  18299. ("/" . org-sparse-tree)
  18300. ("Misc")
  18301. ("o" . org-open-at-point)
  18302. ("?" . org-speed-command-help)
  18303. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18304. (">" . (org-agenda-remove-restriction-lock))
  18305. )
  18306. "The default speed commands.")
  18307. (defun org-print-speed-command (e)
  18308. (if (> (length (car e)) 1)
  18309. (progn
  18310. (princ "\n")
  18311. (princ (car e))
  18312. (princ "\n")
  18313. (princ (make-string (length (car e)) ?-))
  18314. (princ "\n"))
  18315. (princ (car e))
  18316. (princ " ")
  18317. (if (symbolp (cdr e))
  18318. (princ (symbol-name (cdr e)))
  18319. (prin1 (cdr e)))
  18320. (princ "\n")))
  18321. (defun org-speed-command-help ()
  18322. "Show the available speed commands."
  18323. (interactive)
  18324. (if (not org-use-speed-commands)
  18325. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18326. (with-output-to-temp-buffer "*Help*"
  18327. (princ "User-defined Speed commands\n===========================\n")
  18328. (mapc #'org-print-speed-command org-speed-commands-user)
  18329. (princ "\n")
  18330. (princ "Built-in Speed commands\n=======================\n")
  18331. (mapc #'org-print-speed-command org-speed-commands-default))
  18332. (with-current-buffer "*Help*"
  18333. (setq truncate-lines t))))
  18334. (defun org-speed-move-safe (cmd)
  18335. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18336. If not, return to the original position and throw an error."
  18337. (interactive)
  18338. (let ((pos (point)))
  18339. (call-interactively cmd)
  18340. (unless (and (bolp) (org-at-heading-p))
  18341. (goto-char pos)
  18342. (error "Boundary reached while executing %s" cmd))))
  18343. (defvar org-self-insert-command-undo-counter 0)
  18344. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18345. (defvar org-speed-command nil)
  18346. (defun org-speed-command-activate (keys)
  18347. "Hook for activating single-letter speed commands.
  18348. `org-speed-commands-default' specifies a minimal command set.
  18349. Use `org-speed-commands-user' for further customization."
  18350. (when (or (and (bolp) (looking-at org-outline-regexp))
  18351. (and (functionp org-use-speed-commands)
  18352. (funcall org-use-speed-commands)))
  18353. (cdr (assoc keys (append org-speed-commands-user
  18354. org-speed-commands-default)))))
  18355. (defun org-babel-speed-command-activate (keys)
  18356. "Hook for activating single-letter code block commands."
  18357. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18358. (cdr (assoc keys org-babel-key-bindings))))
  18359. (defcustom org-speed-command-hook
  18360. '(org-speed-command-activate org-babel-speed-command-activate)
  18361. "Hook for activating speed commands at strategic locations.
  18362. Hook functions are called in sequence until a valid handler is
  18363. found.
  18364. Each hook takes a single argument, a user-pressed command key
  18365. which is also a `self-insert-command' from the global map.
  18366. Within the hook, examine the cursor position and the command key
  18367. and return nil or a valid handler as appropriate. Handler could
  18368. be one of an interactive command, a function, or a form.
  18369. Set `org-use-speed-commands' to non-nil value to enable this
  18370. hook. The default setting is `org-speed-command-activate'."
  18371. :group 'org-structure
  18372. :version "24.1"
  18373. :type 'hook)
  18374. (defun org-self-insert-command (N)
  18375. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18376. If the cursor is in a table looking at whitespace, the whitespace is
  18377. overwritten, and the table is not marked as requiring realignment."
  18378. (interactive "p")
  18379. (org-check-before-invisible-edit 'insert)
  18380. (cond
  18381. ((and org-use-speed-commands
  18382. (let ((kv (this-command-keys-vector)))
  18383. (setq org-speed-command
  18384. (run-hook-with-args-until-success
  18385. 'org-speed-command-hook
  18386. (make-string 1 (aref kv (1- (length kv))))))))
  18387. (cond
  18388. ((commandp org-speed-command)
  18389. (setq this-command org-speed-command)
  18390. (call-interactively org-speed-command))
  18391. ((functionp org-speed-command)
  18392. (funcall org-speed-command))
  18393. ((and org-speed-command (listp org-speed-command))
  18394. (eval org-speed-command))
  18395. (t (let (org-use-speed-commands)
  18396. (call-interactively 'org-self-insert-command)))))
  18397. ((and
  18398. (org-at-table-p)
  18399. (progn
  18400. ;; Check if we blank the field, and if that triggers align.
  18401. (and (featurep 'org-table) org-table-auto-blank-field
  18402. (memq last-command
  18403. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18404. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18405. ;; Got extra space, this field does not determine
  18406. ;; column width.
  18407. (let (org-table-may-need-update) (org-table-blank-field))
  18408. ;; No extra space, this field may determine column
  18409. ;; width.
  18410. (org-table-blank-field)))
  18411. t)
  18412. (eq N 1)
  18413. (looking-at "[^|\n]* \\( \\)|"))
  18414. ;; There is room for insertion without re-aligning the table.
  18415. (delete-region (match-beginning 1) (match-end 1))
  18416. (self-insert-command N))
  18417. (t
  18418. (setq org-table-may-need-update t)
  18419. (self-insert-command N)
  18420. (org-fix-tags-on-the-fly)
  18421. (when org-self-insert-cluster-for-undo
  18422. (if (not (eq last-command 'org-self-insert-command))
  18423. (setq org-self-insert-command-undo-counter 1)
  18424. (if (>= org-self-insert-command-undo-counter 20)
  18425. (setq org-self-insert-command-undo-counter 1)
  18426. (and (> org-self-insert-command-undo-counter 0)
  18427. buffer-undo-list (listp buffer-undo-list)
  18428. (not (cadr buffer-undo-list)) ; remove nil entry
  18429. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18430. (setq org-self-insert-command-undo-counter
  18431. (1+ org-self-insert-command-undo-counter))))))))
  18432. (defun org-check-before-invisible-edit (kind)
  18433. "Check is editing if kind KIND would be dangerous with invisible text around.
  18434. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18435. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18436. (when (and org-catch-invisible-edits
  18437. (or (not (boundp 'visible-mode)) (not visible-mode))
  18438. (or (get-char-property (point) 'invisible)
  18439. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18440. ;; OK, we need to take a closer look
  18441. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18442. (invisible-before-point (unless (bobp) (get-char-property
  18443. (1- (point)) 'invisible)))
  18444. (border-and-ok-direction
  18445. (or
  18446. ;; Check if we are acting predictably before invisible text
  18447. (and invisible-at-point (not invisible-before-point)
  18448. (memq kind '(insert delete-backward)))
  18449. ;; Check if we are acting predictably after invisible text
  18450. ;; This works not well, and I have turned it off. It seems
  18451. ;; better to always show and stop after invisible text.
  18452. ;; (and (not invisible-at-point) invisible-before-point
  18453. ;; (memq kind '(insert delete)))
  18454. )))
  18455. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18456. (memq invisible-before-point '(outline org-hide-block t)))
  18457. (when (eq org-catch-invisible-edits 'error)
  18458. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18459. (if (and org-custom-properties-overlays
  18460. (y-or-n-p "Display invisible properties in this buffer? "))
  18461. (org-toggle-custom-properties-visibility)
  18462. ;; Make the area visible
  18463. (save-excursion
  18464. (when invisible-before-point
  18465. (goto-char (previous-single-char-property-change
  18466. (point) 'invisible)))
  18467. (outline-show-subtree))
  18468. (cond
  18469. ((eq org-catch-invisible-edits 'show)
  18470. ;; That's it, we do the edit after showing
  18471. (message
  18472. "Unfolding invisible region around point before editing")
  18473. (sit-for 1))
  18474. ((and (eq org-catch-invisible-edits 'smart)
  18475. border-and-ok-direction)
  18476. (message "Unfolding invisible region around point before editing"))
  18477. (t
  18478. ;; Don't do the edit, make the user repeat it in full visibility
  18479. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18480. (defun org-fix-tags-on-the-fly ()
  18481. "Align tags in headline at point.
  18482. Unlike to `org-set-tags', it ignores region and sorting."
  18483. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18484. (org-at-heading-p))
  18485. (let ((org-ignore-region t)
  18486. (org-tags-sort-function nil))
  18487. (org-set-tags nil t))))
  18488. (defun org-delete-backward-char (N)
  18489. "Like `delete-backward-char', insert whitespace at field end in tables.
  18490. When deleting backwards, in tables this function will insert whitespace in
  18491. front of the next \"|\" separator, to keep the table aligned. The table will
  18492. still be marked for re-alignment if the field did fill the entire column,
  18493. because, in this case the deletion might narrow the column."
  18494. (interactive "p")
  18495. (save-match-data
  18496. (org-check-before-invisible-edit 'delete-backward)
  18497. (if (and (org-at-table-p)
  18498. (eq N 1)
  18499. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18500. (looking-at ".*?|"))
  18501. (let ((pos (point))
  18502. (noalign (looking-at "[^|\n\r]* |"))
  18503. (c org-table-may-need-update))
  18504. (backward-delete-char N)
  18505. (unless overwrite-mode
  18506. (skip-chars-forward "^|")
  18507. (insert " ")
  18508. (goto-char (1- pos)))
  18509. ;; noalign: if there were two spaces at the end, this field
  18510. ;; does not determine the width of the column.
  18511. (when noalign (setq org-table-may-need-update c)))
  18512. (backward-delete-char N)
  18513. (org-fix-tags-on-the-fly))))
  18514. (defun org-delete-char (N)
  18515. "Like `delete-char', but insert whitespace at field end in tables.
  18516. When deleting characters, in tables this function will insert whitespace in
  18517. front of the next \"|\" separator, to keep the table aligned. The table will
  18518. still be marked for re-alignment if the field did fill the entire column,
  18519. because, in this case the deletion might narrow the column."
  18520. (interactive "p")
  18521. (save-match-data
  18522. (org-check-before-invisible-edit 'delete)
  18523. (if (and (org-at-table-p)
  18524. (not (bolp))
  18525. (not (= (char-after) ?|))
  18526. (eq N 1))
  18527. (if (looking-at ".*?|")
  18528. (let ((pos (point))
  18529. (noalign (looking-at "[^|\n\r]* |"))
  18530. (c org-table-may-need-update))
  18531. (replace-match
  18532. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18533. (goto-char pos)
  18534. ;; noalign: if there were two spaces at the end, this field
  18535. ;; does not determine the width of the column.
  18536. (when noalign (setq org-table-may-need-update c)))
  18537. (delete-char N))
  18538. (delete-char N)
  18539. (org-fix-tags-on-the-fly))))
  18540. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18541. (put 'org-self-insert-command 'delete-selection
  18542. (lambda ()
  18543. (not (run-hook-with-args-until-success
  18544. 'self-insert-uses-region-functions))))
  18545. (put 'orgtbl-self-insert-command 'delete-selection
  18546. (lambda ()
  18547. (not (run-hook-with-args-until-success
  18548. 'self-insert-uses-region-functions))))
  18549. (put 'org-delete-char 'delete-selection 'supersede)
  18550. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18551. (put 'org-yank 'delete-selection 'yank)
  18552. ;; Make `flyspell-mode' delay after some commands
  18553. (put 'org-self-insert-command 'flyspell-delayed t)
  18554. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18555. (put 'org-delete-char 'flyspell-delayed t)
  18556. (put 'org-delete-backward-char 'flyspell-delayed t)
  18557. ;; Make pabbrev-mode expand after Org mode commands
  18558. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18559. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18560. (defun org-remap (map &rest commands)
  18561. "In MAP, remap the functions given in COMMANDS.
  18562. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18563. (let (new old)
  18564. (while commands
  18565. (setq old (pop commands) new (pop commands))
  18566. (org-defkey map (vector 'remap old) new))))
  18567. (defun org-transpose-words ()
  18568. "Transpose words for Org.
  18569. This uses the `org-mode-transpose-word-syntax-table' syntax
  18570. table, which interprets characters in `org-emphasis-alist' as
  18571. word constituents."
  18572. (interactive)
  18573. (with-syntax-table org-mode-transpose-word-syntax-table
  18574. (call-interactively 'transpose-words)))
  18575. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18576. (when (eq org-enable-table-editor 'optimized)
  18577. ;; If the user wants maximum table support, we need to hijack
  18578. ;; some standard editing functions
  18579. (org-remap org-mode-map
  18580. 'self-insert-command 'org-self-insert-command
  18581. 'delete-char 'org-delete-char
  18582. 'delete-backward-char 'org-delete-backward-char)
  18583. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18584. (defvar org-ctrl-c-ctrl-c-hook nil
  18585. "Hook for functions attaching themselves to `C-c C-c'.
  18586. This can be used to add additional functionality to the C-c C-c
  18587. key which executes context-dependent commands. This hook is run
  18588. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18589. run after the last test.
  18590. Each function will be called with no arguments. The function
  18591. must check if the context is appropriate for it to act. If yes,
  18592. it should do its thing and then return a non-nil value. If the
  18593. context is wrong, just do nothing and return nil.")
  18594. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18595. "Hook for functions attaching themselves to `C-c C-c'.
  18596. This can be used to add additional functionality to the C-c C-c
  18597. key which executes context-dependent commands. This hook is run
  18598. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18599. before the first test.
  18600. Each function will be called with no arguments. The function
  18601. must check if the context is appropriate for it to act. If yes,
  18602. it should do its thing and then return a non-nil value. If the
  18603. context is wrong, just do nothing and return nil.")
  18604. (defvar org-tab-first-hook nil
  18605. "Hook for functions to attach themselves to TAB.
  18606. See `org-ctrl-c-ctrl-c-hook' for more information.
  18607. This hook runs as the first action when TAB is pressed, even before
  18608. `org-cycle' messes around with the `outline-regexp' to cater for
  18609. inline tasks and plain list item folding.
  18610. If any function in this hook returns t, any other actions that
  18611. would have been caused by TAB (such as table field motion or visibility
  18612. cycling) will not occur.")
  18613. (defvar org-tab-after-check-for-table-hook nil
  18614. "Hook for functions to attach themselves to TAB.
  18615. See `org-ctrl-c-ctrl-c-hook' for more information.
  18616. This hook runs after it has been established that the cursor is not in a
  18617. table, but before checking if the cursor is in a headline or if global cycling
  18618. should be done.
  18619. If any function in this hook returns t, not other actions like visibility
  18620. cycling will be done.")
  18621. (defvar org-tab-after-check-for-cycling-hook nil
  18622. "Hook for functions to attach themselves to TAB.
  18623. See `org-ctrl-c-ctrl-c-hook' for more information.
  18624. This hook runs after it has been established that not table field motion and
  18625. not visibility should be done because of current context. This is probably
  18626. the place where a package like yasnippets can hook in.")
  18627. (defvar org-tab-before-tab-emulation-hook nil
  18628. "Hook for functions to attach themselves to TAB.
  18629. See `org-ctrl-c-ctrl-c-hook' for more information.
  18630. This hook runs after every other options for TAB have been exhausted, but
  18631. before indentation and \t insertion takes place.")
  18632. (defvar org-metaleft-hook nil
  18633. "Hook for functions attaching themselves to `M-left'.
  18634. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18635. (defvar org-metaright-hook nil
  18636. "Hook for functions attaching themselves to `M-right'.
  18637. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18638. (defvar org-metaup-hook nil
  18639. "Hook for functions attaching themselves to `M-up'.
  18640. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18641. (defvar org-metadown-hook nil
  18642. "Hook for functions attaching themselves to `M-down'.
  18643. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18644. (defvar org-shiftmetaleft-hook nil
  18645. "Hook for functions attaching themselves to `M-S-left'.
  18646. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18647. (defvar org-shiftmetaright-hook nil
  18648. "Hook for functions attaching themselves to `M-S-right'.
  18649. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18650. (defvar org-shiftmetaup-hook nil
  18651. "Hook for functions attaching themselves to `M-S-up'.
  18652. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18653. (defvar org-shiftmetadown-hook nil
  18654. "Hook for functions attaching themselves to `M-S-down'.
  18655. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18656. (defvar org-metareturn-hook nil
  18657. "Hook for functions attaching themselves to `M-RET'.
  18658. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18659. (defvar org-shiftup-hook nil
  18660. "Hook for functions attaching themselves to `S-up'.
  18661. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18662. (defvar org-shiftup-final-hook nil
  18663. "Hook for functions attaching themselves to `S-up'.
  18664. This one runs after all other options except shift-select have been excluded.
  18665. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18666. (defvar org-shiftdown-hook nil
  18667. "Hook for functions attaching themselves to `S-down'.
  18668. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18669. (defvar org-shiftdown-final-hook nil
  18670. "Hook for functions attaching themselves to `S-down'.
  18671. This one runs after all other options except shift-select have been excluded.
  18672. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18673. (defvar org-shiftleft-hook nil
  18674. "Hook for functions attaching themselves to `S-left'.
  18675. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18676. (defvar org-shiftleft-final-hook nil
  18677. "Hook for functions attaching themselves to `S-left'.
  18678. This one runs after all other options except shift-select have been excluded.
  18679. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18680. (defvar org-shiftright-hook nil
  18681. "Hook for functions attaching themselves to `S-right'.
  18682. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18683. (defvar org-shiftright-final-hook nil
  18684. "Hook for functions attaching themselves to `S-right'.
  18685. This one runs after all other options except shift-select have been excluded.
  18686. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18687. (defun org-modifier-cursor-error ()
  18688. "Throw an error, a modified cursor command was applied in wrong context."
  18689. (user-error "This command is active in special context like tables, headlines or items"))
  18690. (defun org-shiftselect-error ()
  18691. "Throw an error because Shift-Cursor command was applied in wrong context."
  18692. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18693. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18694. (user-error "This command works only in special context like headlines or timestamps")))
  18695. (defun org-call-for-shift-select (cmd)
  18696. (let ((this-command-keys-shift-translated t))
  18697. (call-interactively cmd)))
  18698. (defun org-shifttab (&optional arg)
  18699. "Global visibility cycling or move to previous table field.
  18700. Call `org-table-previous-field' within a table.
  18701. When ARG is nil, cycle globally through visibility states.
  18702. When ARG is a numeric prefix, show contents of this level."
  18703. (interactive "P")
  18704. (cond
  18705. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18706. ((integerp arg)
  18707. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18708. (message "Content view to level: %d" arg)
  18709. (org-content (prefix-numeric-value arg2))
  18710. (org-cycle-show-empty-lines t)
  18711. (setq org-cycle-global-status 'overview)))
  18712. (t (call-interactively 'org-global-cycle))))
  18713. (defun org-shiftmetaleft ()
  18714. "Promote subtree or delete table column.
  18715. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18716. `org-table-delete-column', depending on context. See the
  18717. individual commands for more information."
  18718. (interactive)
  18719. (cond
  18720. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18721. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18722. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18723. ((if (not (org-region-active-p)) (org-at-item-p)
  18724. (save-excursion (goto-char (region-beginning))
  18725. (org-at-item-p)))
  18726. (call-interactively 'org-outdent-item-tree))
  18727. (t (org-modifier-cursor-error))))
  18728. (defun org-shiftmetaright ()
  18729. "Demote subtree or insert table column.
  18730. Calls `org-demote-subtree', `org-indent-item-tree', or
  18731. `org-table-insert-column', depending on context. See the
  18732. individual commands for more information."
  18733. (interactive)
  18734. (cond
  18735. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18736. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18737. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18738. ((if (not (org-region-active-p)) (org-at-item-p)
  18739. (save-excursion (goto-char (region-beginning))
  18740. (org-at-item-p)))
  18741. (call-interactively 'org-indent-item-tree))
  18742. (t (org-modifier-cursor-error))))
  18743. (defun org-shiftmetaup (&optional _arg)
  18744. "Drag the line at point up.
  18745. In a table, kill the current row.
  18746. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18747. but also adjust the previous clocked item in the clock history.
  18748. Everywhere else, drag the line at point up."
  18749. (interactive "P")
  18750. (cond
  18751. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18752. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18753. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18754. (call-interactively 'org-timestamp-up)))
  18755. (t (call-interactively 'org-drag-line-backward))))
  18756. (defun org-shiftmetadown (&optional _arg)
  18757. "Drag the line at point down.
  18758. In a table, insert an empty row at the current line.
  18759. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18760. but also adjust the previous clocked item in the clock history.
  18761. Everywhere else, drag the line at point down."
  18762. (interactive "P")
  18763. (cond
  18764. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18765. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18766. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18767. (call-interactively 'org-timestamp-down)))
  18768. (t (call-interactively 'org-drag-line-forward))))
  18769. (defsubst org-hidden-tree-error ()
  18770. (user-error
  18771. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18772. (defun org-metaleft (&optional _arg)
  18773. "Promote heading, list item at point or move table column left.
  18774. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18775. depending on context. With no specific context, calls the Emacs
  18776. default `backward-word'. See the individual commands for more
  18777. information.
  18778. This function runs the hook `org-metaleft-hook' as a first step,
  18779. and returns at first non-nil value."
  18780. (interactive "P")
  18781. (cond
  18782. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18783. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18784. ((org-with-limited-levels
  18785. (or (org-at-heading-p)
  18786. (and (org-region-active-p)
  18787. (save-excursion
  18788. (goto-char (region-beginning))
  18789. (org-at-heading-p)))))
  18790. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18791. (call-interactively 'org-do-promote))
  18792. ;; At an inline task.
  18793. ((org-at-heading-p)
  18794. (call-interactively 'org-inlinetask-promote))
  18795. ((or (org-at-item-p)
  18796. (and (org-region-active-p)
  18797. (save-excursion
  18798. (goto-char (region-beginning))
  18799. (org-at-item-p))))
  18800. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18801. (call-interactively 'org-outdent-item))
  18802. (t (call-interactively 'backward-word))))
  18803. (defun org-metaright (&optional _arg)
  18804. "Demote heading, list item at point or move table column right.
  18805. In front of a drawer or a block keyword, indent it correctly.
  18806. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18807. `org-indent-drawer' or `org-indent-block' depending on context.
  18808. With no specific context, calls the Emacs default `forward-word'.
  18809. See the individual commands for more information.
  18810. This function runs the hook `org-metaright-hook' as a first step,
  18811. and returns at first non-nil value."
  18812. (interactive "P")
  18813. (cond
  18814. ((run-hook-with-args-until-success 'org-metaright-hook))
  18815. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18816. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18817. ((org-at-block-p) (call-interactively 'org-indent-block))
  18818. ((org-with-limited-levels
  18819. (or (org-at-heading-p)
  18820. (and (org-region-active-p)
  18821. (save-excursion
  18822. (goto-char (region-beginning))
  18823. (org-at-heading-p)))))
  18824. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18825. (call-interactively 'org-do-demote))
  18826. ;; At an inline task.
  18827. ((org-at-heading-p)
  18828. (call-interactively 'org-inlinetask-demote))
  18829. ((or (org-at-item-p)
  18830. (and (org-region-active-p)
  18831. (save-excursion
  18832. (goto-char (region-beginning))
  18833. (org-at-item-p))))
  18834. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18835. (call-interactively 'org-indent-item))
  18836. (t (call-interactively 'forward-word))))
  18837. (defun org-check-for-hidden (what)
  18838. "Check if there are hidden headlines/items in the current visual line.
  18839. WHAT can be either `headlines' or `items'. If the current line is
  18840. an outline or item heading and it has a folded subtree below it,
  18841. this function returns t, nil otherwise."
  18842. (let ((re (cond
  18843. ((eq what 'headlines) org-outline-regexp-bol)
  18844. ((eq what 'items) (org-item-beginning-re))
  18845. (t (error "This should not happen"))))
  18846. beg end)
  18847. (save-excursion
  18848. (catch 'exit
  18849. (unless (org-region-active-p)
  18850. (setq beg (point-at-bol))
  18851. (beginning-of-line 2)
  18852. (while (and (not (eobp)) ;; this is like `next-line'
  18853. (get-char-property (1- (point)) 'invisible))
  18854. (beginning-of-line 2))
  18855. (setq end (point))
  18856. (goto-char beg)
  18857. (goto-char (point-at-eol))
  18858. (setq end (max end (point)))
  18859. (while (re-search-forward re end t)
  18860. (when (get-char-property (match-beginning 0) 'invisible)
  18861. (throw 'exit t))))
  18862. nil))))
  18863. (defun org-metaup (&optional _arg)
  18864. "Move subtree up or move table row up.
  18865. Calls `org-move-subtree-up' or `org-table-move-row' or
  18866. `org-move-item-up', depending on context. See the individual commands
  18867. for more information."
  18868. (interactive "P")
  18869. (cond
  18870. ((run-hook-with-args-until-success 'org-metaup-hook))
  18871. ((org-region-active-p)
  18872. (let* ((a (min (region-beginning) (region-end)))
  18873. (b (1- (max (region-beginning) (region-end))))
  18874. (c (save-excursion (goto-char a)
  18875. (move-beginning-of-line 0)))
  18876. (d (save-excursion (goto-char a)
  18877. (move-end-of-line 0) (point))))
  18878. (transpose-regions a b c d)
  18879. (goto-char c)))
  18880. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18881. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18882. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18883. (t (org-drag-element-backward))))
  18884. (defun org-metadown (&optional _arg)
  18885. "Move subtree down or move table row down.
  18886. Calls `org-move-subtree-down' or `org-table-move-row' or
  18887. `org-move-item-down', depending on context. See the individual
  18888. commands for more information."
  18889. (interactive "P")
  18890. (cond
  18891. ((run-hook-with-args-until-success 'org-metadown-hook))
  18892. ((org-region-active-p)
  18893. (let* ((a (min (region-beginning) (region-end)))
  18894. (b (max (region-beginning) (region-end)))
  18895. (c (save-excursion (goto-char b)
  18896. (move-beginning-of-line 1)))
  18897. (d (save-excursion (goto-char b)
  18898. (move-end-of-line 1) (1+ (point)))))
  18899. (transpose-regions a b c d)
  18900. (goto-char d)))
  18901. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18902. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18903. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18904. (t (org-drag-element-forward))))
  18905. (defun org-shiftup (&optional arg)
  18906. "Increase item in timestamp or increase priority of current headline.
  18907. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18908. depending on context. See the individual commands for more information."
  18909. (interactive "P")
  18910. (cond
  18911. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18912. ((and org-support-shift-select (org-region-active-p))
  18913. (org-call-for-shift-select 'previous-line))
  18914. ((org-at-timestamp-p t)
  18915. (call-interactively (if org-edit-timestamp-down-means-later
  18916. 'org-timestamp-down 'org-timestamp-up)))
  18917. ((and (not (eq org-support-shift-select 'always))
  18918. org-enable-priority-commands
  18919. (org-at-heading-p))
  18920. (call-interactively 'org-priority-up))
  18921. ((and (not org-support-shift-select) (org-at-item-p))
  18922. (call-interactively 'org-previous-item))
  18923. ((org-clocktable-try-shift 'up arg))
  18924. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18925. (org-support-shift-select
  18926. (org-call-for-shift-select 'previous-line))
  18927. (t (org-shiftselect-error))))
  18928. (defun org-shiftdown (&optional arg)
  18929. "Decrease item in timestamp or decrease priority of current headline.
  18930. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18931. depending on context. See the individual commands for more information."
  18932. (interactive "P")
  18933. (cond
  18934. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18935. ((and org-support-shift-select (org-region-active-p))
  18936. (org-call-for-shift-select 'next-line))
  18937. ((org-at-timestamp-p t)
  18938. (call-interactively (if org-edit-timestamp-down-means-later
  18939. 'org-timestamp-up 'org-timestamp-down)))
  18940. ((and (not (eq org-support-shift-select 'always))
  18941. org-enable-priority-commands
  18942. (org-at-heading-p))
  18943. (call-interactively 'org-priority-down))
  18944. ((and (not org-support-shift-select) (org-at-item-p))
  18945. (call-interactively 'org-next-item))
  18946. ((org-clocktable-try-shift 'down arg))
  18947. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18948. (org-support-shift-select
  18949. (org-call-for-shift-select 'next-line))
  18950. (t (org-shiftselect-error))))
  18951. (defun org-shiftright (&optional arg)
  18952. "Cycle the thing at point or in the current line, depending on context.
  18953. Depending on context, this does one of the following:
  18954. - switch a timestamp at point one day into the future
  18955. - on a headline, switch to the next TODO keyword.
  18956. - on an item, switch entire list to the next bullet type
  18957. - on a property line, switch to the next allowed value
  18958. - on a clocktable definition line, move time block into the future"
  18959. (interactive "P")
  18960. (cond
  18961. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18962. ((and org-support-shift-select (org-region-active-p))
  18963. (org-call-for-shift-select 'forward-char))
  18964. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  18965. ((and (not (eq org-support-shift-select 'always))
  18966. (org-at-heading-p))
  18967. (let ((org-inhibit-logging
  18968. (not org-treat-S-cursor-todo-selection-as-state-change))
  18969. (org-inhibit-blocking
  18970. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18971. (org-call-with-arg 'org-todo 'right)))
  18972. ((or (and org-support-shift-select
  18973. (not (eq org-support-shift-select 'always))
  18974. (org-at-item-bullet-p))
  18975. (and (not org-support-shift-select) (org-at-item-p)))
  18976. (org-call-with-arg 'org-cycle-list-bullet nil))
  18977. ((and (not (eq org-support-shift-select 'always))
  18978. (org-at-property-p))
  18979. (call-interactively 'org-property-next-allowed-value))
  18980. ((org-clocktable-try-shift 'right arg))
  18981. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18982. (org-support-shift-select
  18983. (org-call-for-shift-select 'forward-char))
  18984. (t (org-shiftselect-error))))
  18985. (defun org-shiftleft (&optional arg)
  18986. "Cycle the thing at point or in the current line, depending on context.
  18987. Depending on context, this does one of the following:
  18988. - switch a timestamp at point one day into the past
  18989. - on a headline, switch to the previous TODO keyword.
  18990. - on an item, switch entire list to the previous bullet type
  18991. - on a property line, switch to the previous allowed value
  18992. - on a clocktable definition line, move time block into the past"
  18993. (interactive "P")
  18994. (cond
  18995. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18996. ((and org-support-shift-select (org-region-active-p))
  18997. (org-call-for-shift-select 'backward-char))
  18998. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  18999. ((and (not (eq org-support-shift-select 'always))
  19000. (org-at-heading-p))
  19001. (let ((org-inhibit-logging
  19002. (not org-treat-S-cursor-todo-selection-as-state-change))
  19003. (org-inhibit-blocking
  19004. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19005. (org-call-with-arg 'org-todo 'left)))
  19006. ((or (and org-support-shift-select
  19007. (not (eq org-support-shift-select 'always))
  19008. (org-at-item-bullet-p))
  19009. (and (not org-support-shift-select) (org-at-item-p)))
  19010. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19011. ((and (not (eq org-support-shift-select 'always))
  19012. (org-at-property-p))
  19013. (call-interactively 'org-property-previous-allowed-value))
  19014. ((org-clocktable-try-shift 'left arg))
  19015. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19016. (org-support-shift-select
  19017. (org-call-for-shift-select 'backward-char))
  19018. (t (org-shiftselect-error))))
  19019. (defun org-shiftcontrolright ()
  19020. "Switch to next TODO set."
  19021. (interactive)
  19022. (cond
  19023. ((and org-support-shift-select (org-region-active-p))
  19024. (org-call-for-shift-select 'forward-word))
  19025. ((and (not (eq org-support-shift-select 'always))
  19026. (org-at-heading-p))
  19027. (org-call-with-arg 'org-todo 'nextset))
  19028. (org-support-shift-select
  19029. (org-call-for-shift-select 'forward-word))
  19030. (t (org-shiftselect-error))))
  19031. (defun org-shiftcontrolleft ()
  19032. "Switch to previous TODO set."
  19033. (interactive)
  19034. (cond
  19035. ((and org-support-shift-select (org-region-active-p))
  19036. (org-call-for-shift-select 'backward-word))
  19037. ((and (not (eq org-support-shift-select 'always))
  19038. (org-at-heading-p))
  19039. (org-call-with-arg 'org-todo 'previousset))
  19040. (org-support-shift-select
  19041. (org-call-for-shift-select 'backward-word))
  19042. (t (org-shiftselect-error))))
  19043. (defun org-shiftcontrolup (&optional n)
  19044. "Change timestamps synchronously up in CLOCK log lines.
  19045. Optional argument N tells to change by that many units."
  19046. (interactive "P")
  19047. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19048. (let (org-support-shift-select)
  19049. (org-clock-timestamps-up n))
  19050. (user-error "Not at a clock log")))
  19051. (defun org-shiftcontroldown (&optional n)
  19052. "Change timestamps synchronously down in CLOCK log lines.
  19053. Optional argument N tells to change by that many units."
  19054. (interactive "P")
  19055. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19056. (let (org-support-shift-select)
  19057. (org-clock-timestamps-down n))
  19058. (user-error "Not at a clock log")))
  19059. (defun org-increase-number-at-point (&optional inc)
  19060. "Increment the number at point.
  19061. With an optional prefix numeric argument INC, increment using
  19062. this numeric value."
  19063. (interactive "p")
  19064. (if (not (number-at-point))
  19065. (user-error "Not on a number")
  19066. (unless inc (setq inc 1))
  19067. (let ((pos (point))
  19068. (beg (skip-chars-backward "-+^/*0-9eE."))
  19069. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19070. (setq nap (buffer-substring-no-properties
  19071. (+ pos beg) (+ pos beg end)))
  19072. (delete-region (+ pos beg) (+ pos beg end))
  19073. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19074. (when (org-at-table-p)
  19075. (org-table-align)
  19076. (org-table-end-of-field 1))))
  19077. (defun org-decrease-number-at-point (&optional inc)
  19078. "Decrement the number at point.
  19079. With an optional prefix numeric argument INC, decrement using
  19080. this numeric value."
  19081. (interactive "p")
  19082. (org-increase-number-at-point (- (or inc 1))))
  19083. (defun org-ctrl-c-ret ()
  19084. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19085. (interactive)
  19086. (cond
  19087. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19088. (t (call-interactively 'org-insert-heading))))
  19089. (defun org-find-visible ()
  19090. (let ((s (point)))
  19091. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19092. (get-char-property s 'invisible)))
  19093. s))
  19094. (defun org-find-invisible ()
  19095. (let ((s (point)))
  19096. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19097. (not (get-char-property s 'invisible))))
  19098. s))
  19099. (defun org-copy-visible (beg end)
  19100. "Copy the visible parts of the region."
  19101. (interactive "r")
  19102. (let (snippets s)
  19103. (save-excursion
  19104. (save-restriction
  19105. (narrow-to-region beg end)
  19106. (setq s (goto-char (point-min)))
  19107. (while (not (= (point) (point-max)))
  19108. (goto-char (org-find-invisible))
  19109. (push (buffer-substring s (point)) snippets)
  19110. (setq s (goto-char (org-find-visible))))))
  19111. (kill-new (apply 'concat (nreverse snippets)))))
  19112. (defun org-copy-special ()
  19113. "Copy region in table or copy current subtree.
  19114. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19115. context. See the individual commands for more information."
  19116. (interactive)
  19117. (call-interactively
  19118. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19119. (defun org-cut-special ()
  19120. "Cut region in table or cut current subtree.
  19121. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19122. context. See the individual commands for more information."
  19123. (interactive)
  19124. (call-interactively
  19125. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19126. (defun org-paste-special (arg)
  19127. "Paste rectangular region into table, or past subtree relative to level.
  19128. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19129. See the individual commands for more information."
  19130. (interactive "P")
  19131. (if (org-at-table-p)
  19132. (org-table-paste-rectangle)
  19133. (org-paste-subtree arg)))
  19134. (defun org-edit-special (&optional arg)
  19135. "Call a special editor for the element at point.
  19136. When at a table, call the formula editor with `org-table-edit-formulas'.
  19137. When in a source code block, call `org-edit-src-code'.
  19138. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19139. When in an export block, call `org-edit-export-block'.
  19140. When at an #+INCLUDE keyword, visit the included file.
  19141. When at a footnote reference, call `org-edit-footnote-reference'
  19142. On a link, call `ffap' to visit the link at point.
  19143. Otherwise, return a user error."
  19144. (interactive "P")
  19145. (let ((element (org-element-at-point)))
  19146. (barf-if-buffer-read-only)
  19147. (pcase (org-element-type element)
  19148. (`src-block
  19149. (if (not arg) (org-edit-src-code)
  19150. (let* ((info (org-babel-get-src-block-info))
  19151. (lang (nth 0 info))
  19152. (params (nth 2 info))
  19153. (session (cdr (assq :session params))))
  19154. (if (not session) (org-edit-src-code)
  19155. ;; At a src-block with a session and function called with
  19156. ;; an ARG: switch to the buffer related to the inferior
  19157. ;; process.
  19158. (switch-to-buffer
  19159. (funcall (intern (concat "org-babel-prep-session:" lang))
  19160. session params))))))
  19161. (`keyword
  19162. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19163. (org-open-link-from-string
  19164. (format "[[%s]]"
  19165. (expand-file-name
  19166. (let ((value (org-element-property :value element)))
  19167. (cond ((not (org-string-nw-p value))
  19168. (user-error "No file to edit"))
  19169. ((string-match "\\`\"\\(.*?\\)\"" value)
  19170. (match-string 1 value))
  19171. ((string-match "\\`[^ \t\"]\\S-*" value)
  19172. (match-string 0 value))
  19173. (t (user-error "No valid file specified")))))))
  19174. (user-error "No special environment to edit here")))
  19175. (`table
  19176. (if (eq (org-element-property :type element) 'table.el)
  19177. (org-edit-table.el)
  19178. (call-interactively 'org-table-edit-formulas)))
  19179. ;; Only Org tables contain `table-row' type elements.
  19180. (`table-row (call-interactively 'org-table-edit-formulas))
  19181. (`example-block (org-edit-src-code))
  19182. (`export-block (org-edit-export-block))
  19183. (`fixed-width (org-edit-fixed-width-region))
  19184. (_
  19185. ;; No notable element at point. Though, we may be at a link or
  19186. ;; a footnote reference, which are objects. Thus, scan deeper.
  19187. (let ((context (org-element-context element)))
  19188. (pcase (org-element-type context)
  19189. (`footnote-reference (org-edit-footnote-reference))
  19190. (`inline-src-block (org-edit-inline-src-code))
  19191. (`link (call-interactively #'ffap))
  19192. (_ (user-error "No special environment to edit here"))))))))
  19193. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19194. (defun org-ctrl-c-ctrl-c (&optional arg)
  19195. "Set tags in headline, or update according to changed information at point.
  19196. This command does many different things, depending on context:
  19197. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19198. this is what we do.
  19199. - If the cursor is on a statistics cookie, update it.
  19200. - If the cursor is in a headline, prompt for tags and insert them
  19201. into the current line, aligned to `org-tags-column'. When called
  19202. with prefix arg, realign all tags in the current buffer.
  19203. - If the cursor is in one of the special #+KEYWORD lines, this
  19204. triggers scanning the buffer for these lines and updating the
  19205. information.
  19206. - If the cursor is inside a table, realign the table. This command
  19207. works even if the automatic table editor has been turned off.
  19208. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19209. the entire table.
  19210. - If the cursor is at a footnote reference or definition, jump to
  19211. the corresponding definition or references, respectively.
  19212. - If the cursor is a the beginning of a dynamic block, update it.
  19213. - If the current buffer is a capture buffer, close note and file it.
  19214. - If the cursor is on a <<<target>>>, update radio targets and
  19215. corresponding links in this buffer.
  19216. - If the cursor is on a numbered item in a plain list, renumber the
  19217. ordered list.
  19218. - If the cursor is on a checkbox, toggle it.
  19219. - If the cursor is on a code block, evaluate it. The variable
  19220. `org-confirm-babel-evaluate' can be used to control prompting
  19221. before code block evaluation, by default every code block
  19222. evaluation requires confirmation. Code block evaluation can be
  19223. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19224. (interactive "P")
  19225. (cond
  19226. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19227. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19228. (org-remove-occur-highlights)
  19229. (message "Temporary highlights/overlays removed from current buffer"))
  19230. ((and (local-variable-p 'org-finish-function)
  19231. (fboundp org-finish-function))
  19232. (funcall org-finish-function))
  19233. ((org-babel-hash-at-point))
  19234. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19235. ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
  19236. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19237. (user-error
  19238. (substitute-command-keys
  19239. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19240. (t
  19241. (let* ((context
  19242. (org-element-lineage
  19243. (org-element-context)
  19244. ;; Limit to supported contexts.
  19245. '(babel-call clock dynamic-block footnote-definition
  19246. footnote-reference inline-babel-call inline-src-block
  19247. inlinetask item keyword node-property paragraph
  19248. plain-list property-drawer radio-target src-block
  19249. statistics-cookie table table-cell table-row
  19250. timestamp)
  19251. t))
  19252. (type (org-element-type context)))
  19253. ;; For convenience: at the first line of a paragraph on the same
  19254. ;; line as an item, apply function on that item instead.
  19255. (when (eq type 'paragraph)
  19256. (let ((parent (org-element-property :parent context)))
  19257. (when (and (eq (org-element-type parent) 'item)
  19258. (= (line-beginning-position)
  19259. (org-element-property :begin parent)))
  19260. (setq context parent)
  19261. (setq type 'item))))
  19262. ;; Act according to type of element or object at point.
  19263. (pcase type
  19264. ((or `babel-call `inline-babel-call)
  19265. (let ((info (org-babel-lob-get-info context)))
  19266. (when info (org-babel-execute-src-block nil info))))
  19267. (`clock (org-clock-update-time-maybe))
  19268. (`dynamic-block
  19269. (save-excursion
  19270. (goto-char (org-element-property :post-affiliated context))
  19271. (org-update-dblock)))
  19272. (`footnote-definition
  19273. (goto-char (org-element-property :post-affiliated context))
  19274. (call-interactively 'org-footnote-action))
  19275. (`footnote-reference (call-interactively #'org-footnote-action))
  19276. ((or `headline `inlinetask)
  19277. (save-excursion (goto-char (org-element-property :begin context))
  19278. (call-interactively #'org-set-tags)))
  19279. ((or `inline-src-block `src-block)
  19280. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19281. (org-babel-eval-wipe-error-buffer)
  19282. (org-babel-execute-src-block
  19283. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19284. (`item
  19285. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19286. ;; unconditionally, whereas `C-u' will toggle its presence.
  19287. ;; Without a universal argument, if the item has a checkbox,
  19288. ;; toggle it. Otherwise repair the list.
  19289. (let* ((box (org-element-property :checkbox context))
  19290. (struct (org-element-property :structure context))
  19291. (old-struct (copy-tree struct))
  19292. (parents (org-list-parents-alist struct))
  19293. (prevs (org-list-prevs-alist struct))
  19294. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19295. (org-list-set-checkbox
  19296. (org-element-property :begin context) struct
  19297. (cond ((equal arg '(16)) "[-]")
  19298. ((and (not box) (equal arg '(4))) "[ ]")
  19299. ((or (not box) (equal arg '(4))) nil)
  19300. ((eq box 'on) "[ ]")
  19301. (t "[X]")))
  19302. ;; Mimic `org-list-write-struct' but with grabbing a return
  19303. ;; value from `org-list-struct-fix-box'.
  19304. (org-list-struct-fix-ind struct parents 2)
  19305. (org-list-struct-fix-item-end struct)
  19306. (org-list-struct-fix-bul struct prevs)
  19307. (org-list-struct-fix-ind struct parents)
  19308. (let ((block-item
  19309. (org-list-struct-fix-box struct parents prevs orderedp)))
  19310. (if (and box (equal struct old-struct))
  19311. (if (equal arg '(16))
  19312. (message "Checkboxes already reset")
  19313. (user-error "Cannot toggle this checkbox: %s"
  19314. (if (eq box 'on)
  19315. "all subitems checked"
  19316. "unchecked subitems")))
  19317. (org-list-struct-apply-struct struct old-struct)
  19318. (org-update-checkbox-count-maybe))
  19319. (when block-item
  19320. (message "Checkboxes were removed due to empty box at line %d"
  19321. (org-current-line block-item))))))
  19322. (`keyword
  19323. (let ((org-inhibit-startup-visibility-stuff t)
  19324. (org-startup-align-all-tables nil))
  19325. (when (boundp 'org-table-coordinate-overlays)
  19326. (mapc #'delete-overlay org-table-coordinate-overlays)
  19327. (setq org-table-coordinate-overlays nil))
  19328. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19329. (message "Local setup has been refreshed"))
  19330. (`plain-list
  19331. ;; At a plain list, with a double C-u argument, set
  19332. ;; checkboxes of each item to "[-]", whereas a single one
  19333. ;; will toggle their presence according to the state of the
  19334. ;; first item in the list. Without an argument, repair the
  19335. ;; list.
  19336. (let* ((begin (org-element-property :contents-begin context))
  19337. (beginm (move-marker (make-marker) begin))
  19338. (struct (org-element-property :structure context))
  19339. (old-struct (copy-tree struct))
  19340. (first-box (save-excursion
  19341. (goto-char begin)
  19342. (looking-at org-list-full-item-re)
  19343. (match-string-no-properties 3)))
  19344. (new-box (cond ((equal arg '(16)) "[-]")
  19345. ((equal arg '(4)) (unless first-box "[ ]"))
  19346. ((equal first-box "[X]") "[ ]")
  19347. (t "[X]"))))
  19348. (cond
  19349. (arg
  19350. (dolist (pos
  19351. (org-list-get-all-items
  19352. begin struct (org-list-prevs-alist struct)))
  19353. (org-list-set-checkbox pos struct new-box)))
  19354. ((and first-box (eq (point) begin))
  19355. ;; For convenience, when point is at bol on the first
  19356. ;; item of the list and no argument is provided, simply
  19357. ;; toggle checkbox of that item, if any.
  19358. (org-list-set-checkbox begin struct new-box)))
  19359. (org-list-write-struct
  19360. struct (org-list-parents-alist struct) old-struct)
  19361. (org-update-checkbox-count-maybe)
  19362. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19363. ((or `property-drawer `node-property)
  19364. (call-interactively #'org-property-action))
  19365. (`radio-target
  19366. (call-interactively #'org-update-radio-target-regexp))
  19367. (`statistics-cookie
  19368. (call-interactively #'org-update-statistics-cookies))
  19369. ((or `table `table-cell `table-row)
  19370. ;; At a table, recalculate every field and align it. Also
  19371. ;; send the table if necessary. If the table has
  19372. ;; a `table.el' type, just give up. At a table row or cell,
  19373. ;; maybe recalculate line but always align table.
  19374. (if (eq (org-element-property :type context) 'table.el)
  19375. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19376. Use `\\[org-edit-special]' to edit table.el tables"))
  19377. (let ((org-enable-table-editor t))
  19378. (if (or (eq type 'table)
  19379. ;; Check if point is at a TBLFM line.
  19380. (and (eq type 'table-row)
  19381. (= (point) (org-element-property :end context))))
  19382. (save-excursion
  19383. (if (org-at-TBLFM-p)
  19384. (progn (require 'org-table)
  19385. (org-table-calc-current-TBLFM))
  19386. (goto-char (org-element-property :contents-begin context))
  19387. (org-call-with-arg 'org-table-recalculate (or arg t))
  19388. (orgtbl-send-table 'maybe)))
  19389. (org-table-maybe-eval-formula)
  19390. (cond (arg (call-interactively #'org-table-recalculate))
  19391. ((org-table-maybe-recalculate-line))
  19392. (t (org-table-align)))))))
  19393. (`timestamp (org-timestamp-change 0 'day))
  19394. ((and `nil (guard (org-at-heading-p)))
  19395. ;; When point is on an unsupported object type, we can miss
  19396. ;; the fact that it also is at a heading. Handle it here.
  19397. (call-interactively #'org-set-tags))
  19398. ((guard
  19399. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19400. (_
  19401. (user-error
  19402. (substitute-command-keys
  19403. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19404. (defun org-mode-restart ()
  19405. (interactive)
  19406. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19407. (funcall major-mode)
  19408. (hack-local-variables)
  19409. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19410. (org-indent-mode -1)))
  19411. (message "%s restarted" major-mode))
  19412. (defun org-kill-note-or-show-branches ()
  19413. "Abort storing current note, or call `outline-show-branches'."
  19414. (interactive)
  19415. (if (not org-finish-function)
  19416. (progn
  19417. (outline-hide-subtree)
  19418. (call-interactively 'outline-show-branches))
  19419. (let ((org-note-abort t))
  19420. (funcall org-finish-function))))
  19421. (defun org-delete-indentation (&optional arg)
  19422. "Join current line to previous and fix whitespace at join.
  19423. If previous line is a headline add to headline title. Otherwise
  19424. the function calls `delete-indentation'.
  19425. With a non-nil optional argument, join it to the following one."
  19426. (interactive "*P")
  19427. (if (save-excursion
  19428. (beginning-of-line (if arg 1 0))
  19429. (let ((case-fold-search nil))
  19430. (looking-at org-complex-heading-regexp)))
  19431. ;; At headline.
  19432. (let ((tags-column (when (match-beginning 5)
  19433. (save-excursion (goto-char (match-beginning 5))
  19434. (current-column))))
  19435. (string (concat " " (progn (when arg (forward-line 1))
  19436. (org-trim (delete-and-extract-region
  19437. (line-beginning-position)
  19438. (line-end-position)))))))
  19439. (unless (bobp) (delete-region (point) (1- (point))))
  19440. (goto-char (or (match-end 4)
  19441. (match-beginning 5)
  19442. (match-end 0)))
  19443. (skip-chars-backward " \t")
  19444. (save-excursion (insert string))
  19445. ;; Adjust alignment of tags.
  19446. (cond
  19447. ((not tags-column)) ;no tags
  19448. (org-auto-align-tags (org-set-tags nil t))
  19449. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19450. (delete-indentation arg)))
  19451. (defun org-open-line (n)
  19452. "Insert a new row in tables, call `open-line' elsewhere.
  19453. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19454. As a special case, when a document starts with a table, allow to
  19455. call `open-line' on the very first character."
  19456. (interactive "*p")
  19457. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19458. (org-table-insert-row)
  19459. (open-line n)))
  19460. (defun org-return (&optional indent)
  19461. "Goto next table row or insert a newline.
  19462. Calls `org-table-next-row' or `newline', depending on context.
  19463. When optional INDENT argument is non-nil, call
  19464. `newline-and-indent' instead of `newline'.
  19465. When `org-return-follows-link' is non-nil and point is on
  19466. a timestamp or a link, call `org-open-at-point'. However, it
  19467. will not happen if point is in a table or on a \"dead\"
  19468. object (e.g., within a comment). In these case, you need to use
  19469. `org-open-at-point' directly."
  19470. (interactive)
  19471. (let ((context (if org-return-follows-link (org-element-context)
  19472. (org-element-at-point))))
  19473. (cond
  19474. ;; In a table, call `org-table-next-row'.
  19475. ((or (and (eq (org-element-type context) 'table)
  19476. (>= (point) (org-element-property :contents-begin context))
  19477. (< (point) (org-element-property :contents-end context)))
  19478. (org-element-lineage context '(table-row table-cell) t))
  19479. (org-table-justify-field-maybe)
  19480. (call-interactively #'org-table-next-row))
  19481. ;; On a link or a timestamp, call `org-open-at-point' if
  19482. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19483. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19484. ((and org-return-follows-link
  19485. (or (org-in-regexp org-ts-regexp-both nil t)
  19486. (org-in-regexp org-tsr-regexp-both nil t)
  19487. (org-in-regexp org-any-link-re nil t)))
  19488. (call-interactively #'org-open-at-point))
  19489. ;; Insert newline in heading, but preserve tags.
  19490. ((and (not (bolp))
  19491. (save-excursion (beginning-of-line)
  19492. (let ((case-fold-search nil))
  19493. (looking-at org-complex-heading-regexp))))
  19494. ;; At headline. Split line. However, if point is on keyword,
  19495. ;; priority cookie or tags, do not break any of them: add
  19496. ;; a newline after the headline instead.
  19497. (let ((tags-column (and (match-beginning 5)
  19498. (save-excursion (goto-char (match-beginning 5))
  19499. (current-column))))
  19500. (string
  19501. (when (and (match-end 4) (org-point-in-group (point) 4))
  19502. (delete-and-extract-region (point) (match-end 4)))))
  19503. ;; Adjust tag alignment.
  19504. (cond
  19505. ((not (and tags-column string)))
  19506. (org-auto-align-tags (org-set-tags nil t))
  19507. (t (org--align-tags-here tags-column))) ;preserve tags column
  19508. (end-of-line)
  19509. (org-show-entry)
  19510. (if indent (newline-and-indent) (newline))
  19511. (when string (save-excursion (insert (org-trim string))))))
  19512. ;; In a list, make sure indenting keeps trailing text within.
  19513. ((and indent
  19514. (not (eolp))
  19515. (org-element-lineage context '(item)))
  19516. (let ((trailing-data
  19517. (delete-and-extract-region (point) (line-end-position))))
  19518. (newline-and-indent)
  19519. (save-excursion (insert trailing-data))))
  19520. (t (if indent (newline-and-indent) (newline))))))
  19521. (defun org-return-indent ()
  19522. "Goto next table row or insert a newline and indent.
  19523. Calls `org-table-next-row' or `newline-and-indent', depending on
  19524. context. See the individual commands for more information."
  19525. (interactive)
  19526. (org-return t))
  19527. (defun org-ctrl-c-star ()
  19528. "Compute table, or change heading status of lines.
  19529. Calls `org-table-recalculate' or `org-toggle-heading',
  19530. depending on context."
  19531. (interactive)
  19532. (cond
  19533. ((org-at-table-p)
  19534. (call-interactively 'org-table-recalculate))
  19535. (t
  19536. ;; Convert all lines in region to list items
  19537. (call-interactively 'org-toggle-heading))))
  19538. (defun org-ctrl-c-minus ()
  19539. "Insert separator line in table or modify bullet status of line.
  19540. Also turns a plain line or a region of lines into list items.
  19541. Calls `org-table-insert-hline', `org-toggle-item', or
  19542. `org-cycle-list-bullet', depending on context."
  19543. (interactive)
  19544. (cond
  19545. ((org-at-table-p)
  19546. (call-interactively 'org-table-insert-hline))
  19547. ((org-region-active-p)
  19548. (call-interactively 'org-toggle-item))
  19549. ((org-in-item-p)
  19550. (call-interactively 'org-cycle-list-bullet))
  19551. (t
  19552. (call-interactively 'org-toggle-item))))
  19553. (defun org-toggle-heading (&optional nstars)
  19554. "Convert headings to normal text, or items or text to headings.
  19555. If there is no active region, only convert the current line.
  19556. With a `\\[universal-argument]' prefix, convert the whole list at
  19557. point into heading.
  19558. In a region:
  19559. - If the first non blank line is a headline, remove the stars
  19560. from all headlines in the region.
  19561. - If it is a normal line, turn each and every normal line (i.e.,
  19562. not an heading or an item) in the region into headings. If you
  19563. want to convert only the first line of this region, use one
  19564. universal prefix argument.
  19565. - If it is a plain list item, turn all plain list items into headings.
  19566. When converting a line into a heading, the number of stars is chosen
  19567. such that the lines become children of the current entry. However,
  19568. when a numeric prefix argument is given, its value determines the
  19569. number of stars to add."
  19570. (interactive "P")
  19571. (let ((skip-blanks
  19572. (function
  19573. ;; Return beginning of first non-blank line, starting from
  19574. ;; line at POS.
  19575. (lambda (pos)
  19576. (save-excursion
  19577. (goto-char pos)
  19578. (while (org-at-comment-p) (forward-line))
  19579. (skip-chars-forward " \r\t\n")
  19580. (point-at-bol)))))
  19581. beg end toggled)
  19582. ;; Determine boundaries of changes. If a universal prefix has
  19583. ;; been given, put the list in a region. If region ends at a bol,
  19584. ;; do not consider the last line to be in the region.
  19585. (when (and current-prefix-arg (org-at-item-p))
  19586. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19587. (org-mark-element))
  19588. (if (org-region-active-p)
  19589. (setq beg (funcall skip-blanks (region-beginning))
  19590. end (copy-marker (save-excursion
  19591. (goto-char (region-end))
  19592. (if (bolp) (point) (point-at-eol)))))
  19593. (setq beg (funcall skip-blanks (point-at-bol))
  19594. end (copy-marker (point-at-eol))))
  19595. ;; Ensure inline tasks don't count as headings.
  19596. (org-with-limited-levels
  19597. (save-excursion
  19598. (goto-char beg)
  19599. (cond
  19600. ;; Case 1. Started at an heading: de-star headings.
  19601. ((org-at-heading-p)
  19602. (while (< (point) end)
  19603. (when (org-at-heading-p t)
  19604. (looking-at org-outline-regexp) (replace-match "")
  19605. (setq toggled t))
  19606. (forward-line)))
  19607. ;; Case 2. Started at an item: change items into headlines.
  19608. ;; One star will be added by `org-list-to-subtree'.
  19609. ((org-at-item-p)
  19610. (while (< (point) end)
  19611. (when (org-at-item-p)
  19612. ;; Pay attention to cases when region ends before list.
  19613. (let* ((struct (org-list-struct))
  19614. (list-end
  19615. (min (org-list-get-bottom-point struct) (1+ end))))
  19616. (save-restriction
  19617. (narrow-to-region (point) list-end)
  19618. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19619. (setq toggled t))
  19620. (forward-line)))
  19621. ;; Case 3. Started at normal text: make every line an heading,
  19622. ;; skipping headlines and items.
  19623. (t (let* ((stars
  19624. (make-string
  19625. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19626. (add-stars
  19627. (cond (nstars "") ; stars from prefix only
  19628. ((equal stars "") "*") ; before first heading
  19629. (org-odd-levels-only "**") ; inside heading, odd
  19630. (t "*"))) ; inside heading, oddeven
  19631. (rpl (concat stars add-stars " "))
  19632. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19633. (while (< (point) (if (equal nstars '(4)) lend end))
  19634. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19635. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19636. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19637. (forward-line)))))))
  19638. (unless toggled (message "Cannot toggle heading from here"))))
  19639. (defun org-meta-return (&optional arg)
  19640. "Insert a new heading or wrap a region in a table.
  19641. Calls `org-insert-heading', `org-insert-item' or
  19642. `org-table-wrap-region', depending on context. When called with
  19643. an argument, unconditionally call `org-insert-heading'."
  19644. (interactive "P")
  19645. (org-check-before-invisible-edit 'insert)
  19646. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19647. (call-interactively (cond (arg #'org-insert-heading)
  19648. ((org-at-table-p) #'org-table-wrap-region)
  19649. ((org-in-item-p) #'org-insert-item)
  19650. (t #'org-insert-heading)))))
  19651. ;;; Menu entries
  19652. (defsubst org-in-subtree-not-table-p ()
  19653. "Are we in a subtree and not in a table?"
  19654. (and (not (org-before-first-heading-p))
  19655. (not (org-at-table-p))))
  19656. ;; Define the Org mode menus
  19657. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19658. '("Tbl"
  19659. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19660. ["Next Field" org-cycle (org-at-table-p)]
  19661. ["Previous Field" org-shifttab (org-at-table-p)]
  19662. ["Next Row" org-return (org-at-table-p)]
  19663. "--"
  19664. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19665. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19666. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19667. "--"
  19668. ("Column"
  19669. ["Move Column Left" org-metaleft (org-at-table-p)]
  19670. ["Move Column Right" org-metaright (org-at-table-p)]
  19671. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19672. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19673. ("Row"
  19674. ["Move Row Up" org-metaup (org-at-table-p)]
  19675. ["Move Row Down" org-metadown (org-at-table-p)]
  19676. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19677. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19678. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19679. "--"
  19680. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19681. ("Rectangle"
  19682. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19683. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19684. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19685. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19686. "--"
  19687. ("Calculate"
  19688. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19689. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19690. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19691. "--"
  19692. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19693. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19694. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19695. "--"
  19696. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19697. "--"
  19698. ["Sum Column/Rectangle" org-table-sum
  19699. (or (org-at-table-p) (org-region-active-p))]
  19700. ["Which Column?" org-table-current-column (org-at-table-p)])
  19701. ["Debug Formulas"
  19702. org-table-toggle-formula-debugger
  19703. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19704. ["Show Col/Row Numbers"
  19705. org-table-toggle-coordinate-overlays
  19706. :style toggle
  19707. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19708. "--"
  19709. ["Create" org-table-create (and (not (org-at-table-p))
  19710. org-enable-table-editor)]
  19711. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19712. ["Import from File" org-table-import (not (org-at-table-p))]
  19713. ["Export to File" org-table-export (org-at-table-p)]
  19714. "--"
  19715. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19716. "--"
  19717. ("Plot"
  19718. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19719. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19720. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19721. '("Org"
  19722. ("Show/Hide"
  19723. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19724. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19725. ["Sparse Tree..." org-sparse-tree t]
  19726. ["Reveal Context" org-reveal t]
  19727. ["Show All" outline-show-all t]
  19728. "--"
  19729. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19730. "--"
  19731. ["New Heading" org-insert-heading t]
  19732. ("Navigate Headings"
  19733. ["Up" outline-up-heading t]
  19734. ["Next" outline-next-visible-heading t]
  19735. ["Previous" outline-previous-visible-heading t]
  19736. ["Next Same Level" outline-forward-same-level t]
  19737. ["Previous Same Level" outline-backward-same-level t]
  19738. "--"
  19739. ["Jump" org-goto t])
  19740. ("Edit Structure"
  19741. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19742. "--"
  19743. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19744. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19745. "--"
  19746. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19747. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19748. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19749. "--"
  19750. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19751. "--"
  19752. ["Copy visible text" org-copy-visible t]
  19753. "--"
  19754. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19755. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19756. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19757. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19758. "--"
  19759. ["Sort Region/Children" org-sort t]
  19760. "--"
  19761. ["Convert to odd levels" org-convert-to-odd-levels t]
  19762. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19763. ("Editing"
  19764. ["Emphasis..." org-emphasize t]
  19765. ["Edit Source Example" org-edit-special t]
  19766. "--"
  19767. ["Footnote new/jump" org-footnote-action t]
  19768. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19769. ("Archive"
  19770. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19771. "--"
  19772. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19773. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19774. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19775. )
  19776. "--"
  19777. ("Hyperlinks"
  19778. ["Store Link (Global)" org-store-link t]
  19779. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19780. ["Insert Link" org-insert-link t]
  19781. ["Follow Link" org-open-at-point t]
  19782. "--"
  19783. ["Next link" org-next-link t]
  19784. ["Previous link" org-previous-link t]
  19785. "--"
  19786. ["Descriptive Links"
  19787. org-toggle-link-display
  19788. :style radio
  19789. :selected org-descriptive-links
  19790. ]
  19791. ["Literal Links"
  19792. org-toggle-link-display
  19793. :style radio
  19794. :selected (not org-descriptive-links)])
  19795. "--"
  19796. ("TODO Lists"
  19797. ["TODO/DONE/-" org-todo t]
  19798. ("Select keyword"
  19799. ["Next keyword" org-shiftright (org-at-heading-p)]
  19800. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19801. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19802. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19803. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19804. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19805. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19806. "--"
  19807. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19808. :selected org-enforce-todo-dependencies :style toggle :active t]
  19809. "Settings for tree at point"
  19810. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19811. :selected (org-entry-get nil "ORDERED")
  19812. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19813. ["Do Children parallel" org-toggle-ordered-property :style radio
  19814. :selected (not (org-entry-get nil "ORDERED"))
  19815. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19816. "--"
  19817. ["Set Priority" org-priority t]
  19818. ["Priority Up" org-shiftup t]
  19819. ["Priority Down" org-shiftdown t]
  19820. "--"
  19821. ["Get news from all feeds" org-feed-update-all t]
  19822. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19823. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19824. ("TAGS and Properties"
  19825. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19826. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19827. "--"
  19828. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19829. ["Column view of properties" org-columns t]
  19830. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19831. ("Dates and Scheduling"
  19832. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19833. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19834. ("Change Date"
  19835. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19836. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19837. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19838. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19839. ["Compute Time Range" org-evaluate-time-range t]
  19840. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19841. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19842. "--"
  19843. ["Custom time format" org-toggle-time-stamp-overlays
  19844. :style radio :selected org-display-custom-times]
  19845. "--"
  19846. ["Goto Calendar" org-goto-calendar t]
  19847. ["Date from Calendar" org-date-from-calendar t]
  19848. "--"
  19849. ["Start/Restart Timer" org-timer-start t]
  19850. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19851. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19852. ["Insert Timer String" org-timer t]
  19853. ["Insert Timer Item" org-timer-item t])
  19854. ("Logging work"
  19855. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19856. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19857. ["Clock out" org-clock-out t]
  19858. ["Clock cancel" org-clock-cancel t]
  19859. "--"
  19860. ["Mark as default task" org-clock-mark-default-task t]
  19861. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19862. ["Goto running clock" org-clock-goto t]
  19863. "--"
  19864. ["Display times" org-clock-display t]
  19865. ["Create clock table" org-clock-report t]
  19866. "--"
  19867. ["Record DONE time"
  19868. (progn (setq org-log-done (not org-log-done))
  19869. (message "Switching to %s will %s record a timestamp"
  19870. (car org-done-keywords)
  19871. (if org-log-done "automatically" "not")))
  19872. :style toggle :selected org-log-done])
  19873. "--"
  19874. ["Agenda Command..." org-agenda t]
  19875. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19876. ("File List for Agenda")
  19877. ("Special views current file"
  19878. ["TODO Tree" org-show-todo-tree t]
  19879. ["Check Deadlines" org-check-deadlines t]
  19880. ["Tags/Property tree" org-match-sparse-tree t])
  19881. "--"
  19882. ["Export/Publish..." org-export-dispatch t]
  19883. ("LaTeX"
  19884. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19885. :selected org-cdlatex-mode]
  19886. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19887. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19888. ["Modify math symbol" org-cdlatex-math-modify
  19889. (org-inside-LaTeX-fragment-p)]
  19890. ["Insert citation" org-reftex-citation t])
  19891. "--"
  19892. ("MobileOrg"
  19893. ["Push Files and Views" org-mobile-push t]
  19894. ["Get Captured and Flagged" org-mobile-pull t]
  19895. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19896. "--"
  19897. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19898. "--"
  19899. ("Documentation"
  19900. ["Show Version" org-version t]
  19901. ["Info Documentation" org-info t])
  19902. ("Customize"
  19903. ["Browse Org Group" org-customize t]
  19904. "--"
  19905. ["Expand This Menu" org-create-customize-menu
  19906. (fboundp 'customize-menu-create)])
  19907. ["Send bug report" org-submit-bug-report t]
  19908. "--"
  19909. ("Refresh/Reload"
  19910. ["Refresh setup current buffer" org-mode-restart t]
  19911. ["Reload Org (after update)" org-reload t]
  19912. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19913. ))
  19914. (defun org-info (&optional node)
  19915. "Read documentation for Org in the info system.
  19916. With optional NODE, go directly to that node."
  19917. (interactive)
  19918. (info (format "(org)%s" (or node ""))))
  19919. ;;;###autoload
  19920. (defun org-submit-bug-report ()
  19921. "Submit a bug report on Org via mail.
  19922. Don't hesitate to report any problems or inaccurate documentation.
  19923. If you don't have setup sending mail from (X)Emacs, please copy the
  19924. output buffer into your mail program, as it gives us important
  19925. information about your Org version and configuration."
  19926. (interactive)
  19927. (require 'reporter)
  19928. (defvar reporter-prompt-for-summary-p)
  19929. (org-load-modules-maybe)
  19930. (org-require-autoloaded-modules)
  19931. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19932. (reporter-submit-bug-report
  19933. "emacs-orgmode@gnu.org"
  19934. (org-version nil 'full)
  19935. (let (list)
  19936. (save-window-excursion
  19937. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19938. (delete-other-windows)
  19939. (erase-buffer)
  19940. (insert "You are about to submit a bug report to the Org mailing list.
  19941. We would like to add your full Org and Outline configuration to the
  19942. bug report. This greatly simplifies the work of the maintainer and
  19943. other experts on the mailing list.
  19944. HOWEVER, some variables you have customized may contain private
  19945. information. The names of customers, colleagues, or friends, might
  19946. appear in the form of file names, tags, todo states, or search strings.
  19947. If you answer yes to the prompt, you might want to check and remove
  19948. such private information before sending the email.")
  19949. (add-text-properties (point-min) (point-max) '(face org-warning))
  19950. (when (yes-or-no-p "Include your Org configuration ")
  19951. (mapatoms
  19952. (lambda (v)
  19953. (and (boundp v)
  19954. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19955. (or (and (symbol-value v)
  19956. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19957. (and
  19958. (get v 'custom-type) (get v 'standard-value)
  19959. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19960. (push v list)))))
  19961. (kill-buffer (get-buffer "*Warn about privacy*"))
  19962. list))
  19963. nil nil
  19964. "Remember to cover the basics, that is, what you expected to happen and
  19965. what in fact did happen. You don't know how to make a good report? See
  19966. http://orgmode.org/manual/Feedback.html#Feedback
  19967. Your bug report will be posted to the Org mailing list.
  19968. ------------------------------------------------------------------------")
  19969. (save-excursion
  19970. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19971. (replace-match "\\1Bug: \\3 [\\2]")))))
  19972. (defun org-install-agenda-files-menu ()
  19973. (let ((bl (buffer-list)))
  19974. (save-excursion
  19975. (while bl
  19976. (set-buffer (pop bl))
  19977. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19978. (when (derived-mode-p 'org-mode)
  19979. (easy-menu-change
  19980. '("Org") "File List for Agenda"
  19981. (append
  19982. (list
  19983. ["Edit File List" (org-edit-agenda-file-list) t]
  19984. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19985. ["Remove Current File from List" org-remove-file t]
  19986. ["Cycle through agenda files" org-cycle-agenda-files t]
  19987. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19988. "--")
  19989. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19990. ;;;; Documentation
  19991. (defun org-require-autoloaded-modules ()
  19992. (interactive)
  19993. (mapc #'require
  19994. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19995. org-table org-timer)))
  19996. ;;;###autoload
  19997. (defun org-reload (&optional uncompiled)
  19998. "Reload all org lisp files.
  19999. With prefix arg UNCOMPILED, load the uncompiled versions."
  20000. (interactive "P")
  20001. (require 'loadhist)
  20002. (let* ((org-dir (org-find-library-dir "org"))
  20003. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20004. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20005. (remove-re (format "\\`%s\\'"
  20006. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20007. (feats (delete-dups
  20008. (mapcar 'file-name-sans-extension
  20009. (mapcar 'file-name-nondirectory
  20010. (delq nil
  20011. (mapcar 'feature-file
  20012. features))))))
  20013. (lfeat (append
  20014. (sort
  20015. (setq feats
  20016. (delq nil (mapcar
  20017. (lambda (f)
  20018. (if (and (string-match feature-re f)
  20019. (not (string-match remove-re f)))
  20020. f nil))
  20021. feats)))
  20022. 'string-lessp)
  20023. (list "org-version" "org")))
  20024. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20025. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20026. load-uncore load-misses)
  20027. (setq load-misses
  20028. (delq 't
  20029. (mapcar (lambda (f)
  20030. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20031. (and (string= org-dir contrib-dir)
  20032. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20033. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20034. (add-to-list 'load-uncore f 'append)
  20035. 't)
  20036. f))
  20037. lfeat)))
  20038. (when load-uncore
  20039. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20040. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20041. (if load-misses
  20042. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20043. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20044. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20045. ;;;###autoload
  20046. (defun org-customize ()
  20047. "Call the customize function with org as argument."
  20048. (interactive)
  20049. (org-load-modules-maybe)
  20050. (org-require-autoloaded-modules)
  20051. (customize-browse 'org))
  20052. (defun org-create-customize-menu ()
  20053. "Create a full customization menu for Org mode, insert it into the menu."
  20054. (interactive)
  20055. (org-load-modules-maybe)
  20056. (org-require-autoloaded-modules)
  20057. (if (fboundp 'customize-menu-create)
  20058. (progn
  20059. (easy-menu-change
  20060. '("Org") "Customize"
  20061. `(["Browse Org group" org-customize t]
  20062. "--"
  20063. ,(customize-menu-create 'org)
  20064. ["Set" Custom-set t]
  20065. ["Save" Custom-save t]
  20066. ["Reset to Current" Custom-reset-current t]
  20067. ["Reset to Saved" Custom-reset-saved t]
  20068. ["Reset to Standard Settings" Custom-reset-standard t]))
  20069. (message "\"Org\"-menu now contains full customization menu"))
  20070. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20071. ;;;; Miscellaneous stuff
  20072. ;;; Generally useful functions
  20073. (defun org-get-at-eol (property n)
  20074. "Get text property PROPERTY at the end of line less N characters."
  20075. (get-text-property (- (point-at-eol) n) property))
  20076. (defun org-find-text-property-in-string (prop s)
  20077. "Return the first non-nil value of property PROP in string S."
  20078. (or (get-text-property 0 prop s)
  20079. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20080. prop s)))
  20081. (defun org-display-warning (message)
  20082. "Display the given MESSAGE as a warning."
  20083. (display-warning 'org message :warning))
  20084. (defun org-eval (form)
  20085. "Eval FORM and return result."
  20086. (condition-case error
  20087. (eval form)
  20088. (error (format "%%![Error: %s]" error))))
  20089. (defun org-in-clocktable-p ()
  20090. "Check if the cursor is in a clocktable."
  20091. (let ((pos (point)) start)
  20092. (save-excursion
  20093. (end-of-line 1)
  20094. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20095. (setq start (match-beginning 0))
  20096. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20097. (>= (match-end 0) pos)
  20098. start))))
  20099. (defun org-in-verbatim-emphasis ()
  20100. (save-match-data
  20101. (and (org-in-regexp org-verbatim-re 2)
  20102. (>= (point) (match-beginning 3))
  20103. (<= (point) (match-end 4)))))
  20104. (defun org-overlay-display (ovl text &optional face evap)
  20105. "Make overlay OVL display TEXT with face FACE."
  20106. (overlay-put ovl 'display text)
  20107. (if face (overlay-put ovl 'face face))
  20108. (if evap (overlay-put ovl 'evaporate t)))
  20109. (defun org-overlay-before-string (ovl text &optional face evap)
  20110. "Make overlay OVL display TEXT with face FACE."
  20111. (if face (org-add-props text nil 'face face))
  20112. (overlay-put ovl 'before-string text)
  20113. (if evap (overlay-put ovl 'evaporate t)))
  20114. (defun org-find-overlays (prop &optional pos delete)
  20115. "Find all overlays specifying PROP at POS or point.
  20116. If DELETE is non-nil, delete all those overlays."
  20117. (let (found)
  20118. (dolist (ov (overlays-at (or pos (point))) found)
  20119. (cond ((not (overlay-get ov prop)))
  20120. (delete (delete-overlay ov))
  20121. (t (push ov found))))))
  20122. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20123. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20124. (if (and marker (marker-buffer marker)
  20125. (buffer-live-p (marker-buffer marker)))
  20126. (progn
  20127. (pop-to-buffer-same-window (marker-buffer marker))
  20128. (when (or (> marker (point-max)) (< marker (point-min)))
  20129. (widen))
  20130. (goto-char marker)
  20131. (org-show-context 'org-goto))
  20132. (if bookmark
  20133. (bookmark-jump bookmark)
  20134. (error "Cannot find location"))))
  20135. (defun org-quote-csv-field (s)
  20136. "Quote field for inclusion in CSV material."
  20137. (if (string-match "[\",]" s)
  20138. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20139. s))
  20140. (defun org-force-self-insert (N)
  20141. "Needed to enforce self-insert under remapping."
  20142. (interactive "p")
  20143. (self-insert-command N))
  20144. (defun org-string-width (s)
  20145. "Compute width of string, ignoring invisible characters.
  20146. This ignores character with invisibility property `org-link', and also
  20147. characters with property `org-cwidth', because these will become invisible
  20148. upon the next fontification round."
  20149. (let (b l)
  20150. (when (or (eq t buffer-invisibility-spec)
  20151. (assq 'org-link buffer-invisibility-spec))
  20152. (while (setq b (text-property-any 0 (length s)
  20153. 'invisible 'org-link s))
  20154. (setq s (concat (substring s 0 b)
  20155. (substring s (or (next-single-property-change
  20156. b 'invisible s)
  20157. (length s)))))))
  20158. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20159. (setq s (concat (substring s 0 b)
  20160. (substring s (or (next-single-property-change
  20161. b 'org-cwidth s)
  20162. (length s))))))
  20163. (setq l (string-width s) b -1)
  20164. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20165. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20166. l))
  20167. (defun org-shorten-string (s maxlength)
  20168. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20169. If the string is shorter or has length MAXLENGTH, just return the
  20170. original string. If it is longer, the functions finds a space in the
  20171. string, breaks this string off at that locations and adds three dots
  20172. as ellipsis. Including the ellipsis, the string will not be longer
  20173. than MAXLENGTH. If finding a good breaking point in the string does
  20174. not work, the string is just chopped off in the middle of a word
  20175. if necessary."
  20176. (if (<= (length s) maxlength)
  20177. s
  20178. (let* ((n (max (- maxlength 4) 1))
  20179. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20180. (if (string-match re s)
  20181. (concat (match-string 1 s) "...")
  20182. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20183. (defun org-get-indentation (&optional line)
  20184. "Get the indentation of the current line, interpreting tabs.
  20185. When LINE is given, assume it represents a line and compute its indentation."
  20186. (if line
  20187. (when (string-match "^ *" (org-remove-tabs line))
  20188. (match-end 0))
  20189. (save-excursion
  20190. (beginning-of-line 1)
  20191. (skip-chars-forward " \t")
  20192. (current-column))))
  20193. (defun org-get-string-indentation (s)
  20194. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20195. (let ((n -1) (i 0) (w tab-width) c)
  20196. (catch 'exit
  20197. (while (< (setq n (1+ n)) (length s))
  20198. (setq c (aref s n))
  20199. (cond ((= c ?\ ) (setq i (1+ i)))
  20200. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20201. (t (throw 'exit t)))))
  20202. i))
  20203. (defun org-remove-tabs (s &optional width)
  20204. "Replace tabulators in S with spaces.
  20205. Assumes that s is a single line, starting in column 0."
  20206. (setq width (or width tab-width))
  20207. (while (string-match "\t" s)
  20208. (setq s (replace-match
  20209. (make-string
  20210. (- (* width (/ (+ (match-beginning 0) width) width))
  20211. (match-beginning 0)) ?\ )
  20212. t t s)))
  20213. s)
  20214. (defun org-fix-indentation (line ind)
  20215. "Fix indentation in LINE.
  20216. IND is a cons cell with target and minimum indentation.
  20217. If the current indentation in LINE is smaller than the minimum,
  20218. leave it alone. If it is larger than ind, set it to the target."
  20219. (let* ((l (org-remove-tabs line))
  20220. (i (org-get-indentation l))
  20221. (i1 (car ind)) (i2 (cdr ind)))
  20222. (when (>= i i2) (setq l (substring line i2)))
  20223. (if (> i1 0)
  20224. (concat (make-string i1 ?\ ) l)
  20225. l)))
  20226. (defun org-remove-indentation (code &optional n)
  20227. "Remove maximum common indentation in string CODE and return it.
  20228. N may optionally be the number of columns to remove. Return CODE
  20229. as-is if removal failed."
  20230. (with-temp-buffer
  20231. (insert code)
  20232. (if (org-do-remove-indentation n) (buffer-string) code)))
  20233. (defun org-do-remove-indentation (&optional n)
  20234. "Remove the maximum common indentation from the buffer.
  20235. When optional argument N is a positive integer, remove exactly
  20236. that much characters from indentation, if possible. Return nil
  20237. if it fails."
  20238. (catch :exit
  20239. (goto-char (point-min))
  20240. ;; Find maximum common indentation, if not specified.
  20241. (let ((n (or n
  20242. (let ((min-ind (point-max)))
  20243. (save-excursion
  20244. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20245. (let ((ind (1- (current-column))))
  20246. (if (zerop ind) (throw :exit nil)
  20247. (setq min-ind (min min-ind ind))))))
  20248. min-ind))))
  20249. (if (zerop n) (throw :exit nil)
  20250. ;; Remove exactly N indentation, but give up if not possible.
  20251. (while (not (eobp))
  20252. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20253. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20254. ((< ind n) (throw :exit nil))
  20255. (t (indent-line-to (- ind n))))
  20256. (forward-line)))
  20257. ;; Signal success.
  20258. t))))
  20259. (defun org-fill-template (template alist)
  20260. "Find each %key of ALIST in TEMPLATE and replace it."
  20261. (let ((case-fold-search nil))
  20262. (dolist (entry (sort (copy-sequence alist)
  20263. (lambda (a b) (< (length (car a)) (length (car b))))))
  20264. (setq template
  20265. (replace-regexp-in-string
  20266. (concat "%" (regexp-quote (car entry)))
  20267. (or (cdr entry) "") template t t)))
  20268. template))
  20269. (defun org-base-buffer (buffer)
  20270. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20271. (if (not buffer)
  20272. buffer
  20273. (or (buffer-base-buffer buffer)
  20274. buffer)))
  20275. (defun org-wrap (string &optional width lines)
  20276. "Wrap string to either a number of lines, or a width in characters.
  20277. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20278. that costs. If there is a word longer than WIDTH, the text is actually
  20279. wrapped to the length of that word.
  20280. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20281. many lines, whatever width that takes.
  20282. The return value is a list of lines, without newlines at the end."
  20283. (let* ((words (org-split-string string "[ \t\n]+"))
  20284. (maxword (apply 'max (mapcar 'org-string-width words)))
  20285. w ll)
  20286. (cond (width
  20287. (org-do-wrap words (max maxword width)))
  20288. (lines
  20289. (setq w maxword)
  20290. (setq ll (org-do-wrap words maxword))
  20291. (if (<= (length ll) lines)
  20292. ll
  20293. (setq ll words)
  20294. (while (> (length ll) lines)
  20295. (setq w (1+ w))
  20296. (setq ll (org-do-wrap words w)))
  20297. ll))
  20298. (t (error "Cannot wrap this")))))
  20299. (defun org-do-wrap (words width)
  20300. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20301. (let (lines line)
  20302. (while words
  20303. (setq line (pop words))
  20304. (while (and words (< (+ (length line) (length (car words))) width))
  20305. (setq line (concat line " " (pop words))))
  20306. (setq lines (push line lines)))
  20307. (nreverse lines)))
  20308. (defun org-split-string (string &optional separators)
  20309. "Splits STRING into substrings at SEPARATORS.
  20310. SEPARATORS is a regular expression.
  20311. No empty strings are returned if there are matches at the beginning
  20312. and end of string."
  20313. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20314. (let ((start 0) notfirst list)
  20315. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20316. (if (and notfirst
  20317. (= start (match-beginning 0))
  20318. (< start (length string)))
  20319. (1+ start) start))
  20320. (< (match-beginning 0) (length string)))
  20321. (setq notfirst t)
  20322. (or (eq (match-beginning 0) 0)
  20323. (and (eq (match-beginning 0) (match-end 0))
  20324. (eq (match-beginning 0) start))
  20325. (push (substring string start (match-beginning 0)) list))
  20326. (setq start (match-end 0)))
  20327. (or (eq start (length string))
  20328. (push (substring string start) list))
  20329. (nreverse list)))
  20330. (defun org-quote-vert (s)
  20331. "Replace \"|\" with \"\\vert\"."
  20332. (while (string-match "|" s)
  20333. (setq s (replace-match "\\vert" t t s)))
  20334. s)
  20335. (defun org-uuidgen-p (s)
  20336. "Is S an ID created by UUIDGEN?"
  20337. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20338. (defun org-in-src-block-p (&optional inside)
  20339. "Whether point is in a code source block.
  20340. When INSIDE is non-nil, don't consider we are within a src block
  20341. when point is at #+BEGIN_SRC or #+END_SRC."
  20342. (let ((case-fold-search t))
  20343. (or (and (eq (get-char-property (point) 'src-block) t))
  20344. (and (not inside)
  20345. (save-match-data
  20346. (save-excursion
  20347. (beginning-of-line)
  20348. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20349. (defun org-context ()
  20350. "Return a list of contexts of the current cursor position.
  20351. If several contexts apply, all are returned.
  20352. Each context entry is a list with a symbol naming the context, and
  20353. two positions indicating start and end of the context. Possible
  20354. contexts are:
  20355. :headline anywhere in a headline
  20356. :headline-stars on the leading stars in a headline
  20357. :todo-keyword on a TODO keyword (including DONE) in a headline
  20358. :tags on the TAGS in a headline
  20359. :priority on the priority cookie in a headline
  20360. :item on the first line of a plain list item
  20361. :item-bullet on the bullet/number of a plain list item
  20362. :checkbox on the checkbox in a plain list item
  20363. :table in an Org table
  20364. :table-special on a special filed in a table
  20365. :table-table in a table.el table
  20366. :clocktable in a clocktable
  20367. :src-block in a source block
  20368. :link on a hyperlink
  20369. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20370. :target on a <<target>>
  20371. :radio-target on a <<<radio-target>>>
  20372. :latex-fragment on a LaTeX fragment
  20373. :latex-preview on a LaTeX fragment with overlaid preview image
  20374. This function expects the position to be visible because it uses font-lock
  20375. faces as a help to recognize the following contexts: :table-special, :link,
  20376. and :keyword."
  20377. (let* ((f (get-text-property (point) 'face))
  20378. (faces (if (listp f) f (list f)))
  20379. (case-fold-search t)
  20380. (p (point)) clist o)
  20381. ;; First the large context
  20382. (cond
  20383. ((org-at-heading-p t)
  20384. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20385. (when (progn
  20386. (beginning-of-line 1)
  20387. (looking-at org-todo-line-tags-regexp))
  20388. (push (org-point-in-group p 1 :headline-stars) clist)
  20389. (push (org-point-in-group p 2 :todo-keyword) clist)
  20390. (push (org-point-in-group p 4 :tags) clist))
  20391. (goto-char p)
  20392. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20393. (when (looking-at "\\[#[A-Z0-9]\\]")
  20394. (push (org-point-in-group p 0 :priority) clist)))
  20395. ((org-at-item-p)
  20396. (push (org-point-in-group p 2 :item-bullet) clist)
  20397. (push (list :item (point-at-bol)
  20398. (save-excursion (org-end-of-item) (point)))
  20399. clist)
  20400. (and (org-at-item-checkbox-p)
  20401. (push (org-point-in-group p 0 :checkbox) clist)))
  20402. ((org-at-table-p)
  20403. (push (list :table (org-table-begin) (org-table-end)) clist)
  20404. (when (memq 'org-formula faces)
  20405. (push (list :table-special
  20406. (previous-single-property-change p 'face)
  20407. (next-single-property-change p 'face)) clist)))
  20408. ((org-at-table-p 'any)
  20409. (push (list :table-table) clist)))
  20410. (goto-char p)
  20411. (let ((case-fold-search t))
  20412. ;; New the "medium" contexts: clocktables, source blocks
  20413. (cond ((org-in-clocktable-p)
  20414. (push (list :clocktable
  20415. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20416. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20417. (match-beginning 1))
  20418. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20419. (match-end 0))) clist))
  20420. ((org-in-src-block-p)
  20421. (push (list :src-block
  20422. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20423. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20424. (match-beginning 1))
  20425. (and (search-forward "#+END_SRC" nil t)
  20426. (match-beginning 0))) clist))))
  20427. (goto-char p)
  20428. ;; Now the small context
  20429. (cond
  20430. ((org-at-timestamp-p)
  20431. (push (org-point-in-group p 0 :timestamp) clist))
  20432. ((memq 'org-link faces)
  20433. (push (list :link
  20434. (previous-single-property-change p 'face)
  20435. (next-single-property-change p 'face)) clist))
  20436. ((memq 'org-special-keyword faces)
  20437. (push (list :keyword
  20438. (previous-single-property-change p 'face)
  20439. (next-single-property-change p 'face)) clist))
  20440. ((org-at-target-p)
  20441. (push (org-point-in-group p 0 :target) clist)
  20442. (goto-char (1- (match-beginning 0)))
  20443. (when (looking-at org-radio-target-regexp)
  20444. (push (org-point-in-group p 0 :radio-target) clist))
  20445. (goto-char p))
  20446. ((setq o (cl-some
  20447. (lambda (o)
  20448. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20449. o))
  20450. (overlays-at (point))))
  20451. (push (list :latex-fragment
  20452. (overlay-start o) (overlay-end o)) clist)
  20453. (push (list :latex-preview
  20454. (overlay-start o) (overlay-end o)) clist))
  20455. ((org-inside-LaTeX-fragment-p)
  20456. ;; FIXME: positions wrong.
  20457. (push (list :latex-fragment (point) (point)) clist)))
  20458. (setq clist (nreverse (delq nil clist)))
  20459. clist))
  20460. (defun org-in-regexp (regexp &optional nlines visually)
  20461. "Check if point is inside a match of REGEXP.
  20462. Normally only the current line is checked, but you can include
  20463. NLINES extra lines around point into the search. If VISUALLY is
  20464. set, require that the cursor is not after the match but really
  20465. on, so that the block visually is on the match.
  20466. Return nil or a cons cell (BEG . END) where BEG and END are,
  20467. respectively, the positions at the beginning and the end of the
  20468. match."
  20469. (catch :exit
  20470. (let ((pos (point))
  20471. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20472. (save-excursion
  20473. (beginning-of-line (- 1 (or nlines 0)))
  20474. (while (and (re-search-forward regexp eol t)
  20475. (<= (match-beginning 0) pos))
  20476. (let ((end (match-end 0)))
  20477. (when (or (> end pos) (and (= end pos) (not visually)))
  20478. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20479. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20480. "Non-nil when point is between matches of START-RE and END-RE.
  20481. Also return a non-nil value when point is on one of the matches.
  20482. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20483. buffer positions. Default values are the positions of headlines
  20484. surrounding the point.
  20485. The functions returns a cons cell whose car (resp. cdr) is the
  20486. position before START-RE (resp. after END-RE)."
  20487. (save-match-data
  20488. (let ((pos (point))
  20489. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20490. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20491. beg end)
  20492. (save-excursion
  20493. ;; Point is on a block when on START-RE or if START-RE can be
  20494. ;; found before it...
  20495. (and (or (org-in-regexp start-re)
  20496. (re-search-backward start-re limit-up t))
  20497. (setq beg (match-beginning 0))
  20498. ;; ... and END-RE after it...
  20499. (goto-char (match-end 0))
  20500. (re-search-forward end-re limit-down t)
  20501. (> (setq end (match-end 0)) pos)
  20502. ;; ... without another START-RE in-between.
  20503. (goto-char (match-beginning 0))
  20504. (not (re-search-backward start-re (1+ beg) t))
  20505. ;; Return value.
  20506. (cons beg end))))))
  20507. (defun org-in-block-p (names)
  20508. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20509. NAMES is a list of strings containing names of blocks.
  20510. Return first block name matched, or nil. Beware that in case of
  20511. nested blocks, the returned name may not belong to the closest
  20512. block from point."
  20513. (save-match-data
  20514. (catch 'exit
  20515. (let ((case-fold-search t)
  20516. (lim-up (save-excursion (outline-previous-heading)))
  20517. (lim-down (save-excursion (outline-next-heading))))
  20518. (dolist (name names)
  20519. (let ((n (regexp-quote name)))
  20520. (when (org-between-regexps-p
  20521. (concat "^[ \t]*#\\+begin_" n)
  20522. (concat "^[ \t]*#\\+end_" n)
  20523. lim-up lim-down)
  20524. (throw 'exit n)))))
  20525. nil)))
  20526. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20527. "Call `multi-occur' with buffers for all agenda files."
  20528. (interactive "sOrg-files matching: ")
  20529. (let* ((files (org-agenda-files))
  20530. (tnames (mapcar #'file-truename files))
  20531. (extra org-agenda-text-search-extra-files))
  20532. (when (eq (car extra) 'agenda-archives)
  20533. (setq extra (cdr extra))
  20534. (setq files (org-add-archive-files files)))
  20535. (dolist (f extra)
  20536. (unless (member (file-truename f) tnames)
  20537. (unless (member f files) (setq files (append files (list f))))
  20538. (setq tnames (append tnames (list (file-truename f))))))
  20539. (multi-occur
  20540. (mapcar (lambda (x)
  20541. (with-current-buffer
  20542. ;; FIXME: Why not just (find-file-noselect x)?
  20543. ;; Is it to avoid the "revert buffer" prompt?
  20544. (or (get-file-buffer x) (find-file-noselect x))
  20545. (widen)
  20546. (current-buffer)))
  20547. files)
  20548. regexp)))
  20549. (add-hook 'occur-mode-find-occurrence-hook
  20550. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20551. (defun org-occur-link-in-agenda-files ()
  20552. "Create a link and search for it in the agendas.
  20553. The link is not stored in `org-stored-links', it is just created
  20554. for the search purpose."
  20555. (interactive)
  20556. (let ((link (condition-case nil
  20557. (org-store-link nil)
  20558. (error "Unable to create a link to here"))))
  20559. (org-occur-in-agenda-files (regexp-quote link))))
  20560. (defun org-reverse-string (string)
  20561. "Return the reverse of STRING."
  20562. (apply 'string (reverse (string-to-list string))))
  20563. ;; defsubst org-uniquify must be defined before first use
  20564. (defun org-uniquify-alist (alist)
  20565. "Merge elements of ALIST with the same key.
  20566. For example, in this alist:
  20567. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20568. => \\='((a 1 3) (b 2))
  20569. merge (a 1) and (a 3) into (a 1 3).
  20570. The function returns the new ALIST."
  20571. (let (rtn)
  20572. (dolist (e alist rtn)
  20573. (let (n)
  20574. (if (not (assoc (car e) rtn))
  20575. (push e rtn)
  20576. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20577. (setq rtn (assq-delete-all (car e) rtn))
  20578. (push n rtn))))))
  20579. (defun org-delete-all (elts list)
  20580. "Remove all elements in ELTS from LIST.
  20581. Comparison is done with `equal'. It is a destructive operation
  20582. that may remove elements by altering the list structure."
  20583. (while elts
  20584. (setq list (delete (pop elts) list)))
  20585. list)
  20586. (defun org-back-over-empty-lines ()
  20587. "Move backwards over whitespace, to the beginning of the first empty line.
  20588. Returns the number of empty lines passed."
  20589. (let ((pos (point)))
  20590. (if (cdr (assq 'heading org-blank-before-new-entry))
  20591. (skip-chars-backward " \t\n\r")
  20592. (unless (eobp)
  20593. (forward-line -1)))
  20594. (beginning-of-line 2)
  20595. (goto-char (min (point) pos))
  20596. (count-lines (point) pos)))
  20597. (defun org-skip-whitespace ()
  20598. (skip-chars-forward " \t\n\r"))
  20599. (defun org-point-in-group (point group &optional context)
  20600. "Check if POINT is in match-group GROUP.
  20601. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20602. match. If the match group does not exist or point is not inside it,
  20603. return nil."
  20604. (and (match-beginning group)
  20605. (>= point (match-beginning group))
  20606. (<= point (match-end group))
  20607. (if context
  20608. (list context (match-beginning group) (match-end group))
  20609. t)))
  20610. (defun org-switch-to-buffer-other-window (&rest args)
  20611. "Switch to buffer in a second window on the current frame.
  20612. In particular, do not allow pop-up frames.
  20613. Returns the newly created buffer."
  20614. (org-no-popups
  20615. (apply 'switch-to-buffer-other-window args)))
  20616. (defun org-combine-plists (&rest plists)
  20617. "Create a single property list from all plists in PLISTS.
  20618. The process starts by copying the first list, and then setting properties
  20619. from the other lists. Settings in the last list are the most significant
  20620. ones and overrule settings in the other lists."
  20621. (let ((rtn (copy-sequence (pop plists)))
  20622. p v ls)
  20623. (while plists
  20624. (setq ls (pop plists))
  20625. (while ls
  20626. (setq p (pop ls) v (pop ls))
  20627. (setq rtn (plist-put rtn p v))))
  20628. rtn))
  20629. (defun org-replace-escapes (string table)
  20630. "Replace %-escapes in STRING with values in TABLE.
  20631. TABLE is an association list with keys like \"%a\" and string values.
  20632. The sequences in STRING may contain normal field width and padding information,
  20633. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20634. so values can contain further %-escapes if they are define later in TABLE."
  20635. (let ((tbl (copy-alist table))
  20636. (case-fold-search nil)
  20637. (pchg 0)
  20638. re rpl)
  20639. (dolist (e tbl)
  20640. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20641. (when (and (cdr e) (string-match re (cdr e)))
  20642. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20643. (safe "SREF"))
  20644. (add-text-properties 0 3 (list 'sref sref) safe)
  20645. (setcdr e (replace-match safe t t (cdr e)))))
  20646. (while (string-match re string)
  20647. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20648. (cdr e)))
  20649. (setq string (replace-match rpl t t string))))
  20650. (while (setq pchg (next-property-change pchg string))
  20651. (let ((sref (get-text-property pchg 'sref string)))
  20652. (when (and sref (string-match "SREF" string pchg))
  20653. (setq string (replace-match sref t t string)))))
  20654. string))
  20655. (defun org-find-base-buffer-visiting (file)
  20656. "Like `find-buffer-visiting' but always return the base buffer and
  20657. not an indirect buffer."
  20658. (let ((buf (or (get-file-buffer file)
  20659. (find-buffer-visiting file))))
  20660. (if buf
  20661. (or (buffer-base-buffer buf) buf)
  20662. nil)))
  20663. ;;; TODO: Only called once, from ox-odt which should probably use
  20664. ;;; org-export-inline-image-p or something.
  20665. (defun org-file-image-p (file)
  20666. "Return non-nil if FILE is an image."
  20667. (save-match-data
  20668. (string-match (image-file-name-regexp) file)))
  20669. (defun org-get-cursor-date (&optional with-time)
  20670. "Return the date at cursor in as a time.
  20671. This works in the calendar and in the agenda, anywhere else it just
  20672. returns the current time.
  20673. If WITH-TIME is non-nil, returns the time of the event at point (in
  20674. the agenda) or the current time of the day."
  20675. (let (date day defd tp hod mod)
  20676. (when with-time
  20677. (setq tp (get-text-property (point) 'time))
  20678. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20679. (setq hod (string-to-number (match-string 1 tp))
  20680. mod (string-to-number (match-string 2 tp))))
  20681. (or tp (let ((now (decode-time)))
  20682. (setq hod (nth 2 now)
  20683. mod (nth 1 now)))))
  20684. (cond
  20685. ((eq major-mode 'calendar-mode)
  20686. (setq date (calendar-cursor-to-date)
  20687. defd (encode-time 0 (or mod 0) (or hod 0)
  20688. (nth 1 date) (nth 0 date) (nth 2 date))))
  20689. ((eq major-mode 'org-agenda-mode)
  20690. (setq day (get-text-property (point) 'day))
  20691. (when day
  20692. (setq date (calendar-gregorian-from-absolute day)
  20693. defd (encode-time 0 (or mod 0) (or hod 0)
  20694. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20695. (or defd (current-time))))
  20696. (defun org-mark-subtree (&optional up)
  20697. "Mark the current subtree.
  20698. This puts point at the start of the current subtree, and mark at
  20699. the end. If a numeric prefix UP is given, move up into the
  20700. hierarchy of headlines by UP levels before marking the subtree."
  20701. (interactive "P")
  20702. (org-with-limited-levels
  20703. (cond ((org-at-heading-p) (beginning-of-line))
  20704. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20705. (t (outline-previous-visible-heading 1))))
  20706. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20707. (if (called-interactively-p 'any)
  20708. (call-interactively 'org-mark-element)
  20709. (org-mark-element)))
  20710. (defun org-file-newer-than-p (file time)
  20711. "Non-nil if FILE is newer than TIME.
  20712. FILE is a filename, as a string, TIME is a list of integers, as
  20713. returned by, e.g., `current-time'."
  20714. (and (file-exists-p file)
  20715. ;; Only compare times up to whole seconds as some file-systems
  20716. ;; (e.g. HFS+) do not retain any finer granularity. As
  20717. ;; a consequence, make sure we return non-nil when the two
  20718. ;; times are equal.
  20719. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20720. (cl-subseq time 0 2)))))
  20721. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20722. "Compile a SOURCE file using PROCESS.
  20723. PROCESS is either a function or a list of shell commands, as
  20724. strings. EXT is a file extension, without the leading dot, as
  20725. a string. It is used to check if the process actually succeeded.
  20726. PROCESS must create a file with the same base name and directory
  20727. as SOURCE, but ending with EXT. The function then returns its
  20728. filename. Otherwise, it raises an error. The error message can
  20729. then be refined by providing string ERR-MSG, which is appended to
  20730. the standard message.
  20731. If PROCESS is a function, it is called with a single argument:
  20732. the SOURCE file.
  20733. If it is a list of commands, each of them is called using
  20734. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20735. %O are replaced with, respectively, SOURCE base name, name, full
  20736. name, directory and absolute output file name. It is possible,
  20737. however, to use more place-holders by specifying them in optional
  20738. argument SPEC, as an alist following the pattern
  20739. (CHARACTER . REPLACEMENT-STRING).
  20740. When PROCESS is a list of commands, optional argument LOG-BUF can
  20741. be set to a buffer or a buffer name. `shell-command' then uses
  20742. it for output."
  20743. (let* ((base-name (file-name-base source))
  20744. (full-name (file-truename source))
  20745. (out-dir (or (file-name-directory source) "./"))
  20746. (output (expand-file-name (concat base-name "." ext) out-dir))
  20747. (time (current-time))
  20748. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20749. (save-window-excursion
  20750. (pcase process
  20751. ((pred functionp) (funcall process (shell-quote-argument source)))
  20752. ((pred consp)
  20753. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20754. (spec (append spec
  20755. `((?b . ,(shell-quote-argument base-name))
  20756. (?f . ,(shell-quote-argument source))
  20757. (?F . ,(shell-quote-argument full-name))
  20758. (?o . ,(shell-quote-argument out-dir))
  20759. (?O . ,(shell-quote-argument output))))))
  20760. (dolist (command process)
  20761. (shell-command (format-spec command spec) log-buf))))
  20762. (_ (error "No valid command to process %S%s" source err-msg))))
  20763. ;; Check for process failure. Output file is expected to be
  20764. ;; located in the same directory as SOURCE.
  20765. (unless (org-file-newer-than-p output time)
  20766. (error (format "File %S wasn't produced%s" output err-msg)))
  20767. output))
  20768. ;;; Indentation
  20769. (defun org--get-expected-indentation (element contentsp)
  20770. "Expected indentation column for current line, according to ELEMENT.
  20771. ELEMENT is an element containing point. CONTENTSP is non-nil
  20772. when indentation is to be computed according to contents of
  20773. ELEMENT."
  20774. (let ((type (org-element-type element))
  20775. (start (org-element-property :begin element))
  20776. (post-affiliated (org-element-property :post-affiliated element)))
  20777. (org-with-wide-buffer
  20778. (cond
  20779. (contentsp
  20780. (cl-case type
  20781. ((diary-sexp footnote-definition) 0)
  20782. ((headline inlinetask nil)
  20783. (if (not org-adapt-indentation) 0
  20784. (let ((level (org-current-level)))
  20785. (if level (1+ level) 0))))
  20786. ((item plain-list) (org-list-item-body-column post-affiliated))
  20787. (t
  20788. (goto-char start)
  20789. (org-get-indentation))))
  20790. ((memq type '(headline inlinetask nil))
  20791. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20792. (org--get-expected-indentation element t)
  20793. 0))
  20794. ((memq type '(diary-sexp footnote-definition)) 0)
  20795. ;; First paragraph of a footnote definition or an item.
  20796. ;; Indent like parent.
  20797. ((< (line-beginning-position) start)
  20798. (org--get-expected-indentation
  20799. (org-element-property :parent element) t))
  20800. ;; At first line: indent according to previous sibling, if any,
  20801. ;; ignoring footnote definitions and inline tasks, or parent's
  20802. ;; contents.
  20803. ((= (line-beginning-position) start)
  20804. (catch 'exit
  20805. (while t
  20806. (if (= (point-min) start) (throw 'exit 0)
  20807. (goto-char (1- start))
  20808. (let* ((previous (org-element-at-point))
  20809. (parent previous))
  20810. (while (and parent (<= (org-element-property :end parent) start))
  20811. (setq previous parent
  20812. parent (org-element-property :parent parent)))
  20813. (cond
  20814. ((not previous) (throw 'exit 0))
  20815. ((> (org-element-property :end previous) start)
  20816. (throw 'exit (org--get-expected-indentation previous t)))
  20817. ((memq (org-element-type previous)
  20818. '(footnote-definition inlinetask))
  20819. (setq start (org-element-property :begin previous)))
  20820. (t (goto-char (org-element-property :begin previous))
  20821. (throw 'exit
  20822. (if (bolp) (org-get-indentation)
  20823. ;; At first paragraph in an item or
  20824. ;; a footnote definition.
  20825. (org--get-expected-indentation
  20826. (org-element-property :parent previous) t))))))))))
  20827. ;; Otherwise, move to the first non-blank line above.
  20828. (t
  20829. (beginning-of-line)
  20830. (let ((pos (point)))
  20831. (skip-chars-backward " \r\t\n")
  20832. (cond
  20833. ;; Two blank lines end a footnote definition or a plain
  20834. ;; list. When we indent an empty line after them, the
  20835. ;; containing list or footnote definition is over, so it
  20836. ;; qualifies as a previous sibling. Therefore, we indent
  20837. ;; like its first line.
  20838. ((and (memq type '(footnote-definition plain-list))
  20839. (> (count-lines (point) pos) 2))
  20840. (goto-char start)
  20841. (org-get-indentation))
  20842. ;; Line above is the first one of a paragraph at the
  20843. ;; beginning of an item or a footnote definition. Indent
  20844. ;; like parent.
  20845. ((< (line-beginning-position) start)
  20846. (org--get-expected-indentation
  20847. (org-element-property :parent element) t))
  20848. ;; Line above is the beginning of an element, i.e., point
  20849. ;; was originally on the blank lines between element's start
  20850. ;; and contents.
  20851. ((= (line-beginning-position) post-affiliated)
  20852. (org--get-expected-indentation element t))
  20853. ;; POS is after contents in a greater element. Indent like
  20854. ;; the beginning of the element.
  20855. ;;
  20856. ;; As a special case, if point is at the end of a footnote
  20857. ;; definition or an item, indent like the very last element
  20858. ;; within. If that last element is an item, indent like its
  20859. ;; contents.
  20860. ((and (not (eq type 'paragraph))
  20861. (let ((cend (org-element-property :contents-end element)))
  20862. (and cend (<= cend pos))))
  20863. (if (memq type '(footnote-definition item plain-list))
  20864. (let ((last (org-element-at-point)))
  20865. (org--get-expected-indentation
  20866. last (eq (org-element-type last) 'item)))
  20867. (goto-char start)
  20868. (org-get-indentation)))
  20869. ;; In any other case, indent like the current line.
  20870. (t (org-get-indentation)))))))))
  20871. (defun org--align-node-property ()
  20872. "Align node property at point.
  20873. Alignment is done according to `org-property-format', which see."
  20874. (when (save-excursion
  20875. (beginning-of-line)
  20876. (looking-at org-property-re))
  20877. (replace-match
  20878. (concat (match-string 4)
  20879. (org-trim
  20880. (format org-property-format (match-string 1) (match-string 3))))
  20881. t t)))
  20882. (defun org-indent-line ()
  20883. "Indent line depending on context.
  20884. Indentation is done according to the following rules:
  20885. - Footnote definitions, diary sexps, headlines and inline tasks
  20886. have to start at column 0.
  20887. - On the very first line of an element, consider, in order, the
  20888. next rules until one matches:
  20889. 1. If there's a sibling element before, ignoring footnote
  20890. definitions and inline tasks, indent like its first line.
  20891. 2. If element has a parent, indent like its contents. More
  20892. precisely, if parent is an item, indent after the
  20893. description part, if any, or the bullet (see
  20894. `org-list-description-max-indent'). Else, indent like
  20895. parent's first line.
  20896. 3. Otherwise, indent relatively to current level, if
  20897. `org-adapt-indentation' is non-nil, or to left margin.
  20898. - On a blank line at the end of an element, indent according to
  20899. the type of the element. More precisely
  20900. 1. If element is a plain list, an item, or a footnote
  20901. definition, indent like the very last element within.
  20902. 2. If element is a paragraph, indent like its last non blank
  20903. line.
  20904. 3. Otherwise, indent like its very first line.
  20905. - In the code part of a source block, use language major mode
  20906. to indent current line if `org-src-tab-acts-natively' is
  20907. non-nil. If it is nil, do nothing.
  20908. - Otherwise, indent like the first non-blank line above.
  20909. The function doesn't indent an item as it could break the whole
  20910. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20911. `\\[org-shiftmetaright]'.
  20912. Also align node properties according to `org-property-format'."
  20913. (interactive)
  20914. (cond
  20915. (orgstruct-is-++
  20916. (let ((indent-line-function
  20917. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20918. (indent-according-to-mode)))
  20919. ((org-at-heading-p) 'noindent)
  20920. (t
  20921. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20922. (type (org-element-type element)))
  20923. (cond ((and (memq type '(plain-list item))
  20924. (= (line-beginning-position)
  20925. (org-element-property :post-affiliated element)))
  20926. 'noindent)
  20927. ((and (eq type 'src-block)
  20928. org-src-tab-acts-natively
  20929. (> (line-beginning-position)
  20930. (org-element-property :post-affiliated element))
  20931. (< (line-beginning-position)
  20932. (org-with-wide-buffer
  20933. (goto-char (org-element-property :end element))
  20934. (skip-chars-backward " \r\t\n")
  20935. (line-beginning-position))))
  20936. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20937. (t
  20938. (let ((column (org--get-expected-indentation element nil)))
  20939. ;; Preserve current column.
  20940. (if (<= (current-column) (current-indentation))
  20941. (indent-line-to column)
  20942. (save-excursion (indent-line-to column))))
  20943. ;; Align node property. Also preserve current column.
  20944. (when (eq type 'node-property)
  20945. (let ((column (current-column)))
  20946. (org--align-node-property)
  20947. (org-move-to-column column)))))))))
  20948. (defun org-indent-region (start end)
  20949. "Indent each non-blank line in the region.
  20950. Called from a program, START and END specify the region to
  20951. indent. The function will not indent contents of example blocks,
  20952. verse blocks and export blocks as leading white spaces are
  20953. assumed to be significant there."
  20954. (interactive "r")
  20955. (save-excursion
  20956. (goto-char start)
  20957. (skip-chars-forward " \r\t\n")
  20958. (unless (eobp) (beginning-of-line))
  20959. (let ((indent-to
  20960. (lambda (ind pos)
  20961. ;; Set IND as indentation for all lines between point and
  20962. ;; POS. Blank lines are ignored. Leave point after POS
  20963. ;; once done.
  20964. (let ((limit (copy-marker pos)))
  20965. (while (< (point) limit)
  20966. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20967. (forward-line))
  20968. (set-marker limit nil))))
  20969. (end (copy-marker end)))
  20970. (while (< (point) end)
  20971. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20972. (let* ((element (org-element-at-point))
  20973. (type (org-element-type element))
  20974. (element-end (copy-marker (org-element-property :end element)))
  20975. (ind (org--get-expected-indentation element nil)))
  20976. (cond
  20977. ((or (memq type '(paragraph table table-row))
  20978. (not (or (org-element-property :contents-begin element)
  20979. (memq type
  20980. '(example-block export-block src-block)))))
  20981. ;; Elements here are indented as a single block. Also
  20982. ;; align node properties.
  20983. (when (eq type 'node-property)
  20984. (org--align-node-property)
  20985. (beginning-of-line))
  20986. (funcall indent-to ind (min element-end end)))
  20987. (t
  20988. ;; Elements in this category consist of three parts:
  20989. ;; before the contents, the contents, and after the
  20990. ;; contents. The contents are treated specially,
  20991. ;; according to the element type, or not indented at
  20992. ;; all. Other parts are indented as a single block.
  20993. (let* ((post (copy-marker
  20994. (org-element-property :post-affiliated element)))
  20995. (cbeg
  20996. (copy-marker
  20997. (cond
  20998. ((not (org-element-property :contents-begin element))
  20999. ;; Fake contents for source blocks.
  21000. (org-with-wide-buffer
  21001. (goto-char post)
  21002. (forward-line)
  21003. (point)))
  21004. ((memq type '(footnote-definition item plain-list))
  21005. ;; Contents in these elements could start on
  21006. ;; the same line as the beginning of the
  21007. ;; element. Make sure we start indenting
  21008. ;; from the second line.
  21009. (org-with-wide-buffer
  21010. (goto-char post)
  21011. (end-of-line)
  21012. (skip-chars-forward " \r\t\n")
  21013. (if (eobp) (point) (line-beginning-position))))
  21014. (t (org-element-property :contents-begin element)))))
  21015. (cend (copy-marker
  21016. (or (org-element-property :contents-end element)
  21017. ;; Fake contents for source blocks.
  21018. (org-with-wide-buffer
  21019. (goto-char element-end)
  21020. (skip-chars-backward " \r\t\n")
  21021. (line-beginning-position)))
  21022. t)))
  21023. ;; Do not change items indentation individually as it
  21024. ;; might break the list as a whole. On the other
  21025. ;; hand, when at a plain list, indent it as a whole.
  21026. (cond ((eq type 'plain-list)
  21027. (let ((offset (- ind (org-get-indentation))))
  21028. (unless (zerop offset)
  21029. (indent-rigidly (org-element-property :begin element)
  21030. (org-element-property :end element)
  21031. offset))
  21032. (goto-char cbeg)))
  21033. ((eq type 'item) (goto-char cbeg))
  21034. (t (funcall indent-to ind (min cbeg end))))
  21035. (when (< (point) end)
  21036. (cl-case type
  21037. ((example-block export-block verse-block))
  21038. (src-block
  21039. ;; In a source block, indent source code
  21040. ;; according to language major mode, but only if
  21041. ;; `org-src-tab-acts-natively' is non-nil.
  21042. (when (and (< (point) end) org-src-tab-acts-natively)
  21043. (ignore-errors
  21044. (org-babel-do-in-edit-buffer
  21045. (indent-region (point-min) (point-max))))))
  21046. (t (org-indent-region (point) (min cend end))))
  21047. (goto-char (min cend end))
  21048. (when (< (point) end)
  21049. (funcall indent-to ind (min element-end end))))
  21050. (set-marker post nil)
  21051. (set-marker cbeg nil)
  21052. (set-marker cend nil))))
  21053. (set-marker element-end nil))))
  21054. (set-marker end nil))))
  21055. (defun org-indent-drawer ()
  21056. "Indent the drawer at point."
  21057. (interactive)
  21058. (unless (save-excursion
  21059. (beginning-of-line)
  21060. (looking-at-p org-drawer-regexp))
  21061. (user-error "Not at a drawer"))
  21062. (let ((element (org-element-at-point)))
  21063. (unless (memq (org-element-type element) '(drawer property-drawer))
  21064. (user-error "Not at a drawer"))
  21065. (org-with-wide-buffer
  21066. (org-indent-region (org-element-property :begin element)
  21067. (org-element-property :end element))))
  21068. (message "Drawer at point indented"))
  21069. (defun org-indent-block ()
  21070. "Indent the block at point."
  21071. (interactive)
  21072. (unless (save-excursion
  21073. (beginning-of-line)
  21074. (let ((case-fold-search t))
  21075. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21076. (user-error "Not at a block"))
  21077. (let ((element (org-element-at-point)))
  21078. (unless (memq (org-element-type element)
  21079. '(comment-block center-block dynamic-block example-block
  21080. export-block quote-block special-block
  21081. src-block verse-block))
  21082. (user-error "Not at a block"))
  21083. (org-with-wide-buffer
  21084. (org-indent-region (org-element-property :begin element)
  21085. (org-element-property :end element))))
  21086. (message "Block at point indented"))
  21087. ;;; Filling
  21088. ;; We use our own fill-paragraph and auto-fill functions.
  21089. ;; `org-fill-paragraph' relies on adaptive filling and context
  21090. ;; checking. Appropriate `fill-prefix' is computed with
  21091. ;; `org-adaptive-fill-function'.
  21092. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21093. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21094. ;; `org-adaptive-fill-function' value. Internally,
  21095. ;; `org-comment-line-break-function' breaks the line.
  21096. ;; `org-setup-filling' installs filling and auto-filling related
  21097. ;; variables during `org-mode' initialization.
  21098. (defvar org-element-paragraph-separate) ; org-element.el
  21099. (defun org-setup-filling ()
  21100. (require 'org-element)
  21101. ;; Prevent auto-fill from inserting unwanted new items.
  21102. (when (boundp 'fill-nobreak-predicate)
  21103. (setq-local
  21104. fill-nobreak-predicate
  21105. (org-uniquify
  21106. (append fill-nobreak-predicate
  21107. '(org-fill-line-break-nobreak-p
  21108. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21109. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21110. (setq-local paragraph-start paragraph-ending)
  21111. (setq-local paragraph-separate paragraph-ending))
  21112. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21113. (setq-local auto-fill-inhibit-regexp nil)
  21114. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21115. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21116. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21117. (defun org-fill-line-break-nobreak-p ()
  21118. "Non-nil when a new line at point would create an Org line break."
  21119. (save-excursion
  21120. (skip-chars-backward "[ \t]")
  21121. (skip-chars-backward "\\\\")
  21122. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21123. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21124. "Non-nil when a new line at point would split a timestamp."
  21125. (and (org-at-timestamp-p t)
  21126. (not (looking-at org-ts-regexp-both))))
  21127. (declare-function message-in-body-p "message" ())
  21128. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21129. (defun org-adaptive-fill-function ()
  21130. "Compute a fill prefix for the current line.
  21131. Return fill prefix, as a string, or nil if current line isn't
  21132. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21133. matches in paragraphs or comments, use it."
  21134. (catch 'exit
  21135. (when (derived-mode-p 'message-mode)
  21136. (save-excursion
  21137. (beginning-of-line)
  21138. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21139. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21140. ((looking-at message-cite-prefix-regexp)
  21141. (throw 'exit (match-string-no-properties 0)))
  21142. ((looking-at org-outline-regexp)
  21143. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21144. (org-with-wide-buffer
  21145. (unless (org-at-heading-p)
  21146. (let* ((p (line-beginning-position))
  21147. (element (save-excursion
  21148. (beginning-of-line)
  21149. (org-element-at-point)))
  21150. (type (org-element-type element))
  21151. (post-affiliated (org-element-property :post-affiliated element)))
  21152. (unless (< p post-affiliated)
  21153. (cl-case type
  21154. (comment
  21155. (save-excursion
  21156. (beginning-of-line)
  21157. (looking-at "[ \t]*")
  21158. (concat (match-string 0) "# ")))
  21159. (footnote-definition "")
  21160. ((item plain-list)
  21161. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21162. (paragraph
  21163. ;; Fill prefix is usually the same as the current line,
  21164. ;; unless the paragraph is at the beginning of an item.
  21165. (let ((parent (org-element-property :parent element)))
  21166. (save-excursion
  21167. (beginning-of-line)
  21168. (cond ((eq (org-element-type parent) 'item)
  21169. (make-string (org-list-item-body-column
  21170. (org-element-property :begin parent))
  21171. ?\s))
  21172. ((and adaptive-fill-regexp
  21173. ;; Locally disable
  21174. ;; `adaptive-fill-function' to let
  21175. ;; `fill-context-prefix' handle
  21176. ;; `adaptive-fill-regexp' variable.
  21177. (let (adaptive-fill-function)
  21178. (fill-context-prefix
  21179. post-affiliated
  21180. (org-element-property :end element)))))
  21181. ((looking-at "[ \t]+") (match-string 0))
  21182. (t "")))))
  21183. (comment-block
  21184. ;; Only fill contents if P is within block boundaries.
  21185. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21186. (forward-line)
  21187. (point)))
  21188. (cend (save-excursion
  21189. (goto-char (org-element-property :end element))
  21190. (skip-chars-backward " \r\t\n")
  21191. (line-beginning-position))))
  21192. (when (and (>= p cbeg) (< p cend))
  21193. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21194. (match-string 0)
  21195. "")))))))))))
  21196. (declare-function message-goto-body "message" ())
  21197. (defvar message-cite-prefix-regexp) ; From message.el
  21198. (defun org-fill-paragraph (&optional justify)
  21199. "Fill element at point, when applicable.
  21200. This function only applies to comment blocks, comments, example
  21201. blocks and paragraphs. Also, as a special case, re-align table
  21202. when point is at one.
  21203. If JUSTIFY is non-nil (interactively, with prefix argument),
  21204. justify as well. If `sentence-end-double-space' is non-nil, then
  21205. period followed by one space does not end a sentence, so don't
  21206. break a line there. The variable `fill-column' controls the
  21207. width for filling.
  21208. For convenience, when point is at a plain list, an item or
  21209. a footnote definition, try to fill the first paragraph within."
  21210. (interactive)
  21211. (if (and (derived-mode-p 'message-mode)
  21212. (or (not (message-in-body-p))
  21213. (save-excursion (move-beginning-of-line 1)
  21214. (looking-at message-cite-prefix-regexp))))
  21215. ;; First ensure filling is correct in message-mode.
  21216. (let ((fill-paragraph-function
  21217. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21218. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21219. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21220. (paragraph-separate
  21221. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21222. (fill-paragraph nil))
  21223. (with-syntax-table org-mode-transpose-word-syntax-table
  21224. ;; Move to end of line in order to get the first paragraph
  21225. ;; within a plain list or a footnote definition.
  21226. (let ((element (save-excursion
  21227. (end-of-line)
  21228. (or (ignore-errors (org-element-at-point))
  21229. (user-error "An element cannot be parsed line %d"
  21230. (line-number-at-pos (point)))))))
  21231. ;; First check if point is in a blank line at the beginning of
  21232. ;; the buffer. In that case, ignore filling.
  21233. (cl-case (org-element-type element)
  21234. ;; Use major mode filling function is src blocks.
  21235. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21236. ;; Align Org tables, leave table.el tables as-is.
  21237. (table-row (org-table-align) t)
  21238. (table
  21239. (when (eq (org-element-property :type element) 'org)
  21240. (save-excursion
  21241. (goto-char (org-element-property :post-affiliated element))
  21242. (org-table-align)))
  21243. t)
  21244. (paragraph
  21245. ;; Paragraphs may contain `line-break' type objects.
  21246. (let ((beg (max (point-min)
  21247. (org-element-property :contents-begin element)))
  21248. (end (min (point-max)
  21249. (org-element-property :contents-end element))))
  21250. ;; Do nothing if point is at an affiliated keyword.
  21251. (if (< (line-end-position) beg) t
  21252. (when (derived-mode-p 'message-mode)
  21253. ;; In `message-mode', do not fill following citation
  21254. ;; in current paragraph nor text before message body.
  21255. (let ((body-start (save-excursion (message-goto-body))))
  21256. (when body-start (setq beg (max body-start beg))))
  21257. (when (save-excursion
  21258. (re-search-forward
  21259. (concat "^" message-cite-prefix-regexp) end t))
  21260. (setq end (match-beginning 0))))
  21261. ;; Fill paragraph, taking line breaks into account.
  21262. (save-excursion
  21263. (goto-char beg)
  21264. (let ((cuts (list beg)))
  21265. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21266. (when (eq 'line-break
  21267. (org-element-type
  21268. (save-excursion (backward-char)
  21269. (org-element-context))))
  21270. (push (point) cuts)))
  21271. (dolist (c (delq end cuts))
  21272. (fill-region-as-paragraph c end justify)
  21273. (setq end c))))
  21274. t)))
  21275. ;; Contents of `comment-block' type elements should be
  21276. ;; filled as plain text, but only if point is within block
  21277. ;; markers.
  21278. (comment-block
  21279. (let* ((case-fold-search t)
  21280. (beg (save-excursion
  21281. (goto-char (org-element-property :begin element))
  21282. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21283. (forward-line)
  21284. (point)))
  21285. (end (save-excursion
  21286. (goto-char (org-element-property :end element))
  21287. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21288. (line-beginning-position))))
  21289. (if (or (< (point) beg) (> (point) end)) t
  21290. (fill-region-as-paragraph
  21291. (save-excursion (end-of-line)
  21292. (re-search-backward "^[ \t]*$" beg 'move)
  21293. (line-beginning-position))
  21294. (save-excursion (beginning-of-line)
  21295. (re-search-forward "^[ \t]*$" end 'move)
  21296. (line-beginning-position))
  21297. justify))))
  21298. ;; Fill comments.
  21299. (comment
  21300. (let ((begin (org-element-property :post-affiliated element))
  21301. (end (org-element-property :end element)))
  21302. (when (and (>= (point) begin) (<= (point) end))
  21303. (let ((begin (save-excursion
  21304. (end-of-line)
  21305. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21306. (progn (forward-line) (point))
  21307. begin)))
  21308. (end (save-excursion
  21309. (end-of-line)
  21310. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21311. (1- (line-beginning-position))
  21312. (skip-chars-backward " \r\t\n")
  21313. (line-end-position)))))
  21314. ;; Do not fill comments when at a blank line.
  21315. (when (> end begin)
  21316. (let ((fill-prefix
  21317. (save-excursion
  21318. (beginning-of-line)
  21319. (looking-at "[ \t]*#")
  21320. (let ((comment-prefix (match-string 0)))
  21321. (goto-char (match-end 0))
  21322. (if (looking-at adaptive-fill-regexp)
  21323. (concat comment-prefix (match-string 0))
  21324. (concat comment-prefix " "))))))
  21325. (save-excursion
  21326. (fill-region-as-paragraph begin end justify))))))
  21327. t))
  21328. ;; Ignore every other element.
  21329. (otherwise t))))))
  21330. (defun org-auto-fill-function ()
  21331. "Auto-fill function."
  21332. ;; Check if auto-filling is meaningful.
  21333. (let ((fc (current-fill-column)))
  21334. (when (and fc (> (current-column) fc))
  21335. (let* ((fill-prefix (org-adaptive-fill-function))
  21336. ;; Enforce empty fill prefix, if required. Otherwise, it
  21337. ;; will be computed again.
  21338. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21339. (when fill-prefix (do-auto-fill))))))
  21340. (defun org-comment-line-break-function (&optional soft)
  21341. "Break line at point and indent, continuing comment if within one.
  21342. The inserted newline is marked hard if variable
  21343. `use-hard-newlines' is true, unless optional argument SOFT is
  21344. non-nil."
  21345. (if soft (insert-and-inherit ?\n) (newline 1))
  21346. (save-excursion (forward-char -1) (delete-horizontal-space))
  21347. (delete-horizontal-space)
  21348. (indent-to-left-margin)
  21349. (insert-before-markers-and-inherit fill-prefix))
  21350. ;;; Fixed Width Areas
  21351. (defun org-toggle-fixed-width ()
  21352. "Toggle fixed-width markup.
  21353. Add or remove fixed-width markup on current line, whenever it
  21354. makes sense. Return an error otherwise.
  21355. If a region is active and if it contains only fixed-width areas
  21356. or blank lines, remove all fixed-width markup in it. If the
  21357. region contains anything else, convert all non-fixed-width lines
  21358. to fixed-width ones.
  21359. Blank lines at the end of the region are ignored unless the
  21360. region only contains such lines."
  21361. (interactive)
  21362. (if (not (org-region-active-p))
  21363. ;; No region:
  21364. ;;
  21365. ;; Remove fixed width marker only in a fixed-with element.
  21366. ;;
  21367. ;; Add fixed width maker in paragraphs, in blank lines after
  21368. ;; elements or at the beginning of a headline or an inlinetask,
  21369. ;; and before any one-line elements (e.g., a clock).
  21370. (progn
  21371. (beginning-of-line)
  21372. (let* ((element (org-element-at-point))
  21373. (type (org-element-type element)))
  21374. (cond
  21375. ((and (eq type 'fixed-width)
  21376. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21377. (replace-match
  21378. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21379. ((and (memq type '(babel-call clock comment diary-sexp headline
  21380. horizontal-rule keyword paragraph
  21381. planning))
  21382. (<= (org-element-property :post-affiliated element) (point)))
  21383. (skip-chars-forward " \t")
  21384. (insert ": "))
  21385. ((and (looking-at-p "[ \t]*$")
  21386. (or (eq type 'inlinetask)
  21387. (save-excursion
  21388. (skip-chars-forward " \r\t\n")
  21389. (<= (org-element-property :end element) (point)))))
  21390. (delete-region (point) (line-end-position))
  21391. (org-indent-line)
  21392. (insert ": "))
  21393. (t (user-error "Cannot insert a fixed-width line here")))))
  21394. ;; Region active.
  21395. (let* ((begin (save-excursion
  21396. (goto-char (region-beginning))
  21397. (line-beginning-position)))
  21398. (end (copy-marker
  21399. (save-excursion
  21400. (goto-char (region-end))
  21401. (unless (eolp) (beginning-of-line))
  21402. (if (save-excursion (re-search-backward "\\S-" begin t))
  21403. (progn (skip-chars-backward " \r\t\n") (point))
  21404. (point)))))
  21405. (all-fixed-width-p
  21406. (catch 'not-all-p
  21407. (save-excursion
  21408. (goto-char begin)
  21409. (skip-chars-forward " \r\t\n")
  21410. (when (eobp) (throw 'not-all-p nil))
  21411. (while (< (point) end)
  21412. (let ((element (org-element-at-point)))
  21413. (if (eq (org-element-type element) 'fixed-width)
  21414. (goto-char (org-element-property :end element))
  21415. (throw 'not-all-p nil))))
  21416. t))))
  21417. (if all-fixed-width-p
  21418. (save-excursion
  21419. (goto-char begin)
  21420. (while (< (point) end)
  21421. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21422. (replace-match
  21423. "" nil nil nil
  21424. (if (= (line-end-position) (match-end 0)) 0 1)))
  21425. (forward-line)))
  21426. (let ((min-ind (point-max)))
  21427. ;; Find minimum indentation across all lines.
  21428. (save-excursion
  21429. (goto-char begin)
  21430. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21431. (setq min-ind 0)
  21432. (catch 'zerop
  21433. (while (< (point) end)
  21434. (unless (looking-at-p "[ \t]*$")
  21435. (let ((ind (org-get-indentation)))
  21436. (setq min-ind (min min-ind ind))
  21437. (when (zerop ind) (throw 'zerop t))))
  21438. (forward-line)))))
  21439. ;; Loop over all lines and add fixed-width markup everywhere
  21440. ;; but in fixed-width lines.
  21441. (save-excursion
  21442. (goto-char begin)
  21443. (while (< (point) end)
  21444. (cond
  21445. ((org-at-heading-p)
  21446. (insert ": ")
  21447. (forward-line)
  21448. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21449. (insert ":")
  21450. (forward-line)))
  21451. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21452. (let* ((element (org-element-at-point))
  21453. (element-end (org-element-property :end element)))
  21454. (if (eq (org-element-type element) 'fixed-width)
  21455. (progn (goto-char element-end)
  21456. (skip-chars-backward " \r\t\n")
  21457. (forward-line))
  21458. (let ((limit (min end element-end)))
  21459. (while (< (point) limit)
  21460. (org-move-to-column min-ind t)
  21461. (insert ": ")
  21462. (forward-line))))))
  21463. (t
  21464. (org-move-to-column min-ind t)
  21465. (insert ": ")
  21466. (forward-line)))))))
  21467. (set-marker end nil))))
  21468. ;;; Comments
  21469. ;; Org comments syntax is quite complex. It requires the entire line
  21470. ;; to be just a comment. Also, even with the right syntax at the
  21471. ;; beginning of line, some some elements (i.e. verse-block or
  21472. ;; example-block) don't accept comments. Usual Emacs comment commands
  21473. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21474. ;; Org still relies on `comment-dwim', but cannot trust
  21475. ;; `comment-only-p'. So, `comment-region-function' and
  21476. ;; `uncomment-region-function' both point
  21477. ;; to`org-comment-or-uncomment-region'. Eventually,
  21478. ;; `org-insert-comment' takes care of insertion of comments at the
  21479. ;; beginning of line.
  21480. ;; `org-setup-comments-handling' install comments related variables
  21481. ;; during `org-mode' initialization.
  21482. (defun org-setup-comments-handling ()
  21483. (interactive)
  21484. (setq-local comment-use-syntax nil)
  21485. (setq-local comment-start "# ")
  21486. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21487. (setq-local comment-insert-comment-function 'org-insert-comment)
  21488. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21489. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21490. (defun org-insert-comment ()
  21491. "Insert an empty comment above current line.
  21492. If the line is empty, insert comment at its beginning. When
  21493. point is within a source block, comment according to the related
  21494. major mode."
  21495. (if (let ((element (org-element-at-point)))
  21496. (and (eq (org-element-type element) 'src-block)
  21497. (< (save-excursion
  21498. (goto-char (org-element-property :post-affiliated element))
  21499. (line-end-position))
  21500. (point))
  21501. (> (save-excursion
  21502. (goto-char (org-element-property :end element))
  21503. (skip-chars-backward " \r\t\n")
  21504. (line-beginning-position))
  21505. (point))))
  21506. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21507. (beginning-of-line)
  21508. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21509. (open-line 1))
  21510. (org-indent-line)
  21511. (insert "# ")))
  21512. (defvar comment-empty-lines) ; From newcomment.el.
  21513. (defun org-comment-or-uncomment-region (beg end &rest _)
  21514. "Comment or uncomment each non-blank line in the region.
  21515. Uncomment each non-blank line between BEG and END if it only
  21516. contains commented lines. Otherwise, comment them. If region is
  21517. strictly within a source block, use appropriate comment syntax."
  21518. (if (let ((element (org-element-at-point)))
  21519. (and (eq (org-element-type element) 'src-block)
  21520. (< (save-excursion
  21521. (goto-char (org-element-property :post-affiliated element))
  21522. (line-end-position))
  21523. beg)
  21524. (>= (save-excursion
  21525. (goto-char (org-element-property :end element))
  21526. (skip-chars-backward " \r\t\n")
  21527. (line-beginning-position))
  21528. end)))
  21529. ;; Translate region boundaries for the Org buffer to the source
  21530. ;; buffer.
  21531. (let ((offset (- end beg)))
  21532. (save-excursion
  21533. (goto-char beg)
  21534. (org-babel-do-in-edit-buffer
  21535. (comment-or-uncomment-region (point) (+ offset (point))))))
  21536. (save-restriction
  21537. ;; Restrict region
  21538. (narrow-to-region (save-excursion (goto-char beg)
  21539. (skip-chars-forward " \r\t\n" end)
  21540. (line-beginning-position))
  21541. (save-excursion (goto-char end)
  21542. (skip-chars-backward " \r\t\n" beg)
  21543. (line-end-position)))
  21544. (let ((uncommentp
  21545. ;; UNCOMMENTP is non-nil when every non blank line between
  21546. ;; BEG and END is a comment.
  21547. (save-excursion
  21548. (goto-char (point-min))
  21549. (while (and (not (eobp))
  21550. (let ((element (org-element-at-point)))
  21551. (and (eq (org-element-type element) 'comment)
  21552. (goto-char (min (point-max)
  21553. (org-element-property
  21554. :end element)))))))
  21555. (eobp))))
  21556. (if uncommentp
  21557. ;; Only blank lines and comments in region: uncomment it.
  21558. (save-excursion
  21559. (goto-char (point-min))
  21560. (while (not (eobp))
  21561. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21562. (replace-match "" nil nil nil 1))
  21563. (forward-line)))
  21564. ;; Comment each line in region.
  21565. (let ((min-indent (point-max)))
  21566. ;; First find the minimum indentation across all lines.
  21567. (save-excursion
  21568. (goto-char (point-min))
  21569. (while (and (not (eobp)) (not (zerop min-indent)))
  21570. (unless (looking-at "[ \t]*$")
  21571. (setq min-indent (min min-indent (current-indentation))))
  21572. (forward-line)))
  21573. ;; Then loop over all lines.
  21574. (save-excursion
  21575. (goto-char (point-min))
  21576. (while (not (eobp))
  21577. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21578. ;; Don't get fooled by invisible text (e.g. link path)
  21579. ;; when moving to column MIN-INDENT.
  21580. (let ((buffer-invisibility-spec nil))
  21581. (org-move-to-column min-indent t))
  21582. (insert comment-start))
  21583. (forward-line)))))))))
  21584. (defun org-comment-dwim (_arg)
  21585. "Call `comment-dwim' within a source edit buffer if needed."
  21586. (interactive "*P")
  21587. (if (org-in-src-block-p)
  21588. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21589. (call-interactively 'comment-dwim)))
  21590. ;;; Timestamps API
  21591. ;; This section contains tools to operate on timestamp objects, as
  21592. ;; returned by, e.g. `org-element-context'.
  21593. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21594. "Encode TIMESTAMP object into Emacs internal time.
  21595. Use end of date range or time range when END is non-nil."
  21596. (apply #'encode-time
  21597. (cons 0
  21598. (mapcar
  21599. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21600. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21601. '(:minute-start :hour-start :day-start :month-start
  21602. :year-start))))))
  21603. (defun org-timestamp-has-time-p (timestamp)
  21604. "Non-nil when TIMESTAMP has a time specified."
  21605. (org-element-property :hour-start timestamp))
  21606. (defun org-timestamp-format (timestamp format &optional end utc)
  21607. "Format a TIMESTAMP object into a string.
  21608. FORMAT is a format specifier to be passed to
  21609. `format-time-string'.
  21610. When optional argument END is non-nil, use end of date-range or
  21611. time-range, if possible.
  21612. When optional argument UTC is non-nil, time will be expressed as
  21613. Universal Time."
  21614. (format-time-string
  21615. format (org-timestamp--to-internal-time timestamp end)
  21616. (and utc t)))
  21617. (defun org-timestamp-split-range (timestamp &optional end)
  21618. "Extract a TIMESTAMP object from a date or time range.
  21619. END, when non-nil, means extract the end of the range.
  21620. Otherwise, extract its start.
  21621. Return a new timestamp object."
  21622. (let ((type (org-element-property :type timestamp)))
  21623. (if (memq type '(active inactive diary)) timestamp
  21624. (let ((split-ts (org-element-copy timestamp)))
  21625. ;; Set new type.
  21626. (org-element-put-property
  21627. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21628. ;; Copy start properties over end properties if END is
  21629. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21630. (let ((p-alist '((:minute-start . :minute-end)
  21631. (:hour-start . :hour-end)
  21632. (:day-start . :day-end)
  21633. (:month-start . :month-end)
  21634. (:year-start . :year-end))))
  21635. (dolist (p-cell p-alist)
  21636. (org-element-put-property
  21637. split-ts
  21638. (funcall (if end #'car #'cdr) p-cell)
  21639. (org-element-property
  21640. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21641. ;; Eventually refresh `:raw-value'.
  21642. (org-element-put-property split-ts :raw-value nil)
  21643. (org-element-put-property
  21644. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21645. (defun org-timestamp-translate (timestamp &optional boundary)
  21646. "Translate TIMESTAMP object to custom format.
  21647. Format string is defined in `org-time-stamp-custom-formats',
  21648. which see.
  21649. When optional argument BOUNDARY is non-nil, it is either the
  21650. symbol `start' or `end'. In this case, only translate the
  21651. starting or ending part of TIMESTAMP if it is a date or time
  21652. range. Otherwise, translate both parts.
  21653. Return timestamp as-is if `org-display-custom-times' is nil or if
  21654. it has a `diary' type."
  21655. (let ((type (org-element-property :type timestamp)))
  21656. (if (or (not org-display-custom-times) (eq type 'diary))
  21657. (org-element-interpret-data timestamp)
  21658. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21659. org-time-stamp-custom-formats)))
  21660. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21661. (concat (org-timestamp-format timestamp fmt)
  21662. "--"
  21663. (org-timestamp-format timestamp fmt t))
  21664. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21665. ;;; Other stuff.
  21666. (defvar reftex-docstruct-symbol)
  21667. (defvar org--rds)
  21668. (defun org-reftex-citation ()
  21669. "Use reftex-citation to insert a citation into the buffer.
  21670. This looks for a line like
  21671. #+BIBLIOGRAPHY: foo plain option:-d
  21672. and derives from it that foo.bib is the bibliography file relevant
  21673. for this document. It then installs the necessary environment for RefTeX
  21674. to work in this buffer and calls `reftex-citation' to insert a citation
  21675. into the buffer.
  21676. Export of such citations to both LaTeX and HTML is handled by the contributed
  21677. package ox-bibtex by Taru Karttunen."
  21678. (interactive)
  21679. (let ((reftex-docstruct-symbol 'org--rds)
  21680. org--rds bib)
  21681. (org-with-wide-buffer
  21682. (let ((case-fold-search t)
  21683. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21684. (if (not (save-excursion
  21685. (or (re-search-forward re nil t)
  21686. (re-search-backward re nil t))))
  21687. (user-error "No bibliography defined in file")
  21688. (setq bib (concat (match-string 1) ".bib")
  21689. org--rds (list (list 'bib bib))))))
  21690. (call-interactively 'reftex-citation)))
  21691. ;;;; Functions extending outline functionality
  21692. (defun org-beginning-of-line (&optional n)
  21693. "Go to the beginning of the current visible line.
  21694. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21695. tags on the first attempt, and only move to after the tags when
  21696. the cursor is already beyond the end of the headline.
  21697. With argument N not nil or 1, move forward N - 1 lines first."
  21698. (interactive "^p")
  21699. (let ((origin (point))
  21700. (special (pcase org-special-ctrl-a/e
  21701. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21702. deactivate-mark)
  21703. ;; First move to a visible line.
  21704. (if (bound-and-true-p visual-line-mode)
  21705. (beginning-of-visual-line n)
  21706. (move-beginning-of-line n)
  21707. ;; `move-beginning-of-line' may leave point after invisible
  21708. ;; characters if line starts with such of these (e.g., with
  21709. ;; a link at column 0). Really move to the beginning of the
  21710. ;; current visible line.
  21711. (beginning-of-line))
  21712. (cond
  21713. ;; No special behavior. Point is already at the beginning of
  21714. ;; a line, logical or visual.
  21715. ((not special))
  21716. ;; `beginning-of-visual-line' left point before logical beginning
  21717. ;; of line: point is at the beginning of a visual line. Bail
  21718. ;; out.
  21719. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21720. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21721. ;; At a headline, special position is before the title, but
  21722. ;; after any TODO keyword or priority cookie.
  21723. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21724. (line-end-position)))
  21725. (bol (point)))
  21726. (if (eq special 'reversed)
  21727. (when (and (= origin bol) (eq last-command this-command))
  21728. (goto-char refpos))
  21729. (when (or (> origin refpos) (= origin bol))
  21730. (goto-char refpos)))))
  21731. ((and (looking-at org-list-full-item-re)
  21732. (memq (org-element-type (save-match-data (org-element-at-point)))
  21733. '(item plain-list)))
  21734. ;; Set special position at first white space character after
  21735. ;; bullet, and check-box, if any.
  21736. (let ((after-bullet
  21737. (let ((box (match-end 3)))
  21738. (cond ((not box) (match-end 1))
  21739. ((eq (char-after box) ?\s) (1+ box))
  21740. (t box)))))
  21741. (if (eq special 'reversed)
  21742. (when (and (= (point) origin) (eq last-command this-command))
  21743. (goto-char after-bullet))
  21744. (when (or (> origin after-bullet) (= (point) origin))
  21745. (goto-char after-bullet)))))
  21746. ;; No special context. Point is already at beginning of line.
  21747. (t nil))))
  21748. (defun org-end-of-line (&optional n)
  21749. "Go to the end of the line, but before ellipsis, if any.
  21750. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21751. tags on the first attempt, and only move to after the tags when
  21752. the cursor is already beyond the end of the headline.
  21753. With argument N not nil or 1, move forward N - 1 lines first."
  21754. (interactive "^p")
  21755. (let ((origin (point))
  21756. (special (pcase org-special-ctrl-a/e
  21757. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21758. deactivate-mark)
  21759. ;; First move to a visible line.
  21760. (if (bound-and-true-p visual-line-mode)
  21761. (beginning-of-visual-line n)
  21762. (move-beginning-of-line n))
  21763. (cond
  21764. ;; At a headline, with tags.
  21765. ((and special
  21766. (save-excursion
  21767. (beginning-of-line)
  21768. (let ((case-fold-search nil))
  21769. (looking-at org-complex-heading-regexp)))
  21770. (match-end 5))
  21771. (let ((tags (save-excursion
  21772. (goto-char (match-beginning 5))
  21773. (skip-chars-backward " \t")
  21774. (point)))
  21775. (visual-end (and (bound-and-true-p visual-line-mode)
  21776. (save-excursion
  21777. (end-of-visual-line)
  21778. (point)))))
  21779. ;; If `end-of-visual-line' brings us before end of line or
  21780. ;; even tags, i.e., the headline spans over multiple visual
  21781. ;; lines, move there.
  21782. (cond ((and visual-end
  21783. (< visual-end tags)
  21784. (<= origin visual-end))
  21785. (goto-char visual-end))
  21786. ((eq special 'reversed)
  21787. (if (and (= origin (line-end-position))
  21788. (eq this-command last-command))
  21789. (goto-char tags)
  21790. (end-of-line)))
  21791. (t
  21792. (if (or (< origin tags) (= origin (line-end-position)))
  21793. (goto-char tags)
  21794. (end-of-line))))))
  21795. ((bound-and-true-p visual-line-mode)
  21796. (let ((bol (line-beginning-position)))
  21797. (end-of-visual-line)
  21798. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21799. ;; end of a line, backtrack and use `end-of-line' instead.
  21800. (when (/= bol (line-beginning-position))
  21801. (goto-char bol)
  21802. (end-of-line))))
  21803. (t (end-of-line)))))
  21804. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21805. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21806. (defun org-backward-sentence (&optional _arg)
  21807. "Go to beginning of sentence, or beginning of table field.
  21808. This will call `backward-sentence' or `org-table-beginning-of-field',
  21809. depending on context."
  21810. (interactive)
  21811. (let* ((element (org-element-at-point))
  21812. (contents-begin (org-element-property :contents-begin element))
  21813. (table (org-element-lineage element '(table) t)))
  21814. (if (and table
  21815. (> (point) contents-begin)
  21816. (<= (point) (org-element-property :contents-end table)))
  21817. (call-interactively #'org-table-beginning-of-field)
  21818. (save-restriction
  21819. (when (and contents-begin
  21820. (< (point-min) contents-begin)
  21821. (> (point) contents-begin))
  21822. (narrow-to-region contents-begin
  21823. (org-element-property :contents-end element)))
  21824. (call-interactively #'backward-sentence)))))
  21825. (defun org-forward-sentence (&optional _arg)
  21826. "Go to end of sentence, or end of table field.
  21827. This will call `forward-sentence' or `org-table-end-of-field',
  21828. depending on context."
  21829. (interactive)
  21830. (let* ((element (org-element-at-point))
  21831. (contents-end (org-element-property :contents-end element))
  21832. (table (org-element-lineage element '(table) t)))
  21833. (if (and table
  21834. (>= (point) (org-element-property :contents-begin table))
  21835. (< (point) contents-end))
  21836. (call-interactively #'org-table-end-of-field)
  21837. (save-restriction
  21838. (when (and contents-end
  21839. (> (point-max) contents-end)
  21840. ;; Skip blank lines between elements.
  21841. (< (org-element-property :end element)
  21842. (save-excursion (goto-char contents-end)
  21843. (skip-chars-forward " \r\t\n"))))
  21844. (narrow-to-region (org-element-property :contents-begin element)
  21845. contents-end))
  21846. (call-interactively #'forward-sentence)))))
  21847. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21848. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21849. (defun org-kill-line (&optional _arg)
  21850. "Kill line, to tags or end of line."
  21851. (interactive)
  21852. (cond
  21853. ((or (not org-special-ctrl-k)
  21854. (bolp)
  21855. (not (org-at-heading-p)))
  21856. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21857. org-ctrl-k-protect-subtree
  21858. (or (eq org-ctrl-k-protect-subtree 'error)
  21859. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21860. (user-error "C-k aborted as it would kill a hidden subtree"))
  21861. (call-interactively
  21862. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21863. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21864. (kill-region (point) (match-beginning 1))
  21865. (org-set-tags nil t))
  21866. (t (kill-region (point) (point-at-eol)))))
  21867. (define-key org-mode-map "\C-k" 'org-kill-line)
  21868. (defun org-yank (&optional arg)
  21869. "Yank. If the kill is a subtree, treat it specially.
  21870. This command will look at the current kill and check if is a single
  21871. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21872. cursor is at the beginning of a line or after the stars of a currently
  21873. empty headline, then the yank is handled specially. How exactly depends
  21874. on the value of the following variables.
  21875. `org-yank-folded-subtrees'
  21876. By default, this variable is non-nil, which results in
  21877. subtree(s) being folded after insertion, except if doing so
  21878. would swallow text after the yanked text.
  21879. `org-yank-adjusted-subtrees'
  21880. When non-nil (the default value is nil), the subtree will be
  21881. promoted or demoted in order to fit into the local outline tree
  21882. structure, which means that the level will be adjusted so that it
  21883. becomes the smaller one of the two *visible* surrounding headings.
  21884. Any prefix to this command will cause `yank' to be called directly with
  21885. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21886. will just
  21887. plainly yank the text as it is.
  21888. \[1] The test checks if the first non-white line is a heading
  21889. and if there are no other headings with fewer stars."
  21890. (interactive "P")
  21891. (org-yank-generic 'yank arg))
  21892. (defun org-yank-generic (command arg)
  21893. "Perform some yank-like command.
  21894. This function implements the behavior described in the `org-yank'
  21895. documentation. However, it has been generalized to work for any
  21896. interactive command with similar behavior."
  21897. ;; pretend to be command COMMAND
  21898. (setq this-command command)
  21899. (if arg
  21900. (call-interactively command)
  21901. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21902. (and (org-kill-is-subtree-p)
  21903. (or (bolp)
  21904. (and (looking-at "[ \t]*$")
  21905. (string-match
  21906. "\\`\\*+\\'"
  21907. (buffer-substring (point-at-bol) (point)))))))
  21908. swallowp)
  21909. (cond
  21910. ((and subtreep org-yank-folded-subtrees)
  21911. (let ((beg (point))
  21912. end)
  21913. (if (and subtreep org-yank-adjusted-subtrees)
  21914. (org-paste-subtree nil nil 'for-yank)
  21915. (call-interactively command))
  21916. (setq end (point))
  21917. (goto-char beg)
  21918. (when (and (bolp) subtreep
  21919. (not (setq swallowp
  21920. (org-yank-folding-would-swallow-text beg end))))
  21921. (org-with-limited-levels
  21922. (or (looking-at org-outline-regexp)
  21923. (re-search-forward org-outline-regexp-bol end t))
  21924. (while (and (< (point) end) (looking-at org-outline-regexp))
  21925. (outline-hide-subtree)
  21926. (org-cycle-show-empty-lines 'folded)
  21927. (condition-case nil
  21928. (outline-forward-same-level 1)
  21929. (error (goto-char end))))))
  21930. (when swallowp
  21931. (message
  21932. "Inserted text not folded because that would swallow text"))
  21933. (goto-char end)
  21934. (skip-chars-forward " \t\n\r")
  21935. (beginning-of-line 1)
  21936. (push-mark beg 'nomsg)))
  21937. ((and subtreep org-yank-adjusted-subtrees)
  21938. (let ((beg (point-at-bol)))
  21939. (org-paste-subtree nil nil 'for-yank)
  21940. (push-mark beg 'nomsg)))
  21941. (t
  21942. (call-interactively command))))))
  21943. (defun org-yank-folding-would-swallow-text (beg end)
  21944. "Would hide-subtree at BEG swallow any text after END?"
  21945. (let (level)
  21946. (org-with-limited-levels
  21947. (save-excursion
  21948. (goto-char beg)
  21949. (when (or (looking-at org-outline-regexp)
  21950. (re-search-forward org-outline-regexp-bol end t))
  21951. (setq level (org-outline-level)))
  21952. (goto-char end)
  21953. (skip-chars-forward " \t\r\n\v\f")
  21954. (not (or (eobp)
  21955. (and (bolp) (looking-at-p org-outline-regexp)
  21956. (<= (org-outline-level) level))))))))
  21957. (define-key org-mode-map "\C-y" 'org-yank)
  21958. (defun org-truely-invisible-p ()
  21959. "Check if point is at a character currently not visible.
  21960. This version does not only check the character property, but also
  21961. `visible-mode'."
  21962. ;; Early versions of noutline don't have `outline-invisible-p'.
  21963. (unless (bound-and-true-p visible-mode)
  21964. (outline-invisible-p)))
  21965. (defun org-invisible-p2 ()
  21966. "Check if point is at a character currently not visible."
  21967. (save-excursion
  21968. (when (and (eolp) (not (bobp))) (backward-char 1))
  21969. ;; Early versions of noutline don't have `outline-invisible-p'.
  21970. (outline-invisible-p)))
  21971. (defun org-back-to-heading (&optional invisible-ok)
  21972. "Call `outline-back-to-heading', but provide a better error message."
  21973. (condition-case nil
  21974. (outline-back-to-heading invisible-ok)
  21975. (error (error "Before first headline at position %d in buffer %s"
  21976. (point) (current-buffer)))))
  21977. (defun org-before-first-heading-p ()
  21978. "Before first heading?"
  21979. (save-excursion
  21980. (end-of-line)
  21981. (null (re-search-backward org-outline-regexp-bol nil t))))
  21982. (defun org-at-heading-p (&optional ignored)
  21983. (outline-on-heading-p t))
  21984. (defun org-in-commented-heading-p (&optional no-inheritance)
  21985. "Non-nil if point is under a commented heading.
  21986. This function also checks ancestors of the current headline,
  21987. unless optional argument NO-INHERITANCE is non-nil."
  21988. (cond
  21989. ((org-before-first-heading-p) nil)
  21990. ((let ((headline (nth 4 (org-heading-components))))
  21991. (and headline
  21992. (let ((case-fold-search nil))
  21993. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21994. headline)))))
  21995. (no-inheritance nil)
  21996. (t
  21997. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21998. (defun org-at-comment-p nil
  21999. "Is cursor in a commented line?"
  22000. (save-excursion
  22001. (save-match-data
  22002. (beginning-of-line)
  22003. (looking-at "^[ \t]*# "))))
  22004. (defun org-at-drawer-p nil
  22005. "Is cursor at a drawer keyword?"
  22006. (save-excursion
  22007. (move-beginning-of-line 1)
  22008. (looking-at org-drawer-regexp)))
  22009. (defun org-at-block-p nil
  22010. "Is cursor at a block keyword?"
  22011. (save-excursion
  22012. (move-beginning-of-line 1)
  22013. (looking-at org-block-regexp)))
  22014. (defun org-point-at-end-of-empty-headline ()
  22015. "If point is at the end of an empty headline, return t, else nil.
  22016. If the heading only contains a TODO keyword, it is still still considered
  22017. empty."
  22018. (let ((case-fold-search nil))
  22019. (and (looking-at "[ \t]*$")
  22020. org-todo-line-regexp
  22021. (save-excursion
  22022. (beginning-of-line)
  22023. (looking-at org-todo-line-regexp)
  22024. (string= (match-string 3) "")))))
  22025. (defun org-at-heading-or-item-p ()
  22026. (or (org-at-heading-p) (org-at-item-p)))
  22027. (defun org-at-target-p ()
  22028. (or (org-in-regexp org-radio-target-regexp)
  22029. (org-in-regexp org-target-regexp)))
  22030. ;; Compatibility alias with Org versions < 7.8.03
  22031. (defalias 'org-on-target-p 'org-at-target-p)
  22032. (defun org-up-heading-all (arg)
  22033. "Move to the heading line of which the present line is a subheading.
  22034. This function considers both visible and invisible heading lines.
  22035. With argument, move up ARG levels."
  22036. (outline-up-heading arg t))
  22037. (defun org-up-heading-safe ()
  22038. "Move to the heading line of which the present line is a subheading.
  22039. This version will not throw an error. It will return the level of the
  22040. headline found, or nil if no higher level is found.
  22041. Also, this function will be a lot faster than `outline-up-heading',
  22042. because it relies on stars being the outline starters. This can really
  22043. make a significant difference in outlines with very many siblings."
  22044. (when (ignore-errors (org-back-to-heading t))
  22045. (let ((level-up (1- (funcall outline-level))))
  22046. (and (> level-up 0)
  22047. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22048. (funcall outline-level)))))
  22049. (defun org-first-sibling-p ()
  22050. "Is this heading the first child of its parents?"
  22051. (interactive)
  22052. (let ((re org-outline-regexp-bol)
  22053. level l)
  22054. (unless (org-at-heading-p t)
  22055. (user-error "Not at a heading"))
  22056. (setq level (funcall outline-level))
  22057. (save-excursion
  22058. (if (not (re-search-backward re nil t))
  22059. t
  22060. (setq l (funcall outline-level))
  22061. (< l level)))))
  22062. (defun org-goto-sibling (&optional previous)
  22063. "Goto the next sibling, even if it is invisible.
  22064. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22065. when a sibling was found. When none is found, return nil and don't
  22066. move point."
  22067. (let ((fun (if previous 're-search-backward 're-search-forward))
  22068. (pos (point))
  22069. (re org-outline-regexp-bol)
  22070. level l)
  22071. (when (ignore-errors (org-back-to-heading t))
  22072. (setq level (funcall outline-level))
  22073. (catch 'exit
  22074. (or previous (forward-char 1))
  22075. (while (funcall fun re nil t)
  22076. (setq l (funcall outline-level))
  22077. (when (< l level) (goto-char pos) (throw 'exit nil))
  22078. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22079. (goto-char pos)
  22080. nil))))
  22081. (defun org-show-siblings ()
  22082. "Show all siblings of the current headline."
  22083. (save-excursion
  22084. (while (org-goto-sibling) (org-flag-heading nil)))
  22085. (save-excursion
  22086. (while (org-goto-sibling 'previous)
  22087. (org-flag-heading nil))))
  22088. (defun org-goto-first-child ()
  22089. "Goto the first child, even if it is invisible.
  22090. Return t when a child was found. Otherwise don't move point and
  22091. return nil."
  22092. (let (level (pos (point)) (re org-outline-regexp-bol))
  22093. (when (ignore-errors (org-back-to-heading t))
  22094. (setq level (outline-level))
  22095. (forward-char 1)
  22096. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22097. (progn (goto-char (match-beginning 0)) t)
  22098. (goto-char pos) nil))))
  22099. (defun org-show-hidden-entry ()
  22100. "Show an entry where even the heading is hidden."
  22101. (save-excursion
  22102. (org-show-entry)))
  22103. (defun org-flag-heading (flag &optional entry)
  22104. "Flag the current heading. FLAG non-nil means make invisible.
  22105. When ENTRY is non-nil, show the entire entry."
  22106. (save-excursion
  22107. (org-back-to-heading t)
  22108. ;; Check if we should show the entire entry
  22109. (if entry
  22110. (progn
  22111. (org-show-entry)
  22112. (save-excursion
  22113. (and (outline-next-heading)
  22114. (org-flag-heading nil))))
  22115. (outline-flag-region (max (point-min) (1- (point)))
  22116. (save-excursion (outline-end-of-heading) (point))
  22117. flag))))
  22118. (defun org-get-next-sibling ()
  22119. "Move to next heading of the same level, and return point.
  22120. If there is no such heading, return nil.
  22121. This is like outline-next-sibling, but invisible headings are ok."
  22122. (let ((level (funcall outline-level)))
  22123. (outline-next-heading)
  22124. (while (and (not (eobp)) (> (funcall outline-level) level))
  22125. (outline-next-heading))
  22126. (unless (or (eobp) (< (funcall outline-level) level))
  22127. (point))))
  22128. (defun org-get-last-sibling ()
  22129. "Move to previous heading of the same level, and return point.
  22130. If there is no such heading, return nil."
  22131. (let ((opoint (point))
  22132. (level (funcall outline-level)))
  22133. (outline-previous-heading)
  22134. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22135. (while (and (> (funcall outline-level) level)
  22136. (not (bobp)))
  22137. (outline-previous-heading))
  22138. (unless (< (funcall outline-level) level)
  22139. (point)))))
  22140. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22141. "Goto to the end of a subtree."
  22142. ;; This contains an exact copy of the original function, but it uses
  22143. ;; `org-back-to-heading', to make it work also in invisible
  22144. ;; trees. And is uses an invisible-ok argument.
  22145. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22146. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22147. ;; with many children and grandchildren etc, this can be much faster
  22148. ;; than the outline version.
  22149. (org-back-to-heading invisible-ok)
  22150. (let ((first t)
  22151. (level (funcall outline-level)))
  22152. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22153. ;; A true heading (not a plain list item), in Org
  22154. ;; This means we can easily find the end by looking
  22155. ;; only for the right number of stars. Using a regexp to do
  22156. ;; this is so much faster than using a Lisp loop.
  22157. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22158. (forward-char 1)
  22159. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22160. ;; something else, do it the slow way
  22161. (while (and (not (eobp))
  22162. (or first (> (funcall outline-level) level)))
  22163. (setq first nil)
  22164. (outline-next-heading)))
  22165. (unless to-heading
  22166. (when (memq (preceding-char) '(?\n ?\^M))
  22167. ;; Go to end of line before heading
  22168. (forward-char -1)
  22169. (when (memq (preceding-char) '(?\n ?\^M))
  22170. ;; leave blank line before heading
  22171. (forward-char -1)))))
  22172. (point))
  22173. (defun org-end-of-meta-data (&optional full)
  22174. "Skip planning line and properties drawer in current entry.
  22175. When optional argument FULL is non-nil, also skip empty lines,
  22176. clocking lines and regular drawers at the beginning of the
  22177. entry."
  22178. (org-back-to-heading t)
  22179. (forward-line)
  22180. (when (looking-at-p org-planning-line-re) (forward-line))
  22181. (when (looking-at org-property-drawer-re)
  22182. (goto-char (match-end 0))
  22183. (forward-line))
  22184. (when (and full (not (org-at-heading-p)))
  22185. (catch 'exit
  22186. (let ((end (save-excursion (outline-next-heading) (point)))
  22187. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22188. (while (not (eobp))
  22189. (cond ((looking-at-p org-drawer-regexp)
  22190. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22191. (forward-line)
  22192. (throw 'exit t)))
  22193. ((looking-at-p re) (forward-line))
  22194. (t (throw 'exit t))))))))
  22195. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22196. "Move forward to the ARG'th subheading at same level as this one.
  22197. Stop at the first and last subheadings of a superior heading.
  22198. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22199. non-nil it will also look at invisible ones."
  22200. (interactive "p")
  22201. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22202. (if (and arg (< arg 0))
  22203. (goto-char (point-min))
  22204. (outline-next-heading))
  22205. (org-at-heading-p)
  22206. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22207. (f (if (and arg (< arg 0))
  22208. 're-search-backward
  22209. 're-search-forward))
  22210. (count (if arg (abs arg) 1))
  22211. (result (point)))
  22212. (while (and (prog1 (> count 0)
  22213. (forward-char (if (and arg (< arg 0)) -1 1)))
  22214. (funcall f org-outline-regexp-bol nil 'move))
  22215. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22216. (cond ((< l level) (setq count 0))
  22217. ((and (= l level)
  22218. (or invisible-ok
  22219. (progn
  22220. (goto-char (line-beginning-position))
  22221. (not (outline-invisible-p)))))
  22222. (setq count (1- count))
  22223. (when (eq l level)
  22224. (setq result (point)))))))
  22225. (goto-char result))
  22226. (beginning-of-line 1)))
  22227. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22228. "Move backward to the ARG'th subheading at same level as this one.
  22229. Stop at the first and last subheadings of a superior heading."
  22230. (interactive "p")
  22231. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22232. (defun org-next-visible-heading (arg)
  22233. "Move to the next visible heading.
  22234. This function wraps `outline-next-visible-heading' with
  22235. `org-with-limited-levels' in order to skip over inline tasks and
  22236. respect customization of `org-odd-levels-only'."
  22237. (interactive "p")
  22238. (org-with-limited-levels
  22239. (outline-next-visible-heading arg)))
  22240. (defun org-previous-visible-heading (arg)
  22241. "Move to the previous visible heading.
  22242. This function wraps `outline-previous-visible-heading' with
  22243. `org-with-limited-levels' in order to skip over inline tasks and
  22244. respect customization of `org-odd-levels-only'."
  22245. (interactive "p")
  22246. (org-with-limited-levels
  22247. (outline-previous-visible-heading arg)))
  22248. (defun org-next-block (arg &optional backward block-regexp)
  22249. "Jump to the next block.
  22250. With a prefix argument ARG, jump forward ARG many blocks.
  22251. When BACKWARD is non-nil, jump to the previous block.
  22252. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22253. Match data is set according to this regexp when the function
  22254. returns.
  22255. Return point at beginning of the opening line of found block.
  22256. Throw an error if no block is found."
  22257. (interactive "p")
  22258. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22259. (case-fold-search t)
  22260. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22261. (count (or arg 1))
  22262. (origin (point))
  22263. last-element)
  22264. (if backward (beginning-of-line) (end-of-line))
  22265. (while (and (> count 0) (funcall search-fn re nil t))
  22266. (let ((element (save-excursion
  22267. (goto-char (match-beginning 0))
  22268. (save-match-data (org-element-at-point)))))
  22269. (when (and (memq (org-element-type element)
  22270. '(center-block comment-block dynamic-block
  22271. example-block export-block quote-block
  22272. special-block src-block verse-block))
  22273. (<= (match-beginning 0)
  22274. (org-element-property :post-affiliated element)))
  22275. (setq last-element element)
  22276. (cl-decf count))))
  22277. (if (= count 0)
  22278. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22279. (save-match-data (org-show-context)))
  22280. (goto-char origin)
  22281. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22282. (defun org-previous-block (arg &optional block-regexp)
  22283. "Jump to the previous block.
  22284. With a prefix argument ARG, jump backward ARG many source blocks.
  22285. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22286. (interactive "p")
  22287. (org-next-block arg t block-regexp))
  22288. (defun org-forward-paragraph ()
  22289. "Move forward to beginning of next paragraph or equivalent.
  22290. The function moves point to the beginning of the next visible
  22291. structural element, which can be a paragraph, a table, a list
  22292. item, etc. It also provides some special moves for convenience:
  22293. - On an affiliated keyword, jump to the beginning of the
  22294. relative element.
  22295. - On an item or a footnote definition, move to the second
  22296. element inside, if any.
  22297. - On a table or a property drawer, jump after it.
  22298. - On a verse or source block, stop after blank lines."
  22299. (interactive)
  22300. (when (eobp) (user-error "Cannot move further down"))
  22301. (let* ((deactivate-mark nil)
  22302. (element (org-element-at-point))
  22303. (type (org-element-type element))
  22304. (post-affiliated (org-element-property :post-affiliated element))
  22305. (contents-begin (org-element-property :contents-begin element))
  22306. (contents-end (org-element-property :contents-end element))
  22307. (end (let ((end (org-element-property :end element)) (parent element))
  22308. (while (and (setq parent (org-element-property :parent parent))
  22309. (= (org-element-property :contents-end parent) end))
  22310. (setq end (org-element-property :end parent)))
  22311. end)))
  22312. (cond ((not element)
  22313. (skip-chars-forward " \r\t\n")
  22314. (or (eobp) (beginning-of-line)))
  22315. ;; On affiliated keywords, move to element's beginning.
  22316. ((< (point) post-affiliated)
  22317. (goto-char post-affiliated))
  22318. ;; At a table row, move to the end of the table. Similarly,
  22319. ;; at a node property, move to the end of the property
  22320. ;; drawer.
  22321. ((memq type '(node-property table-row))
  22322. (goto-char (org-element-property
  22323. :end (org-element-property :parent element))))
  22324. ((memq type '(property-drawer table)) (goto-char end))
  22325. ;; Consider blank lines as separators in verse and source
  22326. ;; blocks to ease editing.
  22327. ((memq type '(src-block verse-block))
  22328. (when (eq type 'src-block)
  22329. (setq contents-end
  22330. (save-excursion (goto-char end)
  22331. (skip-chars-backward " \r\t\n")
  22332. (line-beginning-position))))
  22333. (beginning-of-line)
  22334. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22335. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22336. (goto-char end)
  22337. (skip-chars-forward " \r\t\n")
  22338. (if (= (point) contents-end) (goto-char end)
  22339. (beginning-of-line))))
  22340. ;; With no contents, just skip element.
  22341. ((not contents-begin) (goto-char end))
  22342. ;; If contents are invisible, skip the element altogether.
  22343. ((outline-invisible-p (line-end-position))
  22344. (cl-case type
  22345. (headline
  22346. (org-with-limited-levels (outline-next-visible-heading 1)))
  22347. ;; At a plain list, make sure we move to the next item
  22348. ;; instead of skipping the whole list.
  22349. (plain-list (forward-char)
  22350. (org-forward-paragraph))
  22351. (otherwise (goto-char end))))
  22352. ((>= (point) contents-end) (goto-char end))
  22353. ((>= (point) contents-begin)
  22354. ;; This can only happen on paragraphs and plain lists.
  22355. (cl-case type
  22356. (paragraph (goto-char end))
  22357. ;; At a plain list, try to move to second element in
  22358. ;; first item, if possible.
  22359. (plain-list (end-of-line)
  22360. (org-forward-paragraph))))
  22361. ;; When contents start on the middle of a line (e.g. in
  22362. ;; items and footnote definitions), try to reach first
  22363. ;; element starting after current line.
  22364. ((> (line-end-position) contents-begin)
  22365. (end-of-line)
  22366. (org-forward-paragraph))
  22367. (t (goto-char contents-begin)))))
  22368. (defun org-backward-paragraph ()
  22369. "Move backward to start of previous paragraph or equivalent.
  22370. The function moves point to the beginning of the current
  22371. structural element, which can be a paragraph, a table, a list
  22372. item, etc., or to the beginning of the previous visible one if
  22373. point is already there. It also provides some special moves for
  22374. convenience:
  22375. - On an affiliated keyword, jump to the first one.
  22376. - On a table or a property drawer, move to its beginning.
  22377. - On a verse or source block, stop before blank lines."
  22378. (interactive)
  22379. (when (bobp) (user-error "Cannot move further up"))
  22380. (let* ((deactivate-mark nil)
  22381. (element (org-element-at-point))
  22382. (type (org-element-type element))
  22383. (contents-begin (org-element-property :contents-begin element))
  22384. (contents-end (org-element-property :contents-end element))
  22385. (post-affiliated (org-element-property :post-affiliated element))
  22386. (begin (org-element-property :begin element)))
  22387. (cond
  22388. ((not element) (goto-char (point-min)))
  22389. ((= (point) begin)
  22390. (backward-char)
  22391. (org-backward-paragraph))
  22392. ((<= (point) post-affiliated) (goto-char begin))
  22393. ((memq type '(node-property table-row))
  22394. (goto-char (org-element-property
  22395. :post-affiliated (org-element-property :parent element))))
  22396. ((memq type '(property-drawer table)) (goto-char begin))
  22397. ((memq type '(src-block verse-block))
  22398. (when (eq type 'src-block)
  22399. (setq contents-begin
  22400. (save-excursion (goto-char begin) (forward-line) (point))))
  22401. (if (= (point) contents-begin) (goto-char post-affiliated)
  22402. ;; Inside a verse block, see blank lines as paragraph
  22403. ;; separators.
  22404. (let ((origin (point)))
  22405. (skip-chars-backward " \r\t\n" contents-begin)
  22406. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22407. (skip-chars-forward " \r\t\n" origin)
  22408. (if (= (point) origin) (goto-char contents-begin)
  22409. (beginning-of-line))))))
  22410. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22411. ((eq type 'paragraph)
  22412. (goto-char contents-begin)
  22413. ;; When at first paragraph in an item or a footnote definition,
  22414. ;; move directly to beginning of line.
  22415. (let ((parent-contents
  22416. (org-element-property
  22417. :contents-begin (org-element-property :parent element))))
  22418. (when (and parent-contents (= parent-contents contents-begin))
  22419. (beginning-of-line))))
  22420. ;; At the end of a greater element, move to the beginning of the
  22421. ;; last element within.
  22422. ((>= (point) contents-end)
  22423. (goto-char (1- contents-end))
  22424. (org-backward-paragraph))
  22425. (t (goto-char (or post-affiliated begin))))
  22426. ;; Ensure we never leave point invisible.
  22427. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22428. (defun org-forward-element ()
  22429. "Move forward by one element.
  22430. Move to the next element at the same level, when possible."
  22431. (interactive)
  22432. (cond ((eobp) (user-error "Cannot move further down"))
  22433. ((org-with-limited-levels (org-at-heading-p))
  22434. (let ((origin (point)))
  22435. (goto-char (org-end-of-subtree nil t))
  22436. (unless (org-with-limited-levels (org-at-heading-p))
  22437. (goto-char origin)
  22438. (user-error "Cannot move further down"))))
  22439. (t
  22440. (let* ((elem (org-element-at-point))
  22441. (end (org-element-property :end elem))
  22442. (parent (org-element-property :parent elem)))
  22443. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22444. (goto-char (org-element-property :end parent)))
  22445. ((integer-or-marker-p end) (goto-char end))
  22446. (t (message "No element at point")))))))
  22447. (defun org-backward-element ()
  22448. "Move backward by one element.
  22449. Move to the previous element at the same level, when possible."
  22450. (interactive)
  22451. (cond ((bobp) (user-error "Cannot move further up"))
  22452. ((org-with-limited-levels (org-at-heading-p))
  22453. ;; At a headline, move to the previous one, if any, or stay
  22454. ;; here.
  22455. (let ((origin (point)))
  22456. (org-with-limited-levels (org-backward-heading-same-level 1))
  22457. ;; When current headline has no sibling above, move to its
  22458. ;; parent.
  22459. (when (= (point) origin)
  22460. (or (org-with-limited-levels (org-up-heading-safe))
  22461. (progn (goto-char origin)
  22462. (user-error "Cannot move further up"))))))
  22463. (t
  22464. (let* ((elem (org-element-at-point))
  22465. (beg (org-element-property :begin elem)))
  22466. (cond
  22467. ;; Move to beginning of current element if point isn't
  22468. ;; there already.
  22469. ((null beg) (message "No element at point"))
  22470. ((/= (point) beg) (goto-char beg))
  22471. (t (goto-char beg)
  22472. (skip-chars-backward " \r\t\n")
  22473. (unless (bobp)
  22474. (let ((prev (org-element-at-point)))
  22475. (goto-char (org-element-property :begin prev))
  22476. (while (and (setq prev (org-element-property :parent prev))
  22477. (<= (org-element-property :end prev) beg))
  22478. (goto-char (org-element-property :begin prev)))))))))))
  22479. (defun org-up-element ()
  22480. "Move to upper element."
  22481. (interactive)
  22482. (if (org-with-limited-levels (org-at-heading-p))
  22483. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22484. (let* ((elem (org-element-at-point))
  22485. (parent (org-element-property :parent elem)))
  22486. (if parent (goto-char (org-element-property :begin parent))
  22487. (if (org-with-limited-levels (org-before-first-heading-p))
  22488. (user-error "No surrounding element")
  22489. (org-with-limited-levels (org-back-to-heading)))))))
  22490. (defvar org-element-greater-elements)
  22491. (defun org-down-element ()
  22492. "Move to inner element."
  22493. (interactive)
  22494. (let ((element (org-element-at-point)))
  22495. (cond
  22496. ((memq (org-element-type element) '(plain-list table))
  22497. (goto-char (org-element-property :contents-begin element))
  22498. (forward-char))
  22499. ((memq (org-element-type element) org-element-greater-elements)
  22500. ;; If contents are hidden, first disclose them.
  22501. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22502. (goto-char (or (org-element-property :contents-begin element)
  22503. (user-error "No content for this element"))))
  22504. (t (user-error "No inner element")))))
  22505. (defun org-drag-element-backward ()
  22506. "Move backward element at point."
  22507. (interactive)
  22508. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22509. (let* ((elem (or (org-element-at-point)
  22510. (user-error "No element at point")))
  22511. (prev-elem
  22512. (save-excursion
  22513. (goto-char (org-element-property :begin elem))
  22514. (skip-chars-backward " \r\t\n")
  22515. (unless (bobp)
  22516. (let* ((beg (org-element-property :begin elem))
  22517. (prev (org-element-at-point))
  22518. (up prev))
  22519. (while (and (setq up (org-element-property :parent up))
  22520. (<= (org-element-property :end up) beg))
  22521. (setq prev up))
  22522. prev)))))
  22523. ;; Error out if no previous element or previous element is
  22524. ;; a parent of the current one.
  22525. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22526. (user-error "Cannot drag element backward")
  22527. (let ((pos (point)))
  22528. (org-element-swap-A-B prev-elem elem)
  22529. (goto-char (+ (org-element-property :begin prev-elem)
  22530. (- pos (org-element-property :begin elem)))))))))
  22531. (defun org-drag-element-forward ()
  22532. "Move forward element at point."
  22533. (interactive)
  22534. (let* ((pos (point))
  22535. (elem (or (org-element-at-point)
  22536. (user-error "No element at point"))))
  22537. (when (= (point-max) (org-element-property :end elem))
  22538. (user-error "Cannot drag element forward"))
  22539. (goto-char (org-element-property :end elem))
  22540. (let ((next-elem (org-element-at-point)))
  22541. (when (or (org-element-nested-p elem next-elem)
  22542. (and (eq (org-element-type next-elem) 'headline)
  22543. (not (eq (org-element-type elem) 'headline))))
  22544. (goto-char pos)
  22545. (user-error "Cannot drag element forward"))
  22546. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22547. ;; body's length (without final blanks) and by the length of
  22548. ;; blanks between ELEM and NEXT-ELEM.
  22549. (let ((size-next (- (save-excursion
  22550. (goto-char (org-element-property :end next-elem))
  22551. (skip-chars-backward " \r\t\n")
  22552. (forward-line)
  22553. ;; Small correction if buffer doesn't end
  22554. ;; with a newline character.
  22555. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22556. (org-element-property :begin next-elem)))
  22557. (size-blank (- (org-element-property :end elem)
  22558. (save-excursion
  22559. (goto-char (org-element-property :end elem))
  22560. (skip-chars-backward " \r\t\n")
  22561. (forward-line)
  22562. (point)))))
  22563. (org-element-swap-A-B elem next-elem)
  22564. (goto-char (+ pos size-next size-blank))))))
  22565. (defun org-drag-line-forward (arg)
  22566. "Drag the line at point ARG lines forward."
  22567. (interactive "p")
  22568. (dotimes (_ (abs arg))
  22569. (let ((c (current-column)))
  22570. (if (< 0 arg)
  22571. (progn
  22572. (beginning-of-line 2)
  22573. (transpose-lines 1)
  22574. (beginning-of-line 0))
  22575. (transpose-lines 1)
  22576. (beginning-of-line -1))
  22577. (org-move-to-column c))))
  22578. (defun org-drag-line-backward (arg)
  22579. "Drag the line at point ARG lines backward."
  22580. (interactive "p")
  22581. (org-drag-line-forward (- arg)))
  22582. (defun org-mark-element ()
  22583. "Put point at beginning of this element, mark at end.
  22584. Interactively, if this command is repeated or (in Transient Mark
  22585. mode) if the mark is active, it marks the next element after the
  22586. ones already marked."
  22587. (interactive)
  22588. (let (deactivate-mark)
  22589. (if (and (called-interactively-p 'any)
  22590. (or (and (eq last-command this-command) (mark t))
  22591. (and transient-mark-mode mark-active)))
  22592. (set-mark
  22593. (save-excursion
  22594. (goto-char (mark))
  22595. (goto-char (org-element-property :end (org-element-at-point)))))
  22596. (let ((element (org-element-at-point)))
  22597. (end-of-line)
  22598. (push-mark (org-element-property :end element) t t)
  22599. (goto-char (org-element-property :begin element))))))
  22600. (defun org-narrow-to-element ()
  22601. "Narrow buffer to current element."
  22602. (interactive)
  22603. (let ((elem (org-element-at-point)))
  22604. (cond
  22605. ((eq (car elem) 'headline)
  22606. (narrow-to-region
  22607. (org-element-property :begin elem)
  22608. (org-element-property :end elem)))
  22609. ((memq (car elem) org-element-greater-elements)
  22610. (narrow-to-region
  22611. (org-element-property :contents-begin elem)
  22612. (org-element-property :contents-end elem)))
  22613. (t
  22614. (narrow-to-region
  22615. (org-element-property :begin elem)
  22616. (org-element-property :end elem))))))
  22617. (defun org-transpose-element ()
  22618. "Transpose current and previous elements, keeping blank lines between.
  22619. Point is moved after both elements."
  22620. (interactive)
  22621. (org-skip-whitespace)
  22622. (let ((end (org-element-property :end (org-element-at-point))))
  22623. (org-drag-element-backward)
  22624. (goto-char end)))
  22625. (defun org-unindent-buffer ()
  22626. "Un-indent the visible part of the buffer.
  22627. Relative indentation (between items, inside blocks, etc.) isn't
  22628. modified."
  22629. (interactive)
  22630. (unless (eq major-mode 'org-mode)
  22631. (user-error "Cannot un-indent a buffer not in Org mode"))
  22632. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22633. (unindent-tree
  22634. (lambda (contents)
  22635. (dolist (element (reverse contents))
  22636. (if (memq (org-element-type element) '(headline section))
  22637. (funcall unindent-tree (org-element-contents element))
  22638. (save-excursion
  22639. (save-restriction
  22640. (narrow-to-region
  22641. (org-element-property :begin element)
  22642. (org-element-property :end element))
  22643. (org-do-remove-indentation))))))))
  22644. (funcall unindent-tree (org-element-contents parse-tree))))
  22645. (defun org-show-children (&optional level)
  22646. "Show all direct subheadings of this heading.
  22647. Prefix arg LEVEL is how many levels below the current level
  22648. should be shown. Default is enough to cause the following
  22649. heading to appear."
  22650. (interactive "p")
  22651. ;; If `orgstruct-mode' is active, use the slower version.
  22652. (if orgstruct-mode (call-interactively #'outline-show-children)
  22653. (save-excursion
  22654. (org-back-to-heading t)
  22655. (let* ((current-level (funcall outline-level))
  22656. (max-level (org-get-valid-level
  22657. current-level
  22658. (if level (prefix-numeric-value level) 1)))
  22659. (end (save-excursion (org-end-of-subtree t t)))
  22660. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22661. (past-first-child nil)
  22662. ;; Make sure to skip inlinetasks.
  22663. (re (format regexp-fmt
  22664. current-level
  22665. (cond
  22666. ((not (featurep 'org-inlinetask)) "")
  22667. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22668. 3))
  22669. (t (1- org-inlinetask-min-level))))))
  22670. ;; Display parent heading.
  22671. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22672. (forward-line)
  22673. ;; Display children. First child may be deeper than expected
  22674. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22675. ;; MAX-LEVEL accordingly.
  22676. (while (re-search-forward re end t)
  22677. (unless past-first-child
  22678. (setq re (format regexp-fmt
  22679. current-level
  22680. (max (funcall outline-level) max-level)))
  22681. (setq past-first-child t))
  22682. (outline-flag-region
  22683. (line-end-position 0) (line-end-position) nil))))))
  22684. (defun org-show-subtree ()
  22685. "Show everything after this heading at deeper levels."
  22686. (interactive)
  22687. (outline-flag-region
  22688. (point)
  22689. (save-excursion
  22690. (org-end-of-subtree t t))
  22691. nil))
  22692. (defun org-show-entry ()
  22693. "Show the body directly following this heading.
  22694. Show the heading too, if it is currently invisible."
  22695. (interactive)
  22696. (save-excursion
  22697. (ignore-errors
  22698. (org-back-to-heading t)
  22699. (outline-flag-region
  22700. (max (point-min) (1- (point)))
  22701. (save-excursion
  22702. (if (re-search-forward
  22703. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22704. (match-beginning 1)
  22705. (point-max)))
  22706. nil)
  22707. (org-cycle-hide-drawers 'children))))
  22708. (defun org-make-options-regexp (kwds &optional extra)
  22709. "Make a regular expression for keyword lines.
  22710. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22711. when non-nil, is a regexp matching keywords names."
  22712. (concat "^[ \t]*#\\+\\("
  22713. (regexp-opt kwds)
  22714. (and extra (concat (and kwds "\\|") extra))
  22715. "\\):[ \t]*\\(.*\\)"))
  22716. ;;;; Integration with and fixes for other packages
  22717. ;;; Imenu support
  22718. (defvar-local org-imenu-markers nil
  22719. "All markers currently used by Imenu.")
  22720. (defun org-imenu-new-marker (&optional pos)
  22721. "Return a new marker for use by Imenu, and remember the marker."
  22722. (let ((m (make-marker)))
  22723. (move-marker m (or pos (point)))
  22724. (push m org-imenu-markers)
  22725. m))
  22726. (defun org-imenu-get-tree ()
  22727. "Produce the index for Imenu."
  22728. (dolist (x org-imenu-markers) (move-marker x nil))
  22729. (setq org-imenu-markers nil)
  22730. (let* ((case-fold-search nil)
  22731. (n org-imenu-depth)
  22732. (re (concat "^" (org-get-limited-outline-regexp)))
  22733. (subs (make-vector (1+ n) nil))
  22734. (last-level 0)
  22735. m level head0 head)
  22736. (org-with-wide-buffer
  22737. (goto-char (point-max))
  22738. (while (re-search-backward re nil t)
  22739. (setq level (org-reduced-level (funcall outline-level)))
  22740. (when (and (<= level n)
  22741. (looking-at org-complex-heading-regexp)
  22742. (setq head0 (match-string-no-properties 4)))
  22743. (setq head (org-link-display-format head0)
  22744. m (org-imenu-new-marker))
  22745. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22746. (if (>= level last-level)
  22747. (push (cons head m) (aref subs level))
  22748. (push (cons head (aref subs (1+ level))) (aref subs level))
  22749. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22750. (setq last-level level))))
  22751. (aref subs 1)))
  22752. (eval-after-load "imenu"
  22753. '(progn
  22754. (add-hook 'imenu-after-jump-hook
  22755. (lambda ()
  22756. (when (derived-mode-p 'org-mode)
  22757. (org-show-context 'org-goto))))))
  22758. (defun org-link-display-format (s)
  22759. "Replace links in string S with their description.
  22760. If there is no description, use the link target."
  22761. (save-match-data
  22762. (replace-regexp-in-string
  22763. org-bracket-link-analytic-regexp
  22764. (lambda (m)
  22765. (if (match-end 5) (match-string 5 m)
  22766. (concat (match-string 1 m) (match-string 3 m))))
  22767. s nil t)))
  22768. (defun org-toggle-link-display ()
  22769. "Toggle the literal or descriptive display of links."
  22770. (interactive)
  22771. (if org-descriptive-links
  22772. (progn (org-remove-from-invisibility-spec '(org-link))
  22773. (org-restart-font-lock)
  22774. (setq org-descriptive-links nil))
  22775. (progn (add-to-invisibility-spec '(org-link))
  22776. (org-restart-font-lock)
  22777. (setq org-descriptive-links t))))
  22778. ;; Speedbar support
  22779. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22780. "Overlay marking the agenda restriction line in speedbar.")
  22781. (overlay-put org-speedbar-restriction-lock-overlay
  22782. 'face 'org-agenda-restriction-lock)
  22783. (overlay-put org-speedbar-restriction-lock-overlay
  22784. 'help-echo "Agendas are currently limited to this item.")
  22785. (delete-overlay org-speedbar-restriction-lock-overlay)
  22786. (defun org-speedbar-set-agenda-restriction ()
  22787. "Restrict future agenda commands to the location at point in speedbar.
  22788. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22789. (interactive)
  22790. (require 'org-agenda)
  22791. (let (p m tp np dir txt)
  22792. (cond
  22793. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22794. 'org-imenu t))
  22795. (setq m (get-text-property p 'org-imenu-marker))
  22796. (with-current-buffer (marker-buffer m)
  22797. (goto-char m)
  22798. (org-agenda-set-restriction-lock 'subtree)))
  22799. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22800. 'speedbar-function 'speedbar-find-file))
  22801. (setq tp (previous-single-property-change
  22802. (1+ p) 'speedbar-function)
  22803. np (next-single-property-change
  22804. tp 'speedbar-function)
  22805. dir (speedbar-line-directory)
  22806. txt (buffer-substring-no-properties (or tp (point-min))
  22807. (or np (point-max))))
  22808. (with-current-buffer (find-file-noselect
  22809. (let ((default-directory dir))
  22810. (expand-file-name txt)))
  22811. (unless (derived-mode-p 'org-mode)
  22812. (user-error "Cannot restrict to non-Org mode file"))
  22813. (org-agenda-set-restriction-lock 'file)))
  22814. (t (user-error "Don't know how to restrict Org mode agenda")))
  22815. (move-overlay org-speedbar-restriction-lock-overlay
  22816. (point-at-bol) (point-at-eol))
  22817. (setq current-prefix-arg nil)
  22818. (org-agenda-maybe-redo)))
  22819. (defvar speedbar-file-key-map)
  22820. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22821. (eval-after-load "speedbar"
  22822. '(progn
  22823. (speedbar-add-supported-extension ".org")
  22824. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22825. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22826. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22827. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22828. (add-hook 'speedbar-visiting-tag-hook
  22829. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22830. ;;; Fixes and Hacks for problems with other packages
  22831. (defun org--flyspell-object-check-p (element)
  22832. "Non-nil when Flyspell can check object at point.
  22833. ELEMENT is the element at point."
  22834. (let ((object (save-excursion
  22835. (when (looking-at-p "\\>") (backward-char))
  22836. (org-element-context element))))
  22837. (cl-case (org-element-type object)
  22838. ;; Prevent checks in links due to keybinding conflict with
  22839. ;; Flyspell.
  22840. ((code entity export-snippet inline-babel-call
  22841. inline-src-block line-break latex-fragment link macro
  22842. statistics-cookie target timestamp verbatim)
  22843. nil)
  22844. (footnote-reference
  22845. ;; Only in inline footnotes, within the definition.
  22846. (and (eq (org-element-property :type object) 'inline)
  22847. (< (save-excursion
  22848. (goto-char (org-element-property :begin object))
  22849. (search-forward ":" nil t 2))
  22850. (point))))
  22851. (otherwise t))))
  22852. (defun org-mode-flyspell-verify ()
  22853. "Function used for `flyspell-generic-check-word-predicate'."
  22854. (if (org-at-heading-p)
  22855. ;; At a headline or an inlinetask, check title only. This is
  22856. ;; faster than relying on `org-element-at-point'.
  22857. (and (save-excursion (beginning-of-line)
  22858. (and (let ((case-fold-search t))
  22859. (not (looking-at-p "\\*+ END[ \t]*$")))
  22860. (let ((case-fold-search nil))
  22861. (looking-at org-complex-heading-regexp))))
  22862. (match-beginning 4)
  22863. (>= (point) (match-beginning 4))
  22864. (or (not (match-beginning 5))
  22865. (< (point) (match-beginning 5))))
  22866. (let* ((element (org-element-at-point))
  22867. (post-affiliated (org-element-property :post-affiliated element)))
  22868. (cond
  22869. ;; Ignore checks in all affiliated keywords but captions.
  22870. ((< (point) post-affiliated)
  22871. (and (save-excursion
  22872. (beginning-of-line)
  22873. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22874. (> (point) (match-end 0))
  22875. (org--flyspell-object-check-p element)))
  22876. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22877. ((let ((log (org-log-into-drawer)))
  22878. (and log
  22879. (let ((drawer (org-element-lineage element '(drawer))))
  22880. (and drawer
  22881. (eq (compare-strings
  22882. log nil nil
  22883. (org-element-property :drawer-name drawer) nil nil t)
  22884. t)))))
  22885. nil)
  22886. (t
  22887. (cl-case (org-element-type element)
  22888. ((comment quote-section) t)
  22889. (comment-block
  22890. ;; Allow checks between block markers, not on them.
  22891. (and (> (line-beginning-position) post-affiliated)
  22892. (save-excursion
  22893. (end-of-line)
  22894. (skip-chars-forward " \r\t\n")
  22895. (< (point) (org-element-property :end element)))))
  22896. ;; Arbitrary list of keywords where checks are meaningful.
  22897. ;; Make sure point is on the value part of the element.
  22898. (keyword
  22899. (and (member (org-element-property :key element)
  22900. '("DESCRIPTION" "TITLE"))
  22901. (save-excursion
  22902. (search-backward ":" (line-beginning-position) t))))
  22903. ;; Check is globally allowed in paragraphs verse blocks and
  22904. ;; table rows (after affiliated keywords) but some objects
  22905. ;; must not be affected.
  22906. ((paragraph table-row verse-block)
  22907. (let ((cbeg (org-element-property :contents-begin element))
  22908. (cend (org-element-property :contents-end element)))
  22909. (and cbeg (>= (point) cbeg) (< (point) cend)
  22910. (org--flyspell-object-check-p element))))))))))
  22911. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22912. (defun org-remove-flyspell-overlays-in (beg end)
  22913. "Remove flyspell overlays in region."
  22914. (and (bound-and-true-p flyspell-mode)
  22915. (fboundp 'flyspell-delete-region-overlays)
  22916. (flyspell-delete-region-overlays beg end)))
  22917. (defvar flyspell-delayed-commands)
  22918. (eval-after-load "flyspell"
  22919. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22920. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22921. (eval-after-load "bookmark"
  22922. '(if (boundp 'bookmark-after-jump-hook)
  22923. ;; We can use the hook
  22924. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22925. ;; Hook not available, use advice
  22926. (defadvice bookmark-jump (after org-make-visible activate)
  22927. "Make the position visible."
  22928. (org-bookmark-jump-unhide))))
  22929. ;; Make sure saveplace shows the location if it was hidden
  22930. (eval-after-load "saveplace"
  22931. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22932. "Make the position visible."
  22933. (org-bookmark-jump-unhide)))
  22934. ;; Make sure ecb shows the location if it was hidden
  22935. (eval-after-load "ecb"
  22936. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22937. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22938. (when (derived-mode-p 'org-mode)
  22939. (org-show-context))))
  22940. (defun org-bookmark-jump-unhide ()
  22941. "Unhide the current position, to show the bookmark location."
  22942. (and (derived-mode-p 'org-mode)
  22943. (or (outline-invisible-p)
  22944. (save-excursion (goto-char (max (point-min) (1- (point))))
  22945. (outline-invisible-p)))
  22946. (org-show-context 'bookmark-jump)))
  22947. (defun org-mark-jump-unhide ()
  22948. "Make the point visible with `org-show-context' after jumping to the mark."
  22949. (when (and (derived-mode-p 'org-mode)
  22950. (outline-invisible-p))
  22951. (org-show-context 'mark-goto)))
  22952. (eval-after-load "simple"
  22953. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22954. "Make the point visible with `org-show-context'."
  22955. (org-mark-jump-unhide)))
  22956. (eval-after-load "simple"
  22957. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22958. "Make the point visible with `org-show-context'."
  22959. (org-mark-jump-unhide)))
  22960. (eval-after-load "simple"
  22961. '(defadvice pop-global-mark (after org-make-visible activate)
  22962. "Make the point visible with `org-show-context'."
  22963. (org-mark-jump-unhide)))
  22964. ;; Make session.el ignore our circular variable
  22965. (defvar session-globals-exclude)
  22966. (eval-after-load "session"
  22967. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22968. ;;;; Finish up
  22969. (provide 'org)
  22970. (run-hooks 'org-load-hook)
  22971. ;;; org.el ends here