org.el 900 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. (defvar org-inlinetask-min-level)
  66. ;;;; Require other packages
  67. (require 'cl-lib)
  68. (eval-when-compile (require 'gnus-sum))
  69. (require 'calendar)
  70. (require 'find-func)
  71. (require 'format-spec)
  72. (or (eq this-command 'eval-buffer)
  73. (condition-case nil
  74. (load (concat (file-name-directory load-file-name)
  75. "org-loaddefs.el")
  76. nil t t t)
  77. (error
  78. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  79. (sit-for 3)
  80. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  81. (sit-for 3))))
  82. (require 'org-macs)
  83. (require 'org-compat)
  84. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  85. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  86. (defvar org-outline-regexp "\\*+ "
  87. "Regexp to match Org headlines.")
  88. (defvar org-outline-regexp-bol "^\\*+ "
  89. "Regexp to match Org headlines.
  90. This is similar to `org-outline-regexp' but additionally makes
  91. sure that we are at the beginning of the line.")
  92. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  93. "Matches a headline, putting stars and text into groups.
  94. Stars are put in group 1 and the trimmed body in group 2.")
  95. (declare-function calendar-check-holidays "holidays" (date))
  96. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  97. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  98. (declare-function org-add-archive-files "org-archive" (files))
  99. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  100. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  101. (declare-function org-agenda-redo "org-agenda" (&optional all))
  102. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  103. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  104. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  105. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  106. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  107. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  108. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  109. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  110. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  111. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  112. (declare-function org-clock-update-time-maybe "org-clock" ())
  113. (declare-function org-clocking-buffer "org-clock" ())
  114. (declare-function org-clocktable-shift "org-clock" (dir n))
  115. (declare-function
  116. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  117. (declare-function org-element-at-point "org-element" ())
  118. (declare-function org-element-cache-refresh "org-element" (pos))
  119. (declare-function org-element-cache-reset "org-element" (&optional all))
  120. (declare-function org-element-contents "org-element" (element))
  121. (declare-function org-element-context "org-element" (&optional element))
  122. (declare-function org-element-copy "org-element" (datum))
  123. (declare-function org-element-interpret-data "org-element" (data))
  124. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  125. (declare-function org-element-link-parser "org-element" ())
  126. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  127. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  128. (declare-function org-element-property "org-element" (property element))
  129. (declare-function org-element-put-property "org-element" (element property value))
  130. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  131. (declare-function org-element-type "org-element" (element))
  132. (declare-function org-element-update-syntax "org-element" ())
  133. (declare-function org-id-find-id-file "org-id" (id))
  134. (declare-function org-id-get-create "org-id" (&optional force))
  135. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  136. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  137. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  138. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  139. (declare-function org-table-align "org-table" ())
  140. (declare-function org-table-begin "org-table" (&optional table-type))
  141. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  142. (declare-function org-table-blank-field "org-table" ())
  143. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  144. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  145. (declare-function org-table-cut-region "org-table" (beg end))
  146. (declare-function org-table-edit-field "org-table" (arg))
  147. (declare-function org-table-end "org-table" (&optional table-type))
  148. (declare-function org-table-end-of-field "org-table" (&optional n))
  149. (declare-function org-table-insert-row "org-table" (&optional arg))
  150. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  151. (declare-function org-table-maybe-eval-formula "org-table" ())
  152. (declare-function org-table-maybe-recalculate-line "org-table" ())
  153. (declare-function org-table-next-row "org-table" ())
  154. (declare-function org-table-paste-rectangle "org-table" ())
  155. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  156. (declare-function
  157. org-table-sort-lines "org-table"
  158. (&optional with-case sorting-type getkey-func compare-func interactive?))
  159. (declare-function org-table-shrink "org-table" (&optional begin end))
  160. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  161. (declare-function org-table-wrap-region "org-table" (arg))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  164. (declare-function orgtbl-mode "org-table" (&optional arg))
  165. (declare-function org-export-get-backend "ox" (name))
  166. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  167. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  168. (defvar ffap-url-regexp)
  169. (defvar org-element-paragraph-separate)
  170. ;; load languages based on value of `org-babel-load-languages'
  171. (defvar org-babel-load-languages)
  172. ;;;###autoload
  173. (defun org-babel-do-load-languages (sym value)
  174. "Load the languages defined in `org-babel-load-languages'."
  175. (set-default sym value)
  176. (dolist (pair org-babel-load-languages)
  177. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  178. (if active
  179. (require (intern (concat "ob-" lang)))
  180. (funcall 'fmakunbound
  181. (intern (concat "org-babel-execute:" lang)))
  182. (funcall 'fmakunbound
  183. (intern (concat "org-babel-expand-body:" lang)))))))
  184. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  185. ;;;###autoload
  186. (defun org-babel-load-file (file &optional compile)
  187. "Load Emacs Lisp source code blocks in the Org FILE.
  188. This function exports the source code using `org-babel-tangle'
  189. and then loads the resulting file using `load-file'. With prefix
  190. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  191. file to byte-code before it is loaded."
  192. (interactive "fFile to load: \nP")
  193. (let* ((age (lambda (file)
  194. (float-time
  195. (time-subtract (current-time)
  196. (nth 5 (or (file-attributes (file-truename file))
  197. (file-attributes file)))))))
  198. (base-name (file-name-sans-extension file))
  199. (exported-file (concat base-name ".el")))
  200. ;; tangle if the Org file is newer than the elisp file
  201. (unless (and (file-exists-p exported-file)
  202. (> (funcall age file) (funcall age exported-file)))
  203. ;; Tangle-file traversal returns reversed list of tangled files
  204. ;; and we want to evaluate the first target.
  205. (setq exported-file
  206. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  207. (message "%s %s"
  208. (if compile
  209. (progn (byte-compile-file exported-file 'load)
  210. "Compiled and loaded")
  211. (progn (load-file exported-file) "Loaded"))
  212. exported-file)))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org buffers.
  215. This list can be used to load support for any of the languages
  216. below, note that each language will depend on a different set of
  217. system executables and/or Emacs modes. When a language is
  218. \"loaded\", then code blocks in that language can be evaluated
  219. with `org-babel-execute-src-block' bound by default to C-c
  220. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  221. be set to remove code block evaluation from the C-c C-c
  222. keybinding. By default only Emacs Lisp (which has no
  223. requirements) is loaded."
  224. :group 'org-babel
  225. :set 'org-babel-do-load-languages
  226. :version "24.1"
  227. :type '(alist :tag "Babel Languages"
  228. :key-type
  229. (choice
  230. (const :tag "Awk" awk)
  231. (const :tag "C" C)
  232. (const :tag "R" R)
  233. (const :tag "Asymptote" asymptote)
  234. (const :tag "Calc" calc)
  235. (const :tag "Clojure" clojure)
  236. (const :tag "CSS" css)
  237. (const :tag "Ditaa" ditaa)
  238. (const :tag "Dot" dot)
  239. (const :tag "Ebnf2ps" ebnf2ps)
  240. (const :tag "Emacs Lisp" emacs-lisp)
  241. (const :tag "Forth" forth)
  242. (const :tag "Fortran" fortran)
  243. (const :tag "Gnuplot" gnuplot)
  244. (const :tag "Haskell" haskell)
  245. (const :tag "hledger" hledger)
  246. (const :tag "IO" io)
  247. (const :tag "J" J)
  248. (const :tag "Java" java)
  249. (const :tag "Javascript" js)
  250. (const :tag "LaTeX" latex)
  251. (const :tag "Ledger" ledger)
  252. (const :tag "Lilypond" lilypond)
  253. (const :tag "Lisp" lisp)
  254. (const :tag "Makefile" makefile)
  255. (const :tag "Maxima" maxima)
  256. (const :tag "Matlab" matlab)
  257. (const :tag "Mscgen" mscgen)
  258. (const :tag "Ocaml" ocaml)
  259. (const :tag "Octave" octave)
  260. (const :tag "Org" org)
  261. (const :tag "Perl" perl)
  262. (const :tag "Pico Lisp" picolisp)
  263. (const :tag "PlantUML" plantuml)
  264. (const :tag "Python" python)
  265. (const :tag "Ruby" ruby)
  266. (const :tag "Sass" sass)
  267. (const :tag "Scala" scala)
  268. (const :tag "Scheme" scheme)
  269. (const :tag "Screen" screen)
  270. (const :tag "Shell Script" shell)
  271. (const :tag "Shen" shen)
  272. (const :tag "Sql" sql)
  273. (const :tag "Sqlite" sqlite)
  274. (const :tag "Stan" stan)
  275. (const :tag "Vala" vala))
  276. :value-type (boolean :tag "Activate" :value t)))
  277. ;;;; Customization variables
  278. (defcustom org-clone-delete-id nil
  279. "Remove ID property of clones of a subtree.
  280. When non-nil, clones of a subtree don't inherit the ID property.
  281. Otherwise they inherit the ID property with a new unique
  282. identifier."
  283. :type 'boolean
  284. :version "24.1"
  285. :group 'org-id)
  286. ;;; Version
  287. (org-check-version)
  288. ;;;###autoload
  289. (defun org-version (&optional here full message)
  290. "Show the Org version.
  291. Interactively, or when MESSAGE is non-nil, show it in echo area.
  292. With prefix argument, or when HERE is non-nil, insert it at point.
  293. In non-interactive uses, a reduced version string is output unless
  294. FULL is given."
  295. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  296. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  297. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  298. (load-suffixes (list ".el"))
  299. (org-install-dir
  300. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  301. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  302. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  303. (let* ((load-suffixes save-load-suffixes)
  304. (release (org-release))
  305. (git-version (org-git-version))
  306. (version (format "Org mode version %s (%s @ %s)"
  307. release
  308. git-version
  309. (if org-install-dir
  310. (if (string= org-dir org-install-dir)
  311. org-install-dir
  312. (concat "mixed installation! "
  313. org-install-dir
  314. " and "
  315. org-dir))
  316. "org-loaddefs.el can not be found!")))
  317. (version1 (if full version release)))
  318. (when here (insert version1))
  319. (when message (message "%s" version1))
  320. version1)))
  321. (defconst org-version (org-version))
  322. ;;; Syntax Constants
  323. ;;;; Block
  324. (defconst org-block-regexp
  325. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  326. "Regular expression for hiding blocks.")
  327. (defconst org-dblock-start-re
  328. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  329. "Matches the start line of a dynamic block, with parameters.")
  330. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  331. "Matches the end of a dynamic block.")
  332. ;;;; Clock and Planning
  333. (defconst org-clock-string "CLOCK:"
  334. "String used as prefix for timestamps clocking work hours on an item.")
  335. (defvar org-closed-string "CLOSED:"
  336. "String used as the prefix for timestamps logging closing a TODO entry.")
  337. (defvar org-deadline-string "DEADLINE:"
  338. "String to mark deadline entries.
  339. \\<org-mode-map>
  340. A deadline is this string, followed by a time stamp. It must be
  341. a word, terminated by a colon. You can insert a schedule keyword
  342. and a timestamp with `\\[org-deadline]'.")
  343. (defvar org-scheduled-string "SCHEDULED:"
  344. "String to mark scheduled TODO entries.
  345. \\<org-mode-map>
  346. A schedule is this string, followed by a time stamp. It must be
  347. a word, terminated by a colon. You can insert a schedule keyword
  348. and a timestamp with `\\[org-schedule]'.")
  349. (defconst org-ds-keyword-length
  350. (+ 2
  351. (apply #'max
  352. (mapcar #'length
  353. (list org-deadline-string org-scheduled-string
  354. org-clock-string org-closed-string))))
  355. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  356. (defconst org-planning-line-re
  357. (concat "^[ \t]*"
  358. (regexp-opt
  359. (list org-closed-string org-deadline-string org-scheduled-string)
  360. t))
  361. "Matches a line with planning info.
  362. Matched keyword is in group 1.")
  363. (defconst org-clock-line-re
  364. (concat "^[ \t]*" org-clock-string)
  365. "Matches a line with clock info.")
  366. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  367. "Matches the DEADLINE keyword.")
  368. (defconst org-deadline-time-regexp
  369. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  370. "Matches the DEADLINE keyword together with a time stamp.")
  371. (defconst org-deadline-time-hour-regexp
  372. (concat "\\<" org-deadline-string
  373. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  374. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  375. (defconst org-deadline-line-regexp
  376. (concat "\\<\\(" org-deadline-string "\\).*")
  377. "Matches the DEADLINE keyword and the rest of the line.")
  378. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  379. "Matches the SCHEDULED keyword.")
  380. (defconst org-scheduled-time-regexp
  381. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  382. "Matches the SCHEDULED keyword together with a time stamp.")
  383. (defconst org-scheduled-time-hour-regexp
  384. (concat "\\<" org-scheduled-string
  385. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  386. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  387. (defconst org-closed-time-regexp
  388. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  389. "Matches the CLOSED keyword together with a time stamp.")
  390. (defconst org-keyword-time-regexp
  391. (concat "\\<"
  392. (regexp-opt
  393. (list org-scheduled-string org-deadline-string org-closed-string
  394. org-clock-string)
  395. t)
  396. " *[[<]\\([^]>]+\\)[]>]")
  397. "Matches any of the 4 keywords, together with the time stamp.")
  398. (defconst org-keyword-time-not-clock-regexp
  399. (concat
  400. "\\<"
  401. (regexp-opt
  402. (list org-scheduled-string org-deadline-string org-closed-string) t)
  403. " *[[<]\\([^]>]+\\)[]>]")
  404. "Matches any of the 3 keywords, together with the time stamp.")
  405. (defconst org-maybe-keyword-time-regexp
  406. (concat "\\(\\<"
  407. (regexp-opt
  408. (list org-scheduled-string org-deadline-string org-closed-string
  409. org-clock-string)
  410. t)
  411. "\\)?"
  412. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  413. "\\|"
  414. "<%%([^\r\n>]*>\\)")
  415. "Matches a timestamp, possibly preceded by a keyword.")
  416. (defconst org-all-time-keywords
  417. (mapcar (lambda (w) (substring w 0 -1))
  418. (list org-scheduled-string org-deadline-string
  419. org-clock-string org-closed-string))
  420. "List of time keywords.")
  421. ;;;; Drawer
  422. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  423. "Matches first or last line of a hidden block.
  424. Group 1 contains drawer's name or \"END\".")
  425. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  426. "Regular expression matching the first line of a property drawer.")
  427. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  428. "Regular expression matching the last line of a property drawer.")
  429. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  430. "Regular expression matching the first line of a clock drawer.")
  431. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a clock drawer.")
  433. (defconst org-property-drawer-re
  434. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  435. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  436. "[ \t]*:END:[ \t]*$")
  437. "Matches an entire property drawer.")
  438. (defconst org-clock-drawer-re
  439. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  440. org-clock-drawer-end-re "\\)\n?")
  441. "Matches an entire clock drawer.")
  442. ;;;; Headline
  443. (defconst org-heading-keyword-regexp-format
  444. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  445. "Printf format for a regexp matching a headline with some keyword.
  446. This regexp will match the headline of any node which has the
  447. exact keyword that is put into the format. The keyword isn't in
  448. any group by default, but the stars and the body are.")
  449. (defconst org-heading-keyword-maybe-regexp-format
  450. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  451. "Printf format for a regexp matching a headline, possibly with some keyword.
  452. This regexp can match any headline with the specified keyword, or
  453. without a keyword. The keyword isn't in any group by default,
  454. but the stars and the body are.")
  455. (defconst org-archive-tag "ARCHIVE"
  456. "The tag that marks a subtree as archived.
  457. An archived subtree does not open during visibility cycling, and does
  458. not contribute to the agenda listings.")
  459. (eval-and-compile
  460. (defconst org-comment-string "COMMENT"
  461. "Entries starting with this keyword will never be exported.
  462. \\<org-mode-map>
  463. An entry can be toggled between COMMENT and normal with
  464. `\\[org-toggle-comment]'."))
  465. ;;;; LaTeX Environments and Fragments
  466. (defconst org-latex-regexps
  467. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  468. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  469. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  470. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  471. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  472. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  473. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  474. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  475. "Regular expressions for matching embedded LaTeX.")
  476. ;;;; Node Property
  477. (defconst org-effort-property "Effort"
  478. "The property that is being used to keep track of effort estimates.
  479. Effort estimates given in this property need to have the format H:MM.")
  480. ;;;; Table
  481. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  482. "Detect an org-type or table-type table.")
  483. (defconst org-table-line-regexp "^[ \t]*|"
  484. "Detect an org-type table line.")
  485. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  486. "Detect an org-type table line.")
  487. (defconst org-table-hline-regexp "^[ \t]*|-"
  488. "Detect an org-type table hline.")
  489. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  490. "Detect a table-type table hline.")
  491. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  492. "Detect the first line outside a table when searching from within it.
  493. This works for both table types.")
  494. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  495. "Detect a #+TBLFM line.")
  496. ;;;; Timestamp
  497. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp-inactive
  500. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  501. "Regular expression for fast inactive time stamp matching.")
  502. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp0
  505. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  506. "Regular expression matching time strings for analysis.
  507. This one does not require the space after the date, so it can be used
  508. on a string that terminates immediately after the date.")
  509. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.")
  511. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  512. "Regular expression matching time stamps, with groups.")
  513. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  514. "Regular expression matching time stamps (also [..]), with groups.")
  515. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  516. "Regular expression matching a time stamp range.")
  517. (defconst org-tr-regexp-both
  518. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  521. org-ts-regexp "\\)?")
  522. "Regular expression matching a time stamp or time stamp range.")
  523. (defconst org-tsr-regexp-both
  524. (concat org-ts-regexp-both "\\(--?-?"
  525. org-ts-regexp-both "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.
  527. The time stamps may be either active or inactive.")
  528. (defconst org-repeat-re
  529. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  530. "Regular expression for specifying repeated events.
  531. After a match, group 1 contains the repeat expression.")
  532. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  533. "Formats for `format-time-string' which are used for time stamps.")
  534. ;;; The custom variables
  535. (defgroup org nil
  536. "Outline-based notes management and organizer."
  537. :tag "Org"
  538. :group 'outlines
  539. :group 'calendar)
  540. (defcustom org-mode-hook nil
  541. "Mode hook for Org mode, run after the mode was turned on."
  542. :group 'org
  543. :type 'hook)
  544. (defcustom org-load-hook nil
  545. "Hook that is run after org.el has been loaded."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-log-buffer-setup-hook nil
  549. "Hook that is run after an Org log buffer is created."
  550. :group 'org
  551. :version "24.1"
  552. :type 'hook)
  553. (defvar org-modules) ; defined below
  554. (defvar org-modules-loaded nil
  555. "Have the modules been loaded already?")
  556. (defun org-load-modules-maybe (&optional force)
  557. "Load all extensions listed in `org-modules'."
  558. (when (or force (not org-modules-loaded))
  559. (dolist (ext org-modules)
  560. (condition-case nil (require ext)
  561. (error (message "Problems while trying to load feature `%s'" ext))))
  562. (setq org-modules-loaded t)))
  563. (defun org-set-modules (var value)
  564. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  565. (set var value)
  566. (when (featurep 'org)
  567. (org-load-modules-maybe 'force)
  568. (org-element-cache-reset 'all)))
  569. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  570. "Modules that should always be loaded together with org.el.
  571. If a description starts with <C>, the file is not part of Emacs
  572. and loading it will require that you have downloaded and properly
  573. installed the Org mode distribution.
  574. You can also use this system to load external packages (i.e. neither Org
  575. core modules, nor modules from the CONTRIB directory). Just add symbols
  576. to the end of the list. If the package is called org-xyz.el, then you need
  577. to add the symbol `xyz', and the package must have a call to:
  578. (provide \\='org-xyz)
  579. For export specific modules, see also `org-export-backends'."
  580. :group 'org
  581. :set 'org-set-modules
  582. :version "24.4"
  583. :package-version '(Org . "8.0")
  584. :type
  585. '(set :greedy t
  586. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  587. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  588. (const :tag " crypt: Encryption of subtrees" org-crypt)
  589. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  590. (const :tag " docview: Links to doc-view buffers" org-docview)
  591. (const :tag " eww: Store link to url of eww" org-eww)
  592. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  593. (const :tag " habit: Track your consistency with habits" org-habit)
  594. (const :tag " id: Global IDs for identifying entries" org-id)
  595. (const :tag " info: Links to Info nodes" org-info)
  596. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  597. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  598. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  599. (const :tag " mouse: Additional mouse support" org-mouse)
  600. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  601. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  602. (const :tag " tempo: Fast completion for structures" org-tempo)
  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 checklist: Extra functions for checklists in repeated tasks" org-checklist)
  607. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  608. (const :tag "C collector: Collect properties into tables" org-collector)
  609. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  610. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  611. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  612. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  613. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  614. (const :tag "C eval: Include command output as text" org-eval)
  615. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  616. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  617. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  618. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  619. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  620. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  621. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  622. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  623. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  624. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  625. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  626. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  627. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  628. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  629. (const :tag "C registry: A registry for Org links" org-registry)
  630. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  631. (const :tag "C secretary: Team management with Org" org-secretary)
  632. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  633. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  634. (const :tag "C track: Keep up with Org mode development" org-track)
  635. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  636. (const :tag "C vm: Links to VM folders/messages" org-vm)
  637. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  638. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  639. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  640. (defvar org-export-registered-backends) ; From ox.el.
  641. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  642. (declare-function org-export-backend-name "ox" (backend) t)
  643. (defcustom org-export-backends '(ascii html icalendar latex odt)
  644. "List of export back-ends that should be always available.
  645. If a description starts with <C>, the file is not part of Emacs
  646. and loading it will require that you have downloaded and properly
  647. installed the Org mode distribution.
  648. Unlike to `org-modules', libraries in this list will not be
  649. loaded along with Org, but only once the export framework is
  650. needed.
  651. This variable needs to be set before org.el is loaded. If you
  652. need to make a change while Emacs is running, use the customize
  653. interface or run the following code, where VAL stands for the new
  654. value of the variable, after updating it:
  655. (progn
  656. (setq org-export-registered-backends
  657. (cl-remove-if-not
  658. (lambda (backend)
  659. (let ((name (org-export-backend-name backend)))
  660. (or (memq name val)
  661. (catch \\='parentp
  662. (dolist (b val)
  663. (and (org-export-derived-backend-p b name)
  664. (throw \\='parentp t)))))))
  665. org-export-registered-backends))
  666. (let ((new-list (mapcar #\\='org-export-backend-name
  667. org-export-registered-backends)))
  668. (dolist (backend val)
  669. (cond
  670. ((not (load (format \"ox-%s\" backend) t t))
  671. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  672. backend))
  673. ((not (memq backend new-list)) (push backend new-list))))
  674. (set-default \\='org-export-backends new-list)))
  675. Adding a back-end to this list will also pull the back-end it
  676. depends on, if any."
  677. :group 'org
  678. :group 'org-export
  679. :version "26.1"
  680. :package-version '(Org . "9.0")
  681. :initialize 'custom-initialize-set
  682. :set (lambda (var val)
  683. (if (not (featurep 'ox)) (set-default var val)
  684. ;; Any back-end not required anymore (not present in VAL and not
  685. ;; a parent of any back-end in the new value) is removed from the
  686. ;; list of registered back-ends.
  687. (setq org-export-registered-backends
  688. (cl-remove-if-not
  689. (lambda (backend)
  690. (let ((name (org-export-backend-name backend)))
  691. (or (memq name val)
  692. (catch 'parentp
  693. (dolist (b val)
  694. (and (org-export-derived-backend-p b name)
  695. (throw 'parentp t)))))))
  696. org-export-registered-backends))
  697. ;; Now build NEW-LIST of both new back-ends and required
  698. ;; parents.
  699. (let ((new-list (mapcar #'org-export-backend-name
  700. org-export-registered-backends)))
  701. (dolist (backend val)
  702. (cond
  703. ((not (load (format "ox-%s" backend) t t))
  704. (message "Problems while trying to load export back-end `%s'"
  705. backend))
  706. ((not (memq backend new-list)) (push backend new-list))))
  707. ;; Set VAR to that list with fixed dependencies.
  708. (set-default var new-list))))
  709. :type '(set :greedy t
  710. (const :tag " ascii Export buffer to ASCII format" ascii)
  711. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  712. (const :tag " html Export buffer to HTML format" html)
  713. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  714. (const :tag " latex Export buffer to LaTeX format" latex)
  715. (const :tag " man Export buffer to MAN format" man)
  716. (const :tag " md Export buffer to Markdown format" md)
  717. (const :tag " odt Export buffer to ODT format" odt)
  718. (const :tag " org Export buffer to Org format" org)
  719. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  720. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  721. (const :tag "C deck Export buffer to deck.js presentations" deck)
  722. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  723. (const :tag "C groff Export buffer to Groff format" groff)
  724. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  725. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  726. (const :tag "C s5 Export buffer to s5 presentations" s5)
  727. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  728. (eval-after-load 'ox
  729. '(dolist (backend org-export-backends)
  730. (condition-case nil (require (intern (format "ox-%s" backend)))
  731. (error (message "Problems while trying to load export back-end `%s'"
  732. backend)))))
  733. (defcustom org-support-shift-select nil
  734. "Non-nil means make shift-cursor commands select text when possible.
  735. \\<org-mode-map>\
  736. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  737. start selecting a region, or enlarge regions started in this way.
  738. In Org mode, in special contexts, these same keys are used for
  739. other purposes, important enough to compete with shift selection.
  740. Org tries to balance these needs by supporting `shift-select-mode'
  741. outside these special contexts, under control of this variable.
  742. The default of this variable is nil, to avoid confusing behavior. Shifted
  743. cursor keys will then execute Org commands in the following contexts:
  744. - on a headline, changing TODO state (left/right) and priority (up/down)
  745. - on a time stamp, changing the time
  746. - in a plain list item, changing the bullet type
  747. - in a property definition line, switching between allowed values
  748. - in the BEGIN line of a clock table (changing the time block).
  749. Outside these contexts, the commands will throw an error.
  750. When this variable is t and the cursor is not in a special
  751. context, Org mode will support shift-selection for making and
  752. enlarging regions. To make this more effective, the bullet
  753. cycling will no longer happen anywhere in an item line, but only
  754. if the cursor is exactly on the bullet.
  755. If you set this variable to the symbol `always', then the keys
  756. will not be special in headlines, property lines, and item lines,
  757. to make shift selection work there as well. If this is what you
  758. want, you can use the following alternative commands:
  759. `\\[org-todo]' and `\\[org-priority]' \
  760. to change TODO state and priority,
  761. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  762. can be used to switch TODO sets,
  763. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  764. and properties can be edited by hand or in column view.
  765. However, when the cursor is on a timestamp, shift-cursor commands
  766. will still edit the time stamp - this is just too good to give up."
  767. :group 'org
  768. :type '(choice
  769. (const :tag "Never" nil)
  770. (const :tag "When outside special context" t)
  771. (const :tag "Everywhere except timestamps" always)))
  772. (defcustom org-loop-over-headlines-in-active-region nil
  773. "Shall some commands act upon headlines in the active region?
  774. When set to t, some commands will be performed in all headlines
  775. within the active region.
  776. When set to `start-level', some commands will be performed in all
  777. headlines within the active region, provided that these headlines
  778. are of the same level than the first one.
  779. When set to a string, those commands will be performed on the
  780. matching headlines within the active region. Such string must be
  781. a tags/property/todo match as it is used in the agenda tags view.
  782. The list of commands is: `org-schedule', `org-deadline',
  783. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  784. `org-archive-to-archive-sibling'. The archiving commands skip
  785. already archived entries."
  786. :type '(choice (const :tag "Don't loop" nil)
  787. (const :tag "All headlines in active region" t)
  788. (const :tag "In active region, headlines at the same level than the first one" start-level)
  789. (string :tag "Tags/Property/Todo matcher"))
  790. :version "24.1"
  791. :group 'org-todo
  792. :group 'org-archive)
  793. (defcustom org-startup-folded t
  794. "Non-nil means entering Org mode will switch to OVERVIEW.
  795. This can also be configured on a per-file basis by adding one of
  796. the following lines anywhere in the buffer:
  797. #+STARTUP: fold (or `overview', this is equivalent)
  798. #+STARTUP: nofold (or `showall', this is equivalent)
  799. #+STARTUP: content
  800. #+STARTUP: showeverything
  801. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  802. to ignore this option when Org opens agenda files for the first
  803. time."
  804. :group 'org-startup
  805. :type '(choice
  806. (const :tag "nofold: show all" nil)
  807. (const :tag "fold: overview" t)
  808. (const :tag "content: all headlines" content)
  809. (const :tag "show everything, even drawers" showeverything)))
  810. (defcustom org-startup-truncated t
  811. "Non-nil means entering Org mode will set `truncate-lines'.
  812. This is useful since some lines containing links can be very long and
  813. uninteresting. Also tables look terrible when wrapped.
  814. The variable `org-startup-truncated' allows to configure
  815. truncation for Org mode different to the other modes that use the
  816. variable `truncate-lines' and as a shortcut instead of putting
  817. the variable `truncate-lines' into the `org-mode-hook'. If one
  818. wants to configure truncation for Org mode not statically but
  819. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  820. the variable `truncate-lines' has to be used because in such a
  821. case it is too late to set the variable `org-startup-truncated'."
  822. :group 'org-startup
  823. :type 'boolean)
  824. (defcustom org-startup-indented nil
  825. "Non-nil means turn on `org-indent-mode' on startup.
  826. This can also be configured on a per-file basis by adding one of
  827. the following lines anywhere in the buffer:
  828. #+STARTUP: indent
  829. #+STARTUP: noindent"
  830. :group 'org-structure
  831. :type '(choice
  832. (const :tag "Not" nil)
  833. (const :tag "Globally (slow on startup in large files)" t)))
  834. (defcustom org-use-sub-superscripts t
  835. "Non-nil means interpret \"_\" and \"^\" for display.
  836. If you want to control how Org exports those characters, see
  837. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  838. used to be an alias for `org-export-with-sub-superscripts' in
  839. Org <8.0, it is not anymore.
  840. When this option is turned on, you can use TeX-like syntax for
  841. sub- and superscripts within the buffer. Several characters after
  842. \"_\" or \"^\" will be considered as a single item - so grouping
  843. with {} is normally not needed. For example, the following things
  844. will be parsed as single sub- or superscripts:
  845. 10^24 or 10^tau several digits will be considered 1 item.
  846. 10^-12 or 10^-tau a leading sign with digits or a word
  847. x^2-y^3 will be read as x^2 - y^3, because items are
  848. terminated by almost any nonword/nondigit char.
  849. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  850. Still, ambiguity is possible. So when in doubt, use {} to enclose
  851. the sub/superscript. If you set this variable to the symbol `{}',
  852. the braces are *required* in order to trigger interpretations as
  853. sub/superscript. This can be helpful in documents that need \"_\"
  854. frequently in plain text."
  855. :group 'org-startup
  856. :version "24.4"
  857. :package-version '(Org . "8.0")
  858. :type '(choice
  859. (const :tag "Always interpret" t)
  860. (const :tag "Only with braces" {})
  861. (const :tag "Never interpret" nil)))
  862. (defcustom org-startup-with-beamer-mode nil
  863. "Non-nil means turn on `org-beamer-mode' on startup.
  864. This can also be configured on a per-file basis by adding one of
  865. the following lines anywhere in the buffer:
  866. #+STARTUP: beamer"
  867. :group 'org-startup
  868. :version "24.1"
  869. :type 'boolean)
  870. (defcustom org-startup-align-all-tables nil
  871. "Non-nil means align all tables when visiting a file.
  872. This can also be configured on a per-file basis by adding one of
  873. the following lines anywhere in the buffer:
  874. #+STARTUP: align
  875. #+STARTUP: noalign"
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-shrink-all-tables nil
  879. "Non-nil means shrink all table columns with a width cookie.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: shrink"
  883. :group 'org-startup
  884. :type 'boolean
  885. :version "27.1"
  886. :package-version '(Org . "9.2")
  887. :safe #'booleanp)
  888. (defcustom org-startup-with-inline-images nil
  889. "Non-nil means show inline images when loading a new Org file.
  890. This can also be configured on a per-file basis by adding one of
  891. the following lines anywhere in the buffer:
  892. #+STARTUP: inlineimages
  893. #+STARTUP: noinlineimages"
  894. :group 'org-startup
  895. :version "24.1"
  896. :type 'boolean)
  897. (defcustom org-startup-with-latex-preview nil
  898. "Non-nil means preview LaTeX fragments when loading a new Org file.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: latexpreview
  902. #+STARTUP: nolatexpreview"
  903. :group 'org-startup
  904. :version "24.4"
  905. :package-version '(Org . "8.0")
  906. :type 'boolean)
  907. (defcustom org-insert-mode-line-in-empty-file nil
  908. "Non-nil means insert the first line setting Org mode in empty files.
  909. When the function `org-mode' is called interactively in an empty file, this
  910. normally means that the file name does not automatically trigger Org mode.
  911. To ensure that the file will always be in Org mode in the future, a
  912. line enforcing Org mode will be inserted into the buffer, if this option
  913. has been set."
  914. :group 'org-startup
  915. :type 'boolean)
  916. (defcustom org-replace-disputed-keys nil
  917. "Non-nil means use alternative key bindings for some keys.
  918. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  919. These keys are also used by other packages like shift-selection-mode'
  920. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  921. If you want to use Org mode together with one of these other modes,
  922. or more generally if you would like to move some Org mode commands to
  923. other keys, set this variable and configure the keys with the variable
  924. `org-disputed-keys'.
  925. This option is only relevant at load-time of Org mode, and must be set
  926. *before* org.el is loaded. Changing it requires a restart of Emacs to
  927. become effective."
  928. :group 'org-startup
  929. :type 'boolean)
  930. (defcustom org-use-extra-keys nil
  931. "Non-nil means use extra key sequence definitions for certain commands.
  932. This happens automatically if `window-system' is nil. This
  933. variable lets you do the same manually. You must set it before
  934. loading Org."
  935. :group 'org-startup
  936. :type 'boolean)
  937. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  938. (defcustom org-disputed-keys
  939. '(([(shift up)] . [(meta p)])
  940. ([(shift down)] . [(meta n)])
  941. ([(shift left)] . [(meta -)])
  942. ([(shift right)] . [(meta +)])
  943. ([(control shift right)] . [(meta shift +)])
  944. ([(control shift left)] . [(meta shift -)]))
  945. "Keys for which Org mode and other modes compete.
  946. This is an alist, cars are the default keys, second element specifies
  947. the alternative to use when `org-replace-disputed-keys' is t.
  948. Keys can be specified in any syntax supported by `define-key'.
  949. The value of this option takes effect only at Org mode startup,
  950. therefore you'll have to restart Emacs to apply it after changing."
  951. :group 'org-startup
  952. :type 'alist)
  953. (defun org-key (key)
  954. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  955. Or return the original if not disputed."
  956. (when org-replace-disputed-keys
  957. (let* ((nkey (key-description key))
  958. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  959. org-disputed-keys)))
  960. (setq key (if x (cdr x) key))))
  961. key)
  962. (defun org-defkey (keymap key def)
  963. "Define a key, possibly translated, as returned by `org-key'."
  964. (define-key keymap (org-key key) def))
  965. (defcustom org-ellipsis nil
  966. "The ellipsis to use in the Org mode outline.
  967. When nil, just use the standard three dots. When a non-empty string,
  968. use that string instead.
  969. The change affects only Org mode (which will then use its own display table).
  970. Changing this requires executing `\\[org-mode]' in a buffer to become
  971. effective."
  972. :group 'org-startup
  973. :type '(choice (const :tag "Default" nil)
  974. (string :tag "String" :value "...#"))
  975. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  976. (defvar org-display-table nil
  977. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  978. (defgroup org-keywords nil
  979. "Keywords in Org mode."
  980. :tag "Org Keywords"
  981. :group 'org)
  982. (defcustom org-closed-keep-when-no-todo nil
  983. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  984. :group 'org-todo
  985. :group 'org-keywords
  986. :version "24.4"
  987. :package-version '(Org . "8.0")
  988. :type 'boolean)
  989. (defgroup org-structure nil
  990. "Options concerning the general structure of Org files."
  991. :tag "Org Structure"
  992. :group 'org)
  993. (defgroup org-reveal-location nil
  994. "Options about how to make context of a location visible."
  995. :tag "Org Reveal Location"
  996. :group 'org-structure)
  997. (defcustom org-show-context-detail '((agenda . local)
  998. (bookmark-jump . lineage)
  999. (isearch . lineage)
  1000. (default . ancestors))
  1001. "Alist between context and visibility span when revealing a location.
  1002. \\<org-mode-map>Some actions may move point into invisible
  1003. locations. As a consequence, Org always expose a neighborhood
  1004. around point. How much is shown depends on the initial action,
  1005. or context. Valid contexts are
  1006. agenda when exposing an entry from the agenda
  1007. org-goto when using the command `org-goto' (`\\[org-goto]')
  1008. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1009. tags-tree when constructing a sparse tree based on tags matches
  1010. link-search when exposing search matches associated with a link
  1011. mark-goto when exposing the jump goal of a mark
  1012. bookmark-jump when exposing a bookmark location
  1013. isearch when exiting from an incremental search
  1014. default default for all contexts not set explicitly
  1015. Allowed visibility spans are
  1016. minimal show current headline; if point is not on headline,
  1017. also show entry
  1018. local show current headline, entry and next headline
  1019. ancestors show current headline and its direct ancestors; if
  1020. point is not on headline, also show entry
  1021. lineage show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and first child
  1024. tree show current headline, its direct ancestors and all
  1025. their children; if point is not on headline, also show
  1026. entry and all children
  1027. canonical show current headline, its direct ancestors along with
  1028. their entries and children; if point is not located on
  1029. the headline, also show current entry and all children
  1030. As special cases, a nil or t value means show all contexts in
  1031. `minimal' or `canonical' view, respectively.
  1032. Some views can make displayed information very compact, but also
  1033. make it harder to edit the location of the match. In such
  1034. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1035. more context."
  1036. :group 'org-reveal-location
  1037. :version "26.1"
  1038. :package-version '(Org . "9.0")
  1039. :type '(choice
  1040. (const :tag "Canonical" t)
  1041. (const :tag "Minimal" nil)
  1042. (repeat :greedy t :tag "Individual contexts"
  1043. (cons
  1044. (choice :tag "Context"
  1045. (const agenda)
  1046. (const org-goto)
  1047. (const occur-tree)
  1048. (const tags-tree)
  1049. (const link-search)
  1050. (const mark-goto)
  1051. (const bookmark-jump)
  1052. (const isearch)
  1053. (const default))
  1054. (choice :tag "Detail level"
  1055. (const minimal)
  1056. (const local)
  1057. (const ancestors)
  1058. (const lineage)
  1059. (const tree)
  1060. (const canonical))))))
  1061. (defcustom org-indirect-buffer-display 'other-window
  1062. "How should indirect tree buffers be displayed?
  1063. This applies to indirect buffers created with the commands
  1064. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1065. Valid values are:
  1066. current-window Display in the current window
  1067. other-window Just display in another window.
  1068. dedicated-frame Create one new frame, and re-use it each time.
  1069. new-frame Make a new frame each time. Note that in this case
  1070. previously-made indirect buffers are kept, and you need to
  1071. kill these buffers yourself."
  1072. :group 'org-structure
  1073. :group 'org-agenda-windows
  1074. :type '(choice
  1075. (const :tag "In current window" current-window)
  1076. (const :tag "In current frame, other window" other-window)
  1077. (const :tag "Each time a new frame" new-frame)
  1078. (const :tag "One dedicated frame" dedicated-frame)))
  1079. (defcustom org-use-speed-commands nil
  1080. "Non-nil means activate single letter commands at beginning of a headline.
  1081. This may also be a function to test for appropriate locations where speed
  1082. commands should be active.
  1083. For example, to activate speed commands when the point is on any
  1084. star at the beginning of the headline, you can do this:
  1085. (setq org-use-speed-commands
  1086. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1087. :group 'org-structure
  1088. :type '(choice
  1089. (const :tag "Never" nil)
  1090. (const :tag "At beginning of headline stars" t)
  1091. (function)))
  1092. (defcustom org-speed-commands-user nil
  1093. "Alist of additional speed commands.
  1094. This list will be checked before `org-speed-commands-default'
  1095. when the variable `org-use-speed-commands' is non-nil
  1096. and when the cursor is at the beginning of a headline.
  1097. The car of each entry is a string with a single letter, which must
  1098. be assigned to `self-insert-command' in the global map.
  1099. The cdr is either a command to be called interactively, a function
  1100. to be called, or a form to be evaluated.
  1101. An entry that is just a list with a single string will be interpreted
  1102. as a descriptive headline that will be added when listing the speed
  1103. commands in the Help buffer using the `?' speed command."
  1104. :group 'org-structure
  1105. :type '(repeat :value ("k" . ignore)
  1106. (choice :value ("k" . ignore)
  1107. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1108. (cons :tag "Letter and Command"
  1109. (string :tag "Command letter")
  1110. (choice
  1111. (function)
  1112. (sexp))))))
  1113. (defcustom org-bookmark-names-plist
  1114. '(:last-capture "org-capture-last-stored"
  1115. :last-refile "org-refile-last-stored"
  1116. :last-capture-marker "org-capture-last-stored-marker")
  1117. "Names for bookmarks automatically set by some Org commands.
  1118. This can provide strings as names for a number of bookmarks Org sets
  1119. automatically. The following keys are currently implemented:
  1120. :last-capture
  1121. :last-capture-marker
  1122. :last-refile
  1123. When a key does not show up in the property list, the corresponding bookmark
  1124. is not set."
  1125. :group 'org-structure
  1126. :type 'plist)
  1127. (defgroup org-cycle nil
  1128. "Options concerning visibility cycling in Org mode."
  1129. :tag "Org Cycle"
  1130. :group 'org-structure)
  1131. (defcustom org-cycle-skip-children-state-if-no-children t
  1132. "Non-nil means skip CHILDREN state in entries that don't have any."
  1133. :group 'org-cycle
  1134. :type 'boolean)
  1135. (defcustom org-cycle-max-level nil
  1136. "Maximum level which should still be subject to visibility cycling.
  1137. Levels higher than this will, for cycling, be treated as text, not a headline.
  1138. When `org-odd-levels-only' is set, a value of N in this variable actually
  1139. means 2N-1 stars as the limiting headline.
  1140. When nil, cycle all levels.
  1141. Note that the limiting level of cycling is also influenced by
  1142. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1143. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1144. than its value."
  1145. :group 'org-cycle
  1146. :type '(choice
  1147. (const :tag "No limit" nil)
  1148. (integer :tag "Maximum level")))
  1149. (defcustom org-hide-block-startup nil
  1150. "Non-nil means entering Org mode will fold all blocks.
  1151. This can also be set in on a per-file basis with
  1152. #+STARTUP: hideblocks
  1153. #+STARTUP: showblocks"
  1154. :group 'org-startup
  1155. :group 'org-cycle
  1156. :type 'boolean)
  1157. (defcustom org-cycle-global-at-bob nil
  1158. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1159. This makes it possible to do global cycling without having to use `S-TAB'
  1160. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1161. line of the buffer
  1162. must not be a headline -- it may be empty or some other text.
  1163. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1164. sure the cursor stays at the beginning of the buffer.
  1165. When this option is nil, don't do anything special at the beginning of
  1166. the buffer."
  1167. :group 'org-cycle
  1168. :type 'boolean)
  1169. (defcustom org-cycle-level-after-item/entry-creation t
  1170. "Non-nil means cycle entry level or item indentation in new empty entries.
  1171. When the cursor is at the end of an empty headline, i.e., with only stars
  1172. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1173. and then all possible ancestor states, before returning to the original state.
  1174. This makes data entry extremely fast: M-RET to create a new headline,
  1175. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1176. When the cursor is at the end of an empty plain list item, one TAB will
  1177. make it a subitem, two or more tabs will back up to make this an item
  1178. higher up in the item hierarchy."
  1179. :group 'org-cycle
  1180. :type 'boolean)
  1181. (defcustom org-cycle-emulate-tab t
  1182. "Where should `org-cycle' emulate TAB.
  1183. nil Never
  1184. white Only in completely white lines
  1185. whitestart Only at the beginning of lines, before the first non-white char
  1186. t Everywhere except in headlines
  1187. exc-hl-bol Everywhere except at the start of a headline
  1188. If TAB is used in a place where it does not emulate TAB, the current subtree
  1189. visibility is cycled."
  1190. :group 'org-cycle
  1191. :type '(choice (const :tag "Never" nil)
  1192. (const :tag "Only in completely white lines" white)
  1193. (const :tag "Before first char in a line" whitestart)
  1194. (const :tag "Everywhere except in headlines" t)
  1195. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1196. (defcustom org-cycle-separator-lines 2
  1197. "Number of empty lines needed to keep an empty line between collapsed trees.
  1198. If you leave an empty line between the end of a subtree and the following
  1199. headline, this empty line is hidden when the subtree is folded.
  1200. Org mode will leave (exactly) one empty line visible if the number of
  1201. empty lines is equal or larger to the number given in this variable.
  1202. So the default 2 means at least 2 empty lines after the end of a subtree
  1203. are needed to produce free space between a collapsed subtree and the
  1204. following headline.
  1205. If the number is negative, and the number of empty lines is at least -N,
  1206. all empty lines are shown.
  1207. Special case: when 0, never leave empty lines in collapsed view."
  1208. :group 'org-cycle
  1209. :type 'integer)
  1210. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1211. (defcustom org-pre-cycle-hook nil
  1212. "Hook that is run before visibility cycling is happening.
  1213. The function(s) in this hook must accept a single argument which indicates
  1214. the new state that will be set right after running this hook. The
  1215. argument is a symbol. Before a global state change, it can have the values
  1216. `overview', `content', or `all'. Before a local state change, it can have
  1217. the values `folded', `children', or `subtree'."
  1218. :group 'org-cycle
  1219. :type 'hook)
  1220. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1221. org-cycle-show-empty-lines
  1222. org-optimize-window-after-visibility-change)
  1223. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1224. The function(s) in this hook must accept a single argument which indicates
  1225. the new state that was set by the most recent `org-cycle' command. The
  1226. argument is a symbol. After a global state change, it can have the values
  1227. `overview', `contents', or `all'. After a local state change, it can have
  1228. the values `folded', `children', or `subtree'."
  1229. :group 'org-cycle
  1230. :type 'hook
  1231. :version "26.1"
  1232. :package-version '(Org . "8.3"))
  1233. (defgroup org-edit-structure nil
  1234. "Options concerning structure editing in Org mode."
  1235. :tag "Org Edit Structure"
  1236. :group 'org-structure)
  1237. (defcustom org-odd-levels-only nil
  1238. "Non-nil means skip even levels and only use odd levels for the outline.
  1239. This has the effect that two stars are being added/taken away in
  1240. promotion/demotion commands. It also influences how levels are
  1241. handled by the exporters.
  1242. Changing it requires restart of `font-lock-mode' to become effective
  1243. for fontification also in regions already fontified.
  1244. You may also set this on a per-file basis by adding one of the following
  1245. lines to the buffer:
  1246. #+STARTUP: odd
  1247. #+STARTUP: oddeven"
  1248. :group 'org-edit-structure
  1249. :group 'org-appearance
  1250. :type 'boolean)
  1251. (defcustom org-adapt-indentation t
  1252. "Non-nil means adapt indentation to outline node level.
  1253. When this variable is set, Org assumes that you write outlines by
  1254. indenting text in each node to align with the headline (after the
  1255. stars). The following issues are influenced by this variable:
  1256. - The indentation is increased by one space in a demotion
  1257. command, and decreased by one in a promotion command. However,
  1258. in the latter case, if shifting some line in the entry body
  1259. would alter document structure (e.g., insert a new headline),
  1260. indentation is not changed at all.
  1261. - Property drawers and planning information is inserted indented
  1262. when this variable is set. When nil, they will not be indented.
  1263. - TAB indents a line relative to current level. The lines below
  1264. a headline will be indented when this variable is set.
  1265. Note that this is all about true indentation, by adding and
  1266. removing space characters. See also \"org-indent.el\" which does
  1267. level-dependent indentation in a virtual way, i.e. at display
  1268. time in Emacs."
  1269. :group 'org-edit-structure
  1270. :type 'boolean
  1271. :safe #'booleanp)
  1272. (defcustom org-special-ctrl-a/e nil
  1273. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1274. When t, `C-a' will bring back the cursor to the beginning of the
  1275. headline text, i.e. after the stars and after a possible TODO
  1276. keyword. In an item, this will be the position after bullet and
  1277. check-box, if any. When the cursor is already at that position,
  1278. another `C-a' will bring it to the beginning of the line.
  1279. `C-e' will jump to the end of the headline, ignoring the presence
  1280. of tags in the headline. A second `C-e' will then jump to the
  1281. true end of the line, after any tags. This also means that, when
  1282. this variable is non-nil, `C-e' also will never jump beyond the
  1283. end of the heading of a folded section, i.e. not after the
  1284. ellipses.
  1285. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1286. normally, going to the true line boundary first. Only a directly
  1287. following, identical keypress will bring the cursor to the
  1288. special positions.
  1289. This may also be a cons cell where the behavior for `C-a' and
  1290. `C-e' is set separately."
  1291. :group 'org-edit-structure
  1292. :type '(choice
  1293. (const :tag "off" nil)
  1294. (const :tag "on: after stars/bullet and before tags first" t)
  1295. (const :tag "reversed: true line boundary first" reversed)
  1296. (cons :tag "Set C-a and C-e separately"
  1297. (choice :tag "Special C-a"
  1298. (const :tag "off" nil)
  1299. (const :tag "on: after stars/bullet first" t)
  1300. (const :tag "reversed: before stars/bullet first" reversed))
  1301. (choice :tag "Special C-e"
  1302. (const :tag "off" nil)
  1303. (const :tag "on: before tags first" t)
  1304. (const :tag "reversed: after tags first" reversed)))))
  1305. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1306. (defcustom org-special-ctrl-k nil
  1307. "Non-nil means `C-k' will behave specially in headlines.
  1308. When nil, `C-k' will call the default `kill-line' command.
  1309. When t, the following will happen while the cursor is in the headline:
  1310. - When the cursor is at the beginning of a headline, kill the entire
  1311. line and possible the folded subtree below the line.
  1312. - When in the middle of the headline text, kill the headline up to the tags.
  1313. - When after the headline text, kill the tags."
  1314. :group 'org-edit-structure
  1315. :type 'boolean)
  1316. (defcustom org-ctrl-k-protect-subtree nil
  1317. "Non-nil means, do not delete a hidden subtree with C-k.
  1318. When set to the symbol `error', simply throw an error when C-k is
  1319. used to kill (part-of) a headline that has hidden text behind it.
  1320. Any other non-nil value will result in a query to the user, if it is
  1321. OK to kill that hidden subtree. When nil, kill without remorse."
  1322. :group 'org-edit-structure
  1323. :version "24.1"
  1324. :type '(choice
  1325. (const :tag "Do not protect hidden subtrees" nil)
  1326. (const :tag "Protect hidden subtrees with a security query" t)
  1327. (const :tag "Never kill a hidden subtree with C-k" error)))
  1328. (defcustom org-special-ctrl-o t
  1329. "Non-nil means, make `C-o' insert a row in tables."
  1330. :group 'org-edit-structure
  1331. :type 'boolean)
  1332. (defcustom org-catch-invisible-edits nil
  1333. "Check if in invisible region before inserting or deleting a character.
  1334. Valid values are:
  1335. nil Do not check, so just do invisible edits.
  1336. error Throw an error and do nothing.
  1337. show Make point visible, and do the requested edit.
  1338. show-and-error Make point visible, then throw an error and abort the edit.
  1339. smart Make point visible, and do insertion/deletion if it is
  1340. adjacent to visible text and the change feels predictable.
  1341. Never delete a previously invisible character or add in the
  1342. middle or right after an invisible region. Basically, this
  1343. allows insertion and backward-delete right before ellipses.
  1344. FIXME: maybe in this case we should not even show?"
  1345. :group 'org-edit-structure
  1346. :version "24.1"
  1347. :type '(choice
  1348. (const :tag "Do not check" nil)
  1349. (const :tag "Throw error when trying to edit" error)
  1350. (const :tag "Unhide, but do not do the edit" show-and-error)
  1351. (const :tag "Show invisible part and do the edit" show)
  1352. (const :tag "Be smart and do the right thing" smart)))
  1353. (defcustom org-yank-folded-subtrees t
  1354. "Non-nil means when yanking subtrees, fold them.
  1355. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1356. it starts with a heading and all other headings in it are either children
  1357. or siblings, then fold all the subtrees. However, do this only if no
  1358. text after the yank would be swallowed into a folded tree by this action."
  1359. :group 'org-edit-structure
  1360. :type 'boolean)
  1361. (defcustom org-yank-adjusted-subtrees nil
  1362. "Non-nil means when yanking subtrees, adjust the level.
  1363. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1364. this function for details."
  1365. :group 'org-edit-structure
  1366. :type 'boolean)
  1367. (defcustom org-M-RET-may-split-line '((default . t))
  1368. "Non-nil means M-RET will split the line at the cursor position.
  1369. When nil, it will go to the end of the line before making a
  1370. new line.
  1371. You may also set this option in a different way for different
  1372. contexts. Valid contexts are:
  1373. headline when creating a new headline
  1374. item when creating a new item
  1375. table in a table field
  1376. default the value to be used for all contexts not explicitly
  1377. customized"
  1378. :group 'org-structure
  1379. :group 'org-table
  1380. :type '(choice
  1381. (const :tag "Always" t)
  1382. (const :tag "Never" nil)
  1383. (repeat :greedy t :tag "Individual contexts"
  1384. (cons
  1385. (choice :tag "Context"
  1386. (const headline)
  1387. (const item)
  1388. (const table)
  1389. (const default))
  1390. (boolean)))))
  1391. (defcustom org-insert-heading-respect-content nil
  1392. "Non-nil means insert new headings after the current subtree.
  1393. \\<org-mode-map>
  1394. When nil, the new heading is created directly after the current line.
  1395. The commands `\\[org-insert-heading-respect-content]' and \
  1396. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1397. for the duration of the command."
  1398. :group 'org-structure
  1399. :type 'boolean)
  1400. (defcustom org-blank-before-new-entry '((heading . auto)
  1401. (plain-list-item . auto))
  1402. "Should `org-insert-heading' leave a blank line before new heading/item?
  1403. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1404. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1405. which case Org will look at the surrounding headings/items and try to
  1406. make an intelligent decision whether to insert a blank line or not."
  1407. :group 'org-edit-structure
  1408. :type '(list
  1409. (cons (const heading)
  1410. (choice (const :tag "Never" nil)
  1411. (const :tag "Always" t)
  1412. (const :tag "Auto" auto)))
  1413. (cons (const plain-list-item)
  1414. (choice (const :tag "Never" nil)
  1415. (const :tag "Always" t)
  1416. (const :tag "Auto" auto)))))
  1417. (defcustom org-insert-heading-hook nil
  1418. "Hook being run after inserting a new heading."
  1419. :group 'org-edit-structure
  1420. :type 'hook)
  1421. (defcustom org-enable-fixed-width-editor t
  1422. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1423. This currently only means they are never auto-wrapped.
  1424. When nil, such lines will be treated like ordinary lines."
  1425. :group 'org-edit-structure
  1426. :type 'boolean)
  1427. (defgroup org-sparse-trees nil
  1428. "Options concerning sparse trees in Org mode."
  1429. :tag "Org Sparse Trees"
  1430. :group 'org-structure)
  1431. (defcustom org-highlight-sparse-tree-matches t
  1432. "Non-nil means highlight all matches that define a sparse tree.
  1433. The highlights will automatically disappear the next time the buffer is
  1434. changed by an edit command."
  1435. :group 'org-sparse-trees
  1436. :type 'boolean)
  1437. (defcustom org-remove-highlights-with-change t
  1438. "Non-nil means any change to the buffer will remove temporary highlights.
  1439. \\<org-mode-map>\
  1440. Such highlights are created by `org-occur' and `org-clock-display'.
  1441. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1442. to get rid of the highlights.
  1443. The highlights created by `org-toggle-latex-fragment' always need
  1444. `\\[org-toggle-latex-fragment]' to be removed."
  1445. :group 'org-sparse-trees
  1446. :group 'org-time
  1447. :type 'boolean)
  1448. (defcustom org-occur-case-fold-search t
  1449. "Non-nil means `org-occur' should be case-insensitive.
  1450. If set to `smart' the search will be case-insensitive only if it
  1451. doesn't specify any upper case character."
  1452. :group 'org-sparse-trees
  1453. :version "26.1"
  1454. :type '(choice
  1455. (const :tag "Case-sensitive" nil)
  1456. (const :tag "Case-insensitive" t)
  1457. (const :tag "Case-insensitive for lower case searches only" smart)))
  1458. (defcustom org-occur-hook '(org-first-headline-recenter)
  1459. "Hook that is run after `org-occur' has constructed a sparse tree.
  1460. This can be used to recenter the window to show as much of the structure
  1461. as possible."
  1462. :group 'org-sparse-trees
  1463. :type 'hook)
  1464. (defgroup org-table nil
  1465. "Options concerning tables in Org mode."
  1466. :tag "Org Table"
  1467. :group 'org)
  1468. (defcustom org-self-insert-cluster-for-undo nil
  1469. "Non-nil means cluster self-insert commands for undo when possible.
  1470. If this is set, then, like in the Emacs command loop, 20 consecutive
  1471. characters will be undone together.
  1472. This is configurable, because there is some impact on typing performance."
  1473. :group 'org-table
  1474. :type 'boolean)
  1475. (defcustom org-table-tab-recognizes-table.el t
  1476. "Non-nil means TAB will automatically notice a table.el table.
  1477. When it sees such a table, it moves point into it and - if necessary -
  1478. calls `table-recognize-table'."
  1479. :group 'org-table-editing
  1480. :type 'boolean)
  1481. (defgroup org-link nil
  1482. "Options concerning links in Org mode."
  1483. :tag "Org Link"
  1484. :group 'org)
  1485. (defvar-local org-link-abbrev-alist-local nil
  1486. "Buffer-local version of `org-link-abbrev-alist', which see.
  1487. The value of this is taken from the #+LINK lines.")
  1488. (defcustom org-link-parameters
  1489. '(("doi" :follow org--open-doi-link)
  1490. ("elisp" :follow org--open-elisp-link)
  1491. ("file" :complete org-file-complete-link)
  1492. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1493. ("help" :follow org--open-help-link)
  1494. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1495. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1496. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1497. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1498. ("shell" :follow org--open-shell-link))
  1499. "An alist of properties that defines all the links in Org mode.
  1500. The key in each association is a string of the link type.
  1501. Subsequent optional elements make up a p-list of link properties.
  1502. :follow - A function that takes the link path as an argument.
  1503. :export - A function that takes the link path, description and
  1504. export-backend as arguments.
  1505. :store - A function responsible for storing the link. See the
  1506. function `org-store-link-functions'.
  1507. :complete - A function that inserts a link with completion. The
  1508. function takes one optional prefix arg.
  1509. :face - A face for the link, or a function that returns a face.
  1510. The function takes one argument which is the link path. The
  1511. default face is `org-link'.
  1512. :mouse-face - The mouse-face. The default is `highlight'.
  1513. :display - `full' will not fold the link in descriptive
  1514. display. Default is `org-link'.
  1515. :help-echo - A string or function that takes (window object position)
  1516. as arguments and returns a string.
  1517. :keymap - A keymap that is active on the link. The default is
  1518. `org-mouse-map'.
  1519. :htmlize-link - A function for the htmlize-link. Defaults
  1520. to (list :uri \"type:path\")
  1521. :activate-func - A function to run at the end of font-lock
  1522. activation. The function must accept (link-start link-end path bracketp)
  1523. as arguments."
  1524. :group 'org-link
  1525. :type '(alist :tag "Link display parameters"
  1526. :value-type plist)
  1527. :version "26.1"
  1528. :package-version '(Org . "9.1"))
  1529. (defun org-link-get-parameter (type key)
  1530. "Get TYPE link property for KEY.
  1531. TYPE is a string and KEY is a plist keyword."
  1532. (plist-get
  1533. (cdr (assoc type org-link-parameters))
  1534. key))
  1535. (defun org-link-set-parameters (type &rest parameters)
  1536. "Set link TYPE properties to PARAMETERS.
  1537. PARAMETERS should be :key val pairs."
  1538. (let ((data (assoc type org-link-parameters)))
  1539. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1540. (push (cons type parameters) org-link-parameters)
  1541. (org-make-link-regexps)
  1542. (org-element-update-syntax))))
  1543. (defun org-link-types ()
  1544. "Return a list of known link types."
  1545. (mapcar #'car org-link-parameters))
  1546. (defcustom org-link-abbrev-alist nil
  1547. "Alist of link abbreviations.
  1548. The car of each element is a string, to be replaced at the start of a link.
  1549. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1550. links in Org buffers can have an optional tag after a double colon, e.g.,
  1551. [[linkkey:tag][description]]
  1552. The `linkkey' must be a single word, starting with a letter, followed
  1553. by letters, numbers, `-' or `_'.
  1554. If REPLACE is a string, the tag will simply be appended to create the link.
  1555. If the string contains \"%s\", the tag will be inserted there. If the string
  1556. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1557. at that point (see the function `url-hexify-string'). If the string contains
  1558. the specifier \"%(my-function)\", then the custom function `my-function' will
  1559. be invoked: this function takes the tag as its only argument and must return
  1560. a string.
  1561. REPLACE may also be a function that will be called with the tag as the
  1562. only argument to create the link, which should be returned as a string.
  1563. See the manual for examples."
  1564. :group 'org-link
  1565. :type '(repeat
  1566. (cons
  1567. (string :tag "Protocol")
  1568. (choice
  1569. (string :tag "Format")
  1570. (function)))))
  1571. (defcustom org-descriptive-links t
  1572. "Non-nil means Org will display descriptive links.
  1573. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1574. \"Org Website\", hiding the link itself and just displaying its
  1575. description. When set to nil, Org will display the full links
  1576. literally.
  1577. You can interactively set the value of this variable by calling
  1578. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1579. :group 'org-link
  1580. :type 'boolean)
  1581. (defcustom org-link-file-path-type 'adaptive
  1582. "How the path name in file links should be stored.
  1583. Valid values are:
  1584. relative Relative to the current directory, i.e. the directory of the file
  1585. into which the link is being inserted.
  1586. absolute Absolute path, if possible with ~ for home directory.
  1587. noabbrev Absolute path, no abbreviation of home directory.
  1588. adaptive Use relative path for files in the current directory and sub-
  1589. directories of it. For other files, use an absolute path."
  1590. :group 'org-link
  1591. :type '(choice
  1592. (const relative)
  1593. (const absolute)
  1594. (const noabbrev)
  1595. (const adaptive)))
  1596. (defvaralias 'org-activate-links 'org-highlight-links)
  1597. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1598. "Types of links that should be highlighted in Org files.
  1599. This is a list of symbols, each one of them leading to the
  1600. highlighting of a certain link type.
  1601. You can still open links that are not highlighted.
  1602. In principle, it does not hurt to turn on highlighting for all
  1603. link types. There may be a small gain when turning off unused
  1604. link types. The types are:
  1605. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1606. angle Links in angular brackets that may contain whitespace like
  1607. <bbdb:Carsten Dominik>.
  1608. plain Plain links in normal text, no whitespace, like http://google.com.
  1609. radio Text that is matched by a radio target, see manual for details.
  1610. tag Tag settings in a headline (link to tag search).
  1611. date Time stamps (link to calendar).
  1612. footnote Footnote labels.
  1613. If you set this variable during an Emacs session, use `org-mode-restart'
  1614. in the Org buffer so that the change takes effect."
  1615. :group 'org-link
  1616. :group 'org-appearance
  1617. :type '(set :greedy t
  1618. (const :tag "Double bracket links" bracket)
  1619. (const :tag "Angular bracket links" angle)
  1620. (const :tag "Plain text links" plain)
  1621. (const :tag "Radio target matches" radio)
  1622. (const :tag "Tags" tag)
  1623. (const :tag "Timestamps" date)
  1624. (const :tag "Footnotes" footnote)))
  1625. (defcustom org-make-link-description-function nil
  1626. "Function to use for generating link descriptions from links.
  1627. This function must take two parameters: the first one is the
  1628. link, the second one is the description generated by
  1629. `org-insert-link'. The function should return the description to
  1630. use."
  1631. :group 'org-link
  1632. :type '(choice (const nil) (function)))
  1633. (defgroup org-link-store nil
  1634. "Options concerning storing links in Org mode."
  1635. :tag "Org Store Link"
  1636. :group 'org-link)
  1637. (defcustom org-url-hexify-p t
  1638. "When non-nil, hexify URL when creating a link."
  1639. :type 'boolean
  1640. :version "24.3"
  1641. :group 'org-link-store)
  1642. (defcustom org-email-link-description-format "Email %c: %.30s"
  1643. "Format of the description part of a link to an email or usenet message.
  1644. The following %-escapes will be replaced by corresponding information:
  1645. %F full \"From\" field
  1646. %f name, taken from \"From\" field, address if no name
  1647. %T full \"To\" field
  1648. %t first name in \"To\" field, address if no name
  1649. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1650. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1651. %s subject
  1652. %d date
  1653. %m message-id.
  1654. You may use normal field width specification between the % and the letter.
  1655. This is for example useful to limit the length of the subject.
  1656. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1657. :group 'org-link-store
  1658. :type 'string)
  1659. (defcustom org-from-is-user-regexp
  1660. (let (r1 r2)
  1661. (when (and user-mail-address (not (string= user-mail-address "")))
  1662. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1663. (when (and user-full-name (not (string= user-full-name "")))
  1664. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1665. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1666. "Regexp matched against the \"From:\" header of an email or usenet message.
  1667. It should match if the message is from the user him/herself."
  1668. :group 'org-link-store
  1669. :type 'regexp)
  1670. (defcustom org-context-in-file-links t
  1671. "Non-nil means file links from `org-store-link' contain context.
  1672. \\<org-mode-map>
  1673. A search string will be added to the file name with :: as separator
  1674. and used to find the context when the link is activated by the command
  1675. `org-open-at-point'. When this option is t, the entire active region
  1676. will be placed in the search string of the file link. If set to a
  1677. positive integer, only the first n lines of context will be stored.
  1678. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1679. \\[org-store-link]')
  1680. negates this setting for the duration of the command."
  1681. :group 'org-link-store
  1682. :type '(choice boolean integer))
  1683. (defcustom org-keep-stored-link-after-insertion nil
  1684. "Non-nil means keep link in list for entire session.
  1685. \\<org-mode-map>
  1686. The command `org-store-link' adds a link pointing to the current
  1687. location to an internal list. These links accumulate during a session.
  1688. The command `org-insert-link' can be used to insert links into any
  1689. Org file (offering completion for all stored links).
  1690. When this option is nil, every link which has been inserted once using
  1691. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1692. unused
  1693. links more efficient."
  1694. :group 'org-link-store
  1695. :type 'boolean)
  1696. (defgroup org-link-follow nil
  1697. "Options concerning following links in Org mode."
  1698. :tag "Org Follow Link"
  1699. :group 'org-link)
  1700. (defcustom org-link-translation-function nil
  1701. "Function to translate links with different syntax to Org syntax.
  1702. This can be used to translate links created for example by the Planner
  1703. or emacs-wiki packages to Org syntax.
  1704. The function must accept two parameters, a TYPE containing the link
  1705. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1706. which is everything after the link protocol. It should return a cons
  1707. with possibly modified values of type and path.
  1708. Org contains a function for this, so if you set this variable to
  1709. `org-translate-link-from-planner', you should be able follow many
  1710. links created by planner."
  1711. :group 'org-link-follow
  1712. :type '(choice (const nil) (function)))
  1713. (defcustom org-follow-link-hook nil
  1714. "Hook that is run after a link has been followed."
  1715. :group 'org-link-follow
  1716. :type 'hook)
  1717. (defcustom org-tab-follows-link nil
  1718. "Non-nil means on links TAB will follow the link.
  1719. Needs to be set before org.el is loaded.
  1720. This really should not be used, it does not make sense, and the
  1721. implementation is bad."
  1722. :group 'org-link-follow
  1723. :type 'boolean)
  1724. (defcustom org-return-follows-link nil
  1725. "Non-nil means on links RET will follow the link.
  1726. In tables, the special behavior of RET has precedence."
  1727. :group 'org-link-follow
  1728. :type 'boolean)
  1729. (defcustom org-mouse-1-follows-link
  1730. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1731. "Non-nil means mouse-1 on a link will follow the link.
  1732. A longer mouse click will still set point. Needs to be set
  1733. before org.el is loaded."
  1734. :group 'org-link-follow
  1735. :version "26.1"
  1736. :package-version '(Org . "8.3")
  1737. :type '(choice
  1738. (const :tag "A double click follows the link" double)
  1739. (const :tag "Unconditionally follow the link with mouse-1" t)
  1740. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1741. (defcustom org-mark-ring-length 4
  1742. "Number of different positions to be recorded in the ring.
  1743. Changing this requires a restart of Emacs to work correctly."
  1744. :group 'org-link-follow
  1745. :type 'integer)
  1746. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1747. "Non-nil means internal fuzzy links can only match headlines.
  1748. When nil, the a fuzzy link may point to a target or a named
  1749. construct in the document. When set to the special value
  1750. `query-to-create', offer to create a new headline when none
  1751. matched.
  1752. Spaces and statistics cookies are ignored during heading searches."
  1753. :group 'org-link-follow
  1754. :version "24.1"
  1755. :type '(choice
  1756. (const :tag "Use fuzzy text search" nil)
  1757. (const :tag "Match only exact headline" t)
  1758. (const :tag "Match exact headline or query to create it"
  1759. query-to-create))
  1760. :safe #'symbolp)
  1761. (defcustom org-link-frame-setup
  1762. '((vm . vm-visit-folder-other-frame)
  1763. (vm-imap . vm-visit-imap-folder-other-frame)
  1764. (gnus . org-gnus-no-new-news)
  1765. (file . find-file-other-window)
  1766. (wl . wl-other-frame))
  1767. "Setup the frame configuration for following links.
  1768. When following a link with Emacs, it may often be useful to display
  1769. this link in another window or frame. This variable can be used to
  1770. set this up for the different types of links.
  1771. For VM, use any of
  1772. `vm-visit-folder'
  1773. `vm-visit-folder-other-window'
  1774. `vm-visit-folder-other-frame'
  1775. For Gnus, use any of
  1776. `gnus'
  1777. `gnus-other-frame'
  1778. `org-gnus-no-new-news'
  1779. For FILE, use any of
  1780. `find-file'
  1781. `find-file-other-window'
  1782. `find-file-other-frame'
  1783. For Wanderlust use any of
  1784. `wl'
  1785. `wl-other-frame'
  1786. For the calendar, use the variable `calendar-setup'.
  1787. For BBDB, it is currently only possible to display the matches in
  1788. another window."
  1789. :group 'org-link-follow
  1790. :type '(list
  1791. (cons (const vm)
  1792. (choice
  1793. (const vm-visit-folder)
  1794. (const vm-visit-folder-other-window)
  1795. (const vm-visit-folder-other-frame)))
  1796. (cons (const vm-imap)
  1797. (choice
  1798. (const vm-visit-imap-folder)
  1799. (const vm-visit-imap-folder-other-window)
  1800. (const vm-visit-imap-folder-other-frame)))
  1801. (cons (const gnus)
  1802. (choice
  1803. (const gnus)
  1804. (const gnus-other-frame)
  1805. (const org-gnus-no-new-news)))
  1806. (cons (const file)
  1807. (choice
  1808. (const find-file)
  1809. (const find-file-other-window)
  1810. (const find-file-other-frame)))
  1811. (cons (const wl)
  1812. (choice
  1813. (const wl)
  1814. (const wl-other-frame)))))
  1815. (defcustom org-display-internal-link-with-indirect-buffer nil
  1816. "Non-nil means use indirect buffer to display infile links.
  1817. Activating internal links (from one location in a file to another location
  1818. in the same file) normally just jumps to the location. When the link is
  1819. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1820. is displayed in
  1821. another window. When this option is set, the other window actually displays
  1822. an indirect buffer clone of the current buffer, to avoid any visibility
  1823. changes to the current buffer."
  1824. :group 'org-link-follow
  1825. :type 'boolean)
  1826. (defcustom org-open-non-existing-files nil
  1827. "Non-nil means `org-open-file' will open non-existing files.
  1828. When nil, an error will be generated.
  1829. This variable applies only to external applications because they
  1830. might choke on non-existing files. If the link is to a file that
  1831. will be opened in Emacs, the variable is ignored."
  1832. :group 'org-link-follow
  1833. :type 'boolean)
  1834. (defcustom org-open-directory-means-index-dot-org nil
  1835. "Non-nil means a link to a directory really means to index.org.
  1836. When nil, following a directory link will run dired or open a finder/explorer
  1837. window on that directory."
  1838. :group 'org-link-follow
  1839. :type 'boolean)
  1840. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1841. "Non-nil means ask for confirmation before executing shell links.
  1842. Shell links can be dangerous: just think about a link
  1843. [[shell:rm -rf ~/*][Google Search]]
  1844. This link would show up in your Org document as \"Google Search\",
  1845. but really it would remove your entire home directory.
  1846. Therefore we advise against setting this variable to nil.
  1847. Just change it to `y-or-n-p' if you want to confirm with a
  1848. single keystroke rather than having to type \"yes\"."
  1849. :group 'org-link-follow
  1850. :type '(choice
  1851. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1852. (const :tag "with y-or-n (faster)" y-or-n-p)
  1853. (const :tag "no confirmation (dangerous)" nil)))
  1854. (put 'org-confirm-shell-link-function
  1855. 'safe-local-variable
  1856. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1857. (defcustom org-confirm-shell-link-not-regexp ""
  1858. "A regexp to skip confirmation for shell links."
  1859. :group 'org-link-follow
  1860. :version "24.1"
  1861. :type 'regexp)
  1862. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1863. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1864. Elisp links can be dangerous: just think about a link
  1865. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1866. This link would show up in your Org document as \"Google Search\",
  1867. but really it would remove your entire home directory.
  1868. Therefore we advise against setting this variable to nil.
  1869. Just change it to `y-or-n-p' if you want to confirm with a
  1870. single keystroke rather than having to type \"yes\"."
  1871. :group 'org-link-follow
  1872. :type '(choice
  1873. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1874. (const :tag "with y-or-n (faster)" y-or-n-p)
  1875. (const :tag "no confirmation (dangerous)" nil)))
  1876. (put 'org-confirm-shell-link-function
  1877. 'safe-local-variable
  1878. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1879. (defcustom org-confirm-elisp-link-not-regexp ""
  1880. "A regexp to skip confirmation for Elisp links."
  1881. :group 'org-link-follow
  1882. :version "24.1"
  1883. :type 'regexp)
  1884. (defconst org-file-apps-defaults-gnu
  1885. '((remote . emacs)
  1886. (system . mailcap)
  1887. (t . mailcap))
  1888. "Default file applications on a UNIX or GNU/Linux system.
  1889. See `org-file-apps'.")
  1890. (defconst org-file-apps-defaults-macosx
  1891. '((remote . emacs)
  1892. (system . "open %s")
  1893. ("ps.gz" . "gv %s")
  1894. ("eps.gz" . "gv %s")
  1895. ("dvi" . "xdvi %s")
  1896. ("fig" . "xfig %s")
  1897. (t . "open %s"))
  1898. "Default file applications on a macOS system.
  1899. The system \"open\" is known as a default, but we use X11 applications
  1900. for some files for which the OS does not have a good default.
  1901. See `org-file-apps'.")
  1902. (defconst org-file-apps-defaults-windowsnt
  1903. (list '(remote . emacs)
  1904. (cons 'system (lambda (file _path)
  1905. (with-no-warnings (w32-shell-execute "open" file))))
  1906. (cons t (lambda (file _path)
  1907. (with-no-warnings (w32-shell-execute "open" file)))))
  1908. "Default file applications on a Windows NT system.
  1909. The system \"open\" is used for most files.
  1910. See `org-file-apps'.")
  1911. (defcustom org-file-apps
  1912. '((auto-mode . emacs)
  1913. ("\\.mm\\'" . default)
  1914. ("\\.x?html?\\'" . default)
  1915. ("\\.pdf\\'" . default))
  1916. "External applications for opening `file:path' items in a document.
  1917. \\<org-mode-map>\
  1918. Org mode uses system defaults for different file types, but
  1919. you can use this variable to set the application for a given file
  1920. extension. The entries in this list are cons cells where the car identifies
  1921. files and the cdr the corresponding command.
  1922. Possible values for the file identifier are:
  1923. \"string\" A string as a file identifier can be interpreted in different
  1924. ways, depending on its contents:
  1925. - Alphanumeric characters only:
  1926. Match links with this file extension.
  1927. Example: (\"pdf\" . \"evince %s\")
  1928. to open PDFs with evince.
  1929. - Regular expression: Match links where the
  1930. filename matches the regexp. If you want to
  1931. use groups here, use shy groups.
  1932. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1933. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1934. to open *.html and *.xhtml with firefox.
  1935. - Regular expression which contains (non-shy) groups:
  1936. Match links where the whole link, including \"::\", and
  1937. anything after that, matches the regexp.
  1938. In a custom command string, %1, %2, etc. are replaced with
  1939. the parts of the link that were matched by the groups.
  1940. For backwards compatibility, if a command string is given
  1941. that does not use any of the group matches, this case is
  1942. handled identically to the second one (i.e. match against
  1943. file name only).
  1944. In a custom function, you can access the group matches with
  1945. (match-string n link).
  1946. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1947. \"evince -p %1 %s\")
  1948. to open [[file:document.pdf::5]] with evince at page 5.
  1949. `directory' Matches a directory
  1950. `remote' Matches a remote file, accessible through tramp or efs.
  1951. Remote files most likely should be visited through Emacs
  1952. because external applications cannot handle such paths.
  1953. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1954. so all files Emacs knows how to handle. Using this with
  1955. command `emacs' will open most files in Emacs. Beware that this
  1956. will also open html files inside Emacs, unless you add
  1957. (\"html\" . default) to the list as well.
  1958. `system' The system command to open files, like `open' on Windows
  1959. and macOS, and mailcap under GNU/Linux. This is the command
  1960. that will be selected if you call `org-open-at-point' with a
  1961. double prefix argument (`\\[universal-argument] \
  1962. \\[universal-argument] \\[org-open-at-point]').
  1963. t Default for files not matched by any of the other options.
  1964. Possible values for the command are:
  1965. `emacs' The file will be visited by the current Emacs process.
  1966. `default' Use the default application for this file type, which is the
  1967. association for t in the list, most likely in the system-specific
  1968. part. This can be used to overrule an unwanted setting in the
  1969. system-specific variable.
  1970. `system' Use the system command for opening files, like \"open\".
  1971. This command is specified by the entry whose car is `system'.
  1972. Most likely, the system-specific version of this variable
  1973. does define this command, but you can overrule/replace it
  1974. here.
  1975. `mailcap' Use command specified in the mailcaps.
  1976. string A command to be executed by a shell; %s will be replaced
  1977. by the path to the file.
  1978. function A Lisp function, which will be called with two arguments:
  1979. the file path and the original link string, without the
  1980. \"file:\" prefix.
  1981. For more examples, see the system specific constants
  1982. `org-file-apps-defaults-macosx'
  1983. `org-file-apps-defaults-windowsnt'
  1984. `org-file-apps-defaults-gnu'."
  1985. :group 'org-link-follow
  1986. :type '(repeat
  1987. (cons (choice :value ""
  1988. (string :tag "Extension")
  1989. (const :tag "System command to open files" system)
  1990. (const :tag "Default for unrecognized files" t)
  1991. (const :tag "Remote file" remote)
  1992. (const :tag "Links to a directory" directory)
  1993. (const :tag "Any files that have Emacs modes"
  1994. auto-mode))
  1995. (choice :value ""
  1996. (const :tag "Visit with Emacs" emacs)
  1997. (const :tag "Use default" default)
  1998. (const :tag "Use the system command" system)
  1999. (string :tag "Command")
  2000. (function :tag "Function")))))
  2001. (defcustom org-doi-server-url "http://dx.doi.org/"
  2002. "The URL of the DOI server."
  2003. :type 'string
  2004. :version "24.3"
  2005. :group 'org-link-follow)
  2006. (defgroup org-refile nil
  2007. "Options concerning refiling entries in Org mode."
  2008. :tag "Org Refile"
  2009. :group 'org)
  2010. (defcustom org-directory "~/org"
  2011. "Directory with Org files.
  2012. This is just a default location to look for Org files. There is no need
  2013. at all to put your files into this directory. It is used in the
  2014. following situations:
  2015. 1. When a capture template specifies a target file that is not an
  2016. absolute path. The path will then be interpreted relative to
  2017. `org-directory'
  2018. 2. When the value of variable `org-agenda-files' is a single file, any
  2019. relative paths in this file will be taken as relative to
  2020. `org-directory'."
  2021. :group 'org-refile
  2022. :group 'org-capture
  2023. :type 'directory)
  2024. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2025. "Default target for storing notes.
  2026. Used as a fall back file for org-capture.el, for templates that
  2027. do not specify a target file."
  2028. :group 'org-refile
  2029. :group 'org-capture
  2030. :type 'file)
  2031. (defcustom org-reverse-note-order nil
  2032. "Non-nil means store new notes at the beginning of a file or entry.
  2033. When nil, new notes will be filed to the end of a file or entry.
  2034. This can also be a list with cons cells of regular expressions that
  2035. are matched against file names, and values."
  2036. :group 'org-capture
  2037. :group 'org-refile
  2038. :type '(choice
  2039. (const :tag "Reverse always" t)
  2040. (const :tag "Reverse never" nil)
  2041. (repeat :tag "By file name regexp"
  2042. (cons regexp boolean))))
  2043. (defcustom org-log-refile nil
  2044. "Information to record when a task is refiled.
  2045. Possible values are:
  2046. nil Don't add anything
  2047. time Add a time stamp to the task
  2048. note Prompt for a note and add it with template `org-log-note-headings'
  2049. This option can also be set with on a per-file-basis with
  2050. #+STARTUP: nologrefile
  2051. #+STARTUP: logrefile
  2052. #+STARTUP: lognoterefile
  2053. You can have local logging settings for a subtree by setting the LOGGING
  2054. property to one or more of these keywords.
  2055. When bulk-refiling from the agenda, the value `note' is forbidden and
  2056. will temporarily be changed to `time'."
  2057. :group 'org-refile
  2058. :group 'org-progress
  2059. :version "24.1"
  2060. :type '(choice
  2061. (const :tag "No logging" nil)
  2062. (const :tag "Record timestamp" time)
  2063. (const :tag "Record timestamp with note." note)))
  2064. (defcustom org-refile-targets nil
  2065. "Targets for refiling entries with `\\[org-refile]'.
  2066. This is a list of cons cells. Each cell contains:
  2067. - a specification of the files to be considered, either a list of files,
  2068. or a symbol whose function or variable value will be used to retrieve
  2069. a file name or a list of file names. If you use `org-agenda-files' for
  2070. that, all agenda files will be scanned for targets. Nil means consider
  2071. headings in the current buffer.
  2072. - A specification of how to find candidate refile targets. This may be
  2073. any of:
  2074. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2075. This tag has to be present in all target headlines, inheritance will
  2076. not be considered.
  2077. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2078. todo keyword.
  2079. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2080. headlines that are refiling targets.
  2081. - a cons cell (:level . N). Any headline of level N is considered a target.
  2082. Note that, when `org-odd-levels-only' is set, level corresponds to
  2083. order in hierarchy, not to the number of stars.
  2084. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2085. Note that, when `org-odd-levels-only' is set, level corresponds to
  2086. order in hierarchy, not to the number of stars.
  2087. Each element of this list generates a set of possible targets.
  2088. The union of these sets is presented (with completion) to
  2089. the user by `org-refile'.
  2090. You can set the variable `org-refile-target-verify-function' to a function
  2091. to verify each headline found by the simple criteria above.
  2092. When this variable is nil, all top-level headlines in the current buffer
  2093. are used, equivalent to the value `((nil . (:level . 1))'."
  2094. :group 'org-refile
  2095. :type '(repeat
  2096. (cons
  2097. (choice :value org-agenda-files
  2098. (const :tag "All agenda files" org-agenda-files)
  2099. (const :tag "Current buffer" nil)
  2100. (function) (variable) (file))
  2101. (choice :tag "Identify target headline by"
  2102. (cons :tag "Specific tag" (const :value :tag) (string))
  2103. (cons :tag "TODO keyword" (const :value :todo) (string))
  2104. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2105. (cons :tag "Level number" (const :value :level) (integer))
  2106. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2107. (defcustom org-refile-target-verify-function nil
  2108. "Function to verify if the headline at point should be a refile target.
  2109. The function will be called without arguments, with point at the
  2110. beginning of the headline. It should return t and leave point
  2111. where it is if the headline is a valid target for refiling.
  2112. If the target should not be selected, the function must return nil.
  2113. In addition to this, it may move point to a place from where the search
  2114. should be continued. For example, the function may decide that the entire
  2115. subtree of the current entry should be excluded and move point to the end
  2116. of the subtree."
  2117. :group 'org-refile
  2118. :type '(choice
  2119. (const nil)
  2120. (function)))
  2121. (defcustom org-refile-use-cache nil
  2122. "Non-nil means cache refile targets to speed up the process.
  2123. \\<org-mode-map>\
  2124. The cache for a particular file will be updated automatically when
  2125. the buffer has been killed, or when any of the marker used for flagging
  2126. refile targets no longer points at a live buffer.
  2127. If you have added new entries to a buffer that might themselves be targets,
  2128. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2129. if you find that easier, \
  2130. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2131. \\[org-refile]'."
  2132. :group 'org-refile
  2133. :version "24.1"
  2134. :type 'boolean)
  2135. (defcustom org-refile-use-outline-path nil
  2136. "Non-nil means provide refile targets as paths.
  2137. So a level 3 headline will be available as level1/level2/level3.
  2138. When the value is `file', also include the file name (without directory)
  2139. into the path. In this case, you can also stop the completion after
  2140. the file name, to get entries inserted as top level in the file.
  2141. When `full-file-path', include the full file path.
  2142. When `buffer-name', use the buffer name."
  2143. :group 'org-refile
  2144. :type '(choice
  2145. (const :tag "Not" nil)
  2146. (const :tag "Yes" t)
  2147. (const :tag "Start with file name" file)
  2148. (const :tag "Start with full file path" full-file-path)
  2149. (const :tag "Start with buffer name" buffer-name)))
  2150. (defcustom org-outline-path-complete-in-steps t
  2151. "Non-nil means complete the outline path in hierarchical steps.
  2152. When Org uses the refile interface to select an outline path (see
  2153. `org-refile-use-outline-path'), the completion of the path can be
  2154. done in a single go, or it can be done in steps down the headline
  2155. hierarchy. Going in steps is probably the best if you do not use
  2156. a special completion package like `ido' or `icicles'. However,
  2157. when using these packages, going in one step can be very fast,
  2158. while still showing the whole path to the entry."
  2159. :group 'org-refile
  2160. :type 'boolean)
  2161. (defcustom org-refile-allow-creating-parent-nodes nil
  2162. "Non-nil means allow the creation of new nodes as refile targets.
  2163. New nodes are then created by adding \"/new node name\" to the completion
  2164. of an existing node. When the value of this variable is `confirm',
  2165. new node creation must be confirmed by the user (recommended).
  2166. When nil, the completion must match an existing entry.
  2167. Note that, if the new heading is not seen by the criteria
  2168. listed in `org-refile-targets', multiple instances of the same
  2169. heading would be created by trying again to file under the new
  2170. heading."
  2171. :group 'org-refile
  2172. :type '(choice
  2173. (const :tag "Never" nil)
  2174. (const :tag "Always" t)
  2175. (const :tag "Prompt for confirmation" confirm)))
  2176. (defcustom org-refile-active-region-within-subtree nil
  2177. "Non-nil means also refile active region within a subtree.
  2178. By default `org-refile' doesn't allow refiling regions if they
  2179. don't contain a set of subtrees, but it might be convenient to
  2180. do so sometimes: in that case, the first line of the region is
  2181. converted to a headline before refiling."
  2182. :group 'org-refile
  2183. :version "24.1"
  2184. :type 'boolean)
  2185. (defgroup org-todo nil
  2186. "Options concerning TODO items in Org mode."
  2187. :tag "Org TODO"
  2188. :group 'org)
  2189. (defgroup org-progress nil
  2190. "Options concerning Progress logging in Org mode."
  2191. :tag "Org Progress"
  2192. :group 'org-time)
  2193. (defvar org-todo-interpretation-widgets
  2194. '((:tag "Sequence (cycling hits every state)" sequence)
  2195. (:tag "Type (cycling directly to DONE)" type))
  2196. "The available interpretation symbols for customizing `org-todo-keywords'.
  2197. Interested libraries should add to this list.")
  2198. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2199. "List of TODO entry keyword sequences and their interpretation.
  2200. \\<org-mode-map>This is a list of sequences.
  2201. Each sequence starts with a symbol, either `sequence' or `type',
  2202. indicating if the keywords should be interpreted as a sequence of
  2203. action steps, or as different types of TODO items. The first
  2204. keywords are states requiring action - these states will select a headline
  2205. for inclusion into the global TODO list Org produces. If one of the
  2206. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2207. signify that no further action is necessary. If \"|\" is not found,
  2208. the last keyword is treated as the only DONE state of the sequence.
  2209. The command `\\[org-todo]' cycles an entry through these states, and one
  2210. additional state where no keyword is present. For details about this
  2211. cycling, see the manual.
  2212. TODO keywords and interpretation can also be set on a per-file basis with
  2213. the special #+SEQ_TODO and #+TYP_TODO lines.
  2214. Each keyword can optionally specify a character for fast state selection
  2215. \(in combination with the variable `org-use-fast-todo-selection')
  2216. and specifiers for state change logging, using the same syntax that
  2217. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2218. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2219. indicates to record a time stamp each time this state is selected.
  2220. Each keyword may also specify if a timestamp or a note should be
  2221. recorded when entering or leaving the state, by adding additional
  2222. characters in the parenthesis after the keyword. This looks like this:
  2223. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2224. record only the time of the state change. With X and Y being either
  2225. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2226. Y when leaving the state if and only if the *target* state does not
  2227. define X. You may omit any of the fast-selection key or X or /Y,
  2228. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2229. For backward compatibility, this variable may also be just a list
  2230. of keywords. In this case the interpretation (sequence or type) will be
  2231. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2232. :group 'org-todo
  2233. :group 'org-keywords
  2234. :type '(choice
  2235. (repeat :tag "Old syntax, just keywords"
  2236. (string :tag "Keyword"))
  2237. (repeat :tag "New syntax"
  2238. (cons
  2239. (choice
  2240. :tag "Interpretation"
  2241. ;;Quick and dirty way to see
  2242. ;;`org-todo-interpretations'. This takes the
  2243. ;;place of item arguments
  2244. :convert-widget
  2245. (lambda (widget)
  2246. (widget-put widget
  2247. :args (mapcar
  2248. (lambda (x)
  2249. (widget-convert
  2250. (cons 'const x)))
  2251. org-todo-interpretation-widgets))
  2252. widget))
  2253. (repeat
  2254. (string :tag "Keyword"))))))
  2255. (defvar-local org-todo-keywords-1 nil
  2256. "All TODO and DONE keywords active in a buffer.")
  2257. (defvar org-todo-keywords-for-agenda nil)
  2258. (defvar org-done-keywords-for-agenda nil)
  2259. (defvar org-todo-keyword-alist-for-agenda nil)
  2260. (defvar org-tag-alist-for-agenda nil
  2261. "Alist of all tags from all agenda files.")
  2262. (defvar org-tag-groups-alist-for-agenda nil
  2263. "Alist of all groups tags from all current agenda files.")
  2264. (defvar-local org-tag-groups-alist nil)
  2265. (defvar org-agenda-contributing-files nil)
  2266. (defvar-local org-current-tag-alist nil
  2267. "Alist of all tag groups in current buffer.
  2268. This variable takes into consideration `org-tag-alist',
  2269. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2270. (defvar-local org-not-done-keywords nil)
  2271. (defvar-local org-done-keywords nil)
  2272. (defvar-local org-todo-heads nil)
  2273. (defvar-local org-todo-sets nil)
  2274. (defvar-local org-todo-log-states nil)
  2275. (defvar-local org-todo-kwd-alist nil)
  2276. (defvar-local org-todo-key-alist nil)
  2277. (defvar-local org-todo-key-trigger nil)
  2278. (defcustom org-todo-interpretation 'sequence
  2279. "Controls how TODO keywords are interpreted.
  2280. This variable is in principle obsolete and is only used for
  2281. backward compatibility, if the interpretation of todo keywords is
  2282. not given already in `org-todo-keywords'. See that variable for
  2283. more information."
  2284. :group 'org-todo
  2285. :group 'org-keywords
  2286. :type '(choice (const sequence)
  2287. (const type)))
  2288. (defcustom org-use-fast-todo-selection t
  2289. "\\<org-mode-map>\
  2290. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2291. This variable describes if and under what circumstances the cycling
  2292. mechanism for TODO keywords will be replaced by a single-key, direct
  2293. selection scheme.
  2294. When nil, fast selection is never used.
  2295. When the symbol `prefix', it will be used when `org-todo' is called
  2296. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2297. in an Org buffer, and
  2298. `\\[universal-argument] t' in an agenda buffer.
  2299. When t, fast selection is used by default. In this case, the prefix
  2300. argument forces cycling instead.
  2301. In all cases, the special interface is only used if access keys have
  2302. actually been assigned by the user, i.e. if keywords in the configuration
  2303. are followed by a letter in parenthesis, like TODO(t)."
  2304. :group 'org-todo
  2305. :type '(choice
  2306. (const :tag "Never" nil)
  2307. (const :tag "By default" t)
  2308. (const :tag "Only with C-u C-c C-t" prefix)))
  2309. (defcustom org-provide-todo-statistics t
  2310. "Non-nil means update todo statistics after insert and toggle.
  2311. ALL-HEADLINES means update todo statistics by including headlines
  2312. with no TODO keyword as well, counting them as not done.
  2313. A list of TODO keywords means the same, but skip keywords that are
  2314. not in this list.
  2315. When set to a list of two lists, the first list contains keywords
  2316. to consider as TODO keywords, the second list contains keywords
  2317. to consider as DONE keywords.
  2318. When this is set, todo statistics is updated in the parent of the
  2319. current entry each time a todo state is changed."
  2320. :group 'org-todo
  2321. :type '(choice
  2322. (const :tag "Yes, only for TODO entries" t)
  2323. (const :tag "Yes, including all entries" all-headlines)
  2324. (repeat :tag "Yes, for TODOs in this list"
  2325. (string :tag "TODO keyword"))
  2326. (list :tag "Yes, for TODOs and DONEs in these lists"
  2327. (repeat (string :tag "TODO keyword"))
  2328. (repeat (string :tag "DONE keyword")))
  2329. (other :tag "No TODO statistics" nil)))
  2330. (defcustom org-hierarchical-todo-statistics t
  2331. "Non-nil means TODO statistics covers just direct children.
  2332. When nil, all entries in the subtree are considered.
  2333. This has only an effect if `org-provide-todo-statistics' is set.
  2334. To set this to nil for only a single subtree, use a COOKIE_DATA
  2335. property and include the word \"recursive\" into the value."
  2336. :group 'org-todo
  2337. :type 'boolean)
  2338. (defcustom org-after-todo-state-change-hook nil
  2339. "Hook which is run after the state of a TODO item was changed.
  2340. The new state (a string with a TODO keyword, or nil) is available in the
  2341. Lisp variable `org-state'."
  2342. :group 'org-todo
  2343. :type 'hook)
  2344. (defvar org-blocker-hook nil
  2345. "Hook for functions that are allowed to block a state change.
  2346. Functions in this hook should not modify the buffer.
  2347. Each function gets as its single argument a property list,
  2348. see `org-trigger-hook' for more information about this list.
  2349. If any of the functions in this hook returns nil, the state change
  2350. is blocked.")
  2351. (defvar org-trigger-hook nil
  2352. "Hook for functions that are triggered by a state change.
  2353. Each function gets as its single argument a property list with at
  2354. least the following elements:
  2355. (:type type-of-change :position pos-at-entry-start
  2356. :from old-state :to new-state)
  2357. Depending on the type, more properties may be present.
  2358. This mechanism is currently implemented for:
  2359. TODO state changes
  2360. ------------------
  2361. :type todo-state-change
  2362. :from previous state (keyword as a string), or nil, or a symbol
  2363. `todo' or `done', to indicate the general type of state.
  2364. :to new state, like in :from")
  2365. (defcustom org-enforce-todo-dependencies nil
  2366. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2367. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2368. be blocked if any prior sibling is not yet done.
  2369. Finally, if the parent is blocked because of ordered siblings of its own,
  2370. the child will also be blocked."
  2371. :set (lambda (var val)
  2372. (set var val)
  2373. (if val
  2374. (add-hook 'org-blocker-hook
  2375. 'org-block-todo-from-children-or-siblings-or-parent)
  2376. (remove-hook 'org-blocker-hook
  2377. 'org-block-todo-from-children-or-siblings-or-parent)))
  2378. :group 'org-todo
  2379. :type 'boolean)
  2380. (defcustom org-enforce-todo-checkbox-dependencies nil
  2381. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2382. When this is nil, checkboxes have no influence on switching TODO states.
  2383. When non-nil, you first need to check off all check boxes before the TODO
  2384. entry can be switched to DONE.
  2385. This variable needs to be set before org.el is loaded, and you need to
  2386. restart Emacs after a change to make the change effective. The only way
  2387. to change is while Emacs is running is through the customize interface."
  2388. :set (lambda (var val)
  2389. (set var val)
  2390. (if val
  2391. (add-hook 'org-blocker-hook
  2392. 'org-block-todo-from-checkboxes)
  2393. (remove-hook 'org-blocker-hook
  2394. 'org-block-todo-from-checkboxes)))
  2395. :group 'org-todo
  2396. :type 'boolean)
  2397. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2398. "Non-nil means inserting a TODO heading is treated as state change.
  2399. So when the command `\\[org-insert-todo-heading]' is used, state change
  2400. logging will apply if appropriate. When nil, the new TODO item will
  2401. be inserted directly, and no logging will take place."
  2402. :group 'org-todo
  2403. :type 'boolean)
  2404. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2405. "Non-nil means switching TODO states with S-cursor counts as state change.
  2406. This is the default behavior. However, setting this to nil allows a
  2407. convenient way to select a TODO state and bypass any logging associated
  2408. with that."
  2409. :group 'org-todo
  2410. :type 'boolean)
  2411. (defcustom org-todo-state-tags-triggers nil
  2412. "Tag changes that should be triggered by TODO state changes.
  2413. This is a list. Each entry is
  2414. (state-change (tag . flag) .......)
  2415. State-change can be a string with a state, and empty string to indicate the
  2416. state that has no TODO keyword, or it can be one of the symbols `todo'
  2417. or `done', meaning any not-done or done state, respectively."
  2418. :group 'org-todo
  2419. :group 'org-tags
  2420. :type '(repeat
  2421. (cons (choice :tag "When changing to"
  2422. (const :tag "Not-done state" todo)
  2423. (const :tag "Done state" done)
  2424. (string :tag "State"))
  2425. (repeat
  2426. (cons :tag "Tag action"
  2427. (string :tag "Tag")
  2428. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2429. (defcustom org-log-done nil
  2430. "Information to record when a task moves to the DONE state.
  2431. Possible values are:
  2432. nil Don't add anything, just change the keyword
  2433. time Add a time stamp to the task
  2434. note Prompt for a note and add it with template `org-log-note-headings'
  2435. This option can also be set with on a per-file-basis with
  2436. #+STARTUP: nologdone
  2437. #+STARTUP: logdone
  2438. #+STARTUP: lognotedone
  2439. You can have local logging settings for a subtree by setting the LOGGING
  2440. property to one or more of these keywords."
  2441. :group 'org-todo
  2442. :group 'org-progress
  2443. :type '(choice
  2444. (const :tag "No logging" nil)
  2445. (const :tag "Record CLOSED timestamp" time)
  2446. (const :tag "Record CLOSED timestamp with note." note)))
  2447. ;; Normalize old uses of org-log-done.
  2448. (cond
  2449. ((eq org-log-done t) (setq org-log-done 'time))
  2450. ((and (listp org-log-done) (memq 'done org-log-done))
  2451. (setq org-log-done 'note)))
  2452. (defcustom org-log-reschedule nil
  2453. "Information to record when the scheduling date of a tasks is modified.
  2454. Possible values are:
  2455. nil Don't add anything, just change the date
  2456. time Add a time stamp to the task
  2457. note Prompt for a note and add it with template `org-log-note-headings'
  2458. This option can also be set with on a per-file-basis with
  2459. #+STARTUP: nologreschedule
  2460. #+STARTUP: logreschedule
  2461. #+STARTUP: lognotereschedule"
  2462. :group 'org-todo
  2463. :group 'org-progress
  2464. :type '(choice
  2465. (const :tag "No logging" nil)
  2466. (const :tag "Record timestamp" time)
  2467. (const :tag "Record timestamp with note." note)))
  2468. (defcustom org-log-redeadline nil
  2469. "Information to record when the deadline date of a tasks is modified.
  2470. Possible values are:
  2471. nil Don't add anything, just change the date
  2472. time Add a time stamp to the task
  2473. note Prompt for a note and add it with template `org-log-note-headings'
  2474. This option can also be set with on a per-file-basis with
  2475. #+STARTUP: nologredeadline
  2476. #+STARTUP: logredeadline
  2477. #+STARTUP: lognoteredeadline
  2478. You can have local logging settings for a subtree by setting the LOGGING
  2479. property to one or more of these keywords."
  2480. :group 'org-todo
  2481. :group 'org-progress
  2482. :type '(choice
  2483. (const :tag "No logging" nil)
  2484. (const :tag "Record timestamp" time)
  2485. (const :tag "Record timestamp with note." note)))
  2486. (defcustom org-log-note-clock-out nil
  2487. "Non-nil means record a note when clocking out of an item.
  2488. This can also be configured on a per-file basis by adding one of
  2489. the following lines anywhere in the buffer:
  2490. #+STARTUP: lognoteclock-out
  2491. #+STARTUP: nolognoteclock-out"
  2492. :group 'org-todo
  2493. :group 'org-progress
  2494. :type 'boolean)
  2495. (defcustom org-log-done-with-time t
  2496. "Non-nil means the CLOSED time stamp will contain date and time.
  2497. When nil, only the date will be recorded."
  2498. :group 'org-progress
  2499. :type 'boolean)
  2500. (defcustom org-log-note-headings
  2501. '((done . "CLOSING NOTE %t")
  2502. (state . "State %-12s from %-12S %t")
  2503. (note . "Note taken on %t")
  2504. (reschedule . "Rescheduled from %S on %t")
  2505. (delschedule . "Not scheduled, was %S on %t")
  2506. (redeadline . "New deadline from %S on %t")
  2507. (deldeadline . "Removed deadline, was %S on %t")
  2508. (refile . "Refiled on %t")
  2509. (clock-out . ""))
  2510. "Headings for notes added to entries.
  2511. The value is an alist, with the car being a symbol indicating the
  2512. note context, and the cdr is the heading to be used. The heading
  2513. may also be the empty string. The following placeholders can be
  2514. used:
  2515. %t a time stamp.
  2516. %T an active time stamp instead the default inactive one
  2517. %d a short-format time stamp.
  2518. %D an active short-format time stamp.
  2519. %s the new TODO state or time stamp (inactive), in double quotes.
  2520. %S the old TODO state or time stamp (inactive), in double quotes.
  2521. %u the user name.
  2522. %U full user name.
  2523. In fact, it is not a good idea to change the `state' entry,
  2524. because Agenda Log mode depends on the format of these entries."
  2525. :group 'org-todo
  2526. :group 'org-progress
  2527. :type '(list :greedy t
  2528. (cons (const :tag "Heading when closing an item" done) string)
  2529. (cons (const :tag
  2530. "Heading when changing todo state (todo sequence only)"
  2531. state) string)
  2532. (cons (const :tag "Heading when just taking a note" note) string)
  2533. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2534. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2535. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2536. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2537. (cons (const :tag "Heading when refiling" refile) string)
  2538. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2539. (unless (assq 'note org-log-note-headings)
  2540. (push '(note . "%t") org-log-note-headings))
  2541. (defcustom org-log-into-drawer nil
  2542. "Non-nil means insert state change notes and time stamps into a drawer.
  2543. When nil, state changes notes will be inserted after the headline and
  2544. any scheduling and clock lines, but not inside a drawer.
  2545. The value of this variable should be the name of the drawer to use.
  2546. LOGBOOK is proposed as the default drawer for this purpose, you can
  2547. also set this to a string to define the drawer of your choice.
  2548. A value of t is also allowed, representing \"LOGBOOK\".
  2549. A value of t or nil can also be set with on a per-file-basis with
  2550. #+STARTUP: logdrawer
  2551. #+STARTUP: nologdrawer
  2552. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2553. will be ignored.
  2554. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2555. a subtree.
  2556. Do not check directly this variable in a Lisp program. Call
  2557. function `org-log-into-drawer' instead."
  2558. :group 'org-todo
  2559. :group 'org-progress
  2560. :type '(choice
  2561. (const :tag "Not into a drawer" nil)
  2562. (const :tag "LOGBOOK" t)
  2563. (string :tag "Other")))
  2564. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2565. (defun org-log-into-drawer ()
  2566. "Name of the log drawer, as a string, or nil.
  2567. This is the value of `org-log-into-drawer'. However, if the
  2568. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2569. be used instead of the default value."
  2570. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2571. (cond ((equal p "nil") nil)
  2572. ((equal p "t") "LOGBOOK")
  2573. ((stringp p) p)
  2574. (p "LOGBOOK")
  2575. ((stringp org-log-into-drawer) org-log-into-drawer)
  2576. (org-log-into-drawer "LOGBOOK"))))
  2577. (defcustom org-log-state-notes-insert-after-drawers nil
  2578. "Non-nil means insert state change notes after any drawers in entry.
  2579. Only the drawers that *immediately* follow the headline and the
  2580. deadline/scheduled line are skipped.
  2581. When nil, insert notes right after the heading and perhaps the line
  2582. with deadline/scheduling if present.
  2583. This variable will have no effect if `org-log-into-drawer' is
  2584. set."
  2585. :group 'org-todo
  2586. :group 'org-progress
  2587. :type 'boolean)
  2588. (defcustom org-log-states-order-reversed t
  2589. "Non-nil means the latest state note will be directly after heading.
  2590. When nil, the state change notes will be ordered according to time.
  2591. This option can also be set with on a per-file-basis with
  2592. #+STARTUP: logstatesreversed
  2593. #+STARTUP: nologstatesreversed"
  2594. :group 'org-todo
  2595. :group 'org-progress
  2596. :type 'boolean)
  2597. (defcustom org-todo-repeat-to-state nil
  2598. "The TODO state to which a repeater should return the repeating task.
  2599. By default this is the first task of a TODO sequence or the
  2600. previous state of a TYPE_TODO set. But you can specify to use
  2601. the previous state in a TODO sequence or a string.
  2602. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2603. entry, which has precedence over this option."
  2604. :group 'org-todo
  2605. :version "24.1"
  2606. :type '(choice (const :tag "Use the previous TODO state" t)
  2607. (const :tag "Use the head of the TODO sequence" nil)
  2608. (string :tag "Use a specific TODO state")))
  2609. (defcustom org-log-repeat 'time
  2610. "Non-nil means record moving through the DONE state when triggering repeat.
  2611. An auto-repeating task is immediately switched back to TODO when
  2612. marked DONE. If you are not logging state changes (by adding \"@\"
  2613. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2614. record a closing note, there will be no record of the task moving
  2615. through DONE. This variable forces taking a note anyway.
  2616. nil Don't force a record
  2617. time Record a time stamp
  2618. note Prompt for a note and add it with template `org-log-note-headings'
  2619. This option can also be set with on a per-file-basis with
  2620. #+STARTUP: nologrepeat
  2621. #+STARTUP: logrepeat
  2622. #+STARTUP: lognoterepeat
  2623. You can have local logging settings for a subtree by setting the LOGGING
  2624. property to one or more of these keywords."
  2625. :group 'org-todo
  2626. :group 'org-progress
  2627. :type '(choice
  2628. (const :tag "Don't force a record" nil)
  2629. (const :tag "Force recording the DONE state" time)
  2630. (const :tag "Force recording a note with the DONE state" note)))
  2631. (defgroup org-priorities nil
  2632. "Priorities in Org mode."
  2633. :tag "Org Priorities"
  2634. :group 'org-todo)
  2635. (defcustom org-enable-priority-commands t
  2636. "Non-nil means priority commands are active.
  2637. When nil, these commands will be disabled, so that you never accidentally
  2638. set a priority."
  2639. :group 'org-priorities
  2640. :type 'boolean)
  2641. (defcustom org-highest-priority ?A
  2642. "The highest priority of TODO items. A character like ?A, ?B etc.
  2643. Must have a smaller ASCII number than `org-lowest-priority'."
  2644. :group 'org-priorities
  2645. :type 'character)
  2646. (defcustom org-lowest-priority ?C
  2647. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2648. Must have a larger ASCII number than `org-highest-priority'."
  2649. :group 'org-priorities
  2650. :type 'character)
  2651. (defcustom org-default-priority ?B
  2652. "The default priority of TODO items.
  2653. This is the priority an item gets if no explicit priority is given.
  2654. When starting to cycle on an empty priority the first step in the cycle
  2655. depends on `org-priority-start-cycle-with-default'. The resulting first
  2656. step priority must not exceed the range from `org-highest-priority' to
  2657. `org-lowest-priority' which means that `org-default-priority' has to be
  2658. in this range exclusive or inclusive the range boundaries. Else the
  2659. first step refuses to set the default and the second will fall back
  2660. to (depending on the command used) the highest or lowest priority."
  2661. :group 'org-priorities
  2662. :type 'character)
  2663. (defcustom org-priority-start-cycle-with-default t
  2664. "Non-nil means start with default priority when starting to cycle.
  2665. When this is nil, the first step in the cycle will be (depending on the
  2666. command used) one higher or lower than the default priority.
  2667. See also `org-default-priority'."
  2668. :group 'org-priorities
  2669. :type 'boolean)
  2670. (defcustom org-get-priority-function nil
  2671. "Function to extract the priority from a string.
  2672. The string is normally the headline. If this is nil Org computes the
  2673. priority from the priority cookie like [#A] in the headline. It returns
  2674. an integer, increasing by 1000 for each priority level.
  2675. The user can set a different function here, which should take a string
  2676. as an argument and return the numeric priority."
  2677. :group 'org-priorities
  2678. :version "24.1"
  2679. :type '(choice
  2680. (const nil)
  2681. (function)))
  2682. (defgroup org-time nil
  2683. "Options concerning time stamps and deadlines in Org mode."
  2684. :tag "Org Time"
  2685. :group 'org)
  2686. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2687. "Number of minutes to round time stamps to.
  2688. \\<org-mode-map>\
  2689. These are two values, the first applies when first creating a time stamp.
  2690. The second applies when changing it with the commands `S-up' and `S-down'.
  2691. When changing the time stamp, this means that it will change in steps
  2692. of N minutes, as given by the second value.
  2693. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2694. numbers should be factors of 60, so for example 5, 10, 15.
  2695. When this is larger than 1, you can still force an exact time stamp by using
  2696. a double prefix argument to a time stamp command like \
  2697. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2698. and by using a prefix arg to `S-up/down' to specify the exact number
  2699. of minutes to shift."
  2700. :group 'org-time
  2701. :get (lambda (var) ; Make sure both elements are there
  2702. (if (integerp (default-value var))
  2703. (list (default-value var) 5)
  2704. (default-value var)))
  2705. :type '(list
  2706. (integer :tag "when inserting times")
  2707. (integer :tag "when modifying times")))
  2708. ;; Normalize old customizations of this variable.
  2709. (when (integerp org-time-stamp-rounding-minutes)
  2710. (setq org-time-stamp-rounding-minutes
  2711. (list org-time-stamp-rounding-minutes
  2712. org-time-stamp-rounding-minutes)))
  2713. (defcustom org-display-custom-times nil
  2714. "Non-nil means overlay custom formats over all time stamps.
  2715. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2716. To turn this on on a per-file basis, insert anywhere in the file:
  2717. #+STARTUP: customtime"
  2718. :group 'org-time
  2719. :set 'set-default
  2720. :type 'sexp)
  2721. (make-variable-buffer-local 'org-display-custom-times)
  2722. (defcustom org-time-stamp-custom-formats
  2723. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2724. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2725. These are overlaid over the default ISO format if the variable
  2726. `org-display-custom-times' is set. Time like %H:%M should be at the
  2727. end of the second format. The custom formats are also honored by export
  2728. commands, if custom time display is turned on at the time of export."
  2729. :group 'org-time
  2730. :type 'sexp)
  2731. (defun org-time-stamp-format (&optional long inactive)
  2732. "Get the right format for a time string."
  2733. (let ((f (if long (cdr org-time-stamp-formats)
  2734. (car org-time-stamp-formats))))
  2735. (if inactive
  2736. (concat "[" (substring f 1 -1) "]")
  2737. f)))
  2738. (defcustom org-deadline-warning-days 14
  2739. "Number of days before expiration during which a deadline becomes active.
  2740. This variable governs the display in sparse trees and in the agenda.
  2741. When 0 or negative, it means use this number (the absolute value of it)
  2742. even if a deadline has a different individual lead time specified.
  2743. Custom commands can set this variable in the options section."
  2744. :group 'org-time
  2745. :group 'org-agenda-daily/weekly
  2746. :type 'integer)
  2747. (defcustom org-scheduled-delay-days 0
  2748. "Number of days before a scheduled item becomes active.
  2749. This variable governs the display in sparse trees and in the agenda.
  2750. The default value (i.e. 0) means: don't delay scheduled item.
  2751. When negative, it means use this number (the absolute value of it)
  2752. even if a scheduled item has a different individual delay time
  2753. specified.
  2754. Custom commands can set this variable in the options section."
  2755. :group 'org-time
  2756. :group 'org-agenda-daily/weekly
  2757. :version "24.4"
  2758. :package-version '(Org . "8.0")
  2759. :type 'integer)
  2760. (defcustom org-read-date-prefer-future t
  2761. "Non-nil means assume future for incomplete date input from user.
  2762. This affects the following situations:
  2763. 1. The user gives a month but not a year.
  2764. For example, if it is April and you enter \"feb 2\", this will be read
  2765. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2766. 2. The user gives a day, but no month.
  2767. For example, if today is the 15th, and you enter \"3\", Org will read
  2768. this as the third of *next* month. However, if you enter \"17\",
  2769. it will be considered as *this* month.
  2770. If you set this variable to the symbol `time', then also the following
  2771. will work:
  2772. 3. If the user gives a time.
  2773. If the time is before now, it will be interpreted as tomorrow.
  2774. Currently none of this works for ISO week specifications.
  2775. When this option is nil, the current day, month and year will always be
  2776. used as defaults.
  2777. See also `org-agenda-jump-prefer-future'."
  2778. :group 'org-time
  2779. :type '(choice
  2780. (const :tag "Never" nil)
  2781. (const :tag "Check month and day" t)
  2782. (const :tag "Check month, day, and time" time)))
  2783. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2784. "Should the agenda jump command prefer the future for incomplete dates?
  2785. The default is to do the same as configured in `org-read-date-prefer-future'.
  2786. But you can also set a deviating value here.
  2787. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2788. :group 'org-agenda
  2789. :group 'org-time
  2790. :version "24.1"
  2791. :type '(choice
  2792. (const :tag "Use org-read-date-prefer-future"
  2793. org-read-date-prefer-future)
  2794. (const :tag "Never" nil)
  2795. (const :tag "Always" t)))
  2796. (defcustom org-read-date-force-compatible-dates t
  2797. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2798. Depending on the system Emacs is running on, certain dates cannot
  2799. be represented with the type used internally to represent time.
  2800. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2801. correctly. Some systems allow for earlier dates, some for later,
  2802. some for both. One way to find out it to insert any date into an
  2803. Org buffer, putting the cursor on the year and hitting S-up and
  2804. S-down to test the range.
  2805. When this variable is set to t, the date/time prompt will not let
  2806. you specify dates outside the 1970-2037 range, so it is certain that
  2807. these dates will work in whatever version of Emacs you are
  2808. running, and also that you can move a file from one Emacs implementation
  2809. to another. WHenever Org is forcing the year for you, it will display
  2810. a message and beep.
  2811. When this variable is nil, Org will check if the date is
  2812. representable in the specific Emacs implementation you are using.
  2813. If not, it will force a year, usually the current year, and beep
  2814. to remind you. Currently this setting is not recommended because
  2815. the likelihood that you will open your Org files in an Emacs that
  2816. has limited date range is not negligible.
  2817. A workaround for this problem is to use diary sexp dates for time
  2818. stamps outside of this range."
  2819. :group 'org-time
  2820. :version "24.1"
  2821. :type 'boolean)
  2822. (defcustom org-read-date-display-live t
  2823. "Non-nil means display current interpretation of date prompt live.
  2824. This display will be in an overlay, in the minibuffer."
  2825. :group 'org-time
  2826. :type 'boolean)
  2827. (defcustom org-read-date-popup-calendar t
  2828. "Non-nil means pop up a calendar when prompting for a date.
  2829. In the calendar, the date can be selected with mouse-1. However, the
  2830. minibuffer will also be active, and you can simply enter the date as well.
  2831. When nil, only the minibuffer will be available."
  2832. :group 'org-time
  2833. :type 'boolean)
  2834. (defvaralias 'org-popup-calendar-for-date-prompt
  2835. 'org-read-date-popup-calendar)
  2836. (defcustom org-extend-today-until 0
  2837. "The hour when your day really ends. Must be an integer.
  2838. This has influence for the following applications:
  2839. - When switching the agenda to \"today\". It it is still earlier than
  2840. the time given here, the day recognized as TODAY is actually yesterday.
  2841. - When a date is read from the user and it is still before the time given
  2842. here, the current date and time will be assumed to be yesterday, 23:59.
  2843. Also, timestamps inserted in capture templates follow this rule.
  2844. IMPORTANT: This is a feature whose implementation is and likely will
  2845. remain incomplete. Really, it is only here because past midnight seems to
  2846. be the favorite working time of John Wiegley :-)"
  2847. :group 'org-time
  2848. :type 'integer)
  2849. (defcustom org-use-effective-time nil
  2850. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2851. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2852. \"effective time\" of any timestamps between midnight and 8am will be
  2853. 23:59 of the previous day."
  2854. :group 'org-time
  2855. :version "24.1"
  2856. :type 'boolean)
  2857. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2858. "When non-nil, use the last clock out time for `org-todo'.
  2859. Note that this option has precedence over the combined use of
  2860. `org-use-effective-time' and `org-extend-today-until'."
  2861. :group 'org-time
  2862. :version "24.4"
  2863. :package-version '(Org . "8.0")
  2864. :type 'boolean)
  2865. (defcustom org-edit-timestamp-down-means-later nil
  2866. "Non-nil means S-down will increase the time in a time stamp.
  2867. When nil, S-up will increase."
  2868. :group 'org-time
  2869. :type 'boolean)
  2870. (defcustom org-calendar-follow-timestamp-change t
  2871. "Non-nil means make the calendar window follow timestamp changes.
  2872. When a timestamp is modified and the calendar window is visible, it will be
  2873. moved to the new date."
  2874. :group 'org-time
  2875. :type 'boolean)
  2876. (defgroup org-tags nil
  2877. "Options concerning tags in Org mode."
  2878. :tag "Org Tags"
  2879. :group 'org)
  2880. (defcustom org-tag-alist nil
  2881. "Default tags available in Org files.
  2882. The value of this variable is an alist. Associations either:
  2883. (TAG)
  2884. (TAG . SELECT)
  2885. (SPECIAL)
  2886. where TAG is a tag as a string, SELECT is character, used to
  2887. select that tag through the fast tag selection interface, and
  2888. SPECIAL is one of the following keywords: `:startgroup',
  2889. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2890. `:newline'. These keywords are used to define a hierarchy of
  2891. tags. See manual for details.
  2892. When this variable is nil, Org mode bases tag input on what is
  2893. already in the buffer. The value can be overridden locally by
  2894. using a TAGS keyword, e.g.,
  2895. #+TAGS: tag1 tag2
  2896. See also `org-tag-persistent-alist' to sidestep this behavior."
  2897. :group 'org-tags
  2898. :type '(repeat
  2899. (choice
  2900. (cons :tag "Tag with key"
  2901. (string :tag "Tag name")
  2902. (character :tag "Access char"))
  2903. (list :tag "Tag" (string :tag "Tag name"))
  2904. (const :tag "Start radio group" (:startgroup))
  2905. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2906. (const :tag "Group tags delimiter" (:grouptags))
  2907. (const :tag "End radio group" (:endgroup))
  2908. (const :tag "End tag group, non distinct" (:endgrouptag))
  2909. (const :tag "New line" (:newline)))))
  2910. (defcustom org-tag-persistent-alist nil
  2911. "Tags always available in Org files.
  2912. The value of this variable is an alist. Associations either:
  2913. (TAG)
  2914. (TAG . SELECT)
  2915. (SPECIAL)
  2916. where TAG is a tag as a string, SELECT is a character, used to
  2917. select that tag through the fast tag selection interface, and
  2918. SPECIAL is one of the following keywords: `:startgroup',
  2919. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2920. `:newline'. These keywords are used to define a hierarchy of
  2921. tags. See manual for details.
  2922. Unlike to `org-tag-alist', tags defined in this variable do not
  2923. depend on a local TAGS keyword. Instead, to disable these tags
  2924. on a per-file basis, insert anywhere in the file:
  2925. #+STARTUP: noptag"
  2926. :group 'org-tags
  2927. :type '(repeat
  2928. (choice
  2929. (cons :tag "Tag with key"
  2930. (string :tag "Tag name")
  2931. (character :tag "Access char"))
  2932. (list :tag "Tag" (string :tag "Tag name"))
  2933. (const :tag "Start radio group" (:startgroup))
  2934. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2935. (const :tag "Group tags delimiter" (:grouptags))
  2936. (const :tag "End radio group" (:endgroup))
  2937. (const :tag "End tag group, non distinct" (:endgrouptag))
  2938. (const :tag "New line" (:newline)))))
  2939. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2940. "If non-nil, always offer completion for all tags of all agenda files.
  2941. Instead of customizing this variable directly, you might want to
  2942. set it locally for capture buffers, because there no list of
  2943. tags in that file can be created dynamically (there are none).
  2944. (add-hook \\='org-capture-mode-hook
  2945. (lambda ()
  2946. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2947. :group 'org-tags
  2948. :version "24.1"
  2949. :type 'boolean)
  2950. (defvar org-file-tags nil
  2951. "List of tags that can be inherited by all entries in the file.
  2952. The tags will be inherited if the variable `org-use-tag-inheritance'
  2953. says they should be.
  2954. This variable is populated from #+FILETAGS lines.")
  2955. (defcustom org-use-fast-tag-selection 'auto
  2956. "Non-nil means use fast tag selection scheme.
  2957. This is a special interface to select and deselect tags with single keys.
  2958. When nil, fast selection is never used.
  2959. When the symbol `auto', fast selection is used if and only if selection
  2960. characters for tags have been configured, either through the variable
  2961. `org-tag-alist' or through a #+TAGS line in the buffer.
  2962. When t, fast selection is always used and selection keys are assigned
  2963. automatically if necessary."
  2964. :group 'org-tags
  2965. :type '(choice
  2966. (const :tag "Always" t)
  2967. (const :tag "Never" nil)
  2968. (const :tag "When selection characters are configured" auto)))
  2969. (defcustom org-fast-tag-selection-single-key nil
  2970. "Non-nil means fast tag selection exits after first change.
  2971. When nil, you have to press RET to exit it.
  2972. During fast tag selection, you can toggle this flag with `C-c'.
  2973. This variable can also have the value `expert'. In this case, the window
  2974. displaying the tags menu is not even shown, until you press C-c again."
  2975. :group 'org-tags
  2976. :type '(choice
  2977. (const :tag "No" nil)
  2978. (const :tag "Yes" t)
  2979. (const :tag "Expert" expert)))
  2980. (defvar org-fast-tag-selection-include-todo nil
  2981. "Non-nil means fast tags selection interface will also offer TODO states.
  2982. This is an undocumented feature, you should not rely on it.")
  2983. (defcustom org-tags-column -77
  2984. "The column to which tags should be indented in a headline.
  2985. If this number is positive, it specifies the column. If it is negative,
  2986. it means that the tags should be flushright to that column. For example,
  2987. -80 works well for a normal 80 character screen.
  2988. When 0, place tags directly after headline text, with only one space in
  2989. between."
  2990. :group 'org-tags
  2991. :type 'integer)
  2992. (defcustom org-auto-align-tags t
  2993. "Non-nil keeps tags aligned when modifying headlines.
  2994. Some operations (i.e. demoting) change the length of a headline and
  2995. therefore shift the tags around. With this option turned on, after
  2996. each such operation the tags are again aligned to `org-tags-column'."
  2997. :group 'org-tags
  2998. :type 'boolean)
  2999. (defcustom org-use-tag-inheritance t
  3000. "Non-nil means tags in levels apply also for sublevels.
  3001. When nil, only the tags directly given in a specific line apply there.
  3002. This may also be a list of tags that should be inherited, or a regexp that
  3003. matches tags that should be inherited. Additional control is possible
  3004. with the variable `org-tags-exclude-from-inheritance' which gives an
  3005. explicit list of tags to be excluded from inheritance, even if the value of
  3006. `org-use-tag-inheritance' would select it for inheritance.
  3007. If this option is t, a match early-on in a tree can lead to a large
  3008. number of matches in the subtree when constructing the agenda or creating
  3009. a sparse tree. If you only want to see the first match in a tree during
  3010. a search, check out the variable `org-tags-match-list-sublevels'."
  3011. :group 'org-tags
  3012. :type '(choice
  3013. (const :tag "Not" nil)
  3014. (const :tag "Always" t)
  3015. (repeat :tag "Specific tags" (string :tag "Tag"))
  3016. (regexp :tag "Tags matched by regexp")))
  3017. (defcustom org-tags-exclude-from-inheritance nil
  3018. "List of tags that should never be inherited.
  3019. This is a way to exclude a few tags from inheritance. For way to do
  3020. the opposite, to actively allow inheritance for selected tags,
  3021. see the variable `org-use-tag-inheritance'."
  3022. :group 'org-tags
  3023. :type '(repeat (string :tag "Tag")))
  3024. (defun org-tag-inherit-p (tag)
  3025. "Check if TAG is one that should be inherited."
  3026. (cond
  3027. ((member tag org-tags-exclude-from-inheritance) nil)
  3028. ((eq org-use-tag-inheritance t) t)
  3029. ((not org-use-tag-inheritance) nil)
  3030. ((stringp org-use-tag-inheritance)
  3031. (string-match org-use-tag-inheritance tag))
  3032. ((listp org-use-tag-inheritance)
  3033. (member tag org-use-tag-inheritance))
  3034. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3035. (defcustom org-tags-match-list-sublevels t
  3036. "Non-nil means list also sublevels of headlines matching a search.
  3037. This variable applies to tags/property searches, and also to stuck
  3038. projects because this search is based on a tags match as well.
  3039. When set to the symbol `indented', sublevels are indented with
  3040. leading dots.
  3041. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3042. the sublevels of a headline matching a tag search often also match
  3043. the same search. Listing all of them can create very long lists.
  3044. Setting this variable to nil causes subtrees of a match to be skipped.
  3045. This variable is semi-obsolete and probably should always be true. It
  3046. is better to limit inheritance to certain tags using the variables
  3047. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3048. :group 'org-tags
  3049. :type '(choice
  3050. (const :tag "No, don't list them" nil)
  3051. (const :tag "Yes, do list them" t)
  3052. (const :tag "List them, indented with leading dots" indented)))
  3053. (defcustom org-tags-sort-function nil
  3054. "When set, tags are sorted using this function as a comparator."
  3055. :group 'org-tags
  3056. :type '(choice
  3057. (const :tag "No sorting" nil)
  3058. (const :tag "Alphabetical" string<)
  3059. (const :tag "Reverse alphabetical" string>)
  3060. (function :tag "Custom function" nil)))
  3061. (defvar org-tags-history nil
  3062. "History of minibuffer reads for tags.")
  3063. (defvar org-last-tags-completion-table nil
  3064. "The last used completion table for tags.")
  3065. (defvar org-after-tags-change-hook nil
  3066. "Hook that is run after the tags in a line have changed.")
  3067. (defgroup org-properties nil
  3068. "Options concerning properties in Org mode."
  3069. :tag "Org Properties"
  3070. :group 'org)
  3071. (defcustom org-property-format "%-10s %s"
  3072. "How property key/value pairs should be formatted by `indent-line'.
  3073. When `indent-line' hits a property definition, it will format the line
  3074. according to this format, mainly to make sure that the values are
  3075. lined-up with respect to each other."
  3076. :group 'org-properties
  3077. :type 'string)
  3078. (defcustom org-properties-postprocess-alist nil
  3079. "Alist of properties and functions to adjust inserted values.
  3080. Elements of this alist must be of the form
  3081. ([string] [function])
  3082. where [string] must be a property name and [function] must be a
  3083. lambda expression: this lambda expression must take one argument,
  3084. the value to adjust, and return the new value as a string.
  3085. For example, this element will allow the property \"Remaining\"
  3086. to be updated wrt the relation between the \"Effort\" property
  3087. and the clock summary:
  3088. ((\"Remaining\" (lambda(value)
  3089. (let ((clocksum (org-clock-sum-current-item))
  3090. (effort (org-duration-to-minutes
  3091. (org-entry-get (point) \"Effort\"))))
  3092. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3093. :group 'org-properties
  3094. :version "24.1"
  3095. :type '(alist :key-type (string :tag "Property")
  3096. :value-type (function :tag "Function")))
  3097. (defcustom org-use-property-inheritance nil
  3098. "Non-nil means properties apply also for sublevels.
  3099. This setting is chiefly used during property searches. Turning it on can
  3100. cause significant overhead when doing a search, which is why it is not
  3101. on by default.
  3102. When nil, only the properties directly given in the current entry count.
  3103. When t, every property is inherited. The value may also be a list of
  3104. properties that should have inheritance, or a regular expression matching
  3105. properties that should be inherited.
  3106. However, note that some special properties use inheritance under special
  3107. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3108. and the properties ending in \"_ALL\" when they are used as descriptor
  3109. for valid values of a property.
  3110. Note for programmers:
  3111. When querying an entry with `org-entry-get', you can control if inheritance
  3112. should be used. By default, `org-entry-get' looks only at the local
  3113. properties. You can request inheritance by setting the inherit argument
  3114. to t (to force inheritance) or to `selective' (to respect the setting
  3115. in this variable)."
  3116. :group 'org-properties
  3117. :type '(choice
  3118. (const :tag "Not" nil)
  3119. (const :tag "Always" t)
  3120. (repeat :tag "Specific properties" (string :tag "Property"))
  3121. (regexp :tag "Properties matched by regexp")))
  3122. (defun org-property-inherit-p (property)
  3123. "Return a non-nil value if PROPERTY should be inherited."
  3124. (cond
  3125. ((eq org-use-property-inheritance t) t)
  3126. ((not org-use-property-inheritance) nil)
  3127. ((stringp org-use-property-inheritance)
  3128. (string-match org-use-property-inheritance property))
  3129. ((listp org-use-property-inheritance)
  3130. (member-ignore-case property org-use-property-inheritance))
  3131. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3132. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3133. "The default column format, if no other format has been defined.
  3134. This variable can be set on the per-file basis by inserting a line
  3135. #+COLUMNS: %25ITEM ....."
  3136. :group 'org-properties
  3137. :type 'string)
  3138. (defcustom org-columns-ellipses ".."
  3139. "The ellipses to be used when a field in column view is truncated.
  3140. When this is the empty string, as many characters as possible are shown,
  3141. but then there will be no visual indication that the field has been truncated.
  3142. When this is a string of length N, the last N characters of a truncated
  3143. field are replaced by this string. If the column is narrower than the
  3144. ellipses string, only part of the ellipses string will be shown."
  3145. :group 'org-properties
  3146. :type 'string)
  3147. (defconst org-global-properties-fixed
  3148. '(("VISIBILITY_ALL" . "folded children content all")
  3149. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3150. "List of property/value pairs that can be inherited by any entry.
  3151. These are fixed values, for the preset properties. The user variable
  3152. that can be used to add to this list is `org-global-properties'.
  3153. The entries in this list are cons cells where the car is a property
  3154. name and cdr is a string with the value. If the value represents
  3155. multiple items like an \"_ALL\" property, separate the items by
  3156. spaces.")
  3157. (defcustom org-global-properties nil
  3158. "List of property/value pairs that can be inherited by any entry.
  3159. This list will be combined with the constant `org-global-properties-fixed'.
  3160. The entries in this list are cons cells where the car is a property
  3161. name and cdr is a string with the value.
  3162. You can set buffer-local values for the same purpose in the variable
  3163. `org-file-properties' this by adding lines like
  3164. #+PROPERTY: NAME VALUE"
  3165. :group 'org-properties
  3166. :type '(repeat
  3167. (cons (string :tag "Property")
  3168. (string :tag "Value"))))
  3169. (defvar-local org-file-properties nil
  3170. "List of property/value pairs that can be inherited by any entry.
  3171. Valid for the current buffer.
  3172. This variable is populated from #+PROPERTY lines.")
  3173. (defgroup org-agenda nil
  3174. "Options concerning agenda views in Org mode."
  3175. :tag "Org Agenda"
  3176. :group 'org)
  3177. (defvar-local org-category nil
  3178. "Variable used by org files to set a category for agenda display.
  3179. Such files should use a file variable to set it, for example
  3180. # -*- mode: org; org-category: \"ELisp\"
  3181. or contain a special line
  3182. #+CATEGORY: ELisp
  3183. If the file does not specify a category, then file's base name
  3184. is used instead.")
  3185. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3186. (defcustom org-agenda-files nil
  3187. "The files to be used for agenda display.
  3188. If an entry is a directory, all files in that directory that are matched
  3189. by `org-agenda-file-regexp' will be part of the file list.
  3190. If the value of the variable is not a list but a single file name, then
  3191. the list of agenda files is actually stored and maintained in that file,
  3192. one agenda file per line. In this file paths can be given relative to
  3193. `org-directory'. Tilde expansion and environment variable substitution
  3194. are also made.
  3195. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3196. and removed with `\\[org-remove-file]'."
  3197. :group 'org-agenda
  3198. :type '(choice
  3199. (repeat :tag "List of files and directories" file)
  3200. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3201. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3202. "Regular expression to match files for `org-agenda-files'.
  3203. If any element in the list in that variable contains a directory instead
  3204. of a normal file, all files in that directory that are matched by this
  3205. regular expression will be included."
  3206. :group 'org-agenda
  3207. :type 'regexp)
  3208. (defcustom org-agenda-text-search-extra-files nil
  3209. "List of extra files to be searched by text search commands.
  3210. These files will be searched in addition to the agenda files by the
  3211. commands `org-search-view' (`\\[org-agenda] s') \
  3212. and `org-occur-in-agenda-files'.
  3213. Note that these files will only be searched for text search commands,
  3214. not for the other agenda views like todo lists, tag searches or the weekly
  3215. agenda. This variable is intended to list notes and possibly archive files
  3216. that should also be searched by these two commands.
  3217. In fact, if the first element in the list is the symbol `agenda-archives',
  3218. then all archive files of all agenda files will be added to the search
  3219. scope."
  3220. :group 'org-agenda
  3221. :type '(set :greedy t
  3222. (const :tag "Agenda Archives" agenda-archives)
  3223. (repeat :inline t (file))))
  3224. (defvaralias 'org-agenda-multi-occur-extra-files
  3225. 'org-agenda-text-search-extra-files)
  3226. (defcustom org-agenda-skip-unavailable-files nil
  3227. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3228. A nil value means to remove them, after a query, from the list."
  3229. :group 'org-agenda
  3230. :type 'boolean)
  3231. (defcustom org-calendar-to-agenda-key [?c]
  3232. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3233. The command `org-calendar-goto-agenda' will be bound to this key. The
  3234. default is the character `c' because then `c' can be used to switch back and
  3235. forth between agenda and calendar."
  3236. :group 'org-agenda
  3237. :type 'sexp)
  3238. (defcustom org-calendar-insert-diary-entry-key [?i]
  3239. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3240. This option is irrelevant until `org-agenda-diary-file' has been configured
  3241. to point to an Org file. When that is the case, the command
  3242. `org-agenda-diary-entry' will be bound to the key given here, by default
  3243. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3244. if you want to continue doing this, you need to change this to a different
  3245. key."
  3246. :group 'org-agenda
  3247. :type 'sexp)
  3248. (defcustom org-agenda-diary-file 'diary-file
  3249. "File to which to add new entries with the `i' key in agenda and calendar.
  3250. When this is the symbol `diary-file', the functionality in the Emacs
  3251. calendar will be used to add entries to the `diary-file'. But when this
  3252. points to a file, `org-agenda-diary-entry' will be used instead."
  3253. :group 'org-agenda
  3254. :type '(choice
  3255. (const :tag "The standard Emacs diary file" diary-file)
  3256. (file :tag "Special Org file diary entries")))
  3257. (eval-after-load "calendar"
  3258. '(progn
  3259. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3260. 'org-calendar-goto-agenda)
  3261. (add-hook 'calendar-mode-hook
  3262. (lambda ()
  3263. (unless (eq org-agenda-diary-file 'diary-file)
  3264. (define-key calendar-mode-map
  3265. org-calendar-insert-diary-entry-key
  3266. 'org-agenda-diary-entry))))))
  3267. (defgroup org-latex nil
  3268. "Options for embedding LaTeX code into Org mode."
  3269. :tag "Org LaTeX"
  3270. :group 'org)
  3271. (defcustom org-format-latex-options
  3272. '(:foreground default :background default :scale 1.0
  3273. :html-foreground "Black" :html-background "Transparent"
  3274. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3275. "Options for creating images from LaTeX fragments.
  3276. This is a property list with the following properties:
  3277. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3278. `default' means use the foreground of the default face.
  3279. `auto' means use the foreground from the text face.
  3280. :background the background color, or \"Transparent\".
  3281. `default' means use the background of the default face.
  3282. `auto' means use the background from the text face.
  3283. :scale a scaling factor for the size of the images, to get more pixels
  3284. :html-foreground, :html-background, :html-scale
  3285. the same numbers for HTML export.
  3286. :matchers a list indicating which matchers should be used to
  3287. find LaTeX fragments. Valid members of this list are:
  3288. \"begin\" find environments
  3289. \"$1\" find single characters surrounded by $.$
  3290. \"$\" find math expressions surrounded by $...$
  3291. \"$$\" find math expressions surrounded by $$....$$
  3292. \"\\(\" find math expressions surrounded by \\(...\\)
  3293. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3294. :group 'org-latex
  3295. :type 'plist)
  3296. (defcustom org-format-latex-signal-error t
  3297. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3298. When nil, just push out a message."
  3299. :group 'org-latex
  3300. :version "24.1"
  3301. :type 'boolean)
  3302. (defcustom org-latex-to-mathml-jar-file nil
  3303. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3304. Use this to specify additional executable file say a jar file.
  3305. When using MathToWeb as the converter, specify the full-path to
  3306. your mathtoweb.jar file."
  3307. :group 'org-latex
  3308. :version "24.1"
  3309. :type '(choice
  3310. (const :tag "None" nil)
  3311. (file :tag "JAR file" :must-match t)))
  3312. (defcustom org-latex-to-mathml-convert-command nil
  3313. "Command to convert LaTeX fragments to MathML.
  3314. Replace format-specifiers in the command as noted below and use
  3315. `shell-command' to convert LaTeX to MathML.
  3316. %j: Executable file in fully expanded form as specified by
  3317. `org-latex-to-mathml-jar-file'.
  3318. %I: Input LaTeX file in fully expanded form.
  3319. %i: The latex fragment to be converted.
  3320. %o: Output MathML file.
  3321. This command is used by `org-create-math-formula'.
  3322. When using MathToWeb as the converter, set this option to
  3323. \"java -jar %j -unicode -force -df %o %I\".
  3324. When using LaTeXML set this option to
  3325. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3326. :group 'org-latex
  3327. :version "24.1"
  3328. :type '(choice
  3329. (const :tag "None" nil)
  3330. (string :tag "\nShell command")))
  3331. (defcustom org-preview-latex-default-process 'dvipng
  3332. "The default process to convert LaTeX fragments to image files.
  3333. All available processes and theirs documents can be found in
  3334. `org-preview-latex-process-alist', which see."
  3335. :group 'org-latex
  3336. :version "26.1"
  3337. :package-version '(Org . "9.0")
  3338. :type 'symbol)
  3339. (defcustom org-preview-latex-process-alist
  3340. '((dvipng
  3341. :programs ("latex" "dvipng")
  3342. :description "dvi > png"
  3343. :message "you need to install the programs: latex and dvipng."
  3344. :image-input-type "dvi"
  3345. :image-output-type "png"
  3346. :image-size-adjust (1.0 . 1.0)
  3347. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3348. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3349. (dvisvgm
  3350. :programs ("latex" "dvisvgm")
  3351. :description "dvi > svg"
  3352. :message "you need to install the programs: latex and dvisvgm."
  3353. :use-xcolor t
  3354. :image-input-type "dvi"
  3355. :image-output-type "svg"
  3356. :image-size-adjust (1.7 . 1.5)
  3357. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3358. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3359. (imagemagick
  3360. :programs ("latex" "convert")
  3361. :description "pdf > png"
  3362. :message "you need to install the programs: latex and imagemagick."
  3363. :use-xcolor t
  3364. :image-input-type "pdf"
  3365. :image-output-type "png"
  3366. :image-size-adjust (1.0 . 1.0)
  3367. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3368. :image-converter
  3369. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3370. "Definitions of external processes for LaTeX previewing.
  3371. Org mode can use some external commands to generate TeX snippet's images for
  3372. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3373. `org-create-formula-image' how to call them.
  3374. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3375. PROPERTIES accepts the following attributes:
  3376. :programs list of strings, required programs.
  3377. :description string, describe the process.
  3378. :message string, message it when required programs cannot be found.
  3379. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3380. :image-output-type string, output file type of image converter (e.g., \"png\").
  3381. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3382. deal with background and foreground color of image.
  3383. Otherwise, dvipng style background and foreground color
  3384. format are generated. You may then refer to them in
  3385. command options with \"%F\" and \"%B\".
  3386. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3387. image size showed in buffer and the cdr element is for
  3388. HTML file. This option is only useful for process
  3389. developers, users should use variable
  3390. `org-format-latex-options' instead.
  3391. :post-clean list of strings, files matched are to be cleaned up once
  3392. the image is generated. When nil, the files with \".dvi\",
  3393. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3394. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3395. be cleaned up.
  3396. :latex-header list of strings, the LaTeX header of the snippet file.
  3397. When nil, the fallback value is used instead, which is
  3398. controlled by `org-format-latex-header',
  3399. `org-latex-default-packages-alist' and
  3400. `org-latex-packages-alist', which see.
  3401. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3402. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3403. replaced with values defined below.
  3404. :image-converter list of image converter commands strings. Each of them is
  3405. given to the shell and supports any of the following
  3406. place-holders defined below.
  3407. Place-holders used by `:image-converter' and `:latex-compiler':
  3408. %f input file name
  3409. %b base name of input file
  3410. %o base directory of input file
  3411. %O absolute output file name
  3412. Place-holders only used by `:image-converter':
  3413. %F foreground of image
  3414. %B background of image
  3415. %D dpi, which is used to adjust image size by some processing commands.
  3416. %S the image size scale ratio, which is used to adjust image size by some
  3417. processing commands."
  3418. :group 'org-latex
  3419. :version "26.1"
  3420. :package-version '(Org . "9.0")
  3421. :type '(alist :tag "LaTeX to image backends"
  3422. :value-type (plist)))
  3423. (defcustom org-preview-latex-image-directory "ltximg/"
  3424. "Path to store latex preview images.
  3425. A relative path here creates many directories relative to the
  3426. processed org files paths. An absolute path puts all preview
  3427. images at the same place."
  3428. :group 'org-latex
  3429. :version "26.1"
  3430. :package-version '(Org . "9.0")
  3431. :type 'string)
  3432. (defun org-format-latex-mathml-available-p ()
  3433. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3434. (save-match-data
  3435. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3436. org-latex-to-mathml-convert-command)
  3437. (let ((executable (car (split-string
  3438. org-latex-to-mathml-convert-command))))
  3439. (when (executable-find executable)
  3440. (if (string-match
  3441. "%j" org-latex-to-mathml-convert-command)
  3442. (file-readable-p org-latex-to-mathml-jar-file)
  3443. t))))))
  3444. (defcustom org-format-latex-header "\\documentclass{article}
  3445. \\usepackage[usenames]{color}
  3446. \[PACKAGES]
  3447. \[DEFAULT-PACKAGES]
  3448. \\pagestyle{empty} % do not remove
  3449. % The settings below are copied from fullpage.sty
  3450. \\setlength{\\textwidth}{\\paperwidth}
  3451. \\addtolength{\\textwidth}{-3cm}
  3452. \\setlength{\\oddsidemargin}{1.5cm}
  3453. \\addtolength{\\oddsidemargin}{-2.54cm}
  3454. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3455. \\setlength{\\textheight}{\\paperheight}
  3456. \\addtolength{\\textheight}{-\\headheight}
  3457. \\addtolength{\\textheight}{-\\headsep}
  3458. \\addtolength{\\textheight}{-\\footskip}
  3459. \\addtolength{\\textheight}{-3cm}
  3460. \\setlength{\\topmargin}{1.5cm}
  3461. \\addtolength{\\topmargin}{-2.54cm}"
  3462. "The document header used for processing LaTeX fragments.
  3463. It is imperative that this header make sure that no page number
  3464. appears on the page. The package defined in the variables
  3465. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3466. will either replace the placeholder \"[PACKAGES]\" in this
  3467. header, or they will be appended."
  3468. :group 'org-latex
  3469. :type 'string)
  3470. (defun org-set-packages-alist (var val)
  3471. "Set the packages alist and make sure it has 3 elements per entry."
  3472. (set var (mapcar (lambda (x)
  3473. (if (and (consp x) (= (length x) 2))
  3474. (list (car x) (nth 1 x) t)
  3475. x))
  3476. val)))
  3477. (defun org-get-packages-alist (var)
  3478. "Get the packages alist and make sure it has 3 elements per entry."
  3479. (mapcar (lambda (x)
  3480. (if (and (consp x) (= (length x) 2))
  3481. (list (car x) (nth 1 x) t)
  3482. x))
  3483. (default-value var)))
  3484. (defcustom org-latex-default-packages-alist
  3485. '(("AUTO" "inputenc" t ("pdflatex"))
  3486. ("T1" "fontenc" t ("pdflatex"))
  3487. ("" "graphicx" t)
  3488. ("" "grffile" t)
  3489. ("" "longtable" nil)
  3490. ("" "wrapfig" nil)
  3491. ("" "rotating" nil)
  3492. ("normalem" "ulem" t)
  3493. ("" "amsmath" t)
  3494. ("" "textcomp" t)
  3495. ("" "amssymb" t)
  3496. ("" "capt-of" nil)
  3497. ("" "hyperref" nil))
  3498. "Alist of default packages to be inserted in the header.
  3499. Change this only if one of the packages here causes an
  3500. incompatibility with another package you are using.
  3501. The packages in this list are needed by one part or another of
  3502. Org mode to function properly:
  3503. - inputenc, fontenc: for basic font and character selection
  3504. - graphicx: for including images
  3505. - grffile: allow periods and spaces in graphics file names
  3506. - longtable: For multipage tables
  3507. - wrapfig: for figure placement
  3508. - rotating: for sideways figures and tables
  3509. - ulem: for underline and strike-through
  3510. - amsmath: for subscript and superscript and math environments
  3511. - textcomp, amssymb: for various symbols used
  3512. for interpreting the entities in `org-entities'. You can skip
  3513. some of these packages if you don't use any of their symbols.
  3514. - capt-of: for captions outside of floats
  3515. - hyperref: for cross references
  3516. Therefore you should not modify this variable unless you know
  3517. what you are doing. The one reason to change it anyway is that
  3518. you might be loading some other package that conflicts with one
  3519. of the default packages. Each element is either a cell or
  3520. a string.
  3521. A cell is of the format
  3522. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3523. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3524. when compiling LaTeX snippets into images for inclusion into
  3525. non-LaTeX output. COMPILERS is a list of compilers that should
  3526. include the package, see `org-latex-compiler'. If the document
  3527. compiler is not in the list, and the list is non-nil, the package
  3528. will not be inserted in the final document.
  3529. A string will be inserted as-is in the header of the document."
  3530. :group 'org-latex
  3531. :group 'org-export-latex
  3532. :set 'org-set-packages-alist
  3533. :get 'org-get-packages-alist
  3534. :version "26.1"
  3535. :package-version '(Org . "8.3")
  3536. :type '(repeat
  3537. (choice
  3538. (list :tag "options/package pair"
  3539. (string :tag "options")
  3540. (string :tag "package")
  3541. (boolean :tag "Snippet")
  3542. (choice
  3543. (const :tag "For all compilers" nil)
  3544. (repeat :tag "Allowed compiler" string)))
  3545. (string :tag "A line of LaTeX"))))
  3546. (defcustom org-latex-packages-alist nil
  3547. "Alist of packages to be inserted in every LaTeX header.
  3548. These will be inserted after `org-latex-default-packages-alist'.
  3549. Each element is either a cell or a string.
  3550. A cell is of the format:
  3551. (\"options\" \"package\" SNIPPET-FLAG)
  3552. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3553. needed when turning LaTeX snippets into images for inclusion into
  3554. non-LaTeX output.
  3555. A string will be inserted as-is in the header of the document.
  3556. Make sure that you only list packages here which:
  3557. - you want in every file;
  3558. - do not conflict with the setup in `org-format-latex-header';
  3559. - do not conflict with the default packages in
  3560. `org-latex-default-packages-alist'."
  3561. :group 'org-latex
  3562. :group 'org-export-latex
  3563. :set 'org-set-packages-alist
  3564. :get 'org-get-packages-alist
  3565. :type '(repeat
  3566. (choice
  3567. (list :tag "options/package pair"
  3568. (string :tag "options")
  3569. (string :tag "package")
  3570. (boolean :tag "Snippet"))
  3571. (string :tag "A line of LaTeX"))))
  3572. (defgroup org-appearance nil
  3573. "Settings for Org mode appearance."
  3574. :tag "Org Appearance"
  3575. :group 'org)
  3576. (defcustom org-level-color-stars-only nil
  3577. "Non-nil means fontify only the stars in each headline.
  3578. When nil, the entire headline is fontified.
  3579. Changing it requires restart of `font-lock-mode' to become effective
  3580. also in regions already fontified."
  3581. :group 'org-appearance
  3582. :type 'boolean)
  3583. (defcustom org-hide-leading-stars nil
  3584. "Non-nil means hide the first N-1 stars in a headline.
  3585. This works by using the face `org-hide' for these stars. This
  3586. face is white for a light background, and black for a dark
  3587. background. You may have to customize the face `org-hide' to
  3588. make this work.
  3589. Changing it requires restart of `font-lock-mode' to become effective
  3590. also in regions already fontified.
  3591. You may also set this on a per-file basis by adding one of the following
  3592. lines to the buffer:
  3593. #+STARTUP: hidestars
  3594. #+STARTUP: showstars"
  3595. :group 'org-appearance
  3596. :type 'boolean)
  3597. (defcustom org-hidden-keywords nil
  3598. "List of symbols corresponding to keywords to be hidden the org buffer.
  3599. For example, a value \\='(title) for this list will make the document's title
  3600. appear in the buffer without the initial #+TITLE: keyword."
  3601. :group 'org-appearance
  3602. :version "24.1"
  3603. :type '(set (const :tag "#+AUTHOR" author)
  3604. (const :tag "#+DATE" date)
  3605. (const :tag "#+EMAIL" email)
  3606. (const :tag "#+TITLE" title)))
  3607. (defcustom org-custom-properties nil
  3608. "List of properties (as strings) with a special meaning.
  3609. The default use of these custom properties is to let the user
  3610. hide them with `org-toggle-custom-properties-visibility'."
  3611. :group 'org-properties
  3612. :group 'org-appearance
  3613. :version "24.3"
  3614. :type '(repeat (string :tag "Property Name")))
  3615. (defcustom org-fontify-done-headline nil
  3616. "Non-nil means change the face of a headline if it is marked DONE.
  3617. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3618. When this is non-nil, the headline after the keyword is set to the
  3619. `org-headline-done' as an additional indication."
  3620. :group 'org-appearance
  3621. :type 'boolean)
  3622. (defcustom org-fontify-emphasized-text t
  3623. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3624. Changing this variable requires a restart of Emacs to take effect."
  3625. :group 'org-appearance
  3626. :type 'boolean)
  3627. (defcustom org-fontify-whole-heading-line nil
  3628. "Non-nil means fontify the whole line for headings.
  3629. This is useful when setting a background color for the
  3630. org-level-* faces."
  3631. :group 'org-appearance
  3632. :type 'boolean)
  3633. (defcustom org-highlight-latex-and-related nil
  3634. "Non-nil means highlight LaTeX related syntax in the buffer.
  3635. When non nil, the value should be a list containing any of the
  3636. following symbols:
  3637. `latex' Highlight LaTeX snippets and environments.
  3638. `script' Highlight subscript and superscript.
  3639. `entities' Highlight entities."
  3640. :group 'org-appearance
  3641. :version "24.4"
  3642. :package-version '(Org . "8.0")
  3643. :type '(choice
  3644. (const :tag "No highlighting" nil)
  3645. (set :greedy t :tag "Highlight"
  3646. (const :tag "LaTeX snippets and environments" latex)
  3647. (const :tag "Subscript and superscript" script)
  3648. (const :tag "Entities" entities))))
  3649. (defcustom org-hide-emphasis-markers nil
  3650. "Non-nil mean font-lock should hide the emphasis marker characters."
  3651. :group 'org-appearance
  3652. :type 'boolean)
  3653. (defcustom org-hide-macro-markers nil
  3654. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3655. :group 'org-appearance
  3656. :type 'boolean)
  3657. (defcustom org-pretty-entities nil
  3658. "Non-nil means show entities as UTF8 characters.
  3659. When nil, the \\name form remains in the buffer."
  3660. :group 'org-appearance
  3661. :version "24.1"
  3662. :type 'boolean)
  3663. (defcustom org-pretty-entities-include-sub-superscripts t
  3664. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3665. :group 'org-appearance
  3666. :version "24.1"
  3667. :type 'boolean)
  3668. (defvar org-emph-re nil
  3669. "Regular expression for matching emphasis.
  3670. After a match, the match groups contain these elements:
  3671. 0 The match of the full regular expression, including the characters
  3672. before and after the proper match
  3673. 1 The character before the proper match, or empty at beginning of line
  3674. 2 The proper match, including the leading and trailing markers
  3675. 3 The leading marker like * or /, indicating the type of highlighting
  3676. 4 The text between the emphasis markers, not including the markers
  3677. 5 The character after the match, empty at the end of a line")
  3678. (defvar org-verbatim-re nil
  3679. "Regular expression for matching verbatim text.")
  3680. (defvar org-emphasis-regexp-components) ; defined just below
  3681. (defvar org-emphasis-alist) ; defined just below
  3682. (defun org-set-emph-re (var val)
  3683. "Set variable and compute the emphasis regular expression."
  3684. (set var val)
  3685. (when (and (boundp 'org-emphasis-alist)
  3686. (boundp 'org-emphasis-regexp-components)
  3687. org-emphasis-alist org-emphasis-regexp-components)
  3688. (pcase-let*
  3689. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3690. (body (if (<= nl 0) body
  3691. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3692. (template
  3693. (format (concat "\\([%s]\\|^\\)" ;before markers
  3694. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3695. "\\([%s]\\|$\\)") ;after markers
  3696. pre border border body border post)))
  3697. (setq org-emph-re (format template "*/_+"))
  3698. (setq org-verbatim-re (format template "=~")))))
  3699. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3700. ;; set this option proved cumbersome. See this message/thread:
  3701. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3702. (defvar org-emphasis-regexp-components
  3703. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3704. "Components used to build the regular expression for emphasis.
  3705. This is a list with five entries. Terminology: In an emphasis string
  3706. like \" *strong word* \", we call the initial space PREMATCH, the final
  3707. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3708. and \"trong wor\" is the body. The different components in this variable
  3709. specify what is allowed/forbidden in each part:
  3710. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3711. post Chars allowed as postmatch. End of line will be allowed too.
  3712. border The chars *forbidden* as border characters.
  3713. body-regexp A regexp like \".\" to match a body character. Don't use
  3714. non-shy groups here, and don't allow newline here.
  3715. newline The maximum number of newlines allowed in an emphasis exp.
  3716. You need to reload Org or to restart Emacs after setting this.")
  3717. (defcustom org-emphasis-alist
  3718. '(("*" bold)
  3719. ("/" italic)
  3720. ("_" underline)
  3721. ("=" org-verbatim verbatim)
  3722. ("~" org-code verbatim)
  3723. ("+" (:strike-through t)))
  3724. "Alist of characters and faces to emphasize text.
  3725. Text starting and ending with a special character will be emphasized,
  3726. for example *bold*, _underlined_ and /italic/. This variable sets the
  3727. marker characters and the face to be used by font-lock for highlighting
  3728. in Org buffers.
  3729. You need to reload Org or to restart Emacs after customizing this."
  3730. :group 'org-appearance
  3731. :set 'org-set-emph-re
  3732. :version "24.4"
  3733. :package-version '(Org . "8.0")
  3734. :type '(repeat
  3735. (list
  3736. (string :tag "Marker character")
  3737. (choice
  3738. (face :tag "Font-lock-face")
  3739. (plist :tag "Face property list"))
  3740. (option (const verbatim)))))
  3741. (defvar org-protecting-blocks '("src" "example" "export")
  3742. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3743. This is needed for font-lock setup.")
  3744. ;;; Functions and variables from their packages
  3745. ;; Declared here to avoid compiler warnings
  3746. (defvar mark-active)
  3747. ;; Various packages
  3748. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3749. (declare-function calendar-forward-day "cal-move" (arg))
  3750. (declare-function calendar-goto-date "cal-move" (date))
  3751. (declare-function calendar-goto-today "cal-move" ())
  3752. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3753. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3754. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3755. (declare-function cdlatex-tab "ext:cdlatex" ())
  3756. (declare-function dired-get-filename
  3757. "dired"
  3758. (&optional localp no-error-if-not-filep))
  3759. (declare-function iswitchb-read-buffer
  3760. "iswitchb"
  3761. (prompt &optional
  3762. default require-match _predicate start matches-set))
  3763. (declare-function org-agenda-change-all-lines
  3764. "org-agenda"
  3765. (newhead hdmarker &optional fixface just-this))
  3766. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3767. "org-agenda"
  3768. (&optional end))
  3769. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3770. (declare-function org-agenda-format-item
  3771. "org-agenda"
  3772. (extra txt &optional level category tags dotime
  3773. remove-re habitp))
  3774. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3775. (declare-function org-agenda-save-markers-for-cut-and-paste
  3776. "org-agenda"
  3777. (beg end))
  3778. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3779. (declare-function org-agenda-skip "org-agenda" ())
  3780. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3781. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3782. (declare-function org-indent-mode "org-indent" (&optional arg))
  3783. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3784. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3785. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3786. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3787. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3788. (declare-function parse-time-string "parse-time" (string))
  3789. (defvar align-mode-rules-list)
  3790. (defvar calc-embedded-close-formula)
  3791. (defvar calc-embedded-open-formula)
  3792. (defvar calc-embedded-open-mode)
  3793. (defvar font-lock-unfontify-region-function)
  3794. (defvar iswitchb-temp-buflist)
  3795. (defvar org-agenda-tags-todo-honor-ignore-options)
  3796. (defvar remember-data-file)
  3797. (defvar texmathp-why)
  3798. ;;;###autoload
  3799. (defun turn-on-orgtbl ()
  3800. "Unconditionally turn on `orgtbl-mode'."
  3801. (require 'org-table)
  3802. (orgtbl-mode 1))
  3803. (defun org-at-table-p (&optional table-type)
  3804. "Non-nil if the cursor is inside an Org table.
  3805. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3806. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3807. (or (not (derived-mode-p 'org-mode))
  3808. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3809. (and e (or table-type
  3810. (eq 'org (org-element-property :type e))))))))
  3811. (defun org-at-table.el-p ()
  3812. "Non-nil when point is at a table.el table."
  3813. (and (org-match-line "[ \t]*[|+]")
  3814. (let ((element (org-element-at-point)))
  3815. (and (eq (org-element-type element) 'table)
  3816. (eq (org-element-property :type element) 'table.el)))))
  3817. (defun org-at-table-hline-p ()
  3818. "Non-nil when point is inside a hline in a table.
  3819. Assume point is already in a table."
  3820. (org-match-line org-table-hline-regexp))
  3821. (defun org-table-map-tables (function &optional quietly)
  3822. "Apply FUNCTION to the start of all tables in the buffer."
  3823. (org-with-wide-buffer
  3824. (goto-char (point-min))
  3825. (while (re-search-forward org-table-any-line-regexp nil t)
  3826. (unless quietly
  3827. (message "Mapping tables: %d%%"
  3828. (floor (* 100.0 (point)) (buffer-size))))
  3829. (beginning-of-line 1)
  3830. (when (and (looking-at org-table-line-regexp)
  3831. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3832. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3833. (save-excursion (funcall function))
  3834. (or (looking-at org-table-line-regexp)
  3835. (forward-char 1)))
  3836. (re-search-forward org-table-any-border-regexp nil 1)))
  3837. (unless quietly (message "Mapping tables: done")))
  3838. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3839. (declare-function org-clock-update-mode-line "org-clock" ())
  3840. (declare-function org-resolve-clocks "org-clock"
  3841. (&optional also-non-dangling-p prompt last-valid))
  3842. (defun org-at-TBLFM-p (&optional pos)
  3843. "Non-nil when point (or POS) is in #+TBLFM line."
  3844. (save-excursion
  3845. (goto-char (or pos (point)))
  3846. (beginning-of-line)
  3847. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3848. (eq (org-element-type (org-element-at-point)) 'table))))
  3849. (defvar org-clock-start-time)
  3850. (defvar org-clock-marker (make-marker)
  3851. "Marker recording the last clock-in.")
  3852. (defvar org-clock-hd-marker (make-marker)
  3853. "Marker recording the last clock-in, but the headline position.")
  3854. (defvar org-clock-heading ""
  3855. "The heading of the current clock entry.")
  3856. (defun org-clock-is-active ()
  3857. "Return the buffer where the clock is currently running.
  3858. Return nil if no clock is running."
  3859. (marker-buffer org-clock-marker))
  3860. (defun org-check-running-clock ()
  3861. "Check if the current buffer contains the running clock.
  3862. If yes, offer to stop it and to save the buffer with the changes."
  3863. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3864. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3865. (buffer-name))))
  3866. (org-clock-out)
  3867. (when (y-or-n-p "Save changed buffer?")
  3868. (save-buffer))))
  3869. (defun org-clocktable-try-shift (dir n)
  3870. "Check if this line starts a clock table, if yes, shift the time block."
  3871. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3872. (org-clocktable-shift dir n)))
  3873. ;;;###autoload
  3874. (defun org-clock-persistence-insinuate ()
  3875. "Set up hooks for clock persistence."
  3876. (require 'org-clock)
  3877. (add-hook 'org-mode-hook 'org-clock-load)
  3878. (add-hook 'kill-emacs-hook 'org-clock-save))
  3879. (defgroup org-archive nil
  3880. "Options concerning archiving in Org mode."
  3881. :tag "Org Archive"
  3882. :group 'org-structure)
  3883. (defcustom org-archive-location "%s_archive::"
  3884. "The location where subtrees should be archived.
  3885. The value of this variable is a string, consisting of two parts,
  3886. separated by a double-colon. The first part is a filename and
  3887. the second part is a headline.
  3888. When the filename is omitted, archiving happens in the same file.
  3889. %s in the filename will be replaced by the current file
  3890. name (without the directory part). Archiving to a different file
  3891. is useful to keep archived entries from contributing to the
  3892. Org Agenda.
  3893. The archived entries will be filed as subtrees of the specified
  3894. headline. When the headline is omitted, the subtrees are simply
  3895. filed away at the end of the file, as top-level entries. Also in
  3896. the heading you can use %s to represent the file name, this can be
  3897. useful when using the same archive for a number of different files.
  3898. Here are a few examples:
  3899. \"%s_archive::\"
  3900. If the current file is Projects.org, archive in file
  3901. Projects.org_archive, as top-level trees. This is the default.
  3902. \"::* Archived Tasks\"
  3903. Archive in the current file, under the top-level headline
  3904. \"* Archived Tasks\".
  3905. \"~/org/archive.org::\"
  3906. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3907. \"~/org/archive.org::* From %s\"
  3908. Archive in file ~/org/archive.org (absolute path), under headlines
  3909. \"From FILENAME\" where file name is the current file name.
  3910. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3911. The \"datetree/\" string is special, signifying to archive
  3912. items to the datetree. Items are placed in either the CLOSED
  3913. date of the item, or the current date if there is no CLOSED date.
  3914. The heading will be a subentry to the current date. There doesn't
  3915. need to be a heading, but there always needs to be a slash after
  3916. datetree. For example, to store archived items directly in the
  3917. datetree, use \"~/org/datetree.org::datetree/\".
  3918. \"basement::** Finished Tasks\"
  3919. Archive in file ./basement (relative path), as level 3 trees
  3920. below the level 2 heading \"** Finished Tasks\".
  3921. You may set this option on a per-file basis by adding to the buffer a
  3922. line like
  3923. #+ARCHIVE: basement::** Finished Tasks
  3924. You may also define it locally for a subtree by setting an ARCHIVE property
  3925. in the entry. If such a property is found in an entry, or anywhere up
  3926. the hierarchy, it will be used."
  3927. :group 'org-archive
  3928. :type 'string)
  3929. (defcustom org-agenda-skip-archived-trees t
  3930. "Non-nil means the agenda will skip any items located in archived trees.
  3931. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3932. variable is no longer recommended, you should leave it at the value t.
  3933. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3934. :group 'org-archive
  3935. :group 'org-agenda-skip
  3936. :type 'boolean)
  3937. (defcustom org-columns-skip-archived-trees t
  3938. "Non-nil means ignore archived trees when creating column view."
  3939. :group 'org-archive
  3940. :group 'org-properties
  3941. :type 'boolean)
  3942. (defcustom org-cycle-open-archived-trees nil
  3943. "Non-nil means `org-cycle' will open archived trees.
  3944. An archived tree is a tree marked with the tag ARCHIVE.
  3945. When nil, archived trees will stay folded. You can still open them with
  3946. normal outline commands like `show-all', but not with the cycling commands."
  3947. :group 'org-archive
  3948. :group 'org-cycle
  3949. :type 'boolean)
  3950. (defcustom org-sparse-tree-open-archived-trees nil
  3951. "Non-nil means sparse tree construction shows matches in archived trees.
  3952. When nil, matches in these trees are highlighted, but the trees are kept in
  3953. collapsed state."
  3954. :group 'org-archive
  3955. :group 'org-sparse-trees
  3956. :type 'boolean)
  3957. (defcustom org-sparse-tree-default-date-type nil
  3958. "The default date type when building a sparse tree.
  3959. When this is nil, a date is a scheduled or a deadline timestamp.
  3960. Otherwise, these types are allowed:
  3961. all: all timestamps
  3962. active: only active timestamps (<...>)
  3963. inactive: only inactive timestamps ([...])
  3964. scheduled: only scheduled timestamps
  3965. deadline: only deadline timestamps"
  3966. :type '(choice (const :tag "Scheduled or deadline" nil)
  3967. (const :tag "All timestamps" all)
  3968. (const :tag "Only active timestamps" active)
  3969. (const :tag "Only inactive timestamps" inactive)
  3970. (const :tag "Only scheduled timestamps" scheduled)
  3971. (const :tag "Only deadline timestamps" deadline)
  3972. (const :tag "Only closed timestamps" closed))
  3973. :version "26.1"
  3974. :package-version '(Org . "8.3")
  3975. :group 'org-sparse-trees)
  3976. (defun org-cycle-hide-archived-subtrees (state)
  3977. "Re-hide all archived subtrees after a visibility state change.
  3978. STATE should be one of the symbols listed in the docstring of
  3979. `org-cycle-hook'."
  3980. (when (and (not org-cycle-open-archived-trees)
  3981. (not (memq state '(overview folded))))
  3982. (save-excursion
  3983. (let* ((globalp (memq state '(contents all)))
  3984. (beg (if globalp (point-min) (point)))
  3985. (end (if globalp (point-max) (org-end-of-subtree t))))
  3986. (org-hide-archived-subtrees beg end)
  3987. (goto-char beg)
  3988. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3989. (message "%s" (substitute-command-keys
  3990. "Subtree is archived and stays closed. Use \
  3991. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3992. (defun org-force-cycle-archived ()
  3993. "Cycle subtree even if it is archived."
  3994. (interactive)
  3995. (setq this-command 'org-cycle)
  3996. (let ((org-cycle-open-archived-trees t))
  3997. (call-interactively 'org-cycle)))
  3998. (defun org-hide-archived-subtrees (beg end)
  3999. "Re-hide all archived subtrees after a visibility state change."
  4000. (org-with-wide-buffer
  4001. (let ((case-fold-search nil)
  4002. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4003. (goto-char beg)
  4004. ;; Include headline point is currently on.
  4005. (beginning-of-line)
  4006. (while (and (< (point) end) (re-search-forward re end t))
  4007. (when (member org-archive-tag (org-get-tags))
  4008. (org-flag-subtree t)
  4009. (org-end-of-subtree t))))))
  4010. (defun org-flag-subtree (flag)
  4011. (save-excursion
  4012. (org-back-to-heading t)
  4013. (org-flag-region (line-end-position)
  4014. (progn (org-end-of-subtree t) (point))
  4015. flag
  4016. 'outline)))
  4017. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4018. ;; Declare Column View Code
  4019. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4020. (declare-function org-columns-compute "org-colview" (property))
  4021. ;; Declare ID code
  4022. (declare-function org-id-store-link "org-id")
  4023. (declare-function org-id-locations-load "org-id")
  4024. (declare-function org-id-locations-save "org-id")
  4025. (defvar org-id-track-globally)
  4026. ;;; Variables for pre-computed regular expressions, all buffer local
  4027. (defvar-local org-todo-regexp nil
  4028. "Matches any of the TODO state keywords.
  4029. Since TODO keywords are case-sensitive, `case-fold-search' is
  4030. expected to be bound to nil when matching against this regexp.")
  4031. (defvar-local org-not-done-regexp nil
  4032. "Matches any of the TODO state keywords except the last one.
  4033. Since TODO keywords are case-sensitive, `case-fold-search' is
  4034. expected to be bound to nil when matching against this regexp.")
  4035. (defvar-local org-not-done-heading-regexp nil
  4036. "Matches a TODO headline that is not done.
  4037. Since TODO keywords are case-sensitive, `case-fold-search' is
  4038. expected to be bound to nil when matching against this regexp.")
  4039. (defvar-local org-todo-line-regexp nil
  4040. "Matches a headline and puts TODO state into group 2 if present.
  4041. Since TODO keywords are case-sensitive, `case-fold-search' is
  4042. expected to be bound to nil when matching against this regexp.")
  4043. (defvar-local org-complex-heading-regexp nil
  4044. "Matches a headline and puts everything into groups:
  4045. group 1: Stars
  4046. group 2: The TODO keyword, maybe
  4047. group 3: Priority cookie
  4048. group 4: True headline
  4049. group 5: Tags
  4050. Since TODO keywords are case-sensitive, `case-fold-search' is
  4051. expected to be bound to nil when matching against this regexp.")
  4052. (defvar-local org-complex-heading-regexp-format nil
  4053. "Printf format to make regexp to match an exact headline.
  4054. This regexp will match the headline of any node which has the
  4055. exact headline text that is put into the format, but may have any
  4056. TODO state, priority and tags.")
  4057. (defvar-local org-todo-line-tags-regexp nil
  4058. "Matches a headline and puts TODO state into group 2 if present.
  4059. Also put tags into group 4 if tags are present.")
  4060. (defconst org-plain-time-of-day-regexp
  4061. (concat
  4062. "\\(\\<[012]?[0-9]"
  4063. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4064. "\\(--?"
  4065. "\\(\\<[012]?[0-9]"
  4066. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4067. "\\)?")
  4068. "Regular expression to match a plain time or time range.
  4069. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4070. groups carry important information:
  4071. 0 the full match
  4072. 1 the first time, range or not
  4073. 8 the second time, if it is a range.")
  4074. (defconst org-plain-time-extension-regexp
  4075. (concat
  4076. "\\(\\<[012]?[0-9]"
  4077. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4078. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4079. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4080. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4081. groups carry important information:
  4082. 0 the full match
  4083. 7 hours of duration
  4084. 9 minutes of duration")
  4085. (defconst org-stamp-time-of-day-regexp
  4086. (concat
  4087. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4088. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4089. "\\(--?"
  4090. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4091. "Regular expression to match a timestamp time or time range.
  4092. After a match, the following groups carry important information:
  4093. 0 the full match
  4094. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4095. 2 the first time, range or not
  4096. 4 the second time, if it is a range.")
  4097. (defconst org-startup-options
  4098. '(("fold" org-startup-folded t)
  4099. ("overview" org-startup-folded t)
  4100. ("nofold" org-startup-folded nil)
  4101. ("showall" org-startup-folded nil)
  4102. ("showeverything" org-startup-folded showeverything)
  4103. ("content" org-startup-folded content)
  4104. ("indent" org-startup-indented t)
  4105. ("noindent" org-startup-indented nil)
  4106. ("hidestars" org-hide-leading-stars t)
  4107. ("showstars" org-hide-leading-stars nil)
  4108. ("odd" org-odd-levels-only t)
  4109. ("oddeven" org-odd-levels-only nil)
  4110. ("align" org-startup-align-all-tables t)
  4111. ("noalign" org-startup-align-all-tables nil)
  4112. ("shrink" org-startup-shrink-all-tables t)
  4113. ("inlineimages" org-startup-with-inline-images t)
  4114. ("noinlineimages" org-startup-with-inline-images nil)
  4115. ("latexpreview" org-startup-with-latex-preview t)
  4116. ("nolatexpreview" org-startup-with-latex-preview nil)
  4117. ("customtime" org-display-custom-times t)
  4118. ("logdone" org-log-done time)
  4119. ("lognotedone" org-log-done note)
  4120. ("nologdone" org-log-done nil)
  4121. ("lognoteclock-out" org-log-note-clock-out t)
  4122. ("nolognoteclock-out" org-log-note-clock-out nil)
  4123. ("logrepeat" org-log-repeat state)
  4124. ("lognoterepeat" org-log-repeat note)
  4125. ("logdrawer" org-log-into-drawer t)
  4126. ("nologdrawer" org-log-into-drawer nil)
  4127. ("logstatesreversed" org-log-states-order-reversed t)
  4128. ("nologstatesreversed" org-log-states-order-reversed nil)
  4129. ("nologrepeat" org-log-repeat nil)
  4130. ("logreschedule" org-log-reschedule time)
  4131. ("lognotereschedule" org-log-reschedule note)
  4132. ("nologreschedule" org-log-reschedule nil)
  4133. ("logredeadline" org-log-redeadline time)
  4134. ("lognoteredeadline" org-log-redeadline note)
  4135. ("nologredeadline" org-log-redeadline nil)
  4136. ("logrefile" org-log-refile time)
  4137. ("lognoterefile" org-log-refile note)
  4138. ("nologrefile" org-log-refile nil)
  4139. ("fninline" org-footnote-define-inline t)
  4140. ("nofninline" org-footnote-define-inline nil)
  4141. ("fnlocal" org-footnote-section nil)
  4142. ("fnauto" org-footnote-auto-label t)
  4143. ("fnprompt" org-footnote-auto-label nil)
  4144. ("fnconfirm" org-footnote-auto-label confirm)
  4145. ("fnplain" org-footnote-auto-label plain)
  4146. ("fnadjust" org-footnote-auto-adjust t)
  4147. ("nofnadjust" org-footnote-auto-adjust nil)
  4148. ("constcgs" constants-unit-system cgs)
  4149. ("constSI" constants-unit-system SI)
  4150. ("noptag" org-tag-persistent-alist nil)
  4151. ("hideblocks" org-hide-block-startup t)
  4152. ("nohideblocks" org-hide-block-startup nil)
  4153. ("beamer" org-startup-with-beamer-mode t)
  4154. ("entitiespretty" org-pretty-entities t)
  4155. ("entitiesplain" org-pretty-entities nil))
  4156. "Variable associated with STARTUP options for Org.
  4157. Each element is a list of three items: the startup options (as written
  4158. in the #+STARTUP line), the corresponding variable, and the value to set
  4159. this variable to if the option is found. An optional forth element PUSH
  4160. means to push this value onto the list in the variable.")
  4161. (defcustom org-group-tags t
  4162. "When non-nil (the default), use group tags.
  4163. This can be turned on/off through `org-toggle-tags-groups'."
  4164. :group 'org-tags
  4165. :group 'org-startup
  4166. :type 'boolean)
  4167. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4168. (defun org-toggle-tags-groups ()
  4169. "Toggle support for group tags.
  4170. Support for group tags is controlled by the option
  4171. `org-group-tags', which is non-nil by default."
  4172. (interactive)
  4173. (setq org-group-tags (not org-group-tags))
  4174. (cond ((and (derived-mode-p 'org-agenda-mode)
  4175. org-group-tags)
  4176. (org-agenda-redo))
  4177. ((derived-mode-p 'org-mode)
  4178. (let ((org-inhibit-startup t)) (org-mode))))
  4179. (message "Groups tags support has been turned %s"
  4180. (if org-group-tags "on" "off")))
  4181. (defun org-set-regexps-and-options (&optional tags-only)
  4182. "Precompute regular expressions used in the current buffer.
  4183. When optional argument TAGS-ONLY is non-nil, only compute tags
  4184. related expressions."
  4185. (when (derived-mode-p 'org-mode)
  4186. (let ((alist (org--setup-collect-keywords
  4187. (org-make-options-regexp
  4188. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4189. (and (not tags-only)
  4190. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4191. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4192. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4193. ;; Startup options. Get this early since it does change
  4194. ;; behavior for other options (e.g., tags).
  4195. (let ((startup (cdr (assq 'startup alist))))
  4196. (dolist (option startup)
  4197. (let ((entry (assoc-string option org-startup-options t)))
  4198. (when entry
  4199. (let ((var (nth 1 entry))
  4200. (val (nth 2 entry)))
  4201. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4202. (unless (listp (symbol-value var))
  4203. (set (make-local-variable var) nil))
  4204. (add-to-list var val)))))))
  4205. (setq-local org-file-tags
  4206. (mapcar #'org-add-prop-inherited
  4207. (cdr (assq 'filetags alist))))
  4208. (setq org-current-tag-alist
  4209. (append org-tag-persistent-alist
  4210. (let ((tags (cdr (assq 'tags alist))))
  4211. (if tags (org-tag-string-to-alist tags)
  4212. org-tag-alist))))
  4213. (setq org-tag-groups-alist
  4214. (org-tag-alist-to-groups org-current-tag-alist))
  4215. (unless tags-only
  4216. ;; File properties.
  4217. (setq-local org-file-properties (cdr (assq 'property alist)))
  4218. ;; Archive location.
  4219. (let ((archive (cdr (assq 'archive alist))))
  4220. (when archive (setq-local org-archive-location archive)))
  4221. ;; Category.
  4222. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4223. (when cat
  4224. (setq-local org-category (intern cat))
  4225. (setq-local org-file-properties
  4226. (org--update-property-plist
  4227. "CATEGORY" cat org-file-properties))))
  4228. ;; Columns.
  4229. (let ((column (cdr (assq 'columns alist))))
  4230. (when column (setq-local org-columns-default-format column)))
  4231. ;; Constants.
  4232. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4233. ;; Link abbreviations.
  4234. (let ((links (cdr (assq 'link alist))))
  4235. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4236. ;; Priorities.
  4237. (let ((priorities (cdr (assq 'priorities alist))))
  4238. (when priorities
  4239. (setq-local org-highest-priority (nth 0 priorities))
  4240. (setq-local org-lowest-priority (nth 1 priorities))
  4241. (setq-local org-default-priority (nth 2 priorities))))
  4242. ;; Scripts.
  4243. (let ((scripts (assq 'scripts alist)))
  4244. (when scripts
  4245. (setq-local org-use-sub-superscripts (cdr scripts))))
  4246. ;; TODO keywords.
  4247. (setq-local org-todo-kwd-alist nil)
  4248. (setq-local org-todo-key-alist nil)
  4249. (setq-local org-todo-key-trigger nil)
  4250. (setq-local org-todo-keywords-1 nil)
  4251. (setq-local org-done-keywords nil)
  4252. (setq-local org-todo-heads nil)
  4253. (setq-local org-todo-sets nil)
  4254. (setq-local org-todo-log-states nil)
  4255. (let ((todo-sequences
  4256. (or (nreverse (cdr (assq 'todo alist)))
  4257. (let ((d (default-value 'org-todo-keywords)))
  4258. (if (not (stringp (car d))) d
  4259. ;; XXX: Backward compatibility code.
  4260. (list (cons org-todo-interpretation d)))))))
  4261. (dolist (sequence todo-sequences)
  4262. (let* ((sequence (or (run-hook-with-args-until-success
  4263. 'org-todo-setup-filter-hook sequence)
  4264. sequence))
  4265. (sequence-type (car sequence))
  4266. (keywords (cdr sequence))
  4267. (sep (member "|" keywords))
  4268. names alist)
  4269. (dolist (k (remove "|" keywords))
  4270. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4271. k)
  4272. (error "Invalid TODO keyword %s" k))
  4273. (let ((name (match-string 1 k))
  4274. (key (match-string 2 k))
  4275. (log (org-extract-log-state-settings k)))
  4276. (push name names)
  4277. (push (cons name (and key (string-to-char key))) alist)
  4278. (when log (push log org-todo-log-states))))
  4279. (let* ((names (nreverse names))
  4280. (done (if sep (org-remove-keyword-keys (cdr sep))
  4281. (last names)))
  4282. (head (car names))
  4283. (tail (list sequence-type head (car done) (org-last done))))
  4284. (add-to-list 'org-todo-heads head 'append)
  4285. (push names org-todo-sets)
  4286. (setq org-done-keywords (append org-done-keywords done nil))
  4287. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4288. (setq org-todo-key-alist
  4289. (append org-todo-key-alist
  4290. (and alist
  4291. (append '((:startgroup))
  4292. (nreverse alist)
  4293. '((:endgroup))))))
  4294. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4295. (setq org-todo-sets (nreverse org-todo-sets)
  4296. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4297. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4298. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4299. ;; Compute the regular expressions and other local variables.
  4300. ;; Using `org-outline-regexp-bol' would complicate them much,
  4301. ;; because of the fixed white space at the end of that string.
  4302. (unless org-done-keywords
  4303. (setq org-done-keywords
  4304. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4305. (setq org-not-done-keywords
  4306. (org-delete-all org-done-keywords
  4307. (copy-sequence org-todo-keywords-1))
  4308. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4309. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4310. org-not-done-heading-regexp
  4311. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4312. org-todo-line-regexp
  4313. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4314. org-complex-heading-regexp
  4315. (concat "^\\(\\*+\\)"
  4316. "\\(?: +" org-todo-regexp "\\)?"
  4317. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4318. "\\(?: +\\(.*?\\)\\)??"
  4319. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4320. "[ \t]*$")
  4321. org-complex-heading-regexp-format
  4322. (concat "^\\(\\*+\\)"
  4323. "\\(?: +" org-todo-regexp "\\)?"
  4324. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4325. "\\(?: +"
  4326. ;; Stats cookies can be stuck to body.
  4327. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4328. "\\(%s\\)"
  4329. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4330. "\\)"
  4331. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4332. "[ \t]*$")
  4333. org-todo-line-tags-regexp
  4334. (concat "^\\(\\*+\\)"
  4335. "\\(?: +" org-todo-regexp "\\)?"
  4336. "\\(?: +\\(.*?\\)\\)??"
  4337. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4338. "[ \t]*$"))
  4339. (org-compute-latex-and-related-regexp)))))
  4340. (defun org--setup-collect-keywords (regexp &optional files alist)
  4341. "Return setup keywords values as an alist.
  4342. REGEXP matches a subset of setup keywords. FILES is a list of
  4343. file names already visited. It is used to avoid circular setup
  4344. files. ALIST, when non-nil, is the alist computed so far.
  4345. Return value contains the following keys: `archive', `category',
  4346. `columns', `constants', `filetags', `link', `priorities',
  4347. `property', `scripts', `startup', `tags' and `todo'."
  4348. (org-with-wide-buffer
  4349. (goto-char (point-min))
  4350. (let ((case-fold-search t))
  4351. (while (re-search-forward regexp nil t)
  4352. (let ((element (org-element-at-point)))
  4353. (when (eq (org-element-type element) 'keyword)
  4354. (let ((key (org-element-property :key element))
  4355. (value (org-element-property :value element)))
  4356. (cond
  4357. ((equal key "ARCHIVE")
  4358. (when (org-string-nw-p value)
  4359. (push (cons 'archive value) alist)))
  4360. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4361. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4362. ((equal key "CONSTANTS")
  4363. (let* ((constants (assq 'constants alist))
  4364. (store (cdr constants)))
  4365. (dolist (pair (split-string value))
  4366. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4367. pair)
  4368. (let* ((name (match-string 1 pair))
  4369. (value (match-string 2 pair))
  4370. (old (assoc name store)))
  4371. (if old (setcdr old value)
  4372. (push (cons name value) store)))))
  4373. (if constants (setcdr constants store)
  4374. (push (cons 'constants store) alist))))
  4375. ((equal key "FILETAGS")
  4376. (when (org-string-nw-p value)
  4377. (let ((old (assq 'filetags alist))
  4378. (new (apply #'nconc
  4379. (mapcar (lambda (x) (org-split-string x ":"))
  4380. (split-string value)))))
  4381. (if old (setcdr old (append new (cdr old)))
  4382. (push (cons 'filetags new) alist)))))
  4383. ((equal key "LINK")
  4384. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4385. (let ((links (assq 'link alist))
  4386. (pair (cons (match-string-no-properties 1 value)
  4387. (match-string-no-properties 2 value))))
  4388. (if links (push pair (cdr links))
  4389. (push (list 'link pair) alist)))))
  4390. ((equal key "OPTIONS")
  4391. (when (and (org-string-nw-p value)
  4392. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4393. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4394. ((equal key "PRIORITIES")
  4395. (push (cons 'priorities
  4396. (let ((prio (split-string value)))
  4397. (if (< (length prio) 3) '(?A ?C ?B)
  4398. (mapcar #'string-to-char prio))))
  4399. alist))
  4400. ((equal key "PROPERTY")
  4401. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4402. (let* ((property (assq 'property alist))
  4403. (value (org--update-property-plist
  4404. (match-string-no-properties 1 value)
  4405. (match-string-no-properties 2 value)
  4406. (cdr property))))
  4407. (if property (setcdr property value)
  4408. (push (cons 'property value) alist)))))
  4409. ((equal key "STARTUP")
  4410. (let ((startup (assq 'startup alist)))
  4411. (if startup
  4412. (setcdr startup
  4413. (append (cdr startup) (split-string value)))
  4414. (push (cons 'startup (split-string value)) alist))))
  4415. ((equal key "TAGS")
  4416. (let ((tag-cell (assq 'tags alist)))
  4417. (if tag-cell
  4418. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4419. (push (cons 'tags value) alist))))
  4420. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4421. (let ((todo (assq 'todo alist))
  4422. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4423. (split-string value))))
  4424. (if todo (push value (cdr todo))
  4425. (push (list 'todo value) alist))))
  4426. ((equal key "SETUPFILE")
  4427. (unless buffer-read-only ; Do not check in Gnus messages.
  4428. (let ((f (and (org-string-nw-p value)
  4429. (expand-file-name
  4430. (org-unbracket-string "\"" "\"" value)))))
  4431. (when (and f (file-readable-p f) (not (member f files)))
  4432. (with-temp-buffer
  4433. (setq default-directory (file-name-directory f))
  4434. (insert-file-contents f)
  4435. (setq alist
  4436. ;; Fake Org mode to benefit from cache
  4437. ;; without recurring needlessly.
  4438. (let ((major-mode 'org-mode))
  4439. (org--setup-collect-keywords
  4440. regexp (cons f files) alist)))))))))))))))
  4441. alist)
  4442. (defun org-tag-string-to-alist (s)
  4443. "Return tag alist associated to string S.
  4444. S is a value for TAGS keyword or produced with
  4445. `org-tag-alist-to-string'. Return value is an alist suitable for
  4446. `org-tag-alist' or `org-tag-persistent-alist'."
  4447. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4448. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4449. "\\|{.+?}\\)" ; regular expression
  4450. "\\(?:(\\(.\\))\\)?\\'"))
  4451. alist group-flag)
  4452. (dolist (tokens lines (cdr (nreverse alist)))
  4453. (push '(:newline) alist)
  4454. (while tokens
  4455. (let ((token (pop tokens)))
  4456. (pcase token
  4457. ("{"
  4458. (push '(:startgroup) alist)
  4459. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4460. ("}"
  4461. (push '(:endgroup) alist)
  4462. (setq group-flag nil))
  4463. ("["
  4464. (push '(:startgrouptag) alist)
  4465. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4466. ("]"
  4467. (push '(:endgrouptag) alist)
  4468. (setq group-flag nil))
  4469. (":"
  4470. (push '(:grouptags) alist))
  4471. ((guard (string-match tag-re token))
  4472. (let ((tag (match-string 1 token))
  4473. (key (and (match-beginning 2)
  4474. (string-to-char (match-string 2 token)))))
  4475. ;; Push all tags in groups, no matter if they already
  4476. ;; appear somewhere else in the list.
  4477. (when (or group-flag (not (assoc tag alist)))
  4478. (push (cons tag key) alist))))))))))
  4479. (defun org-tag-alist-to-string (alist &optional skip-key)
  4480. "Return tag string associated to ALIST.
  4481. ALIST is an alist, as defined in `org-tag-alist' or
  4482. `org-tag-persistent-alist', or produced with
  4483. `org-tag-string-to-alist'.
  4484. Return value is a string suitable as a value for \"TAGS\"
  4485. keyword.
  4486. When optional argument SKIP-KEY is non-nil, skip selection keys
  4487. next to tags."
  4488. (mapconcat (lambda (token)
  4489. (pcase token
  4490. (`(:startgroup) "{")
  4491. (`(:endgroup) "}")
  4492. (`(:startgrouptag) "[")
  4493. (`(:endgrouptag) "]")
  4494. (`(:grouptags) ":")
  4495. (`(:newline) "\\n")
  4496. ((and
  4497. (guard (not skip-key))
  4498. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4499. (format "%s(%c)" tag key))
  4500. (`(,(and tag (pred stringp)) . ,_) tag)
  4501. (_ (user-error "Invalid tag token: %S" token))))
  4502. alist
  4503. " "))
  4504. (defun org-tag-alist-to-groups (alist)
  4505. "Return group alist from tag ALIST.
  4506. ALIST is an alist, as defined in `org-tag-alist' or
  4507. `org-tag-persistent-alist', or produced with
  4508. `org-tag-string-to-alist'. Return value is an alist following
  4509. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4510. a string, summarizing TAGS, as a list of strings."
  4511. (let (groups group-status current-group)
  4512. (dolist (token alist (nreverse groups))
  4513. (pcase token
  4514. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4515. (`(,(or :endgroup :endgrouptag))
  4516. (when (eq group-status 'append)
  4517. (push (nreverse current-group) groups))
  4518. (setq group-status nil))
  4519. (`(:grouptags) (setq group-status 'append))
  4520. ((and `(,tag . ,_) (guard group-status))
  4521. (if (eq group-status 'append) (push tag current-group)
  4522. (setq current-group (list tag))))
  4523. (_ nil)))))
  4524. (defvar org--file-cache (make-hash-table :test #'equal)
  4525. "Hash table to store contents of files referenced via a URL.
  4526. This is the cache of file URLs read using `org-file-contents'.")
  4527. (defun org-reset-file-cache ()
  4528. "Reset the cache of files downloaded by `org-file-contents'."
  4529. (clrhash org--file-cache))
  4530. (defun org-file-url-p (file)
  4531. "Non-nil if FILE is a URL."
  4532. (require 'ffap)
  4533. (string-match-p ffap-url-regexp file))
  4534. (defun org-file-contents (file &optional noerror nocache)
  4535. "Return the contents of FILE, as a string.
  4536. FILE can be a file name or URL.
  4537. If FILE is a URL, download the contents. If the URL contents are
  4538. already cached in the `org--file-cache' hash table, the download step
  4539. is skipped.
  4540. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4541. from file or URL.
  4542. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4543. is available. This option applies only if FILE is a URL."
  4544. (let* ((is-url (org-file-url-p file))
  4545. (cache (and is-url
  4546. (not nocache)
  4547. (gethash file org--file-cache))))
  4548. (cond
  4549. (cache)
  4550. (is-url
  4551. (with-current-buffer (url-retrieve-synchronously file)
  4552. (goto-char (point-min))
  4553. ;; Move point to after the url-retrieve header.
  4554. (search-forward "\n\n" nil :move)
  4555. ;; Search for the success code only in the url-retrieve header.
  4556. (if (save-excursion
  4557. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4558. ;; Update the cache `org--file-cache' and return contents.
  4559. (puthash file
  4560. (buffer-substring-no-properties (point) (point-max))
  4561. org--file-cache)
  4562. (funcall (if noerror #'message #'user-error)
  4563. "Unable to fetch file from %S"
  4564. file))))
  4565. (t
  4566. (with-temp-buffer
  4567. (condition-case nil
  4568. (progn
  4569. (insert-file-contents file)
  4570. (buffer-string))
  4571. (file-error
  4572. (funcall (if noerror #'message #'user-error)
  4573. "Unable to read file %S"
  4574. file))))))))
  4575. (defun org-extract-log-state-settings (x)
  4576. "Extract the log state setting from a TODO keyword string.
  4577. This will extract info from a string like \"WAIT(w@/!)\"."
  4578. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4579. (let ((kw (match-string 1 x))
  4580. (log1 (and (match-end 3) (match-string 3 x)))
  4581. (log2 (and (match-end 4) (match-string 4 x))))
  4582. (and (or log1 log2)
  4583. (list kw
  4584. (and log1 (if (equal log1 "!") 'time 'note))
  4585. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4586. (defun org-remove-keyword-keys (list)
  4587. "Remove a pair of parenthesis at the end of each string in LIST."
  4588. (mapcar (lambda (x)
  4589. (if (string-match "(.*)$" x)
  4590. (substring x 0 (match-beginning 0))
  4591. x))
  4592. list))
  4593. (defun org-assign-fast-keys (alist)
  4594. "Assign fast keys to a keyword-key alist.
  4595. Respect keys that are already there."
  4596. (let (new e (alt ?0))
  4597. (while (setq e (pop alist))
  4598. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4599. (cdr e)) ;; Key already assigned.
  4600. (push e new)
  4601. (let ((clist (string-to-list (downcase (car e))))
  4602. (used (append new alist)))
  4603. (when (= (car clist) ?@)
  4604. (pop clist))
  4605. (while (and clist (rassoc (car clist) used))
  4606. (pop clist))
  4607. (unless clist
  4608. (while (rassoc alt used)
  4609. (cl-incf alt)))
  4610. (push (cons (car e) (or (car clist) alt)) new))))
  4611. (nreverse new)))
  4612. ;;; Some variables used in various places
  4613. (defvar org-window-configuration nil
  4614. "Used in various places to store a window configuration.")
  4615. (defvar org-selected-window nil
  4616. "Used in various places to store a window configuration.")
  4617. (defvar org-finish-function nil
  4618. "Function to be called when `C-c C-c' is used.
  4619. This is for getting out of special buffers like capture.")
  4620. (defvar org-last-state)
  4621. ;; Defined somewhere in this file, but used before definition.
  4622. (defvar org-entities) ;; defined in org-entities.el
  4623. (defvar org-struct-menu)
  4624. (defvar org-org-menu)
  4625. (defvar org-tbl-menu)
  4626. ;;;; Define the Org mode
  4627. ;; We use a before-change function to check if a table might need
  4628. ;; an update.
  4629. (defvar org-table-may-need-update t
  4630. "Indicates that a table might need an update.
  4631. This variable is set by `org-before-change-function'.
  4632. `org-table-align' sets it back to nil.")
  4633. (defun org-before-change-function (_beg _end)
  4634. "Every change indicates that a table might need an update."
  4635. (setq org-table-may-need-update t))
  4636. (defvar org-mode-map)
  4637. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4638. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4639. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4640. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4641. (defvar org-table-buffer-is-an nil)
  4642. (defvar bidi-paragraph-direction)
  4643. (defvar buffer-face-mode-face)
  4644. (require 'outline)
  4645. ;; Other stuff we need.
  4646. (require 'time-date)
  4647. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4648. (require 'easymenu)
  4649. (autoload 'easy-menu-add "easymenu")
  4650. (require 'overlay)
  4651. ;; (require 'org-macs) moved higher up in the file before it is first used
  4652. (require 'org-entities)
  4653. ;; (require 'org-compat) moved higher up in the file before it is first used
  4654. (require 'org-faces)
  4655. (require 'org-list)
  4656. (require 'org-pcomplete)
  4657. (require 'org-src)
  4658. (require 'org-footnote)
  4659. (require 'org-macro)
  4660. ;; babel
  4661. (require 'ob)
  4662. ;;;###autoload
  4663. (define-derived-mode org-mode outline-mode "Org"
  4664. "Outline-based notes management and organizer, alias
  4665. \"Carsten's outline-mode for keeping track of everything.\"
  4666. Org mode develops organizational tasks around a NOTES file which
  4667. contains information about projects as plain text. Org mode is
  4668. implemented on top of Outline mode, which is ideal to keep the content
  4669. of large files well structured. It supports ToDo items, deadlines and
  4670. time stamps, which magically appear in the diary listing of the Emacs
  4671. calendar. Tables are easily created with a built-in table editor.
  4672. Plain text URL-like links connect to websites, emails (VM), Usenet
  4673. messages (Gnus), BBDB entries, and any files related to the project.
  4674. For printing and sharing of notes, an Org file (or a part of it)
  4675. can be exported as a structured ASCII or HTML file.
  4676. The following commands are available:
  4677. \\{org-mode-map}"
  4678. ;; Get rid of Outline menus, they are not needed
  4679. ;; Need to do this here because define-derived-mode sets up
  4680. ;; the keymap so late. Still, it is a waste to call this each time
  4681. ;; we switch another buffer into Org mode.
  4682. (define-key org-mode-map [menu-bar headings] 'undefined)
  4683. (define-key org-mode-map [menu-bar hide] 'undefined)
  4684. (define-key org-mode-map [menu-bar show] 'undefined)
  4685. (org-load-modules-maybe)
  4686. (org-install-agenda-files-menu)
  4687. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4688. (add-to-invisibility-spec '(org-hide-block . t))
  4689. (add-to-invisibility-spec '(org-hide-drawer . t))
  4690. (setq-local outline-regexp org-outline-regexp)
  4691. (setq-local outline-level 'org-outline-level)
  4692. (setq bidi-paragraph-direction 'left-to-right)
  4693. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4694. (unless org-display-table
  4695. (setq org-display-table (make-display-table)))
  4696. (set-display-table-slot
  4697. org-display-table 4
  4698. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4699. org-ellipsis)))
  4700. (setq buffer-display-table org-display-table))
  4701. (org-set-regexps-and-options)
  4702. (org-set-font-lock-defaults)
  4703. (when (and org-tag-faces (not org-tags-special-faces-re))
  4704. ;; tag faces set outside customize.... force initialization.
  4705. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4706. ;; Calc embedded
  4707. (setq-local calc-embedded-open-mode "# ")
  4708. ;; Modify a few syntax entries
  4709. (modify-syntax-entry ?@ "w")
  4710. (modify-syntax-entry ?\" "\"")
  4711. (modify-syntax-entry ?\\ "_")
  4712. (modify-syntax-entry ?~ "_")
  4713. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4714. ;; Activate before-change-function
  4715. (setq-local org-table-may-need-update t)
  4716. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4717. ;; Check for running clock before killing a buffer
  4718. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4719. ;; Initialize macros templates.
  4720. (org-macro-initialize-templates)
  4721. ;; Initialize radio targets.
  4722. (org-update-radio-target-regexp)
  4723. ;; Indentation.
  4724. (setq-local indent-line-function 'org-indent-line)
  4725. (setq-local indent-region-function 'org-indent-region)
  4726. ;; Filling and auto-filling.
  4727. (org-setup-filling)
  4728. ;; Comments.
  4729. (org-setup-comments-handling)
  4730. ;; Initialize cache.
  4731. (org-element-cache-reset)
  4732. ;; Beginning/end of defun
  4733. (setq-local beginning-of-defun-function 'org-backward-element)
  4734. (setq-local end-of-defun-function
  4735. (lambda ()
  4736. (if (not (org-at-heading-p))
  4737. (org-forward-element)
  4738. (org-forward-element)
  4739. (forward-char -1))))
  4740. ;; Next error for sparse trees
  4741. (setq-local next-error-function 'org-occur-next-match)
  4742. ;; Make sure dependence stuff works reliably, even for users who set it
  4743. ;; too late :-(
  4744. (if org-enforce-todo-dependencies
  4745. (add-hook 'org-blocker-hook
  4746. 'org-block-todo-from-children-or-siblings-or-parent)
  4747. (remove-hook 'org-blocker-hook
  4748. 'org-block-todo-from-children-or-siblings-or-parent))
  4749. (if org-enforce-todo-checkbox-dependencies
  4750. (add-hook 'org-blocker-hook
  4751. 'org-block-todo-from-checkboxes)
  4752. (remove-hook 'org-blocker-hook
  4753. 'org-block-todo-from-checkboxes))
  4754. ;; Align options lines
  4755. (setq-local
  4756. align-mode-rules-list
  4757. '((org-in-buffer-settings
  4758. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4759. (modes . '(org-mode)))))
  4760. ;; Imenu
  4761. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4762. ;; Make isearch reveal context
  4763. (setq-local outline-isearch-open-invisible-function
  4764. (lambda (&rest _) (org-show-context 'isearch)))
  4765. ;; Setup the pcomplete hooks
  4766. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4767. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4768. (setq-local pcomplete-default-completion-function 'ignore)
  4769. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4770. (setq-local pcomplete-termination-string "")
  4771. (setq-local buffer-face-mode-face 'org-default)
  4772. ;; If empty file that did not turn on Org mode automatically, make
  4773. ;; it to.
  4774. (when (and org-insert-mode-line-in-empty-file
  4775. (called-interactively-p 'any)
  4776. (= (point-min) (point-max)))
  4777. (insert "# -*- mode: org -*-\n\n"))
  4778. (unless org-inhibit-startup
  4779. (org-unmodified
  4780. (when org-startup-with-beamer-mode (org-beamer-mode))
  4781. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4782. (org-table-map-tables
  4783. (cond ((and org-startup-align-all-tables
  4784. org-startup-shrink-all-tables)
  4785. (lambda () (org-table-align) (org-table-shrink)))
  4786. (org-startup-align-all-tables #'org-table-align)
  4787. (t #'org-table-shrink))
  4788. t))
  4789. (when org-startup-with-inline-images (org-display-inline-images))
  4790. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4791. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4792. (when org-startup-truncated (setq truncate-lines t))
  4793. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4794. (org-refresh-effort-properties)))
  4795. ;; Try to set `org-hide' face correctly.
  4796. (let ((foreground (org-find-invisible-foreground)))
  4797. (when foreground
  4798. (set-face-foreground 'org-hide foreground))))
  4799. ;; Update `customize-package-emacs-version-alist'
  4800. (add-to-list 'customize-package-emacs-version-alist
  4801. '(Org ("8.0" . "24.4")
  4802. ("8.1" . "24.4")
  4803. ("8.2" . "24.4")
  4804. ("8.2.7" . "24.4")
  4805. ("8.3" . "26.1")
  4806. ("9.0" . "26.1")
  4807. ("9.1" . "26.1")
  4808. ("9.2" . "27.1")))
  4809. (defvar org-mode-transpose-word-syntax-table
  4810. (let ((st (make-syntax-table text-mode-syntax-table)))
  4811. (dolist (c org-emphasis-alist st)
  4812. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4813. (when (fboundp 'abbrev-table-put)
  4814. (abbrev-table-put org-mode-abbrev-table
  4815. :parents (list text-mode-abbrev-table)))
  4816. (defun org-find-invisible-foreground ()
  4817. (let ((candidates (remove
  4818. "unspecified-bg"
  4819. (nconc
  4820. (list (face-background 'default)
  4821. (face-background 'org-default))
  4822. (mapcar
  4823. (lambda (alist)
  4824. (when (boundp alist)
  4825. (cdr (assq 'background-color (symbol-value alist)))))
  4826. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4827. (list (face-foreground 'org-hide))))))
  4828. (car (remove nil candidates))))
  4829. (defun org-current-time (&optional rounding-minutes past)
  4830. "Current time, possibly rounded to ROUNDING-MINUTES.
  4831. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4832. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4833. the rounding returns a past time."
  4834. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4835. (car org-time-stamp-rounding-minutes)))
  4836. (time (decode-time)) res)
  4837. (if (< r 1)
  4838. (current-time)
  4839. (setq res
  4840. (apply 'encode-time
  4841. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4842. (nthcdr 2 time))))
  4843. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4844. (seconds-to-time (- (float-time res) (* r 60)))
  4845. res))))
  4846. (defun org-today ()
  4847. "Return today date, considering `org-extend-today-until'."
  4848. (time-to-days
  4849. (time-subtract (current-time)
  4850. (list 0 (* 3600 org-extend-today-until) 0))))
  4851. ;;;; Font-Lock stuff, including the activators
  4852. (defvar org-mouse-map (make-sparse-keymap))
  4853. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4854. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4855. (when org-mouse-1-follows-link
  4856. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4857. (when org-tab-follows-link
  4858. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4859. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4860. (require 'font-lock)
  4861. (defconst org-non-link-chars "]\t\n\r<>")
  4862. (defvar org-link-types-re nil
  4863. "Matches a link that has a url-like prefix like \"http:\"")
  4864. (defvar org-link-re-with-space nil
  4865. "Matches a link with spaces, optional angular brackets around it.")
  4866. (defvar org-link-re-with-space2 nil
  4867. "Matches a link with spaces, optional angular brackets around it.")
  4868. (defvar org-link-re-with-space3 nil
  4869. "Matches a link with spaces, only for internal part in bracket links.")
  4870. (defvar org-angle-link-re nil
  4871. "Matches link with angular brackets, spaces are allowed.")
  4872. (defvar org-plain-link-re nil
  4873. "Matches plain link, without spaces.")
  4874. (defvar org-bracket-link-regexp nil
  4875. "Matches a link in double brackets.")
  4876. (defvar org-bracket-link-analytic-regexp nil
  4877. "Regular expression used to analyze links.
  4878. Here is what the match groups contain after a match:
  4879. 1: http:
  4880. 2: http
  4881. 3: path
  4882. 4: [desc]
  4883. 5: desc")
  4884. (defvar org-bracket-link-analytic-regexp++ nil
  4885. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4886. (defvar org-any-link-re nil
  4887. "Regular expression matching any link.")
  4888. (defconst org-match-sexp-depth 3
  4889. "Number of stacked braces for sub/superscript matching.")
  4890. (defun org-create-multibrace-regexp (left right n)
  4891. "Create a regular expression which will match a balanced sexp.
  4892. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4893. as single character strings.
  4894. The regexp returned will match the entire expression including the
  4895. delimiters. It will also define a single group which contains the
  4896. match except for the outermost delimiters. The maximum depth of
  4897. stacked delimiters is N. Escaping delimiters is not possible."
  4898. (let* ((nothing (concat "[^" left right "]*?"))
  4899. (or "\\|")
  4900. (re nothing)
  4901. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4902. (while (> n 1)
  4903. (setq n (1- n)
  4904. re (concat re or next)
  4905. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4906. (concat left "\\(" re "\\)" right)))
  4907. (defconst org-match-substring-regexp
  4908. (concat
  4909. "\\(\\S-\\)\\([_^]\\)\\("
  4910. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4911. "\\|"
  4912. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4913. "\\|"
  4914. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4915. "The regular expression matching a sub- or superscript.")
  4916. (defconst org-match-substring-with-braces-regexp
  4917. (concat
  4918. "\\(\\S-\\)\\([_^]\\)"
  4919. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4920. "The regular expression matching a sub- or superscript, forcing braces.")
  4921. (defun org-make-link-regexps ()
  4922. "Update the link regular expressions.
  4923. This should be called after the variable `org-link-parameters' has changed."
  4924. (let ((types-re (regexp-opt (org-link-types) t)))
  4925. (setq org-link-types-re
  4926. (concat "\\`" types-re ":")
  4927. org-link-re-with-space
  4928. (concat "<?" types-re ":"
  4929. "\\([^" org-non-link-chars " ]"
  4930. "[^" org-non-link-chars "]*"
  4931. "[^" org-non-link-chars " ]\\)>?")
  4932. org-link-re-with-space2
  4933. (concat "<?" types-re ":"
  4934. "\\([^" org-non-link-chars " ]"
  4935. "[^\t\n\r]*"
  4936. "[^" org-non-link-chars " ]\\)>?")
  4937. org-link-re-with-space3
  4938. (concat "<?" types-re ":"
  4939. "\\([^" org-non-link-chars " ]"
  4940. "[^\t\n\r]*\\)")
  4941. org-angle-link-re
  4942. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4943. types-re)
  4944. org-plain-link-re
  4945. (concat
  4946. "\\<" types-re ":"
  4947. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4948. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4949. org-bracket-link-regexp
  4950. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4951. org-bracket-link-analytic-regexp
  4952. (concat
  4953. "\\[\\["
  4954. "\\(" types-re ":\\)?"
  4955. "\\([^]]+\\)"
  4956. "\\]"
  4957. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4958. "\\]")
  4959. org-bracket-link-analytic-regexp++
  4960. (concat
  4961. "\\[\\["
  4962. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4963. "\\([^]]+\\)"
  4964. "\\]"
  4965. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4966. "\\]")
  4967. org-any-link-re
  4968. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4969. org-angle-link-re "\\)\\|\\("
  4970. org-plain-link-re "\\)"))))
  4971. (org-make-link-regexps)
  4972. (defvar org-emph-face nil)
  4973. (defun org-do-emphasis-faces (limit)
  4974. "Run through the buffer and emphasize strings."
  4975. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4976. (car org-emphasis-regexp-components))))
  4977. (catch :exit
  4978. (while (re-search-forward quick-re limit t)
  4979. (let* ((marker (match-string 2))
  4980. (verbatim? (member marker '("~" "="))))
  4981. (when (save-excursion
  4982. (goto-char (match-beginning 0))
  4983. (and
  4984. ;; Do not match table hlines.
  4985. (not (and (equal marker "+")
  4986. (org-match-line
  4987. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4988. ;; Do not match headline stars. Do not consider
  4989. ;; stars of a headline as closing marker for bold
  4990. ;; markup either.
  4991. (not (and (equal marker "*")
  4992. (save-excursion
  4993. (forward-char)
  4994. (skip-chars-backward "*")
  4995. (looking-at-p org-outline-regexp-bol))))
  4996. ;; Match full emphasis markup regexp.
  4997. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4998. ;; Do not span over paragraph boundaries.
  4999. (not (string-match-p org-element-paragraph-separate
  5000. (match-string 2)))
  5001. ;; Do not span over cells in table rows.
  5002. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5003. (string-match-p "|" (match-string 4))))))
  5004. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5005. (font-lock-prepend-text-property
  5006. (match-beginning 2) (match-end 2) 'face face)
  5007. (when verbatim?
  5008. (org-remove-flyspell-overlays-in
  5009. (match-beginning 0) (match-end 0)))
  5010. (add-text-properties (match-beginning 2) (match-end 2)
  5011. '(font-lock-multiline t org-emphasis t))
  5012. (when org-hide-emphasis-markers
  5013. (add-text-properties (match-end 4) (match-beginning 5)
  5014. '(invisible org-link))
  5015. (add-text-properties (match-beginning 3) (match-end 3)
  5016. '(invisible org-link)))
  5017. (throw :exit t))))))))
  5018. (defun org-emphasize (&optional char)
  5019. "Insert or change an emphasis, i.e. a font like bold or italic.
  5020. If there is an active region, change that region to a new emphasis.
  5021. If there is no region, just insert the marker characters and position
  5022. the cursor between them.
  5023. CHAR should be the marker character. If it is a space, it means to
  5024. remove the emphasis of the selected region.
  5025. If CHAR is not given (for example in an interactive call) it will be
  5026. prompted for."
  5027. (interactive)
  5028. (let ((erc org-emphasis-regexp-components)
  5029. (string "") beg end move s)
  5030. (if (org-region-active-p)
  5031. (setq beg (region-beginning)
  5032. end (region-end)
  5033. string (buffer-substring beg end))
  5034. (setq move t))
  5035. (unless char
  5036. (message "Emphasis marker or tag: [%s]"
  5037. (mapconcat #'car org-emphasis-alist ""))
  5038. (setq char (read-char-exclusive)))
  5039. (if (equal char ?\s)
  5040. (setq s ""
  5041. move nil)
  5042. (unless (assoc (char-to-string char) org-emphasis-alist)
  5043. (user-error "No such emphasis marker: \"%c\"" char))
  5044. (setq s (char-to-string char)))
  5045. (while (and (> (length string) 1)
  5046. (equal (substring string 0 1) (substring string -1))
  5047. (assoc (substring string 0 1) org-emphasis-alist))
  5048. (setq string (substring string 1 -1)))
  5049. (setq string (concat s string s))
  5050. (when beg (delete-region beg end))
  5051. (unless (or (bolp)
  5052. (string-match (concat "[" (nth 0 erc) "\n]")
  5053. (char-to-string (char-before (point)))))
  5054. (insert " "))
  5055. (unless (or (eobp)
  5056. (string-match (concat "[" (nth 1 erc) "\n]")
  5057. (char-to-string (char-after (point)))))
  5058. (insert " ") (backward-char 1))
  5059. (insert string)
  5060. (and move (backward-char 1))))
  5061. (defconst org-nonsticky-props
  5062. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5063. (defsubst org-rear-nonsticky-at (pos)
  5064. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5065. (defun org-activate-links (limit)
  5066. "Add link properties to links.
  5067. This includes angle, plain, and bracket links."
  5068. (catch :exit
  5069. (while (re-search-forward org-any-link-re limit t)
  5070. (let* ((start (match-beginning 0))
  5071. (end (match-end 0))
  5072. (style (cond ((eq ?< (char-after start)) 'angle)
  5073. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5074. (t 'plain))))
  5075. (when (and (memq style org-highlight-links)
  5076. ;; Do not confuse plain links with tags.
  5077. (not (and (eq style 'plain)
  5078. (let ((face (get-text-property
  5079. (max (1- start) (point-min)) 'face)))
  5080. (if (consp face) (memq 'org-tag face)
  5081. (eq 'org-tag face))))))
  5082. (let* ((link-object (save-excursion
  5083. (goto-char start)
  5084. (save-match-data (org-element-link-parser))))
  5085. (link (org-element-property :raw-link link-object))
  5086. (type (org-element-property :type link-object))
  5087. (path (org-element-property :path link-object))
  5088. (properties ;for link's visible part
  5089. (list
  5090. 'face (pcase (org-link-get-parameter type :face)
  5091. ((and (pred functionp) face) (funcall face path))
  5092. ((and (pred facep) face) face)
  5093. ((and (pred consp) face) face) ;anonymous
  5094. (_ 'org-link))
  5095. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5096. 'highlight)
  5097. 'keymap (or (org-link-get-parameter type :keymap)
  5098. org-mouse-map)
  5099. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5100. ((and (pred stringp) echo) echo)
  5101. ((and (pred functionp) echo) echo)
  5102. (_ (concat "LINK: " link)))
  5103. 'htmlize-link (pcase (org-link-get-parameter type
  5104. :htmlize-link)
  5105. ((and (pred functionp) f) (funcall f))
  5106. (_ `(:uri ,link)))
  5107. 'font-lock-multiline t)))
  5108. (org-remove-flyspell-overlays-in start end)
  5109. (org-rear-nonsticky-at end)
  5110. (if (not (eq 'bracket style))
  5111. (add-text-properties start end properties)
  5112. ;; Handle invisible parts in bracket links.
  5113. (remove-text-properties start end '(invisible nil))
  5114. (let ((hidden
  5115. (append `(invisible
  5116. ,(or (org-link-get-parameter type :display)
  5117. 'org-link))
  5118. properties))
  5119. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5120. (visible-end (or (match-end 4) (match-end 2))))
  5121. (add-text-properties start visible-start hidden)
  5122. (add-text-properties visible-start visible-end properties)
  5123. (add-text-properties visible-end end hidden)
  5124. (org-rear-nonsticky-at visible-start)
  5125. (org-rear-nonsticky-at visible-end)))
  5126. (let ((f (org-link-get-parameter type :activate-func)))
  5127. (when (functionp f)
  5128. (funcall f start end path (eq style 'bracket))))
  5129. (throw :exit t))))) ;signal success
  5130. nil))
  5131. (defun org-activate-code (limit)
  5132. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5133. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5134. (remove-text-properties (match-beginning 0) (match-end 0)
  5135. '(display t invisible t intangible t))
  5136. t))
  5137. (defcustom org-src-fontify-natively t
  5138. "When non-nil, fontify code in code blocks.
  5139. See also the `org-block' face."
  5140. :type 'boolean
  5141. :version "26.1"
  5142. :package-version '(Org . "8.3")
  5143. :group 'org-appearance
  5144. :group 'org-babel)
  5145. (defcustom org-allow-promoting-top-level-subtree nil
  5146. "When non-nil, allow promoting a top level subtree.
  5147. The leading star of the top level headline will be replaced
  5148. by a #."
  5149. :type 'boolean
  5150. :version "24.1"
  5151. :group 'org-appearance)
  5152. (defun org-fontify-meta-lines-and-blocks (limit)
  5153. (condition-case nil
  5154. (org-fontify-meta-lines-and-blocks-1 limit)
  5155. (error (message "Org mode fontification error in %S at %d"
  5156. (current-buffer)
  5157. (line-number-at-pos)))))
  5158. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5159. "Fontify #+ lines and blocks."
  5160. (let ((case-fold-search t))
  5161. (when (re-search-forward
  5162. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5163. limit t)
  5164. (let ((beg (match-beginning 0))
  5165. (block-start (match-end 0))
  5166. (block-end nil)
  5167. (lang (match-string 7))
  5168. (beg1 (line-beginning-position 2))
  5169. (dc1 (downcase (match-string 2)))
  5170. (dc3 (downcase (match-string 3)))
  5171. end end1 quoting block-type)
  5172. (cond
  5173. ((and (match-end 4) (equal dc3 "+begin"))
  5174. ;; Truly a block
  5175. (setq block-type (downcase (match-string 5))
  5176. quoting (member block-type org-protecting-blocks))
  5177. (when (re-search-forward
  5178. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5179. nil t) ;; on purpose, we look further than LIMIT
  5180. (setq end (min (point-max) (match-end 0))
  5181. end1 (min (point-max) (1- (match-beginning 0))))
  5182. (setq block-end (match-beginning 0))
  5183. (when quoting
  5184. (org-remove-flyspell-overlays-in beg1 end1)
  5185. (remove-text-properties beg end
  5186. '(display t invisible t intangible t)))
  5187. (add-text-properties
  5188. beg end '(font-lock-fontified t font-lock-multiline t))
  5189. (add-text-properties beg beg1 '(face org-meta-line))
  5190. (org-remove-flyspell-overlays-in beg beg1)
  5191. (add-text-properties ; For end_src
  5192. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5193. (org-remove-flyspell-overlays-in end1 end)
  5194. (cond
  5195. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5196. (org-src-font-lock-fontify-block lang block-start block-end)
  5197. (add-text-properties beg1 block-end '(src-block t)))
  5198. (quoting
  5199. (add-text-properties beg1 (min (point-max) (1+ end1))
  5200. (list 'face
  5201. (list :inherit
  5202. (let ((face-name
  5203. (intern (format "org-block-%s" lang))))
  5204. (append (and (facep face-name) (list face-name))
  5205. '(org-block))))))) ; end of source block
  5206. ((not org-fontify-quote-and-verse-blocks))
  5207. ((string= block-type "quote")
  5208. (add-face-text-property
  5209. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5210. ((string= block-type "verse")
  5211. (add-face-text-property
  5212. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5213. (add-text-properties beg beg1 '(face org-block-begin-line))
  5214. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5215. '(face org-block-end-line))
  5216. t))
  5217. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5218. (org-remove-flyspell-overlays-in
  5219. (match-beginning 0)
  5220. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5221. (add-text-properties
  5222. beg (match-end 3)
  5223. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5224. '(font-lock-fontified t invisible t)
  5225. '(font-lock-fontified t face org-document-info-keyword)))
  5226. (add-text-properties
  5227. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5228. (if (string-equal dc1 "+title:")
  5229. '(font-lock-fontified t face org-document-title)
  5230. '(font-lock-fontified t face org-document-info))))
  5231. ((string-prefix-p "+caption" dc1)
  5232. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5233. (remove-text-properties (match-beginning 0) (match-end 0)
  5234. '(display t invisible t intangible t))
  5235. ;; Handle short captions.
  5236. (save-excursion
  5237. (beginning-of-line)
  5238. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5239. (add-text-properties (line-beginning-position) (match-end 1)
  5240. '(font-lock-fontified t face org-meta-line))
  5241. (add-text-properties (match-end 0) (line-end-position)
  5242. '(font-lock-fontified t face org-block))
  5243. t)
  5244. ((member dc3 '(" " ""))
  5245. (org-remove-flyspell-overlays-in beg (match-end 0))
  5246. (add-text-properties
  5247. beg (match-end 0)
  5248. '(font-lock-fontified t face font-lock-comment-face)))
  5249. (t ;; just any other in-buffer setting, but not indented
  5250. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5251. (remove-text-properties (match-beginning 0) (match-end 0)
  5252. '(display t invisible t intangible t))
  5253. (add-text-properties beg (match-end 0)
  5254. '(font-lock-fontified t face org-meta-line))
  5255. t))))))
  5256. (defun org-fontify-drawers (limit)
  5257. "Fontify drawers."
  5258. (when (re-search-forward org-drawer-regexp limit t)
  5259. (add-text-properties
  5260. (match-beginning 0) (match-end 0)
  5261. '(font-lock-fontified t face org-special-keyword))
  5262. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5263. t))
  5264. (defun org-fontify-macros (limit)
  5265. "Fontify macros."
  5266. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5267. (add-text-properties
  5268. (match-beginning 0) (match-end 0)
  5269. '(font-lock-fontified t face org-macro))
  5270. (when org-hide-macro-markers
  5271. (add-text-properties (match-end 2) (match-beginning 2)
  5272. '(invisible t))
  5273. (add-text-properties (match-beginning 1) (match-end 1)
  5274. '(invisible t)))
  5275. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5276. t))
  5277. (defun org-activate-footnote-links (limit)
  5278. "Add text properties for footnotes."
  5279. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5280. (when fn
  5281. (let* ((beg (nth 1 fn))
  5282. (end (nth 2 fn))
  5283. (label (car fn))
  5284. (referencep (/= (line-beginning-position) beg)))
  5285. (when (and referencep (nth 3 fn))
  5286. (save-excursion
  5287. (goto-char beg)
  5288. (search-forward (or label "fn:"))
  5289. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5290. (add-text-properties beg end
  5291. (list 'mouse-face 'highlight
  5292. 'keymap org-mouse-map
  5293. 'help-echo
  5294. (if referencep "Footnote reference"
  5295. "Footnote definition")
  5296. 'font-lock-fontified t
  5297. 'font-lock-multiline t
  5298. 'face 'org-footnote))))))
  5299. (defun org-activate-dates (limit)
  5300. "Add text properties for dates."
  5301. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5302. (not (equal (char-before (match-beginning 0)) 91)))
  5303. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5304. (add-text-properties (match-beginning 0) (match-end 0)
  5305. (list 'mouse-face 'highlight
  5306. 'keymap org-mouse-map))
  5307. (org-rear-nonsticky-at (match-end 0))
  5308. (when org-display-custom-times
  5309. ;; If it's a date range, activate custom time for second date.
  5310. (when (match-end 3)
  5311. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5312. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5313. t))
  5314. (defvar-local org-target-link-regexp nil
  5315. "Regular expression matching radio targets in plain text.")
  5316. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5317. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5318. border border border))
  5319. "Regular expression matching a link target.")
  5320. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5321. "Regular expression matching a radio target.")
  5322. (defconst org-any-target-regexp
  5323. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5324. "Regular expression matching any target.")
  5325. (defun org-activate-target-links (limit)
  5326. "Add text properties for target matches."
  5327. (when org-target-link-regexp
  5328. (let ((case-fold-search t))
  5329. (when (re-search-forward org-target-link-regexp limit t)
  5330. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5331. (add-text-properties (match-beginning 1) (match-end 1)
  5332. (list 'mouse-face 'highlight
  5333. 'keymap org-mouse-map
  5334. 'help-echo "Radio target link"
  5335. 'org-linked-text t))
  5336. (org-rear-nonsticky-at (match-end 1))
  5337. t))))
  5338. (defun org-update-radio-target-regexp ()
  5339. "Find all radio targets in this file and update the regular expression.
  5340. Also refresh fontification if needed."
  5341. (interactive)
  5342. (let ((old-regexp org-target-link-regexp)
  5343. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5344. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5345. (targets
  5346. (org-with-wide-buffer
  5347. (goto-char (point-min))
  5348. (let (rtn)
  5349. (while (re-search-forward org-radio-target-regexp nil t)
  5350. ;; Make sure point is really within the object.
  5351. (backward-char)
  5352. (let ((obj (org-element-context)))
  5353. (when (eq (org-element-type obj) 'radio-target)
  5354. (cl-pushnew (org-element-property :value obj) rtn
  5355. :test #'equal))))
  5356. rtn))))
  5357. (setq org-target-link-regexp
  5358. (and targets
  5359. (concat before-re
  5360. (mapconcat
  5361. (lambda (x)
  5362. (replace-regexp-in-string
  5363. " +" "\\s-+" (regexp-quote x) t t))
  5364. targets
  5365. "\\|")
  5366. after-re)))
  5367. (unless (equal old-regexp org-target-link-regexp)
  5368. ;; Clean-up cache.
  5369. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5370. ((not org-target-link-regexp) old-regexp)
  5371. (t
  5372. (concat before-re
  5373. (mapconcat
  5374. (lambda (re)
  5375. (substring re (length before-re)
  5376. (- (length after-re))))
  5377. (list old-regexp org-target-link-regexp)
  5378. "\\|")
  5379. after-re)))))
  5380. (org-with-wide-buffer
  5381. (goto-char (point-min))
  5382. (while (re-search-forward regexp nil t)
  5383. (org-element-cache-refresh (match-beginning 1)))))
  5384. ;; Re fontify buffer.
  5385. (when (memq 'radio org-highlight-links)
  5386. (org-restart-font-lock)))))
  5387. (defvar org-latex-and-related-regexp nil
  5388. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5389. (defun org-compute-latex-and-related-regexp ()
  5390. "Compute regular expression for LaTeX, entities and sub/superscript.
  5391. Result depends on variable `org-highlight-latex-and-related'."
  5392. (setq-local
  5393. org-latex-and-related-regexp
  5394. (let* ((re-sub
  5395. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5396. ((eq org-use-sub-superscripts '{})
  5397. (list org-match-substring-with-braces-regexp))
  5398. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5399. (re-latex
  5400. (when (memq 'latex org-highlight-latex-and-related)
  5401. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5402. (delq nil
  5403. (mapcar (lambda (x)
  5404. (and (member (car x) matchers) (nth 1 x)))
  5405. org-latex-regexps)))))
  5406. (re-entities
  5407. (when (memq 'entities org-highlight-latex-and-related)
  5408. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5409. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5410. (defun org-do-latex-and-related (limit)
  5411. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5412. LIMIT bounds the search for syntax to highlight. Stop at first
  5413. highlighted object, if any. Return t if some highlighting was
  5414. done, nil otherwise."
  5415. (when (org-string-nw-p org-latex-and-related-regexp)
  5416. (catch 'found
  5417. (while (re-search-forward org-latex-and-related-regexp limit t)
  5418. (unless
  5419. (cl-some
  5420. (lambda (f)
  5421. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5422. (save-excursion
  5423. (goto-char (1+ (match-beginning 0)))
  5424. (face-at-point nil t)))
  5425. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5426. '(?_ ?^))
  5427. 1
  5428. 0)))
  5429. (font-lock-prepend-text-property
  5430. (+ offset (match-beginning 0)) (match-end 0)
  5431. 'face 'org-latex-and-related)
  5432. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5433. '(font-lock-multiline t)))
  5434. (throw 'found t)))
  5435. nil)))
  5436. (defun org-restart-font-lock ()
  5437. "Restart `font-lock-mode', to force refontification."
  5438. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5439. (font-lock-mode -1)
  5440. (font-lock-mode 1)))
  5441. (defun org-activate-tags (limit)
  5442. (when (re-search-forward
  5443. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5444. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5445. (add-text-properties (match-beginning 1) (match-end 1)
  5446. (list 'mouse-face 'highlight
  5447. 'keymap org-mouse-map))
  5448. (org-rear-nonsticky-at (match-end 1))
  5449. t))
  5450. (defun org-outline-level ()
  5451. "Compute the outline level of the heading at point.
  5452. If this is called at a normal headline, the level is the number
  5453. of stars. Use `org-reduced-level' to remove the effect of
  5454. `org-odd-levels'. Unlike to `org-current-level', this function
  5455. takes into consideration inlinetasks."
  5456. (org-with-wide-buffer
  5457. (end-of-line)
  5458. (if (re-search-backward org-outline-regexp-bol nil t)
  5459. (1- (- (match-end 0) (match-beginning 0)))
  5460. 0)))
  5461. (defvar org-font-lock-keywords nil)
  5462. (defsubst org-re-property (property &optional literal allow-null value)
  5463. "Return a regexp matching a PROPERTY line.
  5464. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5465. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5466. non-nil, match properties even without a value.
  5467. Match group 3 is set to the value when it exists. If there is no
  5468. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5469. With optional argument VALUE, match only property lines with
  5470. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5471. unless LITERAL is non-nil."
  5472. (concat
  5473. "^\\(?4:[ \t]*\\)"
  5474. (format "\\(?1::\\(?2:%s\\):\\)"
  5475. (if literal property (regexp-quote property)))
  5476. (cond (value
  5477. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5478. (if literal value (regexp-quote value))))
  5479. (allow-null
  5480. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5481. (t
  5482. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5483. (defconst org-property-re
  5484. (org-re-property "\\S-+" 'literal t)
  5485. "Regular expression matching a property line.
  5486. There are four matching groups:
  5487. 1: :PROPKEY: including the leading and trailing colon,
  5488. 2: PROPKEY without the leading and trailing colon,
  5489. 3: PROPVAL without leading or trailing spaces,
  5490. 4: the indentation of the current line,
  5491. 5: trailing whitespace.")
  5492. (defvar org-font-lock-hook nil
  5493. "Functions to be called for special font lock stuff.")
  5494. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5495. (defvar org-font-lock-set-keywords-hook nil
  5496. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5497. This is called after `org-font-lock-extra-keywords' is defined, but before
  5498. it is installed to be used by font lock. This can be useful if something
  5499. needs to be inserted at a specific position in the font-lock sequence.")
  5500. (defun org-font-lock-hook (limit)
  5501. "Run `org-font-lock-hook' within LIMIT."
  5502. (run-hook-with-args 'org-font-lock-hook limit))
  5503. (defun org-set-font-lock-defaults ()
  5504. "Set font lock defaults for the current buffer."
  5505. (let* ((em org-fontify-emphasized-text)
  5506. (lk org-highlight-links)
  5507. (org-font-lock-extra-keywords
  5508. (list
  5509. ;; Call the hook
  5510. '(org-font-lock-hook)
  5511. ;; Headlines
  5512. `(,(if org-fontify-whole-heading-line
  5513. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5514. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5515. (1 (org-get-level-face 1))
  5516. (2 (org-get-level-face 2))
  5517. (3 (org-get-level-face 3)))
  5518. ;; Table lines
  5519. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5520. (1 'org-table t))
  5521. ;; Table internals
  5522. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5523. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5524. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5525. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5526. ;; Drawers
  5527. '(org-fontify-drawers)
  5528. ;; Properties
  5529. (list org-property-re
  5530. '(1 'org-special-keyword t)
  5531. '(3 'org-property-value t))
  5532. ;; Link related fontification.
  5533. '(org-activate-links)
  5534. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5535. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5536. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5537. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5538. ;; Targets.
  5539. (list org-any-target-regexp '(0 'org-target t))
  5540. ;; Diary sexps.
  5541. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5542. ;; Macro
  5543. '(org-fontify-macros)
  5544. ;; TODO keyword
  5545. (list (format org-heading-keyword-regexp-format
  5546. org-todo-regexp)
  5547. '(2 (org-get-todo-face 2) t))
  5548. ;; DONE
  5549. (if org-fontify-done-headline
  5550. (list (format org-heading-keyword-regexp-format
  5551. (concat
  5552. "\\(?:"
  5553. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5554. "\\)"))
  5555. '(2 'org-headline-done t))
  5556. nil)
  5557. ;; Priorities
  5558. '(org-font-lock-add-priority-faces)
  5559. ;; Tags
  5560. '(org-font-lock-add-tag-faces)
  5561. ;; Tags groups
  5562. (when (and org-group-tags org-tag-groups-alist)
  5563. (list (concat org-outline-regexp-bol ".+\\(:"
  5564. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5565. ":\\).*$")
  5566. '(1 'org-tag-group prepend)))
  5567. ;; Special keywords
  5568. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5569. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5570. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5571. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5572. ;; Emphasis
  5573. (when em '(org-do-emphasis-faces))
  5574. ;; Checkboxes
  5575. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5576. 1 'org-checkbox prepend)
  5577. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5578. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5579. (0 (org-get-checkbox-statistics-face) t)))
  5580. ;; Description list items
  5581. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5582. 1 'org-list-dt prepend)
  5583. ;; ARCHIVEd headings
  5584. (list (concat
  5585. org-outline-regexp-bol
  5586. "\\(.*:" org-archive-tag ":.*\\)")
  5587. '(1 'org-archived prepend))
  5588. ;; Specials
  5589. '(org-do-latex-and-related)
  5590. '(org-fontify-entities)
  5591. '(org-raise-scripts)
  5592. ;; Code
  5593. '(org-activate-code (1 'org-code t))
  5594. ;; COMMENT
  5595. (list (format
  5596. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5597. org-todo-regexp
  5598. org-comment-string)
  5599. '(9 'org-special-keyword t))
  5600. ;; Blocks and meta lines
  5601. '(org-fontify-meta-lines-and-blocks))))
  5602. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5603. (run-hooks 'org-font-lock-set-keywords-hook)
  5604. ;; Now set the full font-lock-keywords
  5605. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5606. (setq-local font-lock-defaults
  5607. '(org-font-lock-keywords t nil nil backward-paragraph))
  5608. (kill-local-variable 'font-lock-keywords)
  5609. nil))
  5610. (defun org-toggle-pretty-entities ()
  5611. "Toggle the composition display of entities as UTF8 characters."
  5612. (interactive)
  5613. (setq-local org-pretty-entities (not org-pretty-entities))
  5614. (org-restart-font-lock)
  5615. (if org-pretty-entities
  5616. (message "Entities are now displayed as UTF8 characters")
  5617. (save-restriction
  5618. (widen)
  5619. (decompose-region (point-min) (point-max))
  5620. (message "Entities are now displayed as plain text"))))
  5621. (defvar-local org-custom-properties-overlays nil
  5622. "List of overlays used for custom properties.")
  5623. (defun org-toggle-custom-properties-visibility ()
  5624. "Display or hide properties in `org-custom-properties'."
  5625. (interactive)
  5626. (if org-custom-properties-overlays
  5627. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5628. (setq org-custom-properties-overlays nil))
  5629. (when org-custom-properties
  5630. (org-with-wide-buffer
  5631. (goto-char (point-min))
  5632. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5633. (while (re-search-forward regexp nil t)
  5634. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5635. (when (and end (< (point) end))
  5636. ;; Hide first custom property in current drawer.
  5637. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5638. (overlay-put o 'invisible t)
  5639. (overlay-put o 'org-custom-property t)
  5640. (push o org-custom-properties-overlays))
  5641. ;; Hide additional custom properties in the same drawer.
  5642. (while (re-search-forward regexp end t)
  5643. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5644. (overlay-put o 'invisible t)
  5645. (overlay-put o 'org-custom-property t)
  5646. (push o org-custom-properties-overlays)))))
  5647. ;; Each entry is limited to a single property drawer.
  5648. (outline-next-heading)))))))
  5649. (defun org-fontify-entities (limit)
  5650. "Find an entity to fontify."
  5651. (let (ee)
  5652. (when org-pretty-entities
  5653. (catch 'match
  5654. ;; "\_ "-family is left out on purpose. Only the first one,
  5655. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5656. ;; confusing when adding a second white space character.
  5657. (while (re-search-forward
  5658. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5659. limit t)
  5660. (when (and (not (org-at-comment-p))
  5661. (setq ee (org-entity-get (match-string 1)))
  5662. (= (length (nth 6 ee)) 1))
  5663. (let* ((end (if (equal (match-string 2) "{}")
  5664. (match-end 2)
  5665. (match-end 1))))
  5666. (add-text-properties
  5667. (match-beginning 0) end
  5668. (list 'font-lock-fontified t))
  5669. (compose-region (match-beginning 0) end
  5670. (nth 6 ee) nil)
  5671. (backward-char 1)
  5672. (throw 'match t))))
  5673. nil))))
  5674. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5675. "Fontify string S like in Org mode."
  5676. (with-temp-buffer
  5677. (insert s)
  5678. (let ((org-odd-levels-only odd-levels))
  5679. (org-mode)
  5680. (org-font-lock-ensure)
  5681. (buffer-string))))
  5682. (defvar org-m nil)
  5683. (defvar org-l nil)
  5684. (defvar org-f nil)
  5685. (defun org-get-level-face (n)
  5686. "Get the right face for match N in font-lock matching of headlines."
  5687. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5688. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5689. (if org-cycle-level-faces
  5690. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5691. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5692. (cond
  5693. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5694. ((eq n 2) org-f)
  5695. (t (unless org-level-color-stars-only org-f))))
  5696. (defun org-face-from-face-or-color (context inherit face-or-color)
  5697. "Create a face list that inherits INHERIT, but sets the foreground color.
  5698. When FACE-OR-COLOR is not a string, just return it."
  5699. (if (stringp face-or-color)
  5700. (list :inherit inherit
  5701. (cdr (assoc context org-faces-easy-properties))
  5702. face-or-color)
  5703. face-or-color))
  5704. (defun org-get-todo-face (kwd)
  5705. "Get the right face for a TODO keyword KWD.
  5706. If KWD is a number, get the corresponding match group."
  5707. (when (numberp kwd) (setq kwd (match-string kwd)))
  5708. (or (org-face-from-face-or-color
  5709. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5710. (and (member kwd org-done-keywords) 'org-done)
  5711. 'org-todo))
  5712. (defun org-get-priority-face (priority)
  5713. "Get the right face for PRIORITY.
  5714. PRIORITY is a character."
  5715. (or (org-face-from-face-or-color
  5716. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5717. 'org-priority))
  5718. (defun org-get-tag-face (tag)
  5719. "Get the right face for TAG.
  5720. If TAG is a number, get the corresponding match group."
  5721. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5722. (or (org-face-from-face-or-color
  5723. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5724. 'org-tag)))
  5725. (defun org-font-lock-add-priority-faces (limit)
  5726. "Add the special priority faces."
  5727. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5728. (add-text-properties
  5729. (match-beginning 1) (match-end 1)
  5730. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5731. 'font-lock-fontified t))))
  5732. (defun org-font-lock-add-tag-faces (limit)
  5733. "Add the special tag faces."
  5734. (when (and org-tag-faces org-tags-special-faces-re)
  5735. (while (re-search-forward org-tags-special-faces-re limit t)
  5736. (add-text-properties (match-beginning 1) (match-end 1)
  5737. (list 'face (org-get-tag-face 1)
  5738. 'font-lock-fontified t))
  5739. (backward-char 1))))
  5740. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5741. "Remove fontification and activation overlays from links."
  5742. (font-lock-default-unfontify-region beg end)
  5743. (let* ((buffer-undo-list t)
  5744. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5745. (inhibit-modification-hooks t)
  5746. deactivate-mark buffer-file-name buffer-file-truename)
  5747. (decompose-region beg end)
  5748. (remove-text-properties beg end
  5749. '(mouse-face t keymap t org-linked-text t
  5750. invisible t intangible t
  5751. org-emphasis t))
  5752. (org-remove-font-lock-display-properties beg end)))
  5753. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5754. ((raise 0.3) (height 0.7))
  5755. ((raise -0.5))
  5756. ((raise 0.5)))
  5757. "Display properties for showing superscripts and subscripts.")
  5758. (defun org-remove-font-lock-display-properties (beg end)
  5759. "Remove specific display properties that have been added by font lock.
  5760. The will remove the raise properties that are used to show superscripts
  5761. and subscripts."
  5762. (let (next prop)
  5763. (while (< beg end)
  5764. (setq next (next-single-property-change beg 'display nil end)
  5765. prop (get-text-property beg 'display))
  5766. (when (member prop org-script-display)
  5767. (put-text-property beg next 'display nil))
  5768. (setq beg next))))
  5769. (defun org-raise-scripts (limit)
  5770. "Add raise properties to sub/superscripts."
  5771. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5772. (re-search-forward
  5773. (if (eq org-use-sub-superscripts t)
  5774. org-match-substring-regexp
  5775. org-match-substring-with-braces-regexp)
  5776. limit t))
  5777. (let* ((pos (point)) table-p comment-p
  5778. (mpos (match-beginning 3))
  5779. (emph-p (get-text-property mpos 'org-emphasis))
  5780. (link-p (get-text-property mpos 'mouse-face))
  5781. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5782. (goto-char (point-at-bol))
  5783. (setq table-p (looking-at-p org-table-dataline-regexp)
  5784. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5785. (goto-char pos)
  5786. ;; Handle a_b^c
  5787. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5788. (unless (or comment-p emph-p link-p keyw-p)
  5789. (put-text-property (match-beginning 3) (match-end 0)
  5790. 'display
  5791. (if (equal (char-after (match-beginning 2)) ?^)
  5792. (nth (if table-p 3 1) org-script-display)
  5793. (nth (if table-p 2 0) org-script-display)))
  5794. (add-text-properties (match-beginning 2) (match-end 2)
  5795. (list 'invisible t))
  5796. (when (and (eq (char-after (match-beginning 3)) ?{)
  5797. (eq (char-before (match-end 3)) ?}))
  5798. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5799. (list 'invisible t))
  5800. (add-text-properties (1- (match-end 3)) (match-end 3)
  5801. (list 'invisible t))))
  5802. t)))
  5803. (defun org-remove-empty-overlays-at (pos)
  5804. "Remove outline overlays that do not contain non-white stuff."
  5805. (dolist (o (overlays-at pos))
  5806. (and (eq 'outline (overlay-get o 'invisible))
  5807. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5808. (overlay-end o))))
  5809. (delete-overlay o))))
  5810. (defun org-show-empty-lines-in-parent ()
  5811. "Move to the parent and re-show empty lines before visible headlines."
  5812. (save-excursion
  5813. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5814. (org-cycle-show-empty-lines context))))
  5815. (defun org-files-list ()
  5816. "Return `org-agenda-files' list, plus all open Org files.
  5817. This is useful for operations that need to scan all of a user's
  5818. open and agenda-wise Org files."
  5819. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5820. (dolist (buf (buffer-list))
  5821. (with-current-buffer buf
  5822. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5823. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5824. :test #'equal))))
  5825. files))
  5826. (defsubst org-entry-beginning-position ()
  5827. "Return the beginning position of the current entry."
  5828. (save-excursion (org-back-to-heading t) (point)))
  5829. (defsubst org-entry-end-position ()
  5830. "Return the end position of the current entry."
  5831. (save-excursion (outline-next-heading) (point)))
  5832. (defun org-subtree-end-visible-p ()
  5833. "Is the end of the current subtree visible?"
  5834. (pos-visible-in-window-p
  5835. (save-excursion (org-end-of-subtree t) (point))))
  5836. (defun org-first-headline-recenter ()
  5837. "Move cursor to the first headline and recenter the headline."
  5838. (let ((window (get-buffer-window)))
  5839. (when window
  5840. (goto-char (point-min))
  5841. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5842. (set-window-start window (line-beginning-position))))))
  5843. ;;; Visibility (headlines, blocks, drawers)
  5844. (defun org-flag-region (from to flag spec)
  5845. "Hide or show lines from FROM to TO, according to FLAG.
  5846. SPEC is the invisibility spec, as a symbol."
  5847. (remove-overlays from to 'invisible spec)
  5848. ;; Use `front-advance' since text right before to the beginning of
  5849. ;; the overlay belongs to the visible line than to the contents.
  5850. (when flag
  5851. (let ((o (make-overlay from to nil 'front-advance)))
  5852. (overlay-put o 'evaporate t)
  5853. (overlay-put o 'invisible spec)
  5854. (overlay-put o 'isearch-open-invisible #'delete-overlay))))
  5855. ;;;; Headlines visibility
  5856. (defun org-show-entry ()
  5857. "Show the body directly following this heading.
  5858. Show the heading too, if it is currently invisible."
  5859. (interactive)
  5860. (save-excursion
  5861. (ignore-errors
  5862. (org-back-to-heading t)
  5863. (org-flag-region
  5864. (line-end-position 0)
  5865. (save-excursion
  5866. (if (re-search-forward
  5867. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5868. (match-beginning 1)
  5869. (point-max)))
  5870. nil
  5871. 'outline))))
  5872. (defun org-show-children (&optional level)
  5873. "Show all direct subheadings of this heading.
  5874. Prefix arg LEVEL is how many levels below the current level
  5875. should be shown. Default is enough to cause the following
  5876. heading to appear."
  5877. (interactive "p")
  5878. (save-excursion
  5879. (org-back-to-heading t)
  5880. (let* ((current-level (funcall outline-level))
  5881. (max-level (org-get-valid-level
  5882. current-level
  5883. (if level (prefix-numeric-value level) 1)))
  5884. (end (save-excursion (org-end-of-subtree t t)))
  5885. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5886. (past-first-child nil)
  5887. ;; Make sure to skip inlinetasks.
  5888. (re (format regexp-fmt
  5889. current-level
  5890. (cond
  5891. ((not (featurep 'org-inlinetask)) "")
  5892. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5893. 3))
  5894. (t (1- org-inlinetask-min-level))))))
  5895. ;; Display parent heading.
  5896. (org-flag-heading nil)
  5897. (forward-line)
  5898. ;; Display children. First child may be deeper than expected
  5899. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5900. ;; MAX-LEVEL accordingly.
  5901. (while (re-search-forward re end t)
  5902. (unless past-first-child
  5903. (setq re (format regexp-fmt
  5904. current-level
  5905. (max (funcall outline-level) max-level)))
  5906. (setq past-first-child t))
  5907. (org-flag-heading nil)))))
  5908. (defun org-show-subtree ()
  5909. "Show everything after this heading at deeper levels."
  5910. (interactive)
  5911. (org-flag-region
  5912. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5913. ;;;; Blocks visibility
  5914. (defun org-hide-block-toggle-maybe ()
  5915. "Toggle visibility of block at point.
  5916. Unlike to `org-hide-block-toggle', this function does not throw
  5917. an error. Return a non-nil value when toggling is successful."
  5918. (interactive)
  5919. (ignore-errors (org-hide-block-toggle)))
  5920. (defun org-hide-block-toggle (&optional force)
  5921. "Toggle the visibility of the current block.
  5922. When optional argument FORCE is `off', make block visible. If it
  5923. is non-nil, hide it unconditionally. Throw an error when not at
  5924. a block. Return a non-nil value when toggling is successful."
  5925. (interactive)
  5926. (let ((element (org-element-at-point)))
  5927. (unless (memq (org-element-type element)
  5928. '(center-block comment-block dynamic-block example-block
  5929. export-block quote-block special-block
  5930. src-block verse-block))
  5931. (user-error "Not at a block"))
  5932. (let* ((post (org-element-property :post-affiliated element))
  5933. (start (save-excursion
  5934. (goto-char post)
  5935. (line-end-position)))
  5936. (end (save-excursion
  5937. (goto-char (org-element-property :end element))
  5938. (skip-chars-backward " \t\n")
  5939. (line-end-position))))
  5940. ;; Do nothing when not before or at the block opening line or at
  5941. ;; the block closing line.
  5942. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5943. (cond ((eq force 'off)
  5944. (org-flag-region start end nil 'org-hide-block))
  5945. (force
  5946. (org-flag-region start end t 'org-hide-block))
  5947. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5948. (org-flag-region start end nil 'org-hide-block))
  5949. (t
  5950. (org-flag-region start end t 'org-hide-block)))
  5951. ;; When the block is hidden away, make sure point is left in
  5952. ;; a visible part of the buffer.
  5953. (when (invisible-p (max (1- (point)) (point-min)))
  5954. (goto-char post))
  5955. ;; Signal success.
  5956. t))))
  5957. (defun org-hide-block-toggle-all ()
  5958. "Toggle the visibility of all blocks in the current buffer."
  5959. (org-block-map 'org-hide-block-toggle))
  5960. (defun org-hide-block-all ()
  5961. "Fold all blocks in the current buffer."
  5962. (interactive)
  5963. (org-show-all '(blocks))
  5964. (org-block-map 'org-hide-block-toggle-maybe))
  5965. ;;;; Drawers visibility
  5966. (defun org-cycle-hide-drawers (state &optional exceptions)
  5967. "Re-hide all drawers after a visibility state change.
  5968. STATE should be one of the symbols listed in the docstring of
  5969. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5970. a list of strings specifying which drawers should not be hidden."
  5971. (when (and (derived-mode-p 'org-mode)
  5972. (not (memq state '(overview folded contents))))
  5973. (save-excursion
  5974. (let* ((globalp (eq state 'all))
  5975. (beg (if globalp (point-min) (point)))
  5976. (end (if globalp (point-max)
  5977. (if (eq state 'children)
  5978. (save-excursion (outline-next-heading) (point))
  5979. (org-end-of-subtree t)))))
  5980. (goto-char beg)
  5981. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5982. (unless (member-ignore-case (match-string 1) exceptions)
  5983. (let ((drawer (org-element-at-point)))
  5984. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5985. (org-flag-drawer t drawer)
  5986. ;; Make sure to skip drawer entirely or we might flag
  5987. ;; it another time when matching its ending line with
  5988. ;; `org-drawer-regexp'.
  5989. (goto-char (org-element-property :end drawer))))))))))
  5990. (defun org-flag-drawer (flag &optional element)
  5991. "When FLAG is non-nil, hide the drawer we are at.
  5992. Otherwise make it visible. When optional argument ELEMENT is
  5993. a parsed drawer, as returned by `org-element-at-point', hide or
  5994. show that drawer instead."
  5995. (let ((drawer (or element
  5996. (and (save-excursion
  5997. (beginning-of-line)
  5998. (looking-at-p org-drawer-regexp))
  5999. (org-element-at-point)))))
  6000. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6001. (let ((post (org-element-property :post-affiliated drawer)))
  6002. (org-flag-region
  6003. (save-excursion (goto-char post) (line-end-position))
  6004. (save-excursion (goto-char (org-element-property :end drawer))
  6005. (skip-chars-backward " \t\n")
  6006. (line-end-position))
  6007. flag 'org-hide-drawer)
  6008. ;; When the drawer is hidden away, make sure point lies in
  6009. ;; a visible part of the buffer.
  6010. (when (invisible-p (max (1- (point)) (point-min)))
  6011. (goto-char post))))))
  6012. ;;;; Visibility cycling
  6013. (defvar-local org-cycle-global-status nil)
  6014. (put 'org-cycle-global-status 'org-state t)
  6015. (defvar-local org-cycle-subtree-status nil)
  6016. (put 'org-cycle-subtree-status 'org-state t)
  6017. (defun org-show-all (&optional types)
  6018. "Show all contents in the visible part of the buffer.
  6019. By default, the function expands headings, blocks and drawers.
  6020. When optional argument TYPE is a list of symbols among `blocks',
  6021. `drawers' and `headings', to only expand one specific type."
  6022. (dolist (type (or types '(blocks drawers headings)))
  6023. (org-flag-region (point-min) (point-max) nil
  6024. (pcase type
  6025. (`blocks 'org-hide-block)
  6026. (`drawers 'org-hide-drawer)
  6027. (`headings 'outline)
  6028. (_ (error "Invalid type: %S" type))))))
  6029. ;;;###autoload
  6030. (defun org-cycle (&optional arg)
  6031. "TAB-action and visibility cycling for Org mode.
  6032. This is the command invoked in Org mode by the `TAB' key. Its main
  6033. purpose is outline visibility cycling, but it also invokes other actions
  6034. in special contexts.
  6035. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6036. the entire
  6037. buffer through 3 states (global cycling)
  6038. 1. OVERVIEW: Show only top-level headlines.
  6039. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6040. 3. SHOW ALL: Show everything.
  6041. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6042. switch to the startup visibility,
  6043. determined by the variable `org-startup-folded', and by any VISIBILITY
  6044. properties in the buffer.
  6045. With a `\\[universal-argument] \\[universal-argument] \
  6046. \\[universal-argument]' prefix argument, show the entire buffer, including
  6047. any drawers.
  6048. When inside a table, re-align the table and move to the next field.
  6049. When point is at the beginning of a headline, rotate the subtree started
  6050. by this line through 3 different states (local cycling)
  6051. 1. FOLDED: Only the main headline is shown.
  6052. 2. CHILDREN: The main headline and the direct children are shown.
  6053. From this state, you can move to one of the children
  6054. and zoom in further.
  6055. 3. SUBTREE: Show the entire subtree, including body text.
  6056. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6057. When point is at the beginning of an empty headline and the variable
  6058. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6059. of the headline by demoting and promoting it to likely levels. This
  6060. speeds up creation document structure by pressing `TAB' once or several
  6061. times right after creating a new headline.
  6062. When there is a numeric prefix, go up to a heading with level ARG, do
  6063. a `show-subtree' and return to the previous cursor position. If ARG
  6064. is negative, go up that many levels.
  6065. When point is not at the beginning of a headline, execute the global
  6066. binding for `TAB', which is re-indenting the line. See the option
  6067. `org-cycle-emulate-tab' for details.
  6068. As a special case, if point is at the beginning of the buffer and there is
  6069. no headline in line 1, this function will act as if called with prefix arg
  6070. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6071. prefix arg, but only
  6072. if the variable `org-cycle-global-at-bob' is t."
  6073. (interactive "P")
  6074. (org-load-modules-maybe)
  6075. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6076. (and org-cycle-level-after-item/entry-creation
  6077. (or (org-cycle-level)
  6078. (org-cycle-item-indentation))))
  6079. (let* ((limit-level
  6080. (or org-cycle-max-level
  6081. (and (boundp 'org-inlinetask-min-level)
  6082. org-inlinetask-min-level
  6083. (1- org-inlinetask-min-level))))
  6084. (nstars (and limit-level
  6085. (if org-odd-levels-only
  6086. (and limit-level (1- (* limit-level 2)))
  6087. limit-level)))
  6088. (org-outline-regexp
  6089. (if (not (derived-mode-p 'org-mode))
  6090. outline-regexp
  6091. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6092. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6093. (not (looking-at org-outline-regexp))))
  6094. (org-cycle-hook
  6095. (if bob-special
  6096. (delq 'org-optimize-window-after-visibility-change
  6097. (copy-sequence org-cycle-hook))
  6098. org-cycle-hook))
  6099. (pos (point)))
  6100. (cond
  6101. ((equal arg '(16))
  6102. (setq last-command 'dummy)
  6103. (org-set-startup-visibility)
  6104. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6105. ((equal arg '(64))
  6106. (org-show-all)
  6107. (org-unlogged-message "Entire buffer visible, including drawers"))
  6108. ((equal arg '(4)) (org-cycle-internal-global))
  6109. ;; Try hiding block at point.
  6110. ((org-hide-block-toggle-maybe))
  6111. ;; Try cdlatex TAB completion
  6112. ((org-try-cdlatex-tab))
  6113. ;; Table: enter it or move to the next field.
  6114. ((org-at-table-p 'any)
  6115. (if (org-at-table.el-p)
  6116. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6117. Use `\\[org-edit-special]' to edit table.el tables"))
  6118. (if arg (org-table-edit-field t)
  6119. (org-table-justify-field-maybe)
  6120. (call-interactively 'org-table-next-field))))
  6121. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6122. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6123. (bob-special (org-cycle-internal-global))
  6124. ;; Drawers: delegate to `org-flag-drawer'.
  6125. ((save-excursion
  6126. (beginning-of-line 1)
  6127. (looking-at org-drawer-regexp))
  6128. (org-flag-drawer ; toggle block visibility
  6129. (not (get-char-property (match-end 0) 'invisible))))
  6130. ;; Show-subtree, ARG levels up from here.
  6131. ((integerp arg)
  6132. (save-excursion
  6133. (org-back-to-heading)
  6134. (outline-up-heading (if (< arg 0) (- arg)
  6135. (- (funcall outline-level) arg)))
  6136. (org-show-subtree)))
  6137. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6138. ((and (featurep 'org-inlinetask)
  6139. (org-inlinetask-at-task-p)
  6140. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6141. (org-inlinetask-toggle-visibility))
  6142. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6143. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6144. (save-excursion (move-beginning-of-line 1)
  6145. (looking-at org-outline-regexp)))
  6146. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6147. (org-cycle-internal-local))
  6148. ;; From there: TAB emulation and template completion.
  6149. (buffer-read-only (org-back-to-heading))
  6150. ((run-hook-with-args-until-success
  6151. 'org-tab-after-check-for-cycling-hook))
  6152. ((run-hook-with-args-until-success
  6153. 'org-tab-before-tab-emulation-hook))
  6154. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6155. (or (not (bolp))
  6156. (not (looking-at org-outline-regexp))))
  6157. (call-interactively (global-key-binding "\t")))
  6158. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6159. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6160. (or (and (eq org-cycle-emulate-tab 'white)
  6161. (= (match-end 0) (point-at-eol)))
  6162. (and (eq org-cycle-emulate-tab 'whitestart)
  6163. (>= (match-end 0) pos))))
  6164. t
  6165. (eq org-cycle-emulate-tab t))
  6166. (call-interactively (global-key-binding "\t")))
  6167. (t (save-excursion
  6168. (org-back-to-heading)
  6169. (org-cycle)))))))
  6170. (defun org-cycle-internal-global ()
  6171. "Do the global cycling action."
  6172. ;; Hack to avoid display of messages for .org attachments in Gnus
  6173. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6174. (cond
  6175. ((and (eq last-command this-command)
  6176. (eq org-cycle-global-status 'overview))
  6177. ;; We just created the overview - now do table of contents
  6178. ;; This can be slow in very large buffers, so indicate action
  6179. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6180. (unless ga (org-unlogged-message "CONTENTS..."))
  6181. (org-content)
  6182. (unless ga (org-unlogged-message "CONTENTS...done"))
  6183. (setq org-cycle-global-status 'contents)
  6184. (run-hook-with-args 'org-cycle-hook 'contents))
  6185. ((and (eq last-command this-command)
  6186. (eq org-cycle-global-status 'contents))
  6187. ;; We just showed the table of contents - now show everything
  6188. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6189. (org-show-all '(headings blocks))
  6190. (unless ga (org-unlogged-message "SHOW ALL"))
  6191. (setq org-cycle-global-status 'all)
  6192. (run-hook-with-args 'org-cycle-hook 'all))
  6193. (t
  6194. ;; Default action: go to overview
  6195. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6196. (org-overview)
  6197. (unless ga (org-unlogged-message "OVERVIEW"))
  6198. (setq org-cycle-global-status 'overview)
  6199. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6200. (defvar org-called-with-limited-levels nil
  6201. "Non-nil when `org-with-limited-levels' is currently active.")
  6202. (defun org-cycle-internal-local ()
  6203. "Do the local cycling action."
  6204. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6205. ;; First, determine end of headline (EOH), end of subtree or item
  6206. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6207. (save-excursion
  6208. (if (org-at-item-p)
  6209. (progn
  6210. (beginning-of-line)
  6211. (setq struct (org-list-struct))
  6212. (setq eoh (point-at-eol))
  6213. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6214. (setq has-children (org-list-has-child-p (point) struct)))
  6215. (org-back-to-heading)
  6216. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6217. (setq eos (save-excursion (org-end-of-subtree t t)
  6218. (when (bolp) (backward-char)) (point)))
  6219. (setq has-children
  6220. (or (save-excursion
  6221. (let ((level (funcall outline-level)))
  6222. (outline-next-heading)
  6223. (and (org-at-heading-p t)
  6224. (> (funcall outline-level) level))))
  6225. (save-excursion
  6226. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6227. ;; Determine end invisible part of buffer (EOL)
  6228. (beginning-of-line 2)
  6229. (while (and (not (eobp)) ;This is like `next-line'.
  6230. (get-char-property (1- (point)) 'invisible))
  6231. (goto-char (next-single-char-property-change (point) 'invisible))
  6232. (and (eolp) (beginning-of-line 2)))
  6233. (setq eol (point)))
  6234. ;; Find out what to do next and set `this-command'
  6235. (cond
  6236. ((= eos eoh)
  6237. ;; Nothing is hidden behind this heading
  6238. (unless (org-before-first-heading-p)
  6239. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6240. (org-unlogged-message "EMPTY ENTRY")
  6241. (setq org-cycle-subtree-status nil)
  6242. (save-excursion
  6243. (goto-char eos)
  6244. (outline-next-heading)
  6245. (when (org-invisible-p) (org-flag-heading nil))))
  6246. ((and (or (>= eol eos)
  6247. (not (string-match "\\S-" (buffer-substring eol eos))))
  6248. (or has-children
  6249. (not (setq children-skipped
  6250. org-cycle-skip-children-state-if-no-children))))
  6251. ;; Entire subtree is hidden in one line: children view
  6252. (unless (org-before-first-heading-p)
  6253. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6254. (if (org-at-item-p)
  6255. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6256. (org-show-entry)
  6257. (org-with-limited-levels (org-show-children))
  6258. (org-show-set-visibility 'canonical)
  6259. ;; Fold every list in subtree to top-level items.
  6260. (when (eq org-cycle-include-plain-lists 'integrate)
  6261. (save-excursion
  6262. (org-back-to-heading)
  6263. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6264. (beginning-of-line 1)
  6265. (let* ((struct (org-list-struct))
  6266. (prevs (org-list-prevs-alist struct))
  6267. (end (org-list-get-bottom-point struct)))
  6268. (dolist (e (org-list-get-all-items (point) struct prevs))
  6269. (org-list-set-item-visibility e struct 'folded))
  6270. (goto-char (if (< end eos) end eos)))))))
  6271. (org-unlogged-message "CHILDREN")
  6272. (save-excursion
  6273. (goto-char eos)
  6274. (outline-next-heading)
  6275. (when (org-invisible-p) (org-flag-heading nil)))
  6276. (setq org-cycle-subtree-status 'children)
  6277. (unless (org-before-first-heading-p)
  6278. (run-hook-with-args 'org-cycle-hook 'children)))
  6279. ((or children-skipped
  6280. (and (eq last-command this-command)
  6281. (eq org-cycle-subtree-status 'children)))
  6282. ;; We just showed the children, or no children are there,
  6283. ;; now show everything.
  6284. (unless (org-before-first-heading-p)
  6285. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6286. (org-flag-region eoh eos nil 'outline)
  6287. (org-unlogged-message
  6288. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6289. (setq org-cycle-subtree-status 'subtree)
  6290. (unless (org-before-first-heading-p)
  6291. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6292. (t
  6293. ;; Default action: hide the subtree.
  6294. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6295. (org-flag-region eoh eos t 'outline)
  6296. (org-unlogged-message "FOLDED")
  6297. (setq org-cycle-subtree-status 'folded)
  6298. (unless (org-before-first-heading-p)
  6299. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6300. ;;;###autoload
  6301. (defun org-global-cycle (&optional arg)
  6302. "Cycle the global visibility. For details see `org-cycle'.
  6303. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6304. With a numeric prefix, show all headlines up to that level."
  6305. (interactive "P")
  6306. (let ((org-cycle-include-plain-lists
  6307. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6308. (cond
  6309. ((integerp arg)
  6310. (org-show-all '(headings blocks))
  6311. (outline-hide-sublevels arg)
  6312. (setq org-cycle-global-status 'contents))
  6313. ((equal arg '(4))
  6314. (org-set-startup-visibility)
  6315. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6316. (t
  6317. (org-cycle '(4))))))
  6318. (defun org-set-startup-visibility ()
  6319. "Set the visibility required by startup options and properties."
  6320. (cond
  6321. ((eq org-startup-folded t)
  6322. (org-overview))
  6323. ((eq org-startup-folded 'content)
  6324. (org-content))
  6325. ((or (eq org-startup-folded 'showeverything)
  6326. (eq org-startup-folded nil))
  6327. (org-show-all)))
  6328. (unless (eq org-startup-folded 'showeverything)
  6329. (when org-hide-block-startup (org-hide-block-all))
  6330. (org-set-visibility-according-to-property)
  6331. (org-cycle-hide-archived-subtrees 'all)
  6332. (org-cycle-hide-drawers 'all)
  6333. (org-cycle-show-empty-lines t)))
  6334. (defun org-set-visibility-according-to-property ()
  6335. "Switch subtree visibilities according to :VISIBILITY: property."
  6336. (interactive)
  6337. (org-with-wide-buffer
  6338. (goto-char (point-min))
  6339. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6340. (if (not (org-at-property-p)) (outline-next-heading)
  6341. (let ((state (match-string 3)))
  6342. (save-excursion
  6343. (org-back-to-heading t)
  6344. (outline-hide-subtree)
  6345. (org-reveal)
  6346. (cond
  6347. ((equal state "folded")
  6348. (outline-hide-subtree))
  6349. ((equal state "children")
  6350. (org-show-hidden-entry)
  6351. (org-show-children))
  6352. ((equal state "content")
  6353. (save-excursion
  6354. (save-restriction
  6355. (org-narrow-to-subtree)
  6356. (org-content))))
  6357. ((member state '("all" "showall"))
  6358. (outline-show-subtree)))))))))
  6359. (defun org-overview ()
  6360. "Switch to overview mode, showing only top-level headlines.
  6361. This shows all headlines with a level equal or greater than the level
  6362. of the first headline in the buffer. This is important, because if the
  6363. first headline is not level one, then (hide-sublevels 1) gives confusing
  6364. results."
  6365. (interactive)
  6366. (save-excursion
  6367. (let ((level
  6368. (save-excursion
  6369. (goto-char (point-min))
  6370. (when (re-search-forward org-outline-regexp-bol nil t)
  6371. (goto-char (match-beginning 0))
  6372. (funcall outline-level)))))
  6373. (and level (outline-hide-sublevels level)))))
  6374. (defun org-content (&optional arg)
  6375. "Show all headlines in the buffer, like a table of contents.
  6376. With numerical argument N, show content up to level N."
  6377. (interactive "P")
  6378. (org-overview)
  6379. (save-excursion
  6380. ;; Visit all headings and show their offspring
  6381. (and (integerp arg) (org-overview))
  6382. (goto-char (point-max))
  6383. (catch 'exit
  6384. (while (and (progn (condition-case nil
  6385. (outline-previous-visible-heading 1)
  6386. (error (goto-char (point-min))))
  6387. t)
  6388. (looking-at org-outline-regexp))
  6389. (if (integerp arg)
  6390. (org-show-children (1- arg))
  6391. (outline-show-branches))
  6392. (when (bobp) (throw 'exit nil))))))
  6393. (defun org-optimize-window-after-visibility-change (state)
  6394. "Adjust the window after a change in outline visibility.
  6395. This function is the default value of the hook `org-cycle-hook'."
  6396. (when (get-buffer-window (current-buffer))
  6397. (cond
  6398. ((eq state 'content) nil)
  6399. ((eq state 'all) nil)
  6400. ((eq state 'folded) nil)
  6401. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6402. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6403. (defun org-clean-visibility-after-subtree-move ()
  6404. "Fix visibility issues after moving a subtree."
  6405. ;; First, find a reasonable region to look at:
  6406. ;; Start two siblings above, end three below
  6407. (let* ((beg (save-excursion
  6408. (and (org-get-last-sibling)
  6409. (org-get-last-sibling))
  6410. (point)))
  6411. (end (save-excursion
  6412. (and (org-get-next-sibling)
  6413. (org-get-next-sibling)
  6414. (org-get-next-sibling))
  6415. (if (org-at-heading-p)
  6416. (point-at-eol)
  6417. (point))))
  6418. (level (looking-at "\\*+"))
  6419. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6420. (save-excursion
  6421. (save-restriction
  6422. (narrow-to-region beg end)
  6423. (when re
  6424. ;; Properly fold already folded siblings
  6425. (goto-char (point-min))
  6426. (while (re-search-forward re nil t)
  6427. (when (and (not (org-invisible-p))
  6428. (org-invisible-p (line-end-position)))
  6429. (outline-hide-entry))))
  6430. (org-cycle-hide-drawers 'all)
  6431. (org-cycle-show-empty-lines 'overview)))))
  6432. (defun org-cycle-show-empty-lines (state)
  6433. "Show empty lines above all visible headlines.
  6434. The region to be covered depends on STATE when called through
  6435. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6436. entire buffer covered. Note that an empty line is only shown if there
  6437. are at least `org-cycle-separator-lines' empty lines before the headline."
  6438. (when (/= org-cycle-separator-lines 0)
  6439. (save-excursion
  6440. (let* ((n (abs org-cycle-separator-lines))
  6441. (re (cond
  6442. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6443. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6444. (t (let ((ns (number-to-string (- n 2))))
  6445. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6446. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6447. beg end)
  6448. (cond
  6449. ((memq state '(overview contents t))
  6450. (setq beg (point-min) end (point-max)))
  6451. ((memq state '(children folded))
  6452. (setq beg (point)
  6453. end (progn (org-end-of-subtree t t)
  6454. (line-beginning-position 2)))))
  6455. (when beg
  6456. (goto-char beg)
  6457. (while (re-search-forward re end t)
  6458. (unless (get-char-property (match-end 1) 'invisible)
  6459. (let ((e (match-end 1))
  6460. (b (if (>= org-cycle-separator-lines 0)
  6461. (match-beginning 1)
  6462. (save-excursion
  6463. (goto-char (match-beginning 0))
  6464. (skip-chars-backward " \t\n")
  6465. (line-end-position)))))
  6466. (org-flag-region b e nil 'outline))))))))
  6467. ;; Never hide empty lines at the end of the file.
  6468. (save-excursion
  6469. (goto-char (point-max))
  6470. (outline-previous-heading)
  6471. (outline-end-of-heading)
  6472. (when (and (looking-at "[ \t\n]+")
  6473. (= (match-end 0) (point-max)))
  6474. (org-flag-region (point) (match-end 0) nil 'outline))))
  6475. ;;;; Reveal point location
  6476. (defun org-show-context (&optional key)
  6477. "Make sure point and context are visible.
  6478. Optional argument KEY, when non-nil, is a symbol. See
  6479. `org-show-context-detail' for allowed values and how much is to
  6480. be shown."
  6481. (org-show-set-visibility
  6482. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6483. ((cdr (assq key org-show-context-detail)))
  6484. (t (cdr (assq 'default org-show-context-detail))))))
  6485. (defun org-show-set-visibility (detail)
  6486. "Set visibility around point according to DETAIL.
  6487. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6488. `tree', `canonical' or t. See `org-show-context-detail' for more
  6489. information."
  6490. ;; Show current heading and possibly its entry, following headline
  6491. ;; or all children.
  6492. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6493. (org-flag-heading nil)
  6494. (org-show-entry)
  6495. ;; If point is hidden within a drawer or a block, make sure to
  6496. ;; expose it.
  6497. (dolist (o (overlays-at (point)))
  6498. (when (memq (overlay-get o 'invisible)
  6499. '(org-hide-block org-hide-drawer outline))
  6500. (delete-overlay o)))
  6501. (unless (org-before-first-heading-p)
  6502. (org-with-limited-levels
  6503. (cl-case detail
  6504. ((tree canonical t) (org-show-children))
  6505. ((nil minimal ancestors))
  6506. (t (save-excursion
  6507. (outline-next-heading)
  6508. (org-flag-heading nil)))))))
  6509. ;; Show all siblings.
  6510. (when (eq detail 'lineage) (org-show-siblings))
  6511. ;; Show ancestors, possibly with their children.
  6512. (when (memq detail '(ancestors lineage tree canonical t))
  6513. (save-excursion
  6514. (while (org-up-heading-safe)
  6515. (org-flag-heading nil)
  6516. (when (memq detail '(canonical t)) (org-show-entry))
  6517. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6518. (defvar org-reveal-start-hook nil
  6519. "Hook run before revealing a location.")
  6520. (defun org-reveal (&optional siblings)
  6521. "Show current entry, hierarchy above it, and the following headline.
  6522. This can be used to show a consistent set of context around
  6523. locations exposed with `org-show-context'.
  6524. With optional argument SIBLINGS, on each level of the hierarchy all
  6525. siblings are shown. This repairs the tree structure to what it would
  6526. look like when opened with hierarchical calls to `org-cycle'.
  6527. With a \\[universal-argument] \\[universal-argument] prefix, \
  6528. go to the parent and show the entire tree."
  6529. (interactive "P")
  6530. (run-hooks 'org-reveal-start-hook)
  6531. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6532. ((equal siblings '(16))
  6533. (save-excursion
  6534. (when (org-up-heading-safe)
  6535. (org-show-subtree)
  6536. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6537. (t (org-show-set-visibility 'lineage))))
  6538. ;;; Indirect buffer display of subtrees
  6539. (defvar org-indirect-dedicated-frame nil
  6540. "This is the frame being used for indirect tree display.")
  6541. (defvar org-last-indirect-buffer nil)
  6542. (defun org-tree-to-indirect-buffer (&optional arg)
  6543. "Create indirect buffer and narrow it to current subtree.
  6544. With a numerical prefix ARG, go up to this level and then take that tree.
  6545. If ARG is negative, go up that many levels.
  6546. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6547. indirect buffer previously made with this command, to avoid proliferation of
  6548. indirect buffers. However, when you call the command with a \
  6549. `\\[universal-argument]' prefix, or
  6550. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6551. so that you can work with several indirect buffers at the same time. If
  6552. `org-indirect-buffer-display' is `dedicated-frame', the \
  6553. `\\[universal-argument]' prefix also
  6554. requests that a new frame be made for the new buffer, so that the dedicated
  6555. frame is not changed."
  6556. (interactive "P")
  6557. (let ((cbuf (current-buffer))
  6558. (cwin (selected-window))
  6559. (pos (point))
  6560. beg end level heading ibuf)
  6561. (save-excursion
  6562. (org-back-to-heading t)
  6563. (when (numberp arg)
  6564. (setq level (org-outline-level))
  6565. (when (< arg 0) (setq arg (+ level arg)))
  6566. (while (> (setq level (org-outline-level)) arg)
  6567. (org-up-heading-safe)))
  6568. (setq beg (point)
  6569. heading (org-get-heading 'no-tags))
  6570. (org-end-of-subtree t t)
  6571. (when (org-at-heading-p) (backward-char 1))
  6572. (setq end (point)))
  6573. (when (and (buffer-live-p org-last-indirect-buffer)
  6574. (not (eq org-indirect-buffer-display 'new-frame))
  6575. (not arg))
  6576. (kill-buffer org-last-indirect-buffer))
  6577. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6578. org-last-indirect-buffer ibuf)
  6579. (cond
  6580. ((or (eq org-indirect-buffer-display 'new-frame)
  6581. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6582. (select-frame (make-frame))
  6583. (delete-other-windows)
  6584. (pop-to-buffer-same-window ibuf)
  6585. (org-set-frame-title heading))
  6586. ((eq org-indirect-buffer-display 'dedicated-frame)
  6587. (raise-frame
  6588. (select-frame (or (and org-indirect-dedicated-frame
  6589. (frame-live-p org-indirect-dedicated-frame)
  6590. org-indirect-dedicated-frame)
  6591. (setq org-indirect-dedicated-frame (make-frame)))))
  6592. (delete-other-windows)
  6593. (pop-to-buffer-same-window ibuf)
  6594. (org-set-frame-title (concat "Indirect: " heading)))
  6595. ((eq org-indirect-buffer-display 'current-window)
  6596. (pop-to-buffer-same-window ibuf))
  6597. ((eq org-indirect-buffer-display 'other-window)
  6598. (pop-to-buffer ibuf))
  6599. (t (error "Invalid value")))
  6600. (narrow-to-region beg end)
  6601. (org-show-all '(headings blocks))
  6602. (goto-char pos)
  6603. (run-hook-with-args 'org-cycle-hook 'all)
  6604. (and (window-live-p cwin) (select-window cwin))))
  6605. (defun org-get-indirect-buffer (&optional buffer heading)
  6606. (setq buffer (or buffer (current-buffer)))
  6607. (let ((n 1) (base (buffer-name buffer)) bname)
  6608. (while (buffer-live-p
  6609. (get-buffer
  6610. (setq bname
  6611. (concat base "-"
  6612. (if heading (concat heading "-" (number-to-string n))
  6613. (number-to-string n))))))
  6614. (setq n (1+ n)))
  6615. (condition-case nil
  6616. (make-indirect-buffer buffer bname 'clone)
  6617. (error (make-indirect-buffer buffer bname)))))
  6618. (defun org-set-frame-title (title)
  6619. "Set the title of the current frame to the string TITLE."
  6620. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6621. ;;;; Structure editing
  6622. ;;; Inserting headlines
  6623. (defun org--line-empty-p (n)
  6624. "Is the Nth next line empty?
  6625. Counts the current line as N = 1 and the previous line as N = 0;
  6626. see `beginning-of-line'."
  6627. (save-excursion
  6628. (and (not (bobp))
  6629. (or (beginning-of-line n) t)
  6630. (save-match-data
  6631. (looking-at "[ \t]*$")))))
  6632. (defun org-previous-line-empty-p ()
  6633. "Is the previous line a blank line?
  6634. When NEXT is non-nil, check the next line instead."
  6635. (org--line-empty-p 0))
  6636. (defun org-next-line-empty-p ()
  6637. "Is the previous line a blank line?
  6638. When NEXT is non-nil, check the next line instead."
  6639. (org--line-empty-p 2))
  6640. (defun org--blank-before-heading-p (&optional parent)
  6641. "Non-nil when an empty line should precede a new heading here.
  6642. When optional argument PARENT is non-nil, consider parent
  6643. headline instead of current one."
  6644. (pcase (assq 'heading org-blank-before-new-entry)
  6645. (`(heading . auto)
  6646. (save-excursion
  6647. (org-with-limited-levels
  6648. (unless (and (org-before-first-heading-p)
  6649. (not (outline-next-heading)))
  6650. (org-back-to-heading t)
  6651. (when parent (org-up-heading-safe))
  6652. (cond ((not (bobp))
  6653. (org-previous-line-empty-p))
  6654. ((outline-next-heading)
  6655. (org-previous-line-empty-p))
  6656. ;; Ignore trailing spaces on last buffer line.
  6657. ((progn (skip-chars-backward " \t") (bolp))
  6658. (org-previous-line-empty-p))
  6659. (t nil))))))
  6660. (`(heading . ,value) value)
  6661. (_ nil)))
  6662. (defun org-insert-heading (&optional arg invisible-ok top)
  6663. "Insert a new heading or an item with the same depth at point.
  6664. If point is at the beginning of a heading, insert a new heading
  6665. or a new headline above the current one. When at the beginning
  6666. of a regular line of text, turn it into a heading.
  6667. If point is in the middle of a line, split it and create a new
  6668. headline with the text in the current line after point (see
  6669. `org-M-RET-may-split-line' on how to modify this behavior). As
  6670. a special case, on a headline, splitting can only happen on the
  6671. title itself. E.g., this excludes breaking stars or tags.
  6672. With a `\\[universal-argument]' prefix, set \
  6673. `org-insert-heading-respect-content' to
  6674. a non-nil value for the duration of the command. This forces the
  6675. insertion of a heading after the current subtree, independently
  6676. on the location of point.
  6677. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6678. insert the heading at the end of the tree
  6679. above the current heading. For example, if point is within a
  6680. 2nd-level heading, then it will insert a 2nd-level heading at
  6681. the end of the 1st-level parent subtree.
  6682. When INVISIBLE-OK is set, stop at invisible headlines when going
  6683. back. This is important for non-interactive uses of the
  6684. command.
  6685. When optional argument TOP is non-nil, insert a level 1 heading,
  6686. unconditionally."
  6687. (interactive "P")
  6688. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6689. (level (org-current-level))
  6690. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6691. (cond
  6692. ((or org-insert-heading-respect-content
  6693. (member arg '((4) (16)))
  6694. (and (not invisible-ok)
  6695. (invisible-p (max (1- (point)) (point-min)))))
  6696. ;; Position point at the location of insertion.
  6697. (if (not level) ;before first headline
  6698. (org-with-limited-levels (outline-next-heading))
  6699. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6700. ;; is nil.
  6701. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6702. (cond ((equal arg '(16))
  6703. (org-up-heading-safe)
  6704. (org-end-of-subtree t t))
  6705. (t
  6706. (org-end-of-subtree t t))))
  6707. (unless (bolp) (insert "\n")) ;ensure final newline
  6708. (unless (and blank? (org-previous-line-empty-p))
  6709. (org-N-empty-lines-before-current (if blank? 1 0)))
  6710. (insert stars " \n")
  6711. (forward-char -1))
  6712. ;; At a headline...
  6713. ((org-at-heading-p)
  6714. (cond ((bolp)
  6715. (when blank? (save-excursion (insert "\n")))
  6716. (save-excursion (insert stars " \n"))
  6717. (unless (and blank? (org-previous-line-empty-p))
  6718. (org-N-empty-lines-before-current (if blank? 1 0)))
  6719. (end-of-line))
  6720. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6721. (org-match-line org-complex-heading-regexp)
  6722. (org-pos-in-match-range (point) 4))
  6723. ;; Grab the text that should moved to the new headline.
  6724. ;; Preserve tags.
  6725. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6726. (if (looking-at "[ \t]*$") (replace-match "")
  6727. (org-set-tags nil t))
  6728. (end-of-line)
  6729. (when blank? (insert "\n"))
  6730. (insert "\n" stars " ")
  6731. (when (org-string-nw-p split) (insert split))
  6732. (when (eobp) (save-excursion (insert "\n")))))
  6733. (t
  6734. (end-of-line)
  6735. (when blank? (insert "\n"))
  6736. (insert "\n" stars " ")
  6737. (when (eobp) (save-excursion (insert "\n"))))))
  6738. ;; On regular text, turn line into a headline or split, if
  6739. ;; appropriate.
  6740. ((bolp)
  6741. (insert stars " ")
  6742. (unless (and blank? (org-previous-line-empty-p))
  6743. (org-N-empty-lines-before-current (if blank? 1 0))))
  6744. (t
  6745. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6746. (end-of-line))
  6747. (insert "\n" stars " ")
  6748. (unless (and blank? (org-previous-line-empty-p))
  6749. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6750. (run-hooks 'org-insert-heading-hook))
  6751. (defun org-N-empty-lines-before-current (n)
  6752. "Make the number of empty lines before current exactly N.
  6753. So this will delete or add empty lines."
  6754. (let ((column (current-column)))
  6755. (beginning-of-line)
  6756. (unless (bobp)
  6757. (let ((start (save-excursion
  6758. (skip-chars-backward " \r\t\n")
  6759. (line-end-position))))
  6760. (delete-region start (line-end-position 0))))
  6761. (insert (make-string n ?\n))
  6762. (move-to-column column)))
  6763. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6764. "Return the heading of the current entry, without the stars.
  6765. When NO-TAGS is non-nil, don't include tags.
  6766. When NO-TODO is non-nil, don't include TODO keywords.
  6767. When NO-PRIORITY is non-nil, don't include priority cookie.
  6768. When NO-COMMENT is non-nil, don't include COMMENT string."
  6769. (save-excursion
  6770. (org-back-to-heading t)
  6771. (let ((case-fold-search nil))
  6772. (looking-at org-complex-heading-regexp)
  6773. (let ((todo (and (not no-todo) (match-string 2)))
  6774. (priority (and (not no-priority) (match-string 3)))
  6775. (headline (pcase (match-string 4)
  6776. (`nil "")
  6777. ((and (guard no-comment) h)
  6778. (replace-regexp-in-string
  6779. (eval-when-compile
  6780. (format "\\`%s[ \t]+" org-comment-string))
  6781. "" h))
  6782. (h h)))
  6783. (tags (and (not no-tags) (match-string 5))))
  6784. (mapconcat #'identity
  6785. (delq nil (list todo priority headline tags))
  6786. " ")))))
  6787. (defun org-heading-components ()
  6788. "Return the components of the current heading.
  6789. This is a list with the following elements:
  6790. - the level as an integer
  6791. - the reduced level, different if `org-odd-levels-only' is set.
  6792. - the TODO keyword, or nil
  6793. - the priority character, like ?A, or nil if no priority is given
  6794. - the headline text itself, or the tags string if no headline text
  6795. - the tags string, or nil."
  6796. (save-excursion
  6797. (org-back-to-heading t)
  6798. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6799. (list (length (match-string 1))
  6800. (org-reduced-level (length (match-string 1)))
  6801. (match-string-no-properties 2)
  6802. (and (match-end 3) (aref (match-string 3) 2))
  6803. (match-string-no-properties 4)
  6804. (match-string-no-properties 5)))))
  6805. (defun org-get-entry ()
  6806. "Get the entry text, after heading, entire subtree."
  6807. (save-excursion
  6808. (org-back-to-heading t)
  6809. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6810. (defun org-edit-headline (&optional heading)
  6811. "Edit the current headline.
  6812. Set it to HEADING when provided."
  6813. (interactive)
  6814. (org-with-wide-buffer
  6815. (org-back-to-heading t)
  6816. (let ((case-fold-search nil))
  6817. (when (looking-at org-complex-heading-regexp)
  6818. (let* ((old (match-string-no-properties 4))
  6819. (new (save-match-data
  6820. (org-trim (or heading (read-string "Edit: " old))))))
  6821. (unless (equal old new)
  6822. (if old (replace-match new t t nil 4)
  6823. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6824. (insert " " new))
  6825. (org-set-tags nil t)
  6826. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6827. (defun org-insert-heading-after-current ()
  6828. "Insert a new heading with same level as current, after current subtree."
  6829. (interactive)
  6830. (org-back-to-heading)
  6831. (org-insert-heading)
  6832. (org-move-subtree-down)
  6833. (end-of-line 1))
  6834. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6835. "Insert heading with `org-insert-heading-respect-content' set to t."
  6836. (interactive)
  6837. (org-insert-heading '(4) invisible-ok))
  6838. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6839. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6840. (interactive)
  6841. (org-insert-todo-heading force-state '(4)))
  6842. (defun org-insert-todo-heading (arg &optional force-heading)
  6843. "Insert a new heading with the same level and TODO state as current heading.
  6844. If the heading has no TODO state, or if the state is DONE, use
  6845. the first state (TODO by default). Also with one prefix arg,
  6846. force first state. With two prefix args, force inserting at the
  6847. end of the parent subtree.
  6848. When called at a plain list item, insert a new item with an
  6849. unchecked check box."
  6850. (interactive "P")
  6851. (when (or force-heading (not (org-insert-item 'checkbox)))
  6852. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6853. force-heading))
  6854. (save-excursion
  6855. (org-forward-heading-same-level -1)
  6856. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6857. (let* ((new-mark-x
  6858. (if (or (equal arg '(4))
  6859. (not (match-beginning 2))
  6860. (member (match-string 2) org-done-keywords))
  6861. (car org-todo-keywords-1)
  6862. (match-string 2)))
  6863. (new-mark
  6864. (or
  6865. (run-hook-with-args-until-success
  6866. 'org-todo-get-default-hook new-mark-x nil)
  6867. new-mark-x)))
  6868. (beginning-of-line 1)
  6869. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6870. (if org-treat-insert-todo-heading-as-state-change
  6871. (org-todo new-mark)
  6872. (insert new-mark " "))))
  6873. (when org-provide-todo-statistics
  6874. (org-update-parent-todo-statistics))))
  6875. (defun org-insert-subheading (arg)
  6876. "Insert a new subheading and demote it.
  6877. Works for outline headings and for plain lists alike."
  6878. (interactive "P")
  6879. (org-insert-heading arg)
  6880. (cond
  6881. ((org-at-heading-p) (org-do-demote))
  6882. ((org-at-item-p) (org-indent-item))))
  6883. (defun org-insert-todo-subheading (arg)
  6884. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6885. Works for outline headings and for plain lists alike."
  6886. (interactive "P")
  6887. (org-insert-todo-heading arg)
  6888. (cond
  6889. ((org-at-heading-p) (org-do-demote))
  6890. ((org-at-item-p) (org-indent-item))))
  6891. ;;; Promotion and Demotion
  6892. (defvar org-after-demote-entry-hook nil
  6893. "Hook run after an entry has been demoted.
  6894. The cursor will be at the beginning of the entry.
  6895. When a subtree is being demoted, the hook will be called for each node.")
  6896. (defvar org-after-promote-entry-hook nil
  6897. "Hook run after an entry has been promoted.
  6898. The cursor will be at the beginning of the entry.
  6899. When a subtree is being promoted, the hook will be called for each node.")
  6900. (defun org-promote-subtree ()
  6901. "Promote the entire subtree.
  6902. See also `org-promote'."
  6903. (interactive)
  6904. (save-excursion
  6905. (org-with-limited-levels (org-map-tree 'org-promote)))
  6906. (org-fix-position-after-promote))
  6907. (defun org-demote-subtree ()
  6908. "Demote the entire subtree.
  6909. See `org-demote' and `org-promote'."
  6910. (interactive)
  6911. (save-excursion
  6912. (org-with-limited-levels (org-map-tree 'org-demote)))
  6913. (org-fix-position-after-promote))
  6914. (defun org-do-promote ()
  6915. "Promote the current heading higher up the tree.
  6916. If the region is active in `transient-mark-mode', promote all
  6917. headings in the region."
  6918. (interactive)
  6919. (save-excursion
  6920. (if (org-region-active-p)
  6921. (org-map-region 'org-promote (region-beginning) (region-end))
  6922. (org-promote)))
  6923. (org-fix-position-after-promote))
  6924. (defun org-do-demote ()
  6925. "Demote the current heading lower down the tree.
  6926. If the region is active in `transient-mark-mode', demote all
  6927. headings in the region."
  6928. (interactive)
  6929. (save-excursion
  6930. (if (org-region-active-p)
  6931. (org-map-region 'org-demote (region-beginning) (region-end))
  6932. (org-demote)))
  6933. (org-fix-position-after-promote))
  6934. (defun org-fix-position-after-promote ()
  6935. "Fix cursor position and indentation after demoting/promoting."
  6936. (let ((pos (point)))
  6937. (when (save-excursion
  6938. (beginning-of-line)
  6939. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6940. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6941. (cond ((eobp) (insert " "))
  6942. ((eolp) (insert " "))
  6943. ((equal (char-after) ?\s) (forward-char 1))))))
  6944. (defun org-current-level ()
  6945. "Return the level of the current entry, or nil if before the first headline.
  6946. The level is the number of stars at the beginning of the
  6947. headline. Use `org-reduced-level' to remove the effect of
  6948. `org-odd-levels'. Unlike to `org-outline-level', this function
  6949. ignores inlinetasks."
  6950. (let ((level (org-with-limited-levels (org-outline-level))))
  6951. (and (> level 0) level)))
  6952. (defun org-get-previous-line-level ()
  6953. "Return the outline depth of the last headline before the current line.
  6954. Returns 0 for the first headline in the buffer, and nil if before the
  6955. first headline."
  6956. (and (org-current-level)
  6957. (or (and (/= (line-beginning-position) (point-min))
  6958. (save-excursion (beginning-of-line 0) (org-current-level)))
  6959. 0)))
  6960. (defun org-reduced-level (l)
  6961. "Compute the effective level of a heading.
  6962. This takes into account the setting of `org-odd-levels-only'."
  6963. (cond
  6964. ((zerop l) 0)
  6965. (org-odd-levels-only (1+ (floor (/ l 2))))
  6966. (t l)))
  6967. (defun org-level-increment ()
  6968. "Return the number of stars that will be added or removed at a
  6969. time to headlines when structure editing, based on the value of
  6970. `org-odd-levels-only'."
  6971. (if org-odd-levels-only 2 1))
  6972. (defun org-get-valid-level (level &optional change)
  6973. "Rectify a level change under the influence of `org-odd-levels-only'.
  6974. LEVEL is a current level, CHANGE is by how much the level should
  6975. be modified. Even if CHANGE is nil, LEVEL may be returned
  6976. modified because even level numbers will become the next higher
  6977. odd number. Returns values greater than 0."
  6978. (if org-odd-levels-only
  6979. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6980. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6981. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6982. (max 1 (+ level (or change 0)))))
  6983. (defun org-promote ()
  6984. "Promote the current heading higher up the tree."
  6985. (org-with-wide-buffer
  6986. (org-back-to-heading t)
  6987. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6988. after-change-functions))
  6989. (level (save-match-data (funcall outline-level)))
  6990. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6991. (diff (abs (- level (length up-head) -1))))
  6992. (cond
  6993. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6994. (replace-match "# " nil t))
  6995. ((= level 1)
  6996. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6997. (t (replace-match up-head nil t)))
  6998. (unless (= level 1)
  6999. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7000. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7001. (run-hooks 'org-after-promote-entry-hook))))
  7002. (defun org-demote ()
  7003. "Demote the current heading lower down the tree."
  7004. (org-with-wide-buffer
  7005. (org-back-to-heading t)
  7006. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7007. after-change-functions))
  7008. (level (save-match-data (funcall outline-level)))
  7009. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7010. (diff (abs (- level (length down-head) -1))))
  7011. (replace-match down-head nil t)
  7012. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7013. (when org-adapt-indentation (org-fixup-indentation diff))
  7014. (run-hooks 'org-after-demote-entry-hook))))
  7015. (defun org-cycle-level ()
  7016. "Cycle the level of an empty headline through possible states.
  7017. This goes first to child, then to parent, level, then up the hierarchy.
  7018. After top level, it switches back to sibling level."
  7019. (interactive)
  7020. (let ((org-adapt-indentation nil))
  7021. (when (org-point-at-end-of-empty-headline)
  7022. (setq this-command 'org-cycle-level) ; Only needed for caching
  7023. (let ((cur-level (org-current-level))
  7024. (prev-level (org-get-previous-line-level)))
  7025. (cond
  7026. ;; If first headline in file, promote to top-level.
  7027. ((= prev-level 0)
  7028. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7029. do (org-do-promote)))
  7030. ;; If same level as prev, demote one.
  7031. ((= prev-level cur-level)
  7032. (org-do-demote))
  7033. ;; If parent is top-level, promote to top level if not already.
  7034. ((= prev-level 1)
  7035. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7036. do (org-do-promote)))
  7037. ;; If top-level, return to prev-level.
  7038. ((= cur-level 1)
  7039. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7040. do (org-do-demote)))
  7041. ;; If less than prev-level, promote one.
  7042. ((< cur-level prev-level)
  7043. (org-do-promote))
  7044. ;; If deeper than prev-level, promote until higher than
  7045. ;; prev-level.
  7046. ((> cur-level prev-level)
  7047. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7048. do (org-do-promote))))
  7049. t))))
  7050. (defun org-map-tree (fun)
  7051. "Call FUN for every heading underneath the current one."
  7052. (org-back-to-heading t)
  7053. (let ((level (funcall outline-level)))
  7054. (save-excursion
  7055. (funcall fun)
  7056. (while (and (progn
  7057. (outline-next-heading)
  7058. (> (funcall outline-level) level))
  7059. (not (eobp)))
  7060. (funcall fun)))))
  7061. (defun org-map-region (fun beg end)
  7062. "Call FUN for every heading between BEG and END."
  7063. (let ((org-ignore-region t))
  7064. (save-excursion
  7065. (setq end (copy-marker end))
  7066. (goto-char beg)
  7067. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7068. (< (point) end))
  7069. (funcall fun))
  7070. (while (and (progn
  7071. (outline-next-heading)
  7072. (< (point) end))
  7073. (not (eobp)))
  7074. (funcall fun)))))
  7075. (defun org-fixup-indentation (diff)
  7076. "Change the indentation in the current entry by DIFF.
  7077. DIFF is an integer. Indentation is done according to the
  7078. following rules:
  7079. - Planning information and property drawers are always indented
  7080. according to the new level of the headline;
  7081. - Footnote definitions and their contents are ignored;
  7082. - Inlinetasks' boundaries are not shifted;
  7083. - Empty lines are ignored;
  7084. - Other lines' indentation are shifted by DIFF columns, unless
  7085. it would introduce a structural change in the document, in
  7086. which case no shifting is done at all.
  7087. Assume point is at a heading or an inlinetask beginning."
  7088. (org-with-wide-buffer
  7089. (narrow-to-region (line-beginning-position)
  7090. (save-excursion
  7091. (if (org-with-limited-levels (org-at-heading-p))
  7092. (org-with-limited-levels (outline-next-heading))
  7093. (org-inlinetask-goto-end))
  7094. (point)))
  7095. (forward-line)
  7096. ;; Indent properly planning info and property drawer.
  7097. (when (looking-at-p org-planning-line-re)
  7098. (org-indent-line)
  7099. (forward-line))
  7100. (when (looking-at org-property-drawer-re)
  7101. (goto-char (match-end 0))
  7102. (forward-line)
  7103. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7104. (catch 'no-shift
  7105. (when (zerop diff) (throw 'no-shift nil))
  7106. ;; If DIFF is negative, first check if a shift is possible at all
  7107. ;; (e.g., it doesn't break structure). This can only happen if
  7108. ;; some contents are not properly indented.
  7109. (let ((case-fold-search t))
  7110. (when (< diff 0)
  7111. (let ((diff (- diff))
  7112. (forbidden-re (concat org-outline-regexp
  7113. "\\|"
  7114. (substring org-footnote-definition-re 1))))
  7115. (save-excursion
  7116. (while (not (eobp))
  7117. (cond
  7118. ((looking-at-p "[ \t]*$") (forward-line))
  7119. ((and (looking-at-p org-footnote-definition-re)
  7120. (let ((e (org-element-at-point)))
  7121. (and (eq (org-element-type e) 'footnote-definition)
  7122. (goto-char (org-element-property :end e))))))
  7123. ((looking-at-p org-outline-regexp) (forward-line))
  7124. ;; Give up if shifting would move before column 0 or
  7125. ;; if it would introduce a headline or a footnote
  7126. ;; definition.
  7127. (t
  7128. (skip-chars-forward " \t")
  7129. (let ((ind (current-column)))
  7130. (when (or (< ind diff)
  7131. (and (= ind diff) (looking-at-p forbidden-re)))
  7132. (throw 'no-shift nil)))
  7133. ;; Ignore contents of example blocks and source
  7134. ;; blocks if their indentation is meant to be
  7135. ;; preserved. Jump to block's closing line.
  7136. (beginning-of-line)
  7137. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7138. (let ((e (org-element-at-point)))
  7139. (and (memq (org-element-type e)
  7140. '(example-block src-block))
  7141. (or org-src-preserve-indentation
  7142. (org-element-property :preserve-indent e))
  7143. (goto-char (org-element-property :end e))
  7144. (progn (skip-chars-backward " \r\t\n")
  7145. (beginning-of-line)
  7146. t))))
  7147. (forward-line))))))))
  7148. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7149. ;; by DIFF. Also skip contents of source or example blocks
  7150. ;; when indentation is meant to be preserved.
  7151. (while (not (eobp))
  7152. (cond
  7153. ((and (looking-at-p org-footnote-definition-re)
  7154. (let ((e (org-element-at-point)))
  7155. (and (eq (org-element-type e) 'footnote-definition)
  7156. (goto-char (org-element-property :end e))))))
  7157. ((looking-at-p org-outline-regexp) (forward-line))
  7158. ((looking-at-p "[ \t]*$") (forward-line))
  7159. (t
  7160. (indent-line-to (+ (org-get-indentation) diff))
  7161. (beginning-of-line)
  7162. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7163. (let ((e (org-element-at-point)))
  7164. (and (memq (org-element-type e)
  7165. '(example-block src-block))
  7166. (or org-src-preserve-indentation
  7167. (org-element-property :preserve-indent e))
  7168. (goto-char (org-element-property :end e))
  7169. (progn (skip-chars-backward " \r\t\n")
  7170. (beginning-of-line)
  7171. t))))
  7172. (forward-line)))))))))
  7173. (defun org-convert-to-odd-levels ()
  7174. "Convert an Org file with all levels allowed to one with odd levels.
  7175. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7176. level 5 etc."
  7177. (interactive)
  7178. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7179. (let ((outline-level 'org-outline-level)
  7180. (org-odd-levels-only nil) n)
  7181. (save-excursion
  7182. (goto-char (point-min))
  7183. (while (re-search-forward "^\\*\\*+ " nil t)
  7184. (setq n (- (length (match-string 0)) 2))
  7185. (while (>= (setq n (1- n)) 0)
  7186. (org-demote))
  7187. (end-of-line 1))))))
  7188. (defun org-convert-to-oddeven-levels ()
  7189. "Convert an Org file with only odd levels to one with odd/even levels.
  7190. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7191. file contains a section with an even level, conversion would
  7192. destroy the structure of the file. An error is signaled in this
  7193. case."
  7194. (interactive)
  7195. (goto-char (point-min))
  7196. ;; First check if there are no even levels
  7197. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7198. (org-show-set-visibility 'canonical)
  7199. (error "Not all levels are odd in this file. Conversion not possible"))
  7200. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7201. (let ((outline-regexp org-outline-regexp)
  7202. (outline-level 'org-outline-level)
  7203. (org-odd-levels-only nil) n)
  7204. (save-excursion
  7205. (goto-char (point-min))
  7206. (while (re-search-forward "^\\*\\*+ " nil t)
  7207. (setq n (/ (1- (length (match-string 0))) 2))
  7208. (while (>= (setq n (1- n)) 0)
  7209. (org-promote))
  7210. (end-of-line 1))))))
  7211. (defun org-tr-level (n)
  7212. "Make N odd if required."
  7213. (if org-odd-levels-only (1+ (/ n 2)) n))
  7214. ;;; Vertical tree motion, cutting and pasting of subtrees
  7215. (defun org-move-subtree-up (&optional arg)
  7216. "Move the current subtree up past ARG headlines of the same level."
  7217. (interactive "p")
  7218. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7219. (defun org-move-subtree-down (&optional arg)
  7220. "Move the current subtree down past ARG headlines of the same level."
  7221. (interactive "p")
  7222. (setq arg (prefix-numeric-value arg))
  7223. (org-preserve-local-variables
  7224. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7225. 'org-get-last-sibling))
  7226. (ins-point (make-marker))
  7227. (cnt (abs arg))
  7228. (col (current-column))
  7229. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7230. ;; Select the tree
  7231. (org-back-to-heading)
  7232. (setq beg0 (point))
  7233. (save-excursion
  7234. (setq ne-beg (org-back-over-empty-lines))
  7235. (setq beg (point)))
  7236. (save-match-data
  7237. (save-excursion (outline-end-of-heading)
  7238. (setq folded (org-invisible-p)))
  7239. (progn (org-end-of-subtree nil t)
  7240. (unless (eobp) (backward-char))))
  7241. (outline-next-heading)
  7242. (setq ne-end (org-back-over-empty-lines))
  7243. (setq end (point))
  7244. (goto-char beg0)
  7245. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7246. ;; include less whitespace
  7247. (save-excursion
  7248. (goto-char beg)
  7249. (forward-line (- ne-beg ne-end))
  7250. (setq beg (point))))
  7251. ;; Find insertion point, with error handling
  7252. (while (> cnt 0)
  7253. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7254. (goto-char beg0)
  7255. (user-error "Cannot move past superior level or buffer limit"))
  7256. (setq cnt (1- cnt)))
  7257. (when (> arg 0)
  7258. ;; Moving forward - still need to move over subtree
  7259. (org-end-of-subtree t t)
  7260. (save-excursion
  7261. (org-back-over-empty-lines)
  7262. (or (bolp) (newline))))
  7263. (setq ne-ins (org-back-over-empty-lines))
  7264. (move-marker ins-point (point))
  7265. (setq txt (buffer-substring beg end))
  7266. (org-save-markers-in-region beg end)
  7267. (delete-region beg end)
  7268. (org-remove-empty-overlays-at beg)
  7269. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7270. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7271. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7272. (let ((bbb (point)))
  7273. (insert-before-markers txt)
  7274. (org-reinstall-markers-in-region bbb)
  7275. (move-marker ins-point bbb))
  7276. (or (bolp) (insert "\n"))
  7277. (setq ins-end (point))
  7278. (goto-char ins-point)
  7279. (org-skip-whitespace)
  7280. (when (and (< arg 0)
  7281. (org-first-sibling-p)
  7282. (> ne-ins ne-beg))
  7283. ;; Move whitespace back to beginning
  7284. (save-excursion
  7285. (goto-char ins-end)
  7286. (let ((kill-whole-line t))
  7287. (kill-line (- ne-ins ne-beg)) (point)))
  7288. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7289. (move-marker ins-point nil)
  7290. (if folded
  7291. (outline-hide-subtree)
  7292. (org-show-entry)
  7293. (org-show-children))
  7294. (org-clean-visibility-after-subtree-move)
  7295. ;; move back to the initial column we were at
  7296. (move-to-column col))))
  7297. (defvar org-subtree-clip ""
  7298. "Clipboard for cut and paste of subtrees.
  7299. This is actually only a copy of the kill, because we use the normal kill
  7300. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7301. (defvar org-subtree-clip-folded nil
  7302. "Was the last copied subtree folded?
  7303. This is used to fold the tree back after pasting.")
  7304. (defun org-cut-subtree (&optional n)
  7305. "Cut the current subtree into the clipboard.
  7306. With prefix arg N, cut this many sequential subtrees.
  7307. This is a short-hand for marking the subtree and then cutting it."
  7308. (interactive "p")
  7309. (org-copy-subtree n 'cut))
  7310. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7311. "Copy the current subtree into the clipboard.
  7312. With prefix arg N, copy this many sequential subtrees.
  7313. This is a short-hand for marking the subtree and then copying it.
  7314. If CUT is non-nil, actually cut the subtree.
  7315. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7316. of some markers in the region, even if CUT is non-nil. This is
  7317. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7318. (interactive "p")
  7319. (org-preserve-local-variables
  7320. (let (beg end folded (beg0 (point)))
  7321. (if (called-interactively-p 'any)
  7322. (org-back-to-heading nil) ; take what looks like a subtree
  7323. (org-back-to-heading t)) ; take what is really there
  7324. (setq beg (point))
  7325. (skip-chars-forward " \t\r\n")
  7326. (save-match-data
  7327. (if nosubtrees
  7328. (outline-next-heading)
  7329. (save-excursion (outline-end-of-heading)
  7330. (setq folded (org-invisible-p)))
  7331. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7332. (org-end-of-subtree t t)))
  7333. ;; Include the end of an inlinetask
  7334. (when (and (featurep 'org-inlinetask)
  7335. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7336. "END[ \t]*$")))
  7337. (end-of-line))
  7338. (setq end (point))
  7339. (goto-char beg0)
  7340. (when (> end beg)
  7341. (setq org-subtree-clip-folded folded)
  7342. (when (or cut force-store-markers)
  7343. (org-save-markers-in-region beg end))
  7344. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7345. (setq org-subtree-clip (current-kill 0))
  7346. (message "%s: Subtree(s) with %d characters"
  7347. (if cut "Cut" "Copied")
  7348. (length org-subtree-clip))))))
  7349. (defun org-paste-subtree (&optional level tree for-yank remove)
  7350. "Paste the clipboard as a subtree, with modification of headline level.
  7351. The entire subtree is promoted or demoted in order to match a new headline
  7352. level.
  7353. If the cursor is at the beginning of a headline, the same level as
  7354. that headline is used to paste the tree.
  7355. If not, the new level is derived from the *visible* headings
  7356. before and after the insertion point, and taken to be the inferior headline
  7357. level of the two. So if the previous visible heading is level 3 and the
  7358. next is level 4 (or vice versa), level 4 will be used for insertion.
  7359. This makes sure that the subtree remains an independent subtree and does
  7360. not swallow low level entries.
  7361. You can also force a different level, either by using a numeric prefix
  7362. argument, or by inserting the heading marker by hand. For example, if the
  7363. cursor is after \"*****\", then the tree will be shifted to level 5.
  7364. If optional TREE is given, use this text instead of the kill ring.
  7365. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7366. move back over whitespace before inserting, and move point to the end of
  7367. the inserted text when done.
  7368. When REMOVE is non-nil, remove the subtree from the clipboard."
  7369. (interactive "P")
  7370. (setq tree (or tree (and kill-ring (current-kill 0))))
  7371. (unless (org-kill-is-subtree-p tree)
  7372. (user-error "%s"
  7373. (substitute-command-keys
  7374. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7375. (org-with-limited-levels
  7376. (let* ((visp (not (org-invisible-p)))
  7377. (txt tree)
  7378. (^re_ "\\(\\*+\\)[ \t]*")
  7379. (old-level (if (string-match org-outline-regexp-bol txt)
  7380. (- (match-end 0) (match-beginning 0) 1)
  7381. -1))
  7382. (force-level (cond (level (prefix-numeric-value level))
  7383. ((and (looking-at "[ \t]*$")
  7384. (string-match
  7385. "^\\*+$" (buffer-substring
  7386. (point-at-bol) (point))))
  7387. (- (match-end 0) (match-beginning 0)))
  7388. ((and (bolp)
  7389. (looking-at org-outline-regexp))
  7390. (- (match-end 0) (point) 1))))
  7391. (previous-level (save-excursion
  7392. (condition-case nil
  7393. (progn
  7394. (outline-previous-visible-heading 1)
  7395. (if (looking-at ^re_)
  7396. (- (match-end 0) (match-beginning 0) 1)
  7397. 1))
  7398. (error 1))))
  7399. (next-level (save-excursion
  7400. (condition-case nil
  7401. (progn
  7402. (or (looking-at org-outline-regexp)
  7403. (outline-next-visible-heading 1))
  7404. (if (looking-at ^re_)
  7405. (- (match-end 0) (match-beginning 0) 1)
  7406. 1))
  7407. (error 1))))
  7408. (new-level (or force-level (max previous-level next-level)))
  7409. (shift (if (or (= old-level -1)
  7410. (= new-level -1)
  7411. (= old-level new-level))
  7412. 0
  7413. (- new-level old-level)))
  7414. (delta (if (> shift 0) -1 1))
  7415. (func (if (> shift 0) 'org-demote 'org-promote))
  7416. (org-odd-levels-only nil)
  7417. beg end newend)
  7418. ;; Remove the forced level indicator
  7419. (when force-level
  7420. (delete-region (point-at-bol) (point)))
  7421. ;; Paste
  7422. (beginning-of-line (if (bolp) 1 2))
  7423. (setq beg (point))
  7424. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7425. (insert-before-markers txt)
  7426. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7427. (setq newend (point))
  7428. (org-reinstall-markers-in-region beg)
  7429. (setq end (point))
  7430. (goto-char beg)
  7431. (skip-chars-forward " \t\n\r")
  7432. (setq beg (point))
  7433. (when (and (org-invisible-p) visp)
  7434. (save-excursion (outline-show-heading)))
  7435. ;; Shift if necessary
  7436. (unless (= shift 0)
  7437. (save-restriction
  7438. (narrow-to-region beg end)
  7439. (while (not (= shift 0))
  7440. (org-map-region func (point-min) (point-max))
  7441. (setq shift (+ delta shift)))
  7442. (goto-char (point-min))
  7443. (setq newend (point-max))))
  7444. (when (or (called-interactively-p 'interactive) for-yank)
  7445. (message "Clipboard pasted as level %d subtree" new-level))
  7446. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7447. kill-ring
  7448. (eq org-subtree-clip (current-kill 0))
  7449. org-subtree-clip-folded)
  7450. ;; The tree was folded before it was killed/copied
  7451. (outline-hide-subtree))
  7452. (and for-yank (goto-char newend))
  7453. (and remove (setq kill-ring (cdr kill-ring))))))
  7454. (defun org-kill-is-subtree-p (&optional txt)
  7455. "Check if the current kill is an outline subtree, or a set of trees.
  7456. Returns nil if kill does not start with a headline, or if the first
  7457. headline level is not the largest headline level in the tree.
  7458. So this will actually accept several entries of equal levels as well,
  7459. which is OK for `org-paste-subtree'.
  7460. If optional TXT is given, check this string instead of the current kill."
  7461. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7462. (re (org-get-limited-outline-regexp))
  7463. (^re (concat "^" re))
  7464. (start-level (and kill
  7465. (string-match
  7466. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7467. kill)
  7468. (- (match-end 2) (match-beginning 2) 1)))
  7469. (start (1+ (or (match-beginning 2) -1))))
  7470. (if (not start-level)
  7471. (progn
  7472. nil) ;; does not even start with a heading
  7473. (catch 'exit
  7474. (while (setq start (string-match ^re kill (1+ start)))
  7475. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7476. (throw 'exit nil)))
  7477. t))))
  7478. (defvar org-markers-to-move nil
  7479. "Markers that should be moved with a cut-and-paste operation.
  7480. Those markers are stored together with their positions relative to
  7481. the start of the region.")
  7482. (defun org-save-markers-in-region (beg end)
  7483. "Check markers in region.
  7484. If these markers are between BEG and END, record their position relative
  7485. to BEG, so that after moving the block of text, we can put the markers back
  7486. into place.
  7487. This function gets called just before an entry or tree gets cut from the
  7488. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7489. called immediately, to move the markers with the entries."
  7490. (setq org-markers-to-move nil)
  7491. (when (featurep 'org-clock)
  7492. (org-clock-save-markers-for-cut-and-paste beg end))
  7493. (when (featurep 'org-agenda)
  7494. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7495. (defun org-check-and-save-marker (marker beg end)
  7496. "Check if MARKER is between BEG and END.
  7497. If yes, remember the marker and the distance to BEG."
  7498. (when (and (marker-buffer marker)
  7499. (equal (marker-buffer marker) (current-buffer))
  7500. (>= marker beg) (< marker end))
  7501. (push (cons marker (- marker beg)) org-markers-to-move)))
  7502. (defun org-reinstall-markers-in-region (beg)
  7503. "Move all remembered markers to their position relative to BEG."
  7504. (dolist (x org-markers-to-move)
  7505. (move-marker (car x) (+ beg (cdr x))))
  7506. (setq org-markers-to-move nil))
  7507. (defun org-narrow-to-subtree ()
  7508. "Narrow buffer to the current subtree."
  7509. (interactive)
  7510. (save-excursion
  7511. (save-match-data
  7512. (org-with-limited-levels
  7513. (narrow-to-region
  7514. (progn (org-back-to-heading t) (point))
  7515. (progn (org-end-of-subtree t t)
  7516. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7517. (point)))))))
  7518. (defun org-narrow-to-block ()
  7519. "Narrow buffer to the current block."
  7520. (interactive)
  7521. (let* ((case-fold-search t)
  7522. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7523. "^[ \t]*#\\+end_.*")))
  7524. (if blockp
  7525. (narrow-to-region (car blockp) (cdr blockp))
  7526. (user-error "Not in a block"))))
  7527. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7528. "Clone the task (subtree) at point N times.
  7529. The clones will be inserted as siblings.
  7530. In interactive use, the user will be prompted for the number of
  7531. clones to be produced. If the entry has a timestamp, the user
  7532. will also be prompted for a time shift, which may be a repeater
  7533. as used in time stamps, for example `+3d'. To disable this,
  7534. you can call the function with a universal prefix argument.
  7535. When a valid repeater is given and the entry contains any time
  7536. stamps, the clones will become a sequence in time, with time
  7537. stamps in the subtree shifted for each clone produced. If SHIFT
  7538. is nil or the empty string, time stamps will be left alone. The
  7539. ID property of the original subtree is removed.
  7540. In each clone, all the CLOCK entries will be removed. This
  7541. prevents Org from considering that the clocked times overlap.
  7542. If the original subtree did contain time stamps with a repeater,
  7543. the following will happen:
  7544. - the repeater will be removed in each clone
  7545. - an additional clone will be produced, with the current, unshifted
  7546. date(s) in the entry.
  7547. - the original entry will be placed *after* all the clones, with
  7548. repeater intact.
  7549. - the start days in the repeater in the original entry will be shifted
  7550. to past the last clone.
  7551. In this way you can spell out a number of instances of a repeating task,
  7552. and still retain the repeater to cover future instances of the task.
  7553. As described above, N+1 clones are produced when the original
  7554. subtree has a repeater. Setting N to 0, then, can be used to
  7555. remove the repeater from a subtree and create a shifted clone
  7556. with the original repeater."
  7557. (interactive "nNumber of clones to produce: ")
  7558. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7559. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7560. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7561. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7562. (shift
  7563. (or shift
  7564. (if (and (not (equal current-prefix-arg '(4)))
  7565. (save-excursion
  7566. (goto-char beg)
  7567. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7568. (read-from-minibuffer
  7569. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7570. ""))) ;No time shift
  7571. (doshift
  7572. (and (org-string-nw-p shift)
  7573. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7574. shift)
  7575. (user-error "Invalid shift specification %s" shift)))))
  7576. (goto-char end-of-tree)
  7577. (unless (bolp) (insert "\n"))
  7578. (let* ((end (point))
  7579. (template (buffer-substring beg end))
  7580. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7581. (shift-what (pcase (and doshift (match-string 2 shift))
  7582. (`nil nil)
  7583. ("d" 'day)
  7584. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7585. ("m" 'month)
  7586. ("y" 'year)
  7587. (_ (error "Unsupported time unit"))))
  7588. (nmin 1)
  7589. (nmax n)
  7590. (n-no-remove -1)
  7591. (idprop (org-entry-get nil "ID")))
  7592. (when (and doshift
  7593. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7594. template))
  7595. (delete-region beg end)
  7596. (setq end beg)
  7597. (setq nmin 0)
  7598. (setq nmax (1+ nmax))
  7599. (setq n-no-remove nmax))
  7600. (goto-char end)
  7601. (cl-loop for n from nmin to nmax do
  7602. (insert
  7603. ;; Prepare clone.
  7604. (with-temp-buffer
  7605. (insert template)
  7606. (org-mode)
  7607. (goto-char (point-min))
  7608. (org-show-subtree)
  7609. (and idprop (if org-clone-delete-id
  7610. (org-entry-delete nil "ID")
  7611. (org-id-get-create t)))
  7612. (unless (= n 0)
  7613. (while (re-search-forward org-clock-line-re nil t)
  7614. (delete-region (line-beginning-position)
  7615. (line-beginning-position 2)))
  7616. (goto-char (point-min))
  7617. (while (re-search-forward org-drawer-regexp nil t)
  7618. (org-remove-empty-drawer-at (point))))
  7619. (goto-char (point-min))
  7620. (when doshift
  7621. (while (re-search-forward org-ts-regexp-both nil t)
  7622. (org-timestamp-change (* n shift-n) shift-what))
  7623. (unless (= n n-no-remove)
  7624. (goto-char (point-min))
  7625. (while (re-search-forward org-ts-regexp nil t)
  7626. (save-excursion
  7627. (goto-char (match-beginning 0))
  7628. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7629. (delete-region (match-beginning 1) (match-end 1)))))))
  7630. (buffer-string)))))
  7631. (goto-char beg)))
  7632. ;;; Outline Sorting
  7633. (defun org-sort (&optional with-case)
  7634. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7635. Optional argument WITH-CASE means sort case-sensitively."
  7636. (interactive "P")
  7637. (org-call-with-arg
  7638. (cond ((org-at-table-p) #'org-table-sort-lines)
  7639. ((org-at-item-p) #'org-sort-list)
  7640. (t #'org-sort-entries))
  7641. with-case))
  7642. (defun org-sort-remove-invisible (s)
  7643. "Remove invisible part of links and emphasis markers from string S."
  7644. (remove-text-properties 0 (length s) org-rm-props s)
  7645. (replace-regexp-in-string
  7646. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7647. (replace-regexp-in-string
  7648. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7649. (org-link-display-format s)
  7650. t t) t t))
  7651. (defvar org-priority-regexp) ; defined later in the file
  7652. (defvar org-after-sorting-entries-or-items-hook nil
  7653. "Hook that is run after a bunch of entries or items have been sorted.
  7654. When children are sorted, the cursor is in the parent line when this
  7655. hook gets called. When a region or a plain list is sorted, the cursor
  7656. will be in the first entry of the sorted region/list.")
  7657. (defun org-sort-entries
  7658. (&optional with-case sorting-type getkey-func compare-func property
  7659. interactive?)
  7660. "Sort entries on a certain level of an outline tree.
  7661. If there is an active region, the entries in the region are sorted.
  7662. Else, if the cursor is before the first entry, sort the top-level items.
  7663. Else, the children of the entry at point are sorted.
  7664. Sorting can be alphabetically, numerically, by date/time as given by
  7665. a time stamp, by a property, by priority order, or by a custom function.
  7666. The command prompts for the sorting type unless it has been given to the
  7667. function through the SORTING-TYPE argument, which needs to be a character,
  7668. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7669. the precise meaning of each character:
  7670. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7671. c By creation time, which is assumed to be the first inactive time stamp
  7672. at the beginning of a line.
  7673. d By deadline date/time.
  7674. k By clocking time.
  7675. n Numerically, by converting the beginning of the entry/item to a number.
  7676. o By order of TODO keywords.
  7677. p By priority according to the cookie.
  7678. r By the value of a property.
  7679. s By scheduled date/time.
  7680. t By date/time, either the first active time stamp in the entry, or, if
  7681. none exist, by the first inactive one.
  7682. Capital letters will reverse the sort order.
  7683. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7684. called with point at the beginning of the record. It must return a
  7685. value that is compatible with COMPARE-FUNC, the function used to
  7686. compare entries.
  7687. Comparing entries ignores case by default. However, with an optional argument
  7688. WITH-CASE, the sorting considers case as well.
  7689. Sorting is done against the visible part of the headlines, it ignores hidden
  7690. links.
  7691. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7692. A non-nil value for INTERACTIVE? is used to signal that this
  7693. function is being called interactively."
  7694. (interactive (list current-prefix-arg nil nil nil nil t))
  7695. (let ((case-func (if with-case 'identity 'downcase))
  7696. start beg end stars re re2
  7697. txt what tmp)
  7698. ;; Find beginning and end of region to sort
  7699. (cond
  7700. ((org-region-active-p)
  7701. ;; we will sort the region
  7702. (setq end (region-end)
  7703. what "region")
  7704. (goto-char (region-beginning))
  7705. (unless (org-at-heading-p) (outline-next-heading))
  7706. (setq start (point)))
  7707. ((or (org-at-heading-p)
  7708. (ignore-errors (progn (org-back-to-heading) t)))
  7709. ;; we will sort the children of the current headline
  7710. (org-back-to-heading)
  7711. (setq start (point)
  7712. end (progn (org-end-of-subtree t t)
  7713. (or (bolp) (insert "\n"))
  7714. (when (>= (org-back-over-empty-lines) 1)
  7715. (forward-line 1))
  7716. (point))
  7717. what "children")
  7718. (goto-char start)
  7719. (outline-show-subtree)
  7720. (outline-next-heading))
  7721. (t
  7722. ;; we will sort the top-level entries in this file
  7723. (goto-char (point-min))
  7724. (or (org-at-heading-p) (outline-next-heading))
  7725. (setq start (point))
  7726. (goto-char (point-max))
  7727. (beginning-of-line 1)
  7728. (when (looking-at ".*?\\S-")
  7729. ;; File ends in a non-white line
  7730. (end-of-line 1)
  7731. (insert "\n"))
  7732. (setq end (point-max))
  7733. (setq what "top-level")
  7734. (goto-char start)
  7735. (org-show-all '(headings blocks))))
  7736. (setq beg (point))
  7737. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7738. (looking-at "\\(\\*+\\)")
  7739. (setq stars (match-string 1)
  7740. re (concat "^" (regexp-quote stars) " +")
  7741. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7742. txt (buffer-substring beg end))
  7743. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7744. (when (and (not (equal stars "*")) (string-match re2 txt))
  7745. (user-error "Region to sort contains a level above the first entry"))
  7746. (unless sorting-type
  7747. (message
  7748. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7749. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7750. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7751. what)
  7752. (setq sorting-type (read-char-exclusive)))
  7753. (unless getkey-func
  7754. (and (= (downcase sorting-type) ?f)
  7755. (setq getkey-func
  7756. (or (and interactive?
  7757. (org-read-function
  7758. "Function for extracting keys: "))
  7759. (error "Missing key extractor")))))
  7760. (and (= (downcase sorting-type) ?r)
  7761. (not property)
  7762. (setq property
  7763. (completing-read "Property: "
  7764. (mapcar #'list (org-buffer-property-keys t))
  7765. nil t)))
  7766. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7767. (message "Sorting entries...")
  7768. (save-restriction
  7769. (narrow-to-region start end)
  7770. (let ((restore-clock?
  7771. ;; The clock marker is lost when using `sort-subr'; mark
  7772. ;; the clock with temporary `:org-clock-marker-backup'
  7773. ;; text property.
  7774. (when (and (eq (org-clock-is-active) (current-buffer))
  7775. (<= start (marker-position org-clock-marker))
  7776. (>= end (marker-position org-clock-marker)))
  7777. (org-with-silent-modifications
  7778. (put-text-property (1- org-clock-marker) org-clock-marker
  7779. :org-clock-marker-backup t))
  7780. t))
  7781. (dcst (downcase sorting-type))
  7782. (case-fold-search nil)
  7783. (now (current-time)))
  7784. (org-preserve-local-variables
  7785. (sort-subr
  7786. (/= dcst sorting-type)
  7787. ;; This function moves to the beginning character of the
  7788. ;; "record" to be sorted.
  7789. (lambda nil
  7790. (if (re-search-forward re nil t)
  7791. (goto-char (match-beginning 0))
  7792. (goto-char (point-max))))
  7793. ;; This function moves to the last character of the "record" being
  7794. ;; sorted.
  7795. (lambda nil
  7796. (save-match-data
  7797. (condition-case nil
  7798. (outline-forward-same-level 1)
  7799. (error
  7800. (goto-char (point-max))))))
  7801. ;; This function returns the value that gets sorted against.
  7802. (lambda ()
  7803. (cond
  7804. ((= dcst ?n)
  7805. (if (looking-at org-complex-heading-regexp)
  7806. (string-to-number
  7807. (org-sort-remove-invisible (match-string 4)))
  7808. nil))
  7809. ((= dcst ?a)
  7810. (if (looking-at org-complex-heading-regexp)
  7811. (funcall case-func
  7812. (org-sort-remove-invisible (match-string 4)))
  7813. nil))
  7814. ((= dcst ?k)
  7815. (or (get-text-property (point) :org-clock-minutes) 0))
  7816. ((= dcst ?t)
  7817. (let ((end (save-excursion (outline-next-heading) (point))))
  7818. (if (or (re-search-forward org-ts-regexp end t)
  7819. (re-search-forward org-ts-regexp-both end t))
  7820. (org-time-string-to-seconds (match-string 0))
  7821. (float-time now))))
  7822. ((= dcst ?c)
  7823. (let ((end (save-excursion (outline-next-heading) (point))))
  7824. (if (re-search-forward
  7825. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7826. end t)
  7827. (org-time-string-to-seconds (match-string 0))
  7828. (float-time now))))
  7829. ((= dcst ?s)
  7830. (let ((end (save-excursion (outline-next-heading) (point))))
  7831. (if (re-search-forward org-scheduled-time-regexp end t)
  7832. (org-time-string-to-seconds (match-string 1))
  7833. (float-time now))))
  7834. ((= dcst ?d)
  7835. (let ((end (save-excursion (outline-next-heading) (point))))
  7836. (if (re-search-forward org-deadline-time-regexp end t)
  7837. (org-time-string-to-seconds (match-string 1))
  7838. (float-time now))))
  7839. ((= dcst ?p)
  7840. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7841. (string-to-char (match-string 2))
  7842. org-default-priority))
  7843. ((= dcst ?r)
  7844. (or (org-entry-get nil property) ""))
  7845. ((= dcst ?o)
  7846. (when (looking-at org-complex-heading-regexp)
  7847. (let* ((m (match-string 2))
  7848. (s (if (member m org-done-keywords) '- '+)))
  7849. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7850. ((= dcst ?f)
  7851. (if getkey-func
  7852. (progn
  7853. (setq tmp (funcall getkey-func))
  7854. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7855. tmp)
  7856. (error "Invalid key function `%s'" getkey-func)))
  7857. (t (error "Invalid sorting type `%c'" sorting-type))))
  7858. nil
  7859. (cond
  7860. ((= dcst ?a) 'string<)
  7861. ((= dcst ?f)
  7862. (or compare-func
  7863. (and interactive?
  7864. (org-read-function
  7865. (concat "Function for comparing keys "
  7866. "(empty for default `sort-subr' predicate): ")
  7867. 'allow-empty))))
  7868. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7869. (when restore-clock?
  7870. (move-marker org-clock-marker
  7871. (1+ (next-single-property-change
  7872. start :org-clock-marker-backup)))
  7873. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7874. '(:org-clock-marker-backup t)))))
  7875. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7876. (message "Sorting entries...done")))
  7877. (defun org-contextualize-keys (alist contexts)
  7878. "Return valid elements in ALIST depending on CONTEXTS.
  7879. `org-agenda-custom-commands' or `org-capture-templates' are the
  7880. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7881. or `org-capture-templates-contexts' are the associated contexts
  7882. definitions."
  7883. (let ((contexts
  7884. ;; normalize contexts
  7885. (mapcar
  7886. (lambda(c) (cond ((listp (cadr c))
  7887. (list (car c) (car c) (nth 1 c)))
  7888. ((string= "" (cadr c))
  7889. (list (car c) (car c) (nth 2 c)))
  7890. (t c)))
  7891. contexts))
  7892. (a alist) r s)
  7893. ;; loop over all commands or templates
  7894. (dolist (c a)
  7895. (let (vrules repl)
  7896. (cond
  7897. ((not (assoc (car c) contexts))
  7898. (push c r))
  7899. ((and (assoc (car c) contexts)
  7900. (setq vrules (org-contextualize-validate-key
  7901. (car c) contexts)))
  7902. (mapc (lambda (vr)
  7903. (unless (equal (car vr) (cadr vr))
  7904. (setq repl vr)))
  7905. vrules)
  7906. (if (not repl) (push c r)
  7907. (push (cadr repl) s)
  7908. (push
  7909. (cons (car c)
  7910. (cdr (or (assoc (cadr repl) alist)
  7911. (error "Undefined key `%s' as contextual replacement for `%s'"
  7912. (cadr repl) (car c)))))
  7913. r))))))
  7914. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7915. (delq
  7916. nil
  7917. (delete-dups
  7918. (mapcar (lambda (x)
  7919. (let ((tpl (car x)))
  7920. (unless (delq
  7921. nil
  7922. (mapcar (lambda (y)
  7923. (equal y tpl))
  7924. s))
  7925. x)))
  7926. (reverse r))))))
  7927. (defun org-contextualize-validate-key (key contexts)
  7928. "Check CONTEXTS for agenda or capture KEY."
  7929. (let (res)
  7930. (dolist (r contexts)
  7931. (dolist (rr (car (last r)))
  7932. (when
  7933. (and (equal key (car r))
  7934. (if (functionp rr) (funcall rr)
  7935. (or (and (eq (car rr) 'in-file)
  7936. (buffer-file-name)
  7937. (string-match (cdr rr) (buffer-file-name)))
  7938. (and (eq (car rr) 'in-mode)
  7939. (string-match (cdr rr) (symbol-name major-mode)))
  7940. (and (eq (car rr) 'in-buffer)
  7941. (string-match (cdr rr) (buffer-name)))
  7942. (when (and (eq (car rr) 'not-in-file)
  7943. (buffer-file-name))
  7944. (not (string-match (cdr rr) (buffer-file-name))))
  7945. (when (eq (car rr) 'not-in-mode)
  7946. (not (string-match (cdr rr) (symbol-name major-mode))))
  7947. (when (eq (car rr) 'not-in-buffer)
  7948. (not (string-match (cdr rr) (buffer-name)))))))
  7949. (push r res))))
  7950. (delete-dups (delq nil res))))
  7951. (defun org-context-p (&rest contexts)
  7952. "Check if local context is any of CONTEXTS.
  7953. Possible values in the list of contexts are `table', `headline', and `item'."
  7954. (let ((pos (point)))
  7955. (goto-char (point-at-bol))
  7956. (prog1 (or (and (memq 'table contexts)
  7957. (looking-at "[ \t]*|"))
  7958. (and (memq 'headline contexts)
  7959. (looking-at org-outline-regexp))
  7960. (and (memq 'item contexts)
  7961. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  7962. (and (memq 'item-body contexts)
  7963. (org-in-item-p)))
  7964. (goto-char pos))))
  7965. ;;;###autoload
  7966. (defun org-run-like-in-org-mode (cmd)
  7967. "Run a command, pretending that the current buffer is in Org mode.
  7968. This will temporarily bind local variables that are typically bound in
  7969. Org mode to the values they have in Org mode, and then interactively
  7970. call CMD."
  7971. (org-load-modules-maybe)
  7972. (let (binds)
  7973. (dolist (var (org-get-local-variables))
  7974. (when (or (not (boundp (car var)))
  7975. (eq (symbol-value (car var))
  7976. (default-value (car var))))
  7977. (push (list (car var) `(quote ,(cadr var))) binds)))
  7978. (eval `(let ,binds
  7979. (call-interactively (quote ,cmd))))))
  7980. (defun org-get-category (&optional pos force-refresh)
  7981. "Get the category applying to position POS."
  7982. (save-match-data
  7983. (when force-refresh (org-refresh-category-properties))
  7984. (let ((pos (or pos (point))))
  7985. (or (get-text-property pos 'org-category)
  7986. (progn (org-refresh-category-properties)
  7987. (get-text-property pos 'org-category))))))
  7988. ;;; Refresh properties
  7989. (defun org-refresh-properties (dprop tprop)
  7990. "Refresh buffer text properties.
  7991. DPROP is the drawer property and TPROP is either the
  7992. corresponding text property to set, or an alist with each element
  7993. being a text property (as a symbol) and a function to apply to
  7994. the value of the drawer property."
  7995. (let* ((case-fold-search t)
  7996. (inhibit-read-only t)
  7997. (inherit? (org-property-inherit-p dprop))
  7998. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7999. (global (and inherit? (org--property-global-value dprop nil))))
  8000. (org-with-silent-modifications
  8001. (org-with-point-at 1
  8002. ;; Set global values (e.g., values defined through
  8003. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8004. (when global (put-text-property (point-min) (point-max) tprop global))
  8005. ;; Set local values.
  8006. (while (re-search-forward property-re nil t)
  8007. (when (org-at-property-p)
  8008. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8009. (outline-next-heading))))))
  8010. (defun org-refresh-property (tprop p &optional inherit)
  8011. "Refresh the buffer text property TPROP from the drawer property P.
  8012. The refresh happens only for the current headline, or the whole
  8013. sub-tree if optional argument INHERIT is non-nil."
  8014. (unless (org-before-first-heading-p)
  8015. (save-excursion
  8016. (org-back-to-heading t)
  8017. (let ((start (point))
  8018. (end (save-excursion
  8019. (if inherit (org-end-of-subtree t t)
  8020. (or (outline-next-heading) (point-max))))))
  8021. (if (symbolp tprop)
  8022. ;; TPROP is a text property symbol.
  8023. (put-text-property start end tprop p)
  8024. ;; TPROP is an alist with (property . function) elements.
  8025. (pcase-dolist (`(,prop . ,f) tprop)
  8026. (put-text-property start end prop (funcall f p))))))))
  8027. (defun org-refresh-category-properties ()
  8028. "Refresh category text properties in the buffer."
  8029. (let ((case-fold-search t)
  8030. (inhibit-read-only t)
  8031. (default-category
  8032. (cond ((null org-category)
  8033. (if buffer-file-name
  8034. (file-name-sans-extension
  8035. (file-name-nondirectory buffer-file-name))
  8036. "???"))
  8037. ((symbolp org-category) (symbol-name org-category))
  8038. (t org-category))))
  8039. (org-with-silent-modifications
  8040. (org-with-wide-buffer
  8041. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8042. ;; This is the default category for the buffer. If none is
  8043. ;; found, fall-back to `org-category' or buffer file name.
  8044. (put-text-property
  8045. (point-min) (point-max)
  8046. 'org-category
  8047. (catch 'buffer-category
  8048. (goto-char (point-max))
  8049. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8050. (let ((element (org-element-at-point)))
  8051. (when (eq (org-element-type element) 'keyword)
  8052. (throw 'buffer-category
  8053. (org-element-property :value element)))))
  8054. default-category))
  8055. ;; Set sub-tree specific categories.
  8056. (goto-char (point-min))
  8057. (let ((regexp (org-re-property "CATEGORY")))
  8058. (while (re-search-forward regexp nil t)
  8059. (let ((value (match-string-no-properties 3)))
  8060. (when (org-at-property-p)
  8061. (put-text-property
  8062. (save-excursion (org-back-to-heading t) (point))
  8063. (save-excursion (org-end-of-subtree t t) (point))
  8064. 'org-category
  8065. value)))))))))
  8066. (defun org-refresh-stats-properties ()
  8067. "Refresh stats text properties in the buffer."
  8068. (org-with-silent-modifications
  8069. (org-with-point-at 1
  8070. (let ((regexp (concat org-outline-regexp-bol
  8071. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8072. (while (re-search-forward regexp nil t)
  8073. (let* ((numerator (string-to-number (match-string 1)))
  8074. (denominator (and (match-end 2)
  8075. (string-to-number (match-string 2))))
  8076. (stats (cond ((not denominator) numerator) ;percent
  8077. ((= denominator 0) 0)
  8078. (t (/ (* numerator 100) denominator)))))
  8079. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8080. 'org-stats stats)))))))
  8081. (defun org-refresh-effort-properties ()
  8082. "Refresh effort properties"
  8083. (org-refresh-properties
  8084. org-effort-property
  8085. '((effort . identity)
  8086. (effort-minutes . org-duration-to-minutes))))
  8087. ;;;; Link Stuff
  8088. ;;; Link abbreviations
  8089. (defun org-link-expand-abbrev (link)
  8090. "Apply replacements as defined in `org-link-abbrev-alist'."
  8091. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8092. (let* ((key (match-string 1 link))
  8093. (as (or (assoc key org-link-abbrev-alist-local)
  8094. (assoc key org-link-abbrev-alist)))
  8095. (tag (and (match-end 2) (match-string 3 link)))
  8096. rpl)
  8097. (if (not as)
  8098. link
  8099. (setq rpl (cdr as))
  8100. (cond
  8101. ((symbolp rpl) (funcall rpl tag))
  8102. ((string-match "%(\\([^)]+\\))" rpl)
  8103. (replace-match
  8104. (save-match-data
  8105. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8106. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8107. ((string-match "%h" rpl)
  8108. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8109. (t (concat rpl tag)))))
  8110. link))
  8111. ;;; Storing and inserting links
  8112. (defvar org-insert-link-history nil
  8113. "Minibuffer history for links inserted with `org-insert-link'.")
  8114. (defvar org-stored-links nil
  8115. "Contains the links stored with `org-store-link'.")
  8116. (defvar org-store-link-plist nil
  8117. "Plist with info about the most recently link created with `org-store-link'.")
  8118. (defun org-store-link-functions ()
  8119. "Return a list of functions that are called to create and store a link.
  8120. The functions defined in the :store property of
  8121. `org-link-parameters'.
  8122. Each function will be called in turn until one returns a non-nil
  8123. value. Each function should check if it is responsible for
  8124. creating this link (for example by looking at the major mode).
  8125. If not, it must exit and return nil. If yes, it should return
  8126. a non-nil value after calling `org-store-link-props' with a list
  8127. of properties and values. Special properties are:
  8128. :type The link prefix, like \"http\". This must be given.
  8129. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8130. This is obligatory as well.
  8131. :description Optional default description for the second pair
  8132. of brackets in an Org mode link. The user can still change
  8133. this when inserting this link into an Org mode buffer.
  8134. In addition to these, any additional properties can be specified
  8135. and then used in capture templates."
  8136. (cl-loop for link in org-link-parameters
  8137. with store-func
  8138. do (setq store-func (org-link-get-parameter (car link) :store))
  8139. if store-func
  8140. collect store-func))
  8141. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8142. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8143. ;;;###autoload
  8144. (defun org-store-link (arg &optional interactive?)
  8145. "Store an org-link to the current location.
  8146. \\<org-mode-map>
  8147. This link is added to `org-stored-links' and can later be inserted
  8148. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8149. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8150. A single
  8151. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8152. `org-gnus-prefer-web-links' for links to Usenet articles.
  8153. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8154. skipping storing functions that are not
  8155. part of Org core.
  8156. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8157. prefix ARG forces storing a link for each line in the
  8158. active region.
  8159. Assume the function is called interactively if INTERACTIVE? is
  8160. non-nil."
  8161. (interactive "P\np")
  8162. (org-load-modules-maybe)
  8163. (if (and (equal arg '(64)) (org-region-active-p))
  8164. (save-excursion
  8165. (let ((end (region-end)))
  8166. (goto-char (region-beginning))
  8167. (set-mark (point))
  8168. (while (< (point-at-eol) end)
  8169. (move-end-of-line 1) (activate-mark)
  8170. (let (current-prefix-arg)
  8171. (call-interactively 'org-store-link))
  8172. (move-beginning-of-line 2)
  8173. (set-mark (point)))))
  8174. (setq org-store-link-plist nil)
  8175. (let (link cpltxt desc description search txt custom-id agenda-link)
  8176. (cond
  8177. ;; Store a link using an external link type, if any function is
  8178. ;; available. If more than one can generate a link from current
  8179. ;; location, ask which one to use.
  8180. ((and (not (equal arg '(16)))
  8181. (let ((results-alist nil))
  8182. (dolist (f (org-store-link-functions))
  8183. (when (funcall f)
  8184. ;; XXX: return value is not link's plist, so we
  8185. ;; store the new value before it is modified. It
  8186. ;; would be cleaner to ask store link functions to
  8187. ;; return the plist instead.
  8188. (push (cons f (copy-sequence org-store-link-plist))
  8189. results-alist)))
  8190. (pcase results-alist
  8191. (`nil nil)
  8192. (`((,_ . ,_)) t) ;single choice: nothing to do
  8193. (`((,name . ,_) . ,_)
  8194. ;; Reinstate link plist associated to the chosen
  8195. ;; function.
  8196. (apply #'org-store-link-props
  8197. (cdr (assoc-string
  8198. (completing-read
  8199. "Which function for creating the link? "
  8200. (mapcar #'car results-alist) nil t name)
  8201. results-alist)))
  8202. t))))
  8203. (setq link (plist-get org-store-link-plist :link))
  8204. (setq desc (or (plist-get org-store-link-plist :description)
  8205. link)))
  8206. ;; Store a link from a source code buffer.
  8207. ((org-src-edit-buffer-p)
  8208. (let ((coderef-format (org-src-coderef-format)))
  8209. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8210. (setq link (format "(%s)" (match-string-no-properties 3))))
  8211. (interactive?
  8212. (let ((label (read-string "Code line label: ")))
  8213. (end-of-line)
  8214. (setq link (format coderef-format label))
  8215. (let ((gc (- 79 (length link))))
  8216. (if (< (current-column) gc)
  8217. (org-move-to-column gc t)
  8218. (insert " ")))
  8219. (insert link)
  8220. (setq link (concat "(" label ")"))
  8221. (setq desc nil)))
  8222. (t (setq link nil)))))
  8223. ;; We are in the agenda, link to referenced location
  8224. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8225. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8226. (get-text-property (point) 'org-marker))))
  8227. (when m
  8228. (org-with-point-at m
  8229. (setq agenda-link (org-store-link nil interactive?))))))
  8230. ((eq major-mode 'calendar-mode)
  8231. (let ((cd (calendar-cursor-to-date)))
  8232. (setq link
  8233. (format-time-string
  8234. (car org-time-stamp-formats)
  8235. (apply 'encode-time
  8236. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8237. nil nil nil))))
  8238. (org-store-link-props :type "calendar" :date cd)))
  8239. ((eq major-mode 'help-mode)
  8240. (setq link (concat "help:" (save-excursion
  8241. (goto-char (point-min))
  8242. (looking-at "^[^ ]+")
  8243. (match-string 0))))
  8244. (org-store-link-props :type "help"))
  8245. ((eq major-mode 'w3-mode)
  8246. (setq cpltxt (if (and (buffer-name)
  8247. (not (string-match "Untitled" (buffer-name))))
  8248. (buffer-name)
  8249. (url-view-url t))
  8250. link (url-view-url t))
  8251. (org-store-link-props :type "w3" :url (url-view-url t)))
  8252. ((eq major-mode 'image-mode)
  8253. (setq cpltxt (concat "file:"
  8254. (abbreviate-file-name buffer-file-name))
  8255. link cpltxt)
  8256. (org-store-link-props :type "image" :file buffer-file-name))
  8257. ;; In dired, store a link to the file of the current line
  8258. ((derived-mode-p 'dired-mode)
  8259. (let ((file (dired-get-filename nil t)))
  8260. (setq file (if file
  8261. (abbreviate-file-name
  8262. (expand-file-name (dired-get-filename nil t)))
  8263. ;; otherwise, no file so use current directory.
  8264. default-directory))
  8265. (setq cpltxt (concat "file:" file)
  8266. link cpltxt)))
  8267. ((setq search (run-hook-with-args-until-success
  8268. 'org-create-file-search-functions))
  8269. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8270. "::" search))
  8271. (setq cpltxt (or description link)))
  8272. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8273. (org-with-limited-levels
  8274. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8275. (cond
  8276. ;; Store a link using the target at point
  8277. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8278. (setq cpltxt
  8279. (concat "file:"
  8280. (abbreviate-file-name
  8281. (buffer-file-name (buffer-base-buffer)))
  8282. "::" (match-string 1))
  8283. link cpltxt))
  8284. ((and (featurep 'org-id)
  8285. (or (eq org-id-link-to-org-use-id t)
  8286. (and interactive?
  8287. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8288. (and (eq org-id-link-to-org-use-id
  8289. 'create-if-interactive-and-no-custom-id)
  8290. (not custom-id))))
  8291. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8292. ;; Store a link using the ID at point
  8293. (setq link (condition-case nil
  8294. (prog1 (org-id-store-link)
  8295. (setq desc (or (plist-get org-store-link-plist
  8296. :description)
  8297. "")))
  8298. (error
  8299. ;; Probably before first headline, link only to file
  8300. (concat "file:"
  8301. (abbreviate-file-name
  8302. (buffer-file-name (buffer-base-buffer))))))))
  8303. (t
  8304. ;; Just link to current headline
  8305. (setq cpltxt (concat "file:"
  8306. (abbreviate-file-name
  8307. (buffer-file-name (buffer-base-buffer)))))
  8308. ;; Add a context search string
  8309. (when (org-xor org-context-in-file-links
  8310. (equal arg '(4)))
  8311. (let* ((element (org-element-at-point))
  8312. (name (org-element-property :name element)))
  8313. (setq txt (cond
  8314. ((org-at-heading-p) nil)
  8315. (name)
  8316. ((org-region-active-p)
  8317. (buffer-substring (region-beginning) (region-end)))))
  8318. (when (or (null txt) (string-match "\\S-" txt))
  8319. (setq cpltxt
  8320. (concat cpltxt "::"
  8321. (condition-case nil
  8322. (org-make-org-heading-search-string txt)
  8323. (error "")))
  8324. desc (or name
  8325. (nth 4 (ignore-errors (org-heading-components)))
  8326. "NONE")))))
  8327. (when (string-match "::\\'" cpltxt)
  8328. (setq cpltxt (substring cpltxt 0 -2)))
  8329. (setq link cpltxt)))))
  8330. ((buffer-file-name (buffer-base-buffer))
  8331. ;; Just link to this file here.
  8332. (setq cpltxt (concat "file:"
  8333. (abbreviate-file-name
  8334. (buffer-file-name (buffer-base-buffer)))))
  8335. ;; Add a context string.
  8336. (when (org-xor org-context-in-file-links
  8337. (equal arg '(4)))
  8338. (setq txt (if (org-region-active-p)
  8339. (buffer-substring (region-beginning) (region-end))
  8340. (buffer-substring (point-at-bol) (point-at-eol))))
  8341. ;; Only use search option if there is some text.
  8342. (when (string-match "\\S-" txt)
  8343. (setq cpltxt
  8344. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8345. desc "NONE")))
  8346. (setq link cpltxt))
  8347. (interactive?
  8348. (user-error "No method for storing a link from this buffer"))
  8349. (t (setq link nil)))
  8350. ;; We're done setting link and desc, clean up
  8351. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8352. (setq link (or link cpltxt)
  8353. desc (or desc cpltxt))
  8354. (cond ((not desc))
  8355. ((equal desc "NONE") (setq desc nil))
  8356. (t (setq desc
  8357. (replace-regexp-in-string
  8358. org-bracket-link-analytic-regexp
  8359. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8360. desc))))
  8361. ;; Return the link
  8362. (if (not (and interactive? link))
  8363. (or agenda-link (and link (org-make-link-string link desc)))
  8364. (push (list link desc) org-stored-links)
  8365. (message "Stored: %s" (or desc link))
  8366. (when custom-id
  8367. (setq link (concat "file:" (abbreviate-file-name
  8368. (buffer-file-name)) "::#" custom-id))
  8369. (push (list link desc) org-stored-links))
  8370. (car org-stored-links)))))
  8371. (defun org-store-link-props (&rest plist)
  8372. "Store link properties.
  8373. The properties are pre-processed by extracting names, addresses
  8374. and dates."
  8375. (let ((x (plist-get plist :from)))
  8376. (when x
  8377. (let ((adr (mail-extract-address-components x)))
  8378. (setq plist (plist-put plist :fromname (car adr)))
  8379. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8380. (let ((x (plist-get plist :to)))
  8381. (when x
  8382. (let ((adr (mail-extract-address-components x)))
  8383. (setq plist (plist-put plist :toname (car adr)))
  8384. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8385. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8386. (when x
  8387. (setq plist (plist-put plist :date-timestamp
  8388. (format-time-string
  8389. (org-time-stamp-format t) x)))
  8390. (setq plist (plist-put plist :date-timestamp-inactive
  8391. (format-time-string
  8392. (org-time-stamp-format t t) x)))))
  8393. (let ((from (plist-get plist :from))
  8394. (to (plist-get plist :to)))
  8395. (when (and from to org-from-is-user-regexp)
  8396. (setq plist
  8397. (plist-put plist :fromto
  8398. (if (string-match org-from-is-user-regexp from)
  8399. (concat "to %t")
  8400. (concat "from %f"))))))
  8401. (setq org-store-link-plist plist))
  8402. (defun org-add-link-props (&rest plist)
  8403. "Add these properties to the link property list."
  8404. (let (key value)
  8405. (while plist
  8406. (setq key (pop plist) value (pop plist))
  8407. (setq org-store-link-plist
  8408. (plist-put org-store-link-plist key value)))))
  8409. (defun org-email-link-description (&optional fmt)
  8410. "Return the description part of an email link.
  8411. This takes information from `org-store-link-plist' and formats it
  8412. according to FMT (default from `org-email-link-description-format')."
  8413. (setq fmt (or fmt org-email-link-description-format))
  8414. (let* ((p org-store-link-plist)
  8415. (to (plist-get p :toaddress))
  8416. (from (plist-get p :fromaddress))
  8417. (table
  8418. (list
  8419. (cons "%c" (plist-get p :fromto))
  8420. (cons "%F" (plist-get p :from))
  8421. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8422. (cons "%T" (plist-get p :to))
  8423. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8424. (cons "%s" (plist-get p :subject))
  8425. (cons "%d" (plist-get p :date))
  8426. (cons "%m" (plist-get p :message-id)))))
  8427. (when (string-match "%c" fmt)
  8428. ;; Check if the user wrote this message
  8429. (if (and org-from-is-user-regexp from to
  8430. (save-match-data (string-match org-from-is-user-regexp from)))
  8431. (setq fmt (replace-match "to %t" t t fmt))
  8432. (setq fmt (replace-match "from %f" t t fmt))))
  8433. (org-replace-escapes fmt table)))
  8434. (defun org-make-org-heading-search-string (&optional string)
  8435. "Make search string for the current headline or STRING."
  8436. (let ((s (or string
  8437. (and (derived-mode-p 'org-mode)
  8438. (save-excursion
  8439. (org-back-to-heading t)
  8440. (org-element-property :raw-value (org-element-at-point))))))
  8441. (lines org-context-in-file-links))
  8442. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8443. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8444. (when (and string (integerp lines) (> lines 0))
  8445. (let ((slines (org-split-string s "\n")))
  8446. (when (< lines (length slines))
  8447. (setq s (mapconcat
  8448. 'identity
  8449. (reverse (nthcdr (- (length slines) lines)
  8450. (reverse slines))) "\n")))))
  8451. (mapconcat #'identity (split-string s) " ")))
  8452. (defconst org-link-escape-chars
  8453. ;;%20 %5B %5D %25
  8454. '(?\s ?\[ ?\] ?%)
  8455. "List of characters that should be escaped in a link when stored to Org.
  8456. This is the list that is used for internal purposes.")
  8457. (defun org-make-link-string (link &optional description)
  8458. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8459. (unless (org-string-nw-p link) (error "Empty link"))
  8460. (let ((uri (cond ((string-match org-link-types-re link)
  8461. (concat (match-string 1 link)
  8462. (org-link-escape (substring link (match-end 1)))))
  8463. ((or (file-name-absolute-p link)
  8464. (string-match-p "\\`\\.\\.?/" link))
  8465. (org-link-escape link))
  8466. ;; For readability, do not encode space characters
  8467. ;; in fuzzy links.
  8468. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8469. (description
  8470. (and (org-string-nw-p description)
  8471. ;; Remove brackets from description, as they are fatal.
  8472. (replace-regexp-in-string
  8473. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8474. (org-trim description)))))
  8475. (format "[[%s]%s]"
  8476. uri
  8477. (if description (format "[%s]" description) ""))))
  8478. (defun org-link-escape (text &optional table merge)
  8479. "Return percent escaped representation of TEXT.
  8480. TEXT is a string with the text to escape.
  8481. Optional argument TABLE is a list with characters that should be
  8482. escaped. When nil, `org-link-escape-chars' is used.
  8483. If optional argument MERGE is set, merge TABLE into
  8484. `org-link-escape-chars'."
  8485. (let ((characters-to-encode
  8486. (cond ((null table) org-link-escape-chars)
  8487. (merge (append org-link-escape-chars table))
  8488. (t table))))
  8489. (mapconcat
  8490. (lambda (c)
  8491. (if (or (memq c characters-to-encode)
  8492. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8493. (mapconcat (lambda (e) (format "%%%.2X" e))
  8494. (or (encode-coding-char c 'utf-8)
  8495. (error "Unable to percent escape character: %c" c))
  8496. "")
  8497. (char-to-string c)))
  8498. text "")))
  8499. (defun org-link-unescape (str)
  8500. "Unhex hexified Unicode parts in string STR.
  8501. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8502. reciprocal of `org-link-escape', which see."
  8503. (if (org-string-nw-p str)
  8504. (replace-regexp-in-string
  8505. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8506. str))
  8507. (defun org-link-unescape-compound (hex)
  8508. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8509. Note: this function also decodes single byte encodings like
  8510. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8511. (save-match-data
  8512. (let* ((bytes (cdr (split-string hex "%")))
  8513. (ret "")
  8514. (eat 0)
  8515. (sum 0))
  8516. (while bytes
  8517. (let* ((val (string-to-number (pop bytes) 16))
  8518. (shift-xor
  8519. (if (= 0 eat)
  8520. (cond
  8521. ((>= val 252) (cons 6 252))
  8522. ((>= val 248) (cons 5 248))
  8523. ((>= val 240) (cons 4 240))
  8524. ((>= val 224) (cons 3 224))
  8525. ((>= val 192) (cons 2 192))
  8526. (t (cons 0 0)))
  8527. (cons 6 128))))
  8528. (when (>= val 192) (setq eat (car shift-xor)))
  8529. (setq val (logxor val (cdr shift-xor)))
  8530. (setq sum (+ (lsh sum (car shift-xor)) val))
  8531. (when (> eat 0) (setq eat (- eat 1)))
  8532. (cond
  8533. ((= 0 eat) ;multi byte
  8534. (setq ret (concat ret (char-to-string sum)))
  8535. (setq sum 0))
  8536. ((not bytes) ; single byte(s)
  8537. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8538. ret)))
  8539. (defun org-link-unescape-single-byte-sequence (hex)
  8540. "Unhexify hex-encoded single byte character sequences."
  8541. (mapconcat (lambda (byte)
  8542. (char-to-string (string-to-number byte 16)))
  8543. (cdr (split-string hex "%")) ""))
  8544. (defun org-fixup-message-id-for-http (s)
  8545. "Replace special characters in a message id, so it can be used in an http query."
  8546. (when (string-match "%" s)
  8547. (setq s (mapconcat (lambda (c)
  8548. (if (eq c ?%)
  8549. "%25"
  8550. (char-to-string c)))
  8551. s "")))
  8552. (while (string-match "<" s)
  8553. (setq s (replace-match "%3C" t t s)))
  8554. (while (string-match ">" s)
  8555. (setq s (replace-match "%3E" t t s)))
  8556. (while (string-match "@" s)
  8557. (setq s (replace-match "%40" t t s)))
  8558. s)
  8559. (defun org-link-prettify (link)
  8560. "Return a human-readable representation of LINK.
  8561. The car of LINK must be a raw link.
  8562. The cdr of LINK must be either a link description or nil."
  8563. (let ((desc (or (cadr link) "<no description>")))
  8564. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8565. "<" (car link) ">")))
  8566. ;;;###autoload
  8567. (defun org-insert-link-global ()
  8568. "Insert a link like Org mode does.
  8569. This command can be called in any mode to insert a link in Org syntax."
  8570. (interactive)
  8571. (org-load-modules-maybe)
  8572. (org-run-like-in-org-mode 'org-insert-link))
  8573. (defun org-insert-all-links (arg &optional pre post)
  8574. "Insert all links in `org-stored-links'.
  8575. When a universal prefix, do not delete the links from `org-stored-links'.
  8576. When `ARG' is a number, insert the last N link(s).
  8577. `PRE' and `POST' are optional arguments to define a string to
  8578. prepend or to append."
  8579. (interactive "P")
  8580. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8581. (links (copy-sequence org-stored-links))
  8582. (pr (or pre "- "))
  8583. (po (or post "\n"))
  8584. (cnt 1) l)
  8585. (if (null org-stored-links)
  8586. (message "No link to insert")
  8587. (while (and (or (listp arg) (>= arg cnt))
  8588. (setq l (if (listp arg)
  8589. (pop links)
  8590. (pop org-stored-links))))
  8591. (setq cnt (1+ cnt))
  8592. (insert pr)
  8593. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8594. (insert po)))))
  8595. (defun org-insert-last-stored-link (arg)
  8596. "Insert the last link stored in `org-stored-links'."
  8597. (interactive "p")
  8598. (org-insert-all-links arg "" "\n"))
  8599. (defun org-link-fontify-links-to-this-file ()
  8600. "Fontify links to the current file in `org-stored-links'."
  8601. (let ((f (buffer-file-name)) a b)
  8602. (setq a (mapcar (lambda(l)
  8603. (let ((ll (car l)))
  8604. (when (and (string-match "^file:\\(.+\\)::" ll)
  8605. (equal f (expand-file-name (match-string 1 ll))))
  8606. ll)))
  8607. org-stored-links))
  8608. (when (featurep 'org-id)
  8609. (setq b (mapcar (lambda(l)
  8610. (let ((ll (car l)))
  8611. (when (and (string-match "^id:\\(.+\\)$" ll)
  8612. (equal f (expand-file-name
  8613. (or (org-id-find-id-file
  8614. (match-string 1 ll)) ""))))
  8615. ll)))
  8616. org-stored-links)))
  8617. (mapcar (lambda(l)
  8618. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8619. (delq nil (append a b)))))
  8620. (defvar org--links-history nil)
  8621. (defun org-insert-link (&optional complete-file link-location default-description)
  8622. "Insert a link. At the prompt, enter the link.
  8623. Completion can be used to insert any of the link protocol prefixes in use.
  8624. The history can be used to select a link previously stored with
  8625. `org-store-link'. When the empty string is entered (i.e. if you just
  8626. press `RET' at the prompt), the link defaults to the most recently
  8627. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8628. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8629. You will also be prompted for a description, and if one is given, it will
  8630. be displayed in the buffer instead of the link.
  8631. If there is already a link at point, this command will allow you to edit
  8632. link and description parts.
  8633. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8634. file name can be
  8635. selected using completion. The path to the file will be relative to the
  8636. current directory if the file is in the current directory or a subdirectory.
  8637. Otherwise, the link will be the absolute path as completed in the minibuffer
  8638. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8639. option `org-link-file-path-type'.
  8640. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8641. absolute path even if the file is in
  8642. the current directory or below.
  8643. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8644. prefix negates `org-keep-stored-link-after-insertion'.
  8645. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8646. the link location instead of reading one interactively.
  8647. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8648. be used as the default description. Otherwise, if
  8649. `org-make-link-description-function' is non-nil, this function
  8650. will be called with the link target, and the result will be the
  8651. default link description. When called non-interactivily, don't
  8652. allow to edit the default description."
  8653. (interactive "P")
  8654. (let* ((wcf (current-window-configuration))
  8655. (origbuf (current-buffer))
  8656. (region (when (org-region-active-p)
  8657. (buffer-substring (region-beginning) (region-end))))
  8658. (remove (and region (list (region-beginning) (region-end))))
  8659. (desc region)
  8660. (link link-location)
  8661. (abbrevs org-link-abbrev-alist-local)
  8662. entry all-prefixes auto-desc)
  8663. (cond
  8664. (link-location) ; specified by arg, just use it.
  8665. ((org-in-regexp org-bracket-link-regexp 1)
  8666. ;; We do have a link at point, and we are going to edit it.
  8667. (setq remove (list (match-beginning 0) (match-end 0)))
  8668. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8669. (setq link (read-string "Link: "
  8670. (org-link-unescape
  8671. (match-string-no-properties 1)))))
  8672. ((or (org-in-regexp org-angle-link-re)
  8673. (org-in-regexp org-plain-link-re))
  8674. ;; Convert to bracket link
  8675. (setq remove (list (match-beginning 0) (match-end 0))
  8676. link (read-string "Link: "
  8677. (org-unbracket-string "<" ">" (match-string 0)))))
  8678. ((member complete-file '((4) (16)))
  8679. ;; Completing read for file names.
  8680. (setq link (org-file-complete-link complete-file)))
  8681. (t
  8682. ;; Read link, with completion for stored links.
  8683. (org-link-fontify-links-to-this-file)
  8684. (org-switch-to-buffer-other-window "*Org Links*")
  8685. (with-current-buffer "*Org Links*"
  8686. (erase-buffer)
  8687. (insert "Insert a link.
  8688. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8689. (when org-stored-links
  8690. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8691. (insert (mapconcat 'org-link-prettify
  8692. (reverse org-stored-links) "\n")))
  8693. (goto-char (point-min)))
  8694. (let ((cw (selected-window)))
  8695. (select-window (get-buffer-window "*Org Links*" 'visible))
  8696. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8697. (unless (pos-visible-in-window-p (point-max))
  8698. (org-fit-window-to-buffer))
  8699. (and (window-live-p cw) (select-window cw)))
  8700. (setq all-prefixes (append (mapcar 'car abbrevs)
  8701. (mapcar 'car org-link-abbrev-alist)
  8702. (org-link-types)))
  8703. (unwind-protect
  8704. ;; Fake a link history, containing the stored links.
  8705. (let ((org--links-history
  8706. (append (mapcar #'car org-stored-links)
  8707. org-insert-link-history)))
  8708. (setq link
  8709. (org-completing-read
  8710. "Link: "
  8711. (append
  8712. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8713. (mapcar #'car org-stored-links))
  8714. nil nil nil
  8715. 'org--links-history
  8716. (caar org-stored-links)))
  8717. (unless (org-string-nw-p link) (user-error "No link selected"))
  8718. (dolist (l org-stored-links)
  8719. (when (equal link (cadr l))
  8720. (setq link (car l))
  8721. (setq auto-desc t)))
  8722. (when (or (member link all-prefixes)
  8723. (and (equal ":" (substring link -1))
  8724. (member (substring link 0 -1) all-prefixes)
  8725. (setq link (substring link 0 -1))))
  8726. (setq link (with-current-buffer origbuf
  8727. (org-link-try-special-completion link)))))
  8728. (set-window-configuration wcf)
  8729. (kill-buffer "*Org Links*"))
  8730. (setq entry (assoc link org-stored-links))
  8731. (or entry (push link org-insert-link-history))
  8732. (setq desc (or desc (nth 1 entry)))))
  8733. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8734. (not org-keep-stored-link-after-insertion))
  8735. (setq org-stored-links (delq (assoc link org-stored-links)
  8736. org-stored-links)))
  8737. (when (and (string-match org-plain-link-re link)
  8738. (not (string-match org-ts-regexp link)))
  8739. ;; URL-like link, normalize the use of angular brackets.
  8740. (setq link (org-unbracket-string "<" ">" link)))
  8741. ;; Check if we are linking to the current file with a search
  8742. ;; option If yes, simplify the link by using only the search
  8743. ;; option.
  8744. (when (and buffer-file-name
  8745. (let ((case-fold-search nil))
  8746. (string-match "\\`file:\\(.+?\\)::" link)))
  8747. (let ((path (match-string-no-properties 1 link))
  8748. (search (substring-no-properties link (match-end 0))))
  8749. (save-match-data
  8750. (when (equal (file-truename buffer-file-name) (file-truename path))
  8751. ;; We are linking to this same file, with a search option
  8752. (setq link search)))))
  8753. ;; Check if we can/should use a relative path. If yes, simplify
  8754. ;; the link.
  8755. (let ((case-fold-search nil))
  8756. (when (string-match "\\`\\(file\\|docview\\):" link)
  8757. (let* ((type (match-string-no-properties 0 link))
  8758. (path-start (match-end 0))
  8759. (search (and (string-match "::\\(.*\\)\\'" link)
  8760. (match-string 1 link)))
  8761. (path
  8762. (if search
  8763. (substring-no-properties
  8764. link path-start (match-beginning 0))
  8765. (substring-no-properties link (match-end 0))))
  8766. (origpath path))
  8767. (cond
  8768. ((or (eq org-link-file-path-type 'absolute)
  8769. (equal complete-file '(16)))
  8770. (setq path (abbreviate-file-name (expand-file-name path))))
  8771. ((eq org-link-file-path-type 'noabbrev)
  8772. (setq path (expand-file-name path)))
  8773. ((eq org-link-file-path-type 'relative)
  8774. (setq path (file-relative-name path)))
  8775. (t
  8776. (save-match-data
  8777. (if (string-match (concat "^" (regexp-quote
  8778. (expand-file-name
  8779. (file-name-as-directory
  8780. default-directory))))
  8781. (expand-file-name path))
  8782. ;; We are linking a file with relative path name.
  8783. (setq path (substring (expand-file-name path)
  8784. (match-end 0)))
  8785. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8786. (setq link (concat type path (and search (concat "::" search))))
  8787. (when (equal desc origpath)
  8788. (setq desc path)))))
  8789. (unless auto-desc
  8790. (let ((initial-input
  8791. (cond
  8792. (default-description)
  8793. ((not org-make-link-description-function) desc)
  8794. (t (condition-case nil
  8795. (funcall org-make-link-description-function link desc)
  8796. (error
  8797. (message "Can't get link description from `%s'"
  8798. (symbol-name org-make-link-description-function))
  8799. (sit-for 2)
  8800. nil))))))
  8801. (setq desc (if (called-interactively-p 'any)
  8802. (read-string "Description: " initial-input)
  8803. initial-input))))
  8804. (unless (string-match "\\S-" desc) (setq desc nil))
  8805. (when remove (apply 'delete-region remove))
  8806. (insert (org-make-link-string link desc))
  8807. ;; Redisplay so as the new link has proper invisible characters.
  8808. (sit-for 0)))
  8809. (defun org-link-try-special-completion (type)
  8810. "If there is completion support for link type TYPE, offer it."
  8811. (let ((fun (org-link-get-parameter type :complete)))
  8812. (if (functionp fun)
  8813. (funcall fun)
  8814. (read-string "Link (no completion support): " (concat type ":")))))
  8815. (defun org-file-complete-link (&optional arg)
  8816. "Create a file link using completion."
  8817. (let ((file (read-file-name "File: "))
  8818. (pwd (file-name-as-directory (expand-file-name ".")))
  8819. (pwd1 (file-name-as-directory (abbreviate-file-name
  8820. (expand-file-name ".")))))
  8821. (cond ((equal arg '(16))
  8822. (concat "file:"
  8823. (abbreviate-file-name (expand-file-name file))))
  8824. ((string-match
  8825. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8826. (concat "file:" (match-string 1 file)))
  8827. ((string-match
  8828. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8829. (expand-file-name file))
  8830. (concat "file:"
  8831. (match-string 1 (expand-file-name file))))
  8832. (t (concat "file:" file)))))
  8833. ;;; Opening/following a link
  8834. (defvar org-link-search-failed nil)
  8835. (defvar org-open-link-functions nil
  8836. "Hook for functions finding a plain text link.
  8837. These functions must take a single argument, the link content.
  8838. They will be called for links that look like [[link text][description]]
  8839. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8840. like a filename (e.g. \"./blue.png\").
  8841. These functions will be called *before* Org attempts to resolve the
  8842. link by doing text searches in the current buffer - so if you want a
  8843. link \"[[target]]\" to still find \"<<target>>\", your function should
  8844. handle this as a special case.
  8845. When the function does handle the link, it must return a non-nil value.
  8846. If it decides that it is not responsible for this link, it must return
  8847. nil to indicate that that Org can continue with other options like
  8848. exact and fuzzy text search.")
  8849. (defun org-next-link (&optional search-backward)
  8850. "Move forward to the next link.
  8851. If the link is in hidden text, expose it."
  8852. (interactive "P")
  8853. (when (and org-link-search-failed (eq this-command last-command))
  8854. (goto-char (point-min))
  8855. (message "Link search wrapped back to beginning of buffer"))
  8856. (setq org-link-search-failed nil)
  8857. (let* ((pos (point))
  8858. (ct (org-context))
  8859. (a (assq :link ct))
  8860. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8861. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8862. ((looking-at org-any-link-re)
  8863. ;; Don't stay stuck at link without an org-link face
  8864. (forward-char (if search-backward -1 1))))
  8865. (if (funcall srch-fun org-any-link-re nil t)
  8866. (progn
  8867. (goto-char (match-beginning 0))
  8868. (when (org-invisible-p) (org-show-context)))
  8869. (goto-char pos)
  8870. (setq org-link-search-failed t)
  8871. (message "No further link found"))))
  8872. (defun org-previous-link ()
  8873. "Move backward to the previous link.
  8874. If the link is in hidden text, expose it."
  8875. (interactive)
  8876. (funcall 'org-next-link t))
  8877. (defun org-translate-link (s)
  8878. "Translate a link string if a translation function has been defined."
  8879. (with-temp-buffer
  8880. (insert (org-trim s))
  8881. (org-trim (org-element-interpret-data (org-element-context)))))
  8882. (defun org-translate-link-from-planner (type path)
  8883. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8884. This is still an experimental function, your mileage may vary."
  8885. (cond
  8886. ((member type '("http" "https" "news" "ftp"))
  8887. ;; standard Internet links are the same.
  8888. nil)
  8889. ((and (equal type "irc") (string-match "^//" path))
  8890. ;; Planner has two / at the beginning of an irc link, we have 1.
  8891. ;; We should have zero, actually....
  8892. (setq path (substring path 1)))
  8893. ((and (equal type "lisp") (string-match "^/" path))
  8894. ;; Planner has a slash, we do not.
  8895. (setq type "elisp" path (substring path 1)))
  8896. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8897. ;; A typical message link. Planner has the id after the final slash,
  8898. ;; we separate it with a hash mark
  8899. (setq path (concat (match-string 1 path) "#"
  8900. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8901. (cons type path))
  8902. (defun org-find-file-at-mouse (ev)
  8903. "Open file link or URL at mouse."
  8904. (interactive "e")
  8905. (mouse-set-point ev)
  8906. (org-open-at-point 'in-emacs))
  8907. (defun org-open-at-mouse (ev)
  8908. "Open file link or URL at mouse.
  8909. See the docstring of `org-open-file' for details."
  8910. (interactive "e")
  8911. (mouse-set-point ev)
  8912. (when (eq major-mode 'org-agenda-mode)
  8913. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8914. (org-open-at-point))
  8915. (defvar org-window-config-before-follow-link nil
  8916. "The window configuration before following a link.
  8917. This is saved in case the need arises to restore it.")
  8918. ;;;###autoload
  8919. (defun org-open-at-point-global ()
  8920. "Follow a link or time-stamp like Org mode does.
  8921. This command can be called in any mode to follow an external link
  8922. or a time-stamp that has Org mode syntax. Its behavior is
  8923. undefined when called on internal links (e.g., fuzzy links).
  8924. Raise an error when there is nothing to follow. "
  8925. (interactive)
  8926. (cond ((org-in-regexp org-any-link-re)
  8927. (org-open-link-from-string (match-string-no-properties 0)))
  8928. ((or (org-in-regexp org-ts-regexp-both nil t)
  8929. (org-in-regexp org-tsr-regexp-both nil t))
  8930. (org-follow-timestamp-link))
  8931. (t (user-error "No link found"))))
  8932. ;;;###autoload
  8933. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8934. "Open a link in the string S, as if it was in Org mode."
  8935. (interactive "sLink: \nP")
  8936. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8937. (with-temp-buffer
  8938. (let ((org-inhibit-startup (not reference-buffer)))
  8939. (org-mode)
  8940. (insert s)
  8941. (goto-char (point-min))
  8942. (when reference-buffer
  8943. (setq org-link-abbrev-alist-local
  8944. (with-current-buffer reference-buffer
  8945. org-link-abbrev-alist-local)))
  8946. (org-open-at-point arg reference-buffer)))))
  8947. (defvar org-open-at-point-functions nil
  8948. "Hook that is run when following a link at point.
  8949. Functions in this hook must return t if they identify and follow
  8950. a link at point. If they don't find anything interesting at point,
  8951. they must return nil.")
  8952. (defvar org-link-search-inhibit-query nil)
  8953. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8954. (defun org--open-doi-link (path)
  8955. "Open a \"doi\" type link.
  8956. PATH is a the path to search for, as a string."
  8957. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8958. (defun org--open-elisp-link (path)
  8959. "Open a \"elisp\" type link.
  8960. PATH is the sexp to evaluate, as a string."
  8961. (let ((cmd path))
  8962. (if (or (and (org-string-nw-p
  8963. org-confirm-elisp-link-not-regexp)
  8964. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8965. (not org-confirm-elisp-link-function)
  8966. (funcall org-confirm-elisp-link-function
  8967. (format "Execute \"%s\" as elisp? "
  8968. (org-add-props cmd nil 'face 'org-warning))))
  8969. (message "%s => %s" cmd
  8970. (if (eq (string-to-char cmd) ?\()
  8971. (eval (read cmd))
  8972. (call-interactively (read cmd))))
  8973. (user-error "Abort"))))
  8974. (defun org--open-help-link (path)
  8975. "Open a \"help\" type link.
  8976. PATH is a symbol name, as a string."
  8977. (pcase (intern path)
  8978. ((and (pred fboundp) variable) (describe-function variable))
  8979. ((and (pred boundp) function) (describe-variable function))
  8980. (name (user-error "Unknown function or variable: %s" name))))
  8981. (defun org--open-shell-link (path)
  8982. "Open a \"shell\" type link.
  8983. PATH is the command to execute, as a string."
  8984. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8985. (cmd path))
  8986. (if (or (and (org-string-nw-p
  8987. org-confirm-shell-link-not-regexp)
  8988. (string-match
  8989. org-confirm-shell-link-not-regexp cmd))
  8990. (not org-confirm-shell-link-function)
  8991. (funcall org-confirm-shell-link-function
  8992. (format "Execute \"%s\" in shell? "
  8993. (org-add-props cmd nil
  8994. 'face 'org-warning))))
  8995. (progn
  8996. (message "Executing %s" cmd)
  8997. (shell-command cmd buf)
  8998. (when (featurep 'midnight)
  8999. (setq clean-buffer-list-kill-buffer-names
  9000. (cons (buffer-name buf)
  9001. clean-buffer-list-kill-buffer-names))))
  9002. (user-error "Abort"))))
  9003. (defun org-open-at-point (&optional arg reference-buffer)
  9004. "Open link, timestamp, footnote or tags at point.
  9005. When point is on a link, follow it. Normally, files will be
  9006. opened by an appropriate application. If the optional prefix
  9007. argument ARG is non-nil, Emacs will visit the file. With
  9008. a double prefix argument, try to open outside of Emacs, in the
  9009. application the system uses for this file type.
  9010. When point is on a timestamp, open the agenda at the day
  9011. specified.
  9012. When point is a footnote definition, move to the first reference
  9013. found. If it is on a reference, move to the associated
  9014. definition.
  9015. When point is on a headline, display a list of every link in the
  9016. entry, so it is possible to pick one, or all, of them. If point
  9017. is on a tag, call `org-tags-view' instead.
  9018. When optional argument REFERENCE-BUFFER is non-nil, it should
  9019. specify a buffer from where the link search should happen. This
  9020. is used internally by `org-open-link-from-string'.
  9021. On top of syntactically correct links, this function will also
  9022. try to open links and time-stamps in comments, example
  9023. blocks... i.e., whenever point is on something looking like
  9024. a timestamp or a link."
  9025. (interactive "P")
  9026. ;; On a code block, open block's results.
  9027. (unless (call-interactively 'org-babel-open-src-block-result)
  9028. (org-load-modules-maybe)
  9029. (setq org-window-config-before-follow-link (current-window-configuration))
  9030. (org-remove-occur-highlights nil nil t)
  9031. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9032. (let* ((context
  9033. ;; Only consider supported types, even if they are not
  9034. ;; the closest one.
  9035. (org-element-lineage
  9036. (org-element-context)
  9037. '(clock footnote-definition footnote-reference headline
  9038. inlinetask link timestamp)
  9039. t))
  9040. (type (org-element-type context))
  9041. (value (org-element-property :value context)))
  9042. (cond
  9043. ;; On a headline or an inlinetask, but not on a timestamp,
  9044. ;; a link, a footnote reference.
  9045. ((memq type '(headline inlinetask))
  9046. (org-match-line org-complex-heading-regexp)
  9047. (if (and (match-beginning 5)
  9048. (>= (point) (match-beginning 5))
  9049. (< (point) (match-end 5)))
  9050. ;; On tags.
  9051. (org-tags-view arg (substring (match-string 5) 0 -1))
  9052. ;; Not on tags.
  9053. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9054. (`(nil . ,_)
  9055. (require 'org-attach)
  9056. (org-attach-reveal 'if-exists))
  9057. (`(,links . ,links-end)
  9058. (dolist (link (if (stringp links) (list links) links))
  9059. (search-forward link nil links-end)
  9060. (goto-char (match-beginning 0))
  9061. (org-open-at-point))))))
  9062. ;; On a footnote reference or at definition's label.
  9063. ((or (eq type 'footnote-reference)
  9064. (and (eq type 'footnote-definition)
  9065. (save-excursion
  9066. ;; Do not validate action when point is on the
  9067. ;; spaces right after the footnote label, in
  9068. ;; order to be on par with behaviour on links.
  9069. (skip-chars-forward " \t")
  9070. (let ((begin
  9071. (org-element-property :contents-begin context)))
  9072. (if begin (< (point) begin)
  9073. (= (org-element-property :post-affiliated context)
  9074. (line-beginning-position)))))))
  9075. (org-footnote-action))
  9076. ;; No valid context. Ignore catch-all types like `headline'.
  9077. ;; If point is on something looking like a link or
  9078. ;; a time-stamp, try opening it. It may be useful in
  9079. ;; comments, example blocks...
  9080. ((memq type '(footnote-definition headline inlinetask nil))
  9081. (call-interactively #'org-open-at-point-global))
  9082. ;; On a clock line, make sure point is on the timestamp
  9083. ;; before opening it.
  9084. ((and (eq type 'clock)
  9085. value
  9086. (>= (point) (org-element-property :begin value))
  9087. (<= (point) (org-element-property :end value)))
  9088. (org-follow-timestamp-link))
  9089. ;; Do nothing on white spaces after an object.
  9090. ((>= (point)
  9091. (save-excursion
  9092. (goto-char (org-element-property :end context))
  9093. (skip-chars-backward " \t")
  9094. (point)))
  9095. (user-error "No link found"))
  9096. ((eq type 'timestamp) (org-follow-timestamp-link))
  9097. ((eq type 'link)
  9098. (let ((type (org-element-property :type context))
  9099. (path (org-link-unescape (org-element-property :path context))))
  9100. ;; Switch back to REFERENCE-BUFFER needed when called in
  9101. ;; a temporary buffer through `org-open-link-from-string'.
  9102. (with-current-buffer (or reference-buffer (current-buffer))
  9103. (cond
  9104. ((equal type "file")
  9105. (if (string-match "[*?{]" (file-name-nondirectory path))
  9106. (dired path)
  9107. ;; Look into `org-link-parameters' in order to find
  9108. ;; a DEDICATED-FUNCTION to open file. The function
  9109. ;; will be applied on raw link instead of parsed
  9110. ;; link due to the limitation in `org-add-link-type'
  9111. ;; ("open" function called with a single argument).
  9112. ;; If no such function is found, fallback to
  9113. ;; `org-open-file'.
  9114. (let* ((option (org-element-property :search-option context))
  9115. (app (org-element-property :application context))
  9116. (dedicated-function
  9117. (org-link-get-parameter
  9118. (if app (concat type "+" app) type)
  9119. :follow)))
  9120. (if dedicated-function
  9121. (funcall dedicated-function
  9122. (concat path
  9123. (and option (concat "::" option))))
  9124. (apply #'org-open-file
  9125. path
  9126. (cond (arg)
  9127. ((equal app "emacs") 'emacs)
  9128. ((equal app "sys") 'system))
  9129. (cond ((not option) nil)
  9130. ((string-match-p "\\`[0-9]+\\'" option)
  9131. (list (string-to-number option)))
  9132. (t (list nil
  9133. (org-link-unescape option)))))))))
  9134. ((functionp (org-link-get-parameter type :follow))
  9135. (funcall (org-link-get-parameter type :follow) path))
  9136. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9137. (unless (run-hook-with-args-until-success
  9138. 'org-open-link-functions path)
  9139. (if (not arg) (org-mark-ring-push)
  9140. (switch-to-buffer-other-window
  9141. (org-get-buffer-for-internal-link (current-buffer))))
  9142. (let ((destination
  9143. (org-with-wide-buffer
  9144. (if (equal type "radio")
  9145. (org-search-radio-target
  9146. (org-element-property :path context))
  9147. (org-link-search
  9148. (if (member type '("custom-id" "coderef"))
  9149. (org-element-property :raw-link context)
  9150. path)
  9151. ;; Prevent fuzzy links from matching
  9152. ;; themselves.
  9153. (and (equal type "fuzzy")
  9154. (+ 2 (org-element-property :begin context)))))
  9155. (point))))
  9156. (unless (and (<= (point-min) destination)
  9157. (>= (point-max) destination))
  9158. (widen))
  9159. (goto-char destination))))
  9160. (t (browse-url-at-point))))))
  9161. (t (user-error "No link found")))))
  9162. (run-hook-with-args 'org-follow-link-hook)))
  9163. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9164. "Offer links in the current entry and return the selected link.
  9165. If there is only one link, return it.
  9166. If NTH is an integer, return the NTH link found.
  9167. If ZERO is a string, check also this string for a link, and if
  9168. there is one, return it."
  9169. (with-current-buffer buffer
  9170. (org-with-wide-buffer
  9171. (goto-char marker)
  9172. (let ((cnt ?0)
  9173. have-zero end links link c)
  9174. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9175. (push (match-string 0 zero) links)
  9176. (setq cnt (1- cnt) have-zero t))
  9177. (save-excursion
  9178. (org-back-to-heading t)
  9179. (setq end (save-excursion (outline-next-heading) (point)))
  9180. (while (re-search-forward org-any-link-re end t)
  9181. (push (match-string 0) links))
  9182. (setq links (org-uniquify (reverse links))))
  9183. (cond
  9184. ((null links)
  9185. (message "No links"))
  9186. ((equal (length links) 1)
  9187. (setq link (car links)))
  9188. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9189. (setq link (nth (if have-zero nth (1- nth)) links)))
  9190. (t ; we have to select a link
  9191. (save-excursion
  9192. (save-window-excursion
  9193. (delete-other-windows)
  9194. (with-output-to-temp-buffer "*Select Link*"
  9195. (dolist (l links)
  9196. (cond
  9197. ((not (string-match org-bracket-link-regexp l))
  9198. (princ (format "[%c] %s\n" (cl-incf cnt)
  9199. (org-unbracket-string "<" ">" l))))
  9200. ((match-end 3)
  9201. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9202. (match-string 3 l) (match-string 1 l))))
  9203. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9204. (match-string 1 l)))))))
  9205. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9206. (message "Select link to open, RET to open all:")
  9207. (setq c (read-char-exclusive))
  9208. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9209. (when (equal c ?q) (user-error "Abort"))
  9210. (if (equal c ?\C-m)
  9211. (setq link links)
  9212. (setq nth (- c ?0))
  9213. (when have-zero (setq nth (1+ nth)))
  9214. (unless (and (integerp nth) (>= (length links) nth))
  9215. (user-error "Invalid link selection"))
  9216. (setq link (nth (1- nth) links)))))
  9217. (cons link end)))))
  9218. ;; TODO: These functions are deprecated since `org-open-at-point'
  9219. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9220. (defun org-open-file-with-system (path)
  9221. "Open file at PATH using the system way of opening it."
  9222. (org-open-file path 'system))
  9223. (defun org-open-file-with-emacs (path)
  9224. "Open file at PATH in Emacs."
  9225. (org-open-file path 'emacs))
  9226. ;;; File search
  9227. (defvar org-create-file-search-functions nil
  9228. "List of functions to construct the right search string for a file link.
  9229. These functions are called in turn with point at the location to
  9230. which the link should point.
  9231. A function in the hook should first test if it would like to
  9232. handle this file type, for example by checking the `major-mode'
  9233. or the file extension. If it decides not to handle this file, it
  9234. should just return nil to give other functions a chance. If it
  9235. does handle the file, it must return the search string to be used
  9236. when following the link. The search string will be part of the
  9237. file link, given after a double colon, and `org-open-at-point'
  9238. will automatically search for it. If special measures must be
  9239. taken to make the search successful, another function should be
  9240. added to the companion hook `org-execute-file-search-functions',
  9241. which see.
  9242. A function in this hook may also use `setq' to set the variable
  9243. `description' to provide a suggestion for the descriptive text to
  9244. be used for this link when it gets inserted into an Org buffer
  9245. with \\[org-insert-link].")
  9246. (defvar org-execute-file-search-functions nil
  9247. "List of functions to execute a file search triggered by a link.
  9248. Functions added to this hook must accept a single argument, the
  9249. search string that was part of the file link, the part after the
  9250. double colon. The function must first check if it would like to
  9251. handle this search, for example by checking the `major-mode' or
  9252. the file extension. If it decides not to handle this search, it
  9253. should just return nil to give other functions a chance. If it
  9254. does handle the search, it must return a non-nil value to keep
  9255. other functions from trying.
  9256. Each function can access the current prefix argument through the
  9257. variable `current-prefix-arg'. Note that a single prefix is used
  9258. to force opening a link in Emacs, so it may be good to only use a
  9259. numeric or double prefix to guide the search function.
  9260. In case this is needed, a function in this hook can also restore
  9261. the window configuration before `org-open-at-point' was called using:
  9262. (set-window-configuration org-window-config-before-follow-link)")
  9263. (defun org-search-radio-target (target)
  9264. "Search a radio target matching TARGET in current buffer.
  9265. White spaces are not significant."
  9266. (let ((re (format "<<<%s>>>"
  9267. (mapconcat #'regexp-quote
  9268. (split-string target)
  9269. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9270. (origin (point)))
  9271. (goto-char (point-min))
  9272. (catch :radio-match
  9273. (while (re-search-forward re nil t)
  9274. (backward-char)
  9275. (let ((object (org-element-context)))
  9276. (when (eq (org-element-type object) 'radio-target)
  9277. (goto-char (org-element-property :begin object))
  9278. (org-show-context 'link-search)
  9279. (throw :radio-match nil))))
  9280. (goto-char origin)
  9281. (user-error "No match for radio target: %s" target))))
  9282. (defun org-link-search (s &optional avoid-pos stealth)
  9283. "Search for a search string S.
  9284. If S starts with \"#\", it triggers a custom ID search.
  9285. If S is enclosed within parenthesis, it initiates a coderef
  9286. search.
  9287. If S is surrounded by forward slashes, it is interpreted as
  9288. a regular expression. In Org mode files, this will create an
  9289. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9290. to list matches. If the current buffer is in `dired-mode', grep
  9291. will be used to search in all files.
  9292. When AVOID-POS is given, ignore matches near that position.
  9293. When optional argument STEALTH is non-nil, do not modify
  9294. visibility around point, thus ignoring `org-show-context-detail'
  9295. variable.
  9296. Search is case-insensitive and ignores white spaces. Return type
  9297. of matched result, which is either `dedicated' or `fuzzy'."
  9298. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9299. (let* ((case-fold-search t)
  9300. (origin (point))
  9301. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9302. (starred (eq (string-to-char normalized) ?*))
  9303. (words (split-string (if starred (substring s 1) s)))
  9304. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9305. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9306. type)
  9307. (cond
  9308. ;; Check if there are any special search functions.
  9309. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9310. ((eq (string-to-char s) ?#)
  9311. ;; Look for a custom ID S if S starts with "#".
  9312. (let* ((id (substring normalized 1))
  9313. (match (org-find-property "CUSTOM_ID" id)))
  9314. (if match (progn (goto-char match) (setf type 'dedicated))
  9315. (error "No match for custom ID: %s" id))))
  9316. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9317. ;; Look for coderef targets if S is enclosed within parenthesis.
  9318. (let ((coderef (match-string-no-properties 1 normalized))
  9319. (re (substring s-single-re 1 -1)))
  9320. (goto-char (point-min))
  9321. (catch :coderef-match
  9322. (while (re-search-forward re nil t)
  9323. (let ((element (org-element-at-point)))
  9324. (when (and (memq (org-element-type element)
  9325. '(example-block src-block))
  9326. ;; Build proper regexp according to current
  9327. ;; block's label format.
  9328. (let ((label-fmt
  9329. (regexp-quote
  9330. (or (org-element-property :label-fmt element)
  9331. org-coderef-label-format))))
  9332. (save-excursion
  9333. (beginning-of-line)
  9334. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9335. (format label-fmt coderef))))))
  9336. (setq type 'dedicated)
  9337. (goto-char (match-beginning 1))
  9338. (throw :coderef-match nil))))
  9339. (goto-char origin)
  9340. (error "No match for coderef: %s" coderef))))
  9341. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9342. ;; Look for a regular expression.
  9343. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9344. (match-string 1 s)))
  9345. ;; From here, we handle fuzzy links.
  9346. ;;
  9347. ;; Look for targets, only if not in a headline search.
  9348. ((and (not starred)
  9349. (let ((target (format "<<%s>>" s-multi-re)))
  9350. (catch :target-match
  9351. (goto-char (point-min))
  9352. (while (re-search-forward target nil t)
  9353. (backward-char)
  9354. (let ((context (org-element-context)))
  9355. (when (eq (org-element-type context) 'target)
  9356. (setq type 'dedicated)
  9357. (goto-char (org-element-property :begin context))
  9358. (throw :target-match t))))
  9359. nil))))
  9360. ;; Look for elements named after S, only if not in a headline
  9361. ;; search.
  9362. ((and (not starred)
  9363. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9364. (catch :name-match
  9365. (goto-char (point-min))
  9366. (while (re-search-forward name nil t)
  9367. (let ((element (org-element-at-point)))
  9368. (when (equal words
  9369. (split-string
  9370. (org-element-property :name element)))
  9371. (setq type 'dedicated)
  9372. (beginning-of-line)
  9373. (throw :name-match t))))
  9374. nil))))
  9375. ;; Regular text search. Prefer headlines in Org mode buffers.
  9376. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9377. ;; statistics cookies and tags.
  9378. ((and (derived-mode-p 'org-mode)
  9379. (let ((title-re
  9380. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9381. org-outline-regexp-bol
  9382. org-comment-string
  9383. (mapconcat #'regexp-quote words ".+")))
  9384. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9385. (comment-re (eval-when-compile
  9386. (format "\\`%s[ \t]+" org-comment-string))))
  9387. (goto-char (point-min))
  9388. (catch :found
  9389. (while (re-search-forward title-re nil t)
  9390. (when (equal words
  9391. (split-string
  9392. (replace-regexp-in-string
  9393. cookie-re ""
  9394. (replace-regexp-in-string
  9395. comment-re "" (org-get-heading t t t)))))
  9396. (throw :found t)))
  9397. nil)))
  9398. (beginning-of-line)
  9399. (setq type 'dedicated))
  9400. ;; Offer to create non-existent headline depending on
  9401. ;; `org-link-search-must-match-exact-headline'.
  9402. ((and (derived-mode-p 'org-mode)
  9403. (not org-link-search-inhibit-query)
  9404. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9405. (yes-or-no-p "No match - create this as a new heading? "))
  9406. (goto-char (point-max))
  9407. (unless (bolp) (newline))
  9408. (org-insert-heading nil t t)
  9409. (insert s "\n")
  9410. (beginning-of-line 0))
  9411. ;; Only headlines are looked after. No need to process
  9412. ;; further: throw an error.
  9413. ((and (derived-mode-p 'org-mode)
  9414. (or starred org-link-search-must-match-exact-headline))
  9415. (goto-char origin)
  9416. (error "No match for fuzzy expression: %s" normalized))
  9417. ;; Regular text search.
  9418. ((catch :fuzzy-match
  9419. (goto-char (point-min))
  9420. (while (re-search-forward s-multi-re nil t)
  9421. ;; Skip match if it contains AVOID-POS or it is included in
  9422. ;; a link with a description but outside the description.
  9423. (unless (or (and avoid-pos
  9424. (<= (match-beginning 0) avoid-pos)
  9425. (> (match-end 0) avoid-pos))
  9426. (and (save-match-data
  9427. (org-in-regexp org-bracket-link-regexp))
  9428. (match-beginning 3)
  9429. (or (> (match-beginning 3) (point))
  9430. (<= (match-end 3) (point)))
  9431. (org-element-lineage
  9432. (save-match-data (org-element-context))
  9433. '(link) t)))
  9434. (goto-char (match-beginning 0))
  9435. (setq type 'fuzzy)
  9436. (throw :fuzzy-match t)))
  9437. nil))
  9438. ;; All failed. Throw an error.
  9439. (t (goto-char origin)
  9440. (error "No match for fuzzy expression: %s" normalized)))
  9441. ;; Disclose surroundings of match, if appropriate.
  9442. (when (and (derived-mode-p 'org-mode) (not stealth))
  9443. (org-show-context 'link-search))
  9444. type))
  9445. (defun org-get-buffer-for-internal-link (buffer)
  9446. "Return a buffer to be used for displaying the link target of internal links."
  9447. (cond
  9448. ((not org-display-internal-link-with-indirect-buffer)
  9449. buffer)
  9450. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9451. (message "Buffer is already a clone, not making another one")
  9452. ;; we also do not modify visibility in this case
  9453. buffer)
  9454. (t ; make a new indirect buffer for displaying the link
  9455. (let* ((bn (buffer-name buffer))
  9456. (ibn (concat bn "(Clone)"))
  9457. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9458. (with-current-buffer ib (org-overview))
  9459. ib))))
  9460. (defun org-do-occur (regexp &optional cleanup)
  9461. "Call the Emacs command `occur'.
  9462. If CLEANUP is non-nil, remove the printout of the regular expression
  9463. in the *Occur* buffer. This is useful if the regex is long and not useful
  9464. to read."
  9465. (occur regexp)
  9466. (when cleanup
  9467. (let ((cwin (selected-window)) win beg end)
  9468. (when (setq win (get-buffer-window "*Occur*"))
  9469. (select-window win))
  9470. (goto-char (point-min))
  9471. (when (re-search-forward "match[a-z]+" nil t)
  9472. (setq beg (match-end 0))
  9473. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9474. (setq end (1- (match-beginning 0)))))
  9475. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9476. (goto-char (point-min))
  9477. (select-window cwin))))
  9478. ;;; The mark ring for links jumps
  9479. (defvar org-mark-ring nil
  9480. "Mark ring for positions before jumps in Org mode.")
  9481. (defvar org-mark-ring-last-goto nil
  9482. "Last position in the mark ring used to go back.")
  9483. ;; Fill and close the ring
  9484. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9485. (dotimes (_ org-mark-ring-length)
  9486. (push (make-marker) org-mark-ring))
  9487. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9488. org-mark-ring)
  9489. (defun org-mark-ring-push (&optional pos buffer)
  9490. "Put the current position or POS into the mark ring and rotate it."
  9491. (interactive)
  9492. (setq pos (or pos (point)))
  9493. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9494. (move-marker (car org-mark-ring)
  9495. (or pos (point))
  9496. (or buffer (current-buffer)))
  9497. (message "%s"
  9498. (substitute-command-keys
  9499. "Position saved to mark ring, go back with \
  9500. `\\[org-mark-ring-goto]'.")))
  9501. (defun org-mark-ring-goto (&optional n)
  9502. "Jump to the previous position in the mark ring.
  9503. With prefix arg N, jump back that many stored positions. When
  9504. called several times in succession, walk through the entire ring.
  9505. Org mode commands jumping to a different position in the current file,
  9506. or to another Org file, automatically push the old position onto the ring."
  9507. (interactive "p")
  9508. (let (p m)
  9509. (if (eq last-command this-command)
  9510. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9511. (setq p org-mark-ring))
  9512. (setq org-mark-ring-last-goto p)
  9513. (setq m (car p))
  9514. (pop-to-buffer-same-window (marker-buffer m))
  9515. (goto-char m)
  9516. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9517. (defun org-add-angle-brackets (s)
  9518. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9519. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9520. s)
  9521. ;;; Following specific links
  9522. (defvar org-agenda-buffer-tmp-name)
  9523. (defvar org-agenda-start-on-weekday)
  9524. (defun org-follow-timestamp-link ()
  9525. "Open an agenda view for the time-stamp date/range at point."
  9526. (cond
  9527. ((org-at-date-range-p t)
  9528. (let ((org-agenda-start-on-weekday)
  9529. (t1 (match-string 1))
  9530. (t2 (match-string 2)) tt1 tt2)
  9531. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9532. tt2 (time-to-days (org-time-string-to-time t2)))
  9533. (let ((org-agenda-buffer-tmp-name
  9534. (format "*Org Agenda(a:%s)"
  9535. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9536. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9537. ((org-at-timestamp-p 'lax)
  9538. (let ((org-agenda-buffer-tmp-name
  9539. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9540. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9541. (substring (match-string 1) 0 10)))
  9542. 1)))
  9543. (t (error "This should not happen"))))
  9544. ;;; Following file links
  9545. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9546. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9547. (declare-function mailcap-mime-info
  9548. "mailcap" (string &optional request no-decode))
  9549. (defvar org-wait nil)
  9550. (defun org-open-file (path &optional in-emacs line search)
  9551. "Open the file at PATH.
  9552. First, this expands any special file name abbreviations. Then the
  9553. configuration variable `org-file-apps' is checked if it contains an
  9554. entry for this file type, and if yes, the corresponding command is launched.
  9555. If no application is found, Emacs simply visits the file.
  9556. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9557. With a double \\[universal-argument] \\[universal-argument] \
  9558. prefix arg, Org tries to avoid opening in Emacs
  9559. and to use an external application to visit the file.
  9560. Optional LINE specifies a line to go to, optional SEARCH a string
  9561. to search for. If LINE or SEARCH is given, the file will be
  9562. opened in Emacs, unless an entry from org-file-apps that makes
  9563. use of groups in a regexp matches.
  9564. If you want to change the way frames are used when following a
  9565. link, please customize `org-link-frame-setup'.
  9566. If the file does not exist, an error is thrown."
  9567. (let* ((file (if (equal path "")
  9568. buffer-file-name
  9569. (substitute-in-file-name (expand-file-name path))))
  9570. (file-apps (append org-file-apps (org-default-apps)))
  9571. (apps (cl-remove-if
  9572. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9573. (apps-dlink (cl-remove-if-not
  9574. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9575. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9576. (dirp (unless remp (file-directory-p file)))
  9577. (file (if (and dirp org-open-directory-means-index-dot-org)
  9578. (concat (file-name-as-directory file) "index.org")
  9579. file))
  9580. (a-m-a-p (assq 'auto-mode apps))
  9581. (dfile (downcase file))
  9582. ;; Reconstruct the original link from the PATH, LINE and
  9583. ;; SEARCH args.
  9584. (link (cond (line (concat file "::" (number-to-string line)))
  9585. (search (concat file "::" search))
  9586. (t file)))
  9587. (dlink (downcase link))
  9588. (ext
  9589. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9590. (match-string 1 dfile)))
  9591. (save-position-maybe
  9592. (let ((old-buffer (current-buffer))
  9593. (old-pos (point))
  9594. (old-mode major-mode))
  9595. (lambda ()
  9596. (and (derived-mode-p 'org-mode)
  9597. (eq old-mode 'org-mode)
  9598. (or (not (eq old-buffer (current-buffer)))
  9599. (not (eq old-pos (point))))
  9600. (org-mark-ring-push old-pos old-buffer)))))
  9601. cmd link-match-data)
  9602. (cond
  9603. ((member in-emacs '((16) system))
  9604. (setq cmd (cdr (assq 'system apps))))
  9605. (in-emacs (setq cmd 'emacs))
  9606. (t
  9607. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9608. (and dirp (cdr (assq 'directory apps)))
  9609. ;; First, try matching against apps-dlink if we
  9610. ;; get a match here, store the match data for
  9611. ;; later.
  9612. (let ((match (assoc-default dlink apps-dlink
  9613. 'string-match)))
  9614. (if match
  9615. (progn (setq link-match-data (match-data))
  9616. match)
  9617. (progn (setq in-emacs (or in-emacs line search))
  9618. nil))) ; if we have no match in apps-dlink,
  9619. ; always open the file in emacs if line or search
  9620. ; is given (for backwards compatibility)
  9621. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9622. 'string-match)
  9623. (cdr (assoc ext apps))
  9624. (cdr (assq t apps))))))
  9625. (when (eq cmd 'system)
  9626. (setq cmd (cdr (assq 'system apps))))
  9627. (when (eq cmd 'default)
  9628. (setq cmd (cdr (assoc t apps))))
  9629. (when (eq cmd 'mailcap)
  9630. (require 'mailcap)
  9631. (mailcap-parse-mailcaps)
  9632. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9633. (command (mailcap-mime-info mime-type)))
  9634. (if (stringp command)
  9635. (setq cmd command)
  9636. (setq cmd 'emacs))))
  9637. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9638. (not (file-exists-p file))
  9639. (not org-open-non-existing-files))
  9640. (user-error "No such file: %s" file))
  9641. (cond
  9642. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9643. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9644. (while (string-match "['\"]%s['\"]" cmd)
  9645. (setq cmd (replace-match "%s" t t cmd)))
  9646. (setq cmd (replace-regexp-in-string
  9647. "%s"
  9648. (shell-quote-argument (convert-standard-filename file))
  9649. cmd
  9650. nil t))
  9651. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9652. (save-match-data
  9653. (let ((match-index 1)
  9654. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9655. (set-match-data link-match-data)
  9656. (while (<= match-index number-of-groups)
  9657. (let ((regex (concat "%" (number-to-string match-index)))
  9658. (replace-with (match-string match-index dlink)))
  9659. (while (string-match regex cmd)
  9660. (setq cmd (replace-match replace-with t t cmd))))
  9661. (setq match-index (+ match-index 1)))))
  9662. (save-window-excursion
  9663. (message "Running %s...done" cmd)
  9664. (start-process-shell-command cmd nil cmd)
  9665. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9666. ((or (stringp cmd)
  9667. (eq cmd 'emacs))
  9668. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9669. (widen)
  9670. (cond (line (org-goto-line line)
  9671. (when (derived-mode-p 'org-mode) (org-reveal)))
  9672. (search (condition-case err
  9673. (org-link-search search)
  9674. ;; Save position before error-ing out so user
  9675. ;; can easily move back to the original buffer.
  9676. (error (funcall save-position-maybe)
  9677. (error (nth 1 err)))))))
  9678. ((functionp cmd)
  9679. (save-match-data
  9680. (set-match-data link-match-data)
  9681. (condition-case nil
  9682. (funcall cmd file link)
  9683. ;; FIXME: Remove this check when most default installations
  9684. ;; of Emacs have at least Org 9.0.
  9685. ((debug wrong-number-of-arguments wrong-type-argument
  9686. invalid-function)
  9687. (user-error "Please see Org News for version 9.0 about \
  9688. `org-file-apps'--Lisp error: %S" cmd)))))
  9689. ((consp cmd)
  9690. ;; FIXME: Remove this check when most default installations of
  9691. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9692. ;; fall back to `org-link-frame-setup' for an old usage of
  9693. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9694. (user-error "Please see Org News for version 9.0 about \
  9695. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9696. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9697. (funcall save-position-maybe)))
  9698. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9699. "This function returns non-nil if `entry' uses a regular
  9700. expression which should be matched against the whole link by
  9701. org-open-file.
  9702. It assumes that is the case when the entry uses a regular
  9703. expression which has at least one grouping construct and the
  9704. action is either a lisp form or a command string containing
  9705. `%1', i.e. using at least one subexpression match as a
  9706. parameter."
  9707. (let ((selector (car entry))
  9708. (action (cdr entry)))
  9709. (if (stringp selector)
  9710. (and (> (regexp-opt-depth selector) 0)
  9711. (or (and (stringp action)
  9712. (string-match "%[0-9]" action))
  9713. (consp action)))
  9714. nil)))
  9715. (defun org-default-apps ()
  9716. "Return the default applications for this operating system."
  9717. (cond
  9718. ((eq system-type 'darwin)
  9719. org-file-apps-defaults-macosx)
  9720. ((eq system-type 'windows-nt)
  9721. org-file-apps-defaults-windowsnt)
  9722. (t org-file-apps-defaults-gnu)))
  9723. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9724. "Convert extensions to regular expressions in the cars of LIST.
  9725. Also, weed out any non-string entries, because the return value is used
  9726. only for regexp matching.
  9727. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9728. point to the symbol `emacs', indicating that the file should
  9729. be opened in Emacs."
  9730. (append
  9731. (delq nil
  9732. (mapcar (lambda (x)
  9733. (unless (not (stringp (car x)))
  9734. (if (string-match "\\W" (car x))
  9735. x
  9736. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9737. list))
  9738. (when add-auto-mode
  9739. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9740. (defvar ange-ftp-name-format)
  9741. (defun org-file-remote-p (file)
  9742. "Test whether FILE specifies a location on a remote system.
  9743. Return non-nil if the location is indeed remote.
  9744. For example, the filename \"/user@host:/foo\" specifies a location
  9745. on the system \"/user@host:\"."
  9746. (cond ((fboundp 'file-remote-p)
  9747. (file-remote-p file))
  9748. ((fboundp 'tramp-handle-file-remote-p)
  9749. (tramp-handle-file-remote-p file))
  9750. ((and (boundp 'ange-ftp-name-format)
  9751. (string-match (car ange-ftp-name-format) file))
  9752. t)))
  9753. ;;;; Refiling
  9754. (defun org-get-org-file ()
  9755. "Read a filename, with default directory `org-directory'."
  9756. (let ((default (or org-default-notes-file remember-data-file)))
  9757. (read-file-name (format "File name [%s]: " default)
  9758. (file-name-as-directory org-directory)
  9759. default)))
  9760. (defun org-notes-order-reversed-p ()
  9761. "Check if the current file should receive notes in reversed order."
  9762. (cond
  9763. ((not org-reverse-note-order) nil)
  9764. ((eq t org-reverse-note-order) t)
  9765. ((not (listp org-reverse-note-order)) nil)
  9766. (t (catch 'exit
  9767. (dolist (entry org-reverse-note-order)
  9768. (when (string-match (car entry) buffer-file-name)
  9769. (throw 'exit (cdr entry))))))))
  9770. (defvar org-refile-target-table nil
  9771. "The list of refile targets, created by `org-refile'.")
  9772. (defvar org-agenda-new-buffers nil
  9773. "Buffers created to visit agenda files.")
  9774. (defvar org-refile-cache nil
  9775. "Cache for refile targets.")
  9776. (defvar org-refile-markers nil
  9777. "All the markers used for caching refile locations.")
  9778. (defun org-refile-marker (pos)
  9779. "Get a new refile marker, but only if caching is in use."
  9780. (if (not org-refile-use-cache)
  9781. pos
  9782. (let ((m (make-marker)))
  9783. (move-marker m pos)
  9784. (push m org-refile-markers)
  9785. m)))
  9786. (defun org-refile-cache-clear ()
  9787. "Clear the refile cache and disable all the markers."
  9788. (dolist (m org-refile-markers) (move-marker m nil))
  9789. (setq org-refile-markers nil)
  9790. (setq org-refile-cache nil)
  9791. (message "Refile cache has been cleared"))
  9792. (defun org-refile-cache-check-set (set)
  9793. "Check if all the markers in the cache still have live buffers."
  9794. (let (marker)
  9795. (catch 'exit
  9796. (while (and set (setq marker (nth 3 (pop set))))
  9797. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9798. (when (and marker (null (marker-buffer marker)))
  9799. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9800. (sit-for 3)
  9801. (throw 'exit nil)))
  9802. t)))
  9803. (defun org-refile-cache-put (set &rest identifiers)
  9804. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9805. (let* ((key (sha1 (prin1-to-string identifiers)))
  9806. (entry (assoc key org-refile-cache)))
  9807. (if entry
  9808. (setcdr entry set)
  9809. (push (cons key set) org-refile-cache))))
  9810. (defun org-refile-cache-get (&rest identifiers)
  9811. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9812. (cond
  9813. ((not org-refile-cache) nil)
  9814. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9815. (t
  9816. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9817. org-refile-cache))))
  9818. (and set (org-refile-cache-check-set set) set)))))
  9819. (defvar org-outline-path-cache nil
  9820. "Alist between buffer positions and outline paths.
  9821. It value is an alist (POSITION . PATH) where POSITION is the
  9822. buffer position at the beginning of an entry and PATH is a list
  9823. of strings describing the outline path for that entry, in reverse
  9824. order.")
  9825. (defun org-refile-get-targets (&optional default-buffer)
  9826. "Produce a table with refile targets."
  9827. (let ((case-fold-search nil)
  9828. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9829. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9830. targets tgs files desc descre)
  9831. (message "Getting targets...")
  9832. (with-current-buffer (or default-buffer (current-buffer))
  9833. (dolist (entry entries)
  9834. (setq files (car entry) desc (cdr entry))
  9835. (cond
  9836. ((null files) (setq files (list (current-buffer))))
  9837. ((eq files 'org-agenda-files)
  9838. (setq files (org-agenda-files 'unrestricted)))
  9839. ((and (symbolp files) (fboundp files))
  9840. (setq files (funcall files)))
  9841. ((and (symbolp files) (boundp files))
  9842. (setq files (symbol-value files))))
  9843. (when (stringp files) (setq files (list files)))
  9844. (cond
  9845. ((eq (car desc) :tag)
  9846. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9847. ((eq (car desc) :todo)
  9848. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9849. ((eq (car desc) :regexp)
  9850. (setq descre (cdr desc)))
  9851. ((eq (car desc) :level)
  9852. (setq descre (concat "^\\*\\{" (number-to-string
  9853. (if org-odd-levels-only
  9854. (1- (* 2 (cdr desc)))
  9855. (cdr desc)))
  9856. "\\}[ \t]")))
  9857. ((eq (car desc) :maxlevel)
  9858. (setq descre (concat "^\\*\\{1," (number-to-string
  9859. (if org-odd-levels-only
  9860. (1- (* 2 (cdr desc)))
  9861. (cdr desc)))
  9862. "\\}[ \t]")))
  9863. (t (error "Bad refiling target description %s" desc)))
  9864. (dolist (f files)
  9865. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9866. (or
  9867. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9868. (progn
  9869. (when (bufferp f)
  9870. (setq f (buffer-file-name (buffer-base-buffer f))))
  9871. (setq f (and f (expand-file-name f)))
  9872. (when (eq org-refile-use-outline-path 'file)
  9873. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9874. (when (eq org-refile-use-outline-path 'buffer-name)
  9875. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9876. (when (eq org-refile-use-outline-path 'full-file-path)
  9877. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9878. (org-with-wide-buffer
  9879. (goto-char (point-min))
  9880. (setq org-outline-path-cache nil)
  9881. (while (re-search-forward descre nil t)
  9882. (beginning-of-line)
  9883. (let ((case-fold-search nil))
  9884. (looking-at org-complex-heading-regexp))
  9885. (let ((begin (point))
  9886. (heading (match-string-no-properties 4)))
  9887. (unless (or (and
  9888. org-refile-target-verify-function
  9889. (not
  9890. (funcall org-refile-target-verify-function)))
  9891. (not heading))
  9892. (let ((re (format org-complex-heading-regexp-format
  9893. (regexp-quote heading)))
  9894. (target
  9895. (if (not org-refile-use-outline-path) heading
  9896. (mapconcat
  9897. #'identity
  9898. (append
  9899. (pcase org-refile-use-outline-path
  9900. (`file (list (file-name-nondirectory
  9901. (buffer-file-name
  9902. (buffer-base-buffer)))))
  9903. (`full-file-path
  9904. (list (buffer-file-name
  9905. (buffer-base-buffer))))
  9906. (`buffer-name
  9907. (list (buffer-name
  9908. (buffer-base-buffer))))
  9909. (_ nil))
  9910. (mapcar (lambda (s) (replace-regexp-in-string
  9911. "/" "\\/" s nil t))
  9912. (org-get-outline-path t t)))
  9913. "/"))))
  9914. (push (list target f re (org-refile-marker (point)))
  9915. tgs)))
  9916. (when (= (point) begin)
  9917. ;; Verification function has not moved point.
  9918. (end-of-line)))))))
  9919. (when org-refile-use-cache
  9920. (org-refile-cache-put tgs (buffer-file-name) descre))
  9921. (setq targets (append tgs targets))))))
  9922. (message "Getting targets...done")
  9923. (delete-dups (nreverse targets))))
  9924. (defun org--get-outline-path-1 (&optional use-cache)
  9925. "Return outline path to current headline.
  9926. Outline path is a list of strings, in reverse order. When
  9927. optional argument USE-CACHE is non-nil, make use of a cache. See
  9928. `org-get-outline-path' for details.
  9929. Assume buffer is widened and point is on a headline."
  9930. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9931. (let ((p (point))
  9932. (heading (let ((case-fold-search nil))
  9933. (looking-at org-complex-heading-regexp)
  9934. (if (not (match-end 4)) ""
  9935. ;; Remove statistics cookies.
  9936. (org-trim
  9937. (org-link-display-format
  9938. (replace-regexp-in-string
  9939. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9940. (match-string-no-properties 4))))))))
  9941. (if (org-up-heading-safe)
  9942. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9943. (when use-cache
  9944. (push (cons p path) org-outline-path-cache))
  9945. path)
  9946. ;; This is a new root node. Since we assume we are moving
  9947. ;; forward, we can drop previous cache so as to limit number
  9948. ;; of associations there.
  9949. (let ((path (list heading)))
  9950. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9951. path)))))
  9952. (defun org-get-outline-path (&optional with-self use-cache)
  9953. "Return the outline path to the current entry.
  9954. An outline path is a list of ancestors for current headline, as
  9955. a list of strings. Statistics cookies are removed and links are
  9956. replaced with their description, if any, or their path otherwise.
  9957. When optional argument WITH-SELF is non-nil, the path also
  9958. includes the current headline.
  9959. When optional argument USE-CACHE is non-nil, cache outline paths
  9960. between calls to this function so as to avoid backtracking. This
  9961. argument is useful when planning to find more than one outline
  9962. path in the same document. In that case, there are two
  9963. conditions to satisfy:
  9964. - `org-outline-path-cache' is set to nil before starting the
  9965. process;
  9966. - outline paths are computed by increasing buffer positions."
  9967. (org-with-wide-buffer
  9968. (and (or (and with-self (org-back-to-heading t))
  9969. (org-up-heading-safe))
  9970. (reverse (org--get-outline-path-1 use-cache)))))
  9971. (defun org-format-outline-path (path &optional width prefix separator)
  9972. "Format the outline path PATH for display.
  9973. WIDTH is the maximum number of characters that is available.
  9974. PREFIX is a prefix to be included in the returned string,
  9975. such as the file name.
  9976. SEPARATOR is inserted between the different parts of the path,
  9977. the default is \"/\"."
  9978. (setq width (or width 79))
  9979. (setq path (delq nil path))
  9980. (unless (> width 0)
  9981. (user-error "Argument `width' must be positive"))
  9982. (setq separator (or separator "/"))
  9983. (let* ((org-odd-levels-only nil)
  9984. (fpath (concat
  9985. prefix (and prefix path separator)
  9986. (mapconcat
  9987. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9988. (cl-loop for head in path
  9989. for n from 0
  9990. collect (org-add-props
  9991. head nil 'face
  9992. (nth (% n org-n-level-faces) org-level-faces)))
  9993. separator))))
  9994. (when (> (length fpath) width)
  9995. (if (< width 7)
  9996. ;; It's unlikely that `width' will be this small, but don't
  9997. ;; waste characters by adding ".." if it is.
  9998. (setq fpath (substring fpath 0 width))
  9999. (setf (substring fpath (- width 2)) "..")))
  10000. fpath))
  10001. (defun org-display-outline-path (&optional file current separator just-return-string)
  10002. "Display the current outline path in the echo area.
  10003. If FILE is non-nil, prepend the output with the file name.
  10004. If CURRENT is non-nil, append the current heading to the output.
  10005. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10006. the different parts of the path and defaults to \"/\".
  10007. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10008. (interactive "P")
  10009. (let* (case-fold-search
  10010. (bfn (buffer-file-name (buffer-base-buffer)))
  10011. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10012. res)
  10013. (when current (setq path (append path
  10014. (save-excursion
  10015. (org-back-to-heading t)
  10016. (when (looking-at org-complex-heading-regexp)
  10017. (list (match-string 4)))))))
  10018. (setq res
  10019. (org-format-outline-path
  10020. path
  10021. (1- (frame-width))
  10022. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10023. separator))
  10024. (if just-return-string
  10025. (org-no-properties res)
  10026. (org-unlogged-message "%s" res))))
  10027. (defvar org-refile-history nil
  10028. "History for refiling operations.")
  10029. (defvar org-after-refile-insert-hook nil
  10030. "Hook run after `org-refile' has inserted its stuff at the new location.
  10031. Note that this is still *before* the stuff will be removed from
  10032. the *old* location.")
  10033. (defvar org-capture-last-stored-marker)
  10034. (defvar org-refile-keep nil
  10035. "Non-nil means `org-refile' will copy instead of refile.")
  10036. (defun org-copy ()
  10037. "Like `org-refile', but copy."
  10038. (interactive)
  10039. (let ((org-refile-keep t))
  10040. (funcall 'org-refile nil nil nil "Copy")))
  10041. (defun org-refile (&optional arg default-buffer rfloc msg)
  10042. "Move the entry or entries at point to another heading.
  10043. The list of target headings is compiled using the information in
  10044. `org-refile-targets', which see.
  10045. At the target location, the entry is filed as a subitem of the
  10046. target heading. Depending on `org-reverse-note-order', the new
  10047. subitem will either be the first or the last subitem.
  10048. If there is an active region, all entries in that region will be
  10049. refiled. However, the region must fulfill the requirement that
  10050. the first heading sets the top-level of the moved text.
  10051. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10052. location
  10053. and not actually move anything.
  10054. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10055. location where the last
  10056. refiling operation has put the subtree.
  10057. With a numeric prefix argument of `2', refile to the running clock.
  10058. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10059. being set to t and copy to the target location, don't move it.
  10060. Beware that keeping refiled entries may result in duplicated ID
  10061. properties.
  10062. RFLOC can be a refile location obtained in a different way.
  10063. MSG is a string to replace \"Refile\" in the default prompt with
  10064. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10065. See also `org-refile-use-outline-path'.
  10066. If you are using target caching (see `org-refile-use-cache'), you
  10067. have to clear the target cache in order to find new targets.
  10068. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10069. prefix argument (`C-u C-u C-u C-c C-w')."
  10070. (interactive "P")
  10071. (if (member arg '(0 (64)))
  10072. (org-refile-cache-clear)
  10073. (let* ((actionmsg (cond (msg msg)
  10074. ((equal arg 3) "Refile (and keep)")
  10075. (t "Refile")))
  10076. (regionp (org-region-active-p))
  10077. (region-start (and regionp (region-beginning)))
  10078. (region-end (and regionp (region-end)))
  10079. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10080. pos it nbuf file level reversed)
  10081. (setq last-command nil)
  10082. (when regionp
  10083. (goto-char region-start)
  10084. (or (bolp) (goto-char (point-at-bol)))
  10085. (setq region-start (point))
  10086. (unless (or (org-kill-is-subtree-p
  10087. (buffer-substring region-start region-end))
  10088. (prog1 org-refile-active-region-within-subtree
  10089. (let ((s (point-at-eol)))
  10090. (org-toggle-heading)
  10091. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10092. (user-error "The region is not a (sequence of) subtree(s)")))
  10093. (if (equal arg '(16))
  10094. (org-refile-goto-last-stored)
  10095. (when (or
  10096. (and (equal arg 2)
  10097. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10098. (prog1
  10099. (setq it (list (or org-clock-heading "running clock")
  10100. (buffer-file-name
  10101. (marker-buffer org-clock-hd-marker))
  10102. ""
  10103. (marker-position org-clock-hd-marker)))
  10104. (setq arg nil)))
  10105. (setq it
  10106. (or rfloc
  10107. (let (heading-text)
  10108. (save-excursion
  10109. (unless (and arg (listp arg))
  10110. (org-back-to-heading t)
  10111. (setq heading-text
  10112. (replace-regexp-in-string
  10113. org-bracket-link-regexp
  10114. "\\3"
  10115. (or (nth 4 (org-heading-components))
  10116. ""))))
  10117. (org-refile-get-location
  10118. (cond ((and arg (listp arg)) "Goto")
  10119. (regionp (concat actionmsg " region to"))
  10120. (t (concat actionmsg " subtree \""
  10121. heading-text "\" to")))
  10122. default-buffer
  10123. (and (not (equal '(4) arg))
  10124. org-refile-allow-creating-parent-nodes)))))))
  10125. (setq file (nth 1 it)
  10126. pos (nth 3 it))
  10127. (when (and (not arg)
  10128. pos
  10129. (equal (buffer-file-name) file)
  10130. (if regionp
  10131. (and (>= pos region-start)
  10132. (<= pos region-end))
  10133. (and (>= pos (point))
  10134. (< pos (save-excursion
  10135. (org-end-of-subtree t t))))))
  10136. (error "Cannot refile to position inside the tree or region"))
  10137. (setq nbuf (or (find-buffer-visiting file)
  10138. (find-file-noselect file)))
  10139. (if (and arg (not (equal arg 3)))
  10140. (progn
  10141. (pop-to-buffer-same-window nbuf)
  10142. (goto-char (cond (pos)
  10143. ((org-notes-order-reversed-p) (point-min))
  10144. (t (point-max))))
  10145. (org-show-context 'org-goto))
  10146. (if regionp
  10147. (progn
  10148. (org-kill-new (buffer-substring region-start region-end))
  10149. (org-save-markers-in-region region-start region-end))
  10150. (org-copy-subtree 1 nil t))
  10151. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10152. (find-file-noselect file)))
  10153. (setq reversed (org-notes-order-reversed-p))
  10154. (org-with-wide-buffer
  10155. (if pos
  10156. (progn
  10157. (goto-char pos)
  10158. (setq level (org-get-valid-level (funcall outline-level) 1))
  10159. (goto-char
  10160. (if reversed
  10161. (or (outline-next-heading) (point-max))
  10162. (or (save-excursion (org-get-next-sibling))
  10163. (org-end-of-subtree t t)
  10164. (point-max)))))
  10165. (setq level 1)
  10166. (if (not reversed)
  10167. (goto-char (point-max))
  10168. (goto-char (point-min))
  10169. (or (outline-next-heading) (goto-char (point-max)))))
  10170. (unless (bolp) (newline))
  10171. (org-paste-subtree level nil nil t)
  10172. (when org-log-refile
  10173. (org-add-log-setup 'refile nil nil org-log-refile)
  10174. (unless (eq org-log-refile 'note)
  10175. (save-excursion (org-add-log-note))))
  10176. (and org-auto-align-tags
  10177. (let ((org-loop-over-headlines-in-active-region nil))
  10178. (org-set-tags nil t)))
  10179. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10180. :last-refile)))
  10181. (when bookmark-name
  10182. (with-demoted-errors
  10183. (bookmark-set bookmark-name))))
  10184. ;; If we are refiling for capture, make sure that the
  10185. ;; last-capture pointers point here
  10186. (when (bound-and-true-p org-capture-is-refiling)
  10187. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10188. :last-capture-marker)))
  10189. (when bookmark-name
  10190. (with-demoted-errors
  10191. (bookmark-set bookmark-name))))
  10192. (move-marker org-capture-last-stored-marker (point)))
  10193. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10194. (run-hooks 'org-after-refile-insert-hook)))
  10195. (unless org-refile-keep
  10196. (if regionp
  10197. (delete-region (point) (+ (point) (- region-end region-start)))
  10198. (org-preserve-local-variables
  10199. (delete-region
  10200. (and (org-back-to-heading t) (point))
  10201. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10202. (when (featurep 'org-inlinetask)
  10203. (org-inlinetask-remove-END-maybe))
  10204. (setq org-markers-to-move nil)
  10205. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10206. (defun org-refile-goto-last-stored ()
  10207. "Go to the location where the last refile was stored."
  10208. (interactive)
  10209. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10210. (message "This is the location of the last refile"))
  10211. (defun org-refile--get-location (refloc tbl)
  10212. "When user refile to REFLOC, find the associated target in TBL.
  10213. Also check `org-refile-target-table'."
  10214. (car (delq
  10215. nil
  10216. (mapcar
  10217. (lambda (r) (or (assoc r tbl)
  10218. (assoc r org-refile-target-table)))
  10219. (list (replace-regexp-in-string "/$" "" refloc)
  10220. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10221. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10222. "Prompt the user for a refile location, using PROMPT.
  10223. PROMPT should not be suffixed with a colon and a space, because
  10224. this function appends the default value from
  10225. `org-refile-history' automatically, if that is not empty."
  10226. (let ((org-refile-targets org-refile-targets)
  10227. (org-refile-use-outline-path org-refile-use-outline-path))
  10228. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10229. (unless org-refile-target-table
  10230. (user-error "No refile targets"))
  10231. (let* ((cbuf (current-buffer))
  10232. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10233. (cfunc (if (and org-refile-use-outline-path
  10234. org-outline-path-complete-in-steps)
  10235. #'org-olpath-completing-read
  10236. #'completing-read))
  10237. (extra (if org-refile-use-outline-path "/" ""))
  10238. (cbnex (concat (buffer-name) extra))
  10239. (filename (and cfn (expand-file-name cfn)))
  10240. (tbl (mapcar
  10241. (lambda (x)
  10242. (if (and (not (member org-refile-use-outline-path
  10243. '(file full-file-path)))
  10244. (not (equal filename (nth 1 x))))
  10245. (cons (concat (car x) extra " ("
  10246. (file-name-nondirectory (nth 1 x)) ")")
  10247. (cdr x))
  10248. (cons (concat (car x) extra) (cdr x))))
  10249. org-refile-target-table))
  10250. (completion-ignore-case t)
  10251. cdef
  10252. (prompt (concat prompt
  10253. (or (and (car org-refile-history)
  10254. (concat " (default " (car org-refile-history) ")"))
  10255. (and (assoc cbnex tbl) (setq cdef cbnex)
  10256. (concat " (default " cbnex ")"))) ": "))
  10257. pa answ parent-target child parent old-hist)
  10258. (setq old-hist org-refile-history)
  10259. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10260. nil 'org-refile-history (or cdef (car org-refile-history))))
  10261. (if (setq pa (org-refile--get-location answ tbl))
  10262. (progn
  10263. (org-refile-check-position pa)
  10264. (when (or (not org-refile-history)
  10265. (not (eq old-hist org-refile-history))
  10266. (not (equal (car pa) (car org-refile-history))))
  10267. (setq org-refile-history
  10268. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10269. org-refile-history
  10270. (cdr org-refile-history))))
  10271. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10272. (pop org-refile-history)))
  10273. pa)
  10274. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10275. (progn
  10276. (setq parent (match-string 1 answ)
  10277. child (match-string 2 answ))
  10278. (setq parent-target (org-refile--get-location parent tbl))
  10279. (when (and parent-target
  10280. (or (eq new-nodes t)
  10281. (and (eq new-nodes 'confirm)
  10282. (y-or-n-p (format "Create new node \"%s\"? "
  10283. child)))))
  10284. (org-refile-new-child parent-target child)))
  10285. (user-error "Invalid target location")))))
  10286. (declare-function org-string-nw-p "org-macs" (s))
  10287. (defun org-refile-check-position (refile-pointer)
  10288. "Check if the refile pointer matches the headline to which it points."
  10289. (let* ((file (nth 1 refile-pointer))
  10290. (re (nth 2 refile-pointer))
  10291. (pos (nth 3 refile-pointer))
  10292. buffer)
  10293. (if (and (not (markerp pos)) (not file))
  10294. (user-error "Please indicate a target file in the refile path")
  10295. (when (org-string-nw-p re)
  10296. (setq buffer (if (markerp pos)
  10297. (marker-buffer pos)
  10298. (or (find-buffer-visiting file)
  10299. (find-file-noselect file))))
  10300. (with-current-buffer buffer
  10301. (org-with-wide-buffer
  10302. (goto-char pos)
  10303. (beginning-of-line 1)
  10304. (unless (looking-at-p re)
  10305. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10306. (defun org-refile-new-child (parent-target child)
  10307. "Use refile target PARENT-TARGET to add new CHILD below it."
  10308. (unless parent-target
  10309. (error "Cannot find parent for new node"))
  10310. (let ((file (nth 1 parent-target))
  10311. (pos (nth 3 parent-target))
  10312. level)
  10313. (with-current-buffer (or (find-buffer-visiting file)
  10314. (find-file-noselect file))
  10315. (org-with-wide-buffer
  10316. (if pos
  10317. (goto-char pos)
  10318. (goto-char (point-max))
  10319. (unless (bolp) (newline)))
  10320. (when (looking-at org-outline-regexp)
  10321. (setq level (funcall outline-level))
  10322. (org-end-of-subtree t t))
  10323. (org-back-over-empty-lines)
  10324. (insert "\n" (make-string
  10325. (if pos (org-get-valid-level level 1) 1) ?*)
  10326. " " child "\n")
  10327. (beginning-of-line 0)
  10328. (list (concat (car parent-target) "/" child) file "" (point))))))
  10329. (defun org-olpath-completing-read (prompt collection &rest args)
  10330. "Read an outline path like a file name."
  10331. (let ((thetable collection))
  10332. (apply #'completing-read
  10333. prompt
  10334. (lambda (string predicate &optional flag)
  10335. (cond
  10336. ((eq flag nil) (try-completion string thetable))
  10337. ((eq flag t)
  10338. (let ((l (length string)))
  10339. (mapcar (lambda (x)
  10340. (let ((r (substring x l))
  10341. (f (if (string-match " ([^)]*)$" x)
  10342. (match-string 0 x)
  10343. "")))
  10344. (if (string-match "/" r)
  10345. (concat string (substring r 0 (match-end 0)) f)
  10346. x)))
  10347. (all-completions string thetable predicate))))
  10348. ;; Exact match?
  10349. ((eq flag 'lambda) (assoc string thetable))))
  10350. args)))
  10351. ;;;; Dynamic blocks
  10352. (defun org-find-dblock (name)
  10353. "Find the first dynamic block with name NAME in the buffer.
  10354. If not found, stay at current position and return nil."
  10355. (let ((case-fold-search t) pos)
  10356. (save-excursion
  10357. (goto-char (point-min))
  10358. (setq pos (and (re-search-forward
  10359. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10360. (match-beginning 0))))
  10361. (when pos (goto-char pos))
  10362. pos))
  10363. (defun org-create-dblock (plist)
  10364. "Create a dynamic block section, with parameters taken from PLIST.
  10365. PLIST must contain a :name entry which is used as the name of the block."
  10366. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10367. (end-of-line 1)
  10368. (newline))
  10369. (let ((col (current-column))
  10370. (name (plist-get plist :name)))
  10371. (insert "#+BEGIN: " name)
  10372. (while plist
  10373. (if (eq (car plist) :name)
  10374. (setq plist (cddr plist))
  10375. (insert " " (prin1-to-string (pop plist)))))
  10376. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10377. (beginning-of-line -2)))
  10378. (defun org-prepare-dblock ()
  10379. "Prepare dynamic block for refresh.
  10380. This empties the block, puts the cursor at the insert position and returns
  10381. the property list including an extra property :name with the block name."
  10382. (unless (looking-at org-dblock-start-re)
  10383. (user-error "Not at a dynamic block"))
  10384. (let* ((begdel (1+ (match-end 0)))
  10385. (name (org-no-properties (match-string 1)))
  10386. (params (append (list :name name)
  10387. (read (concat "(" (match-string 3) ")")))))
  10388. (save-excursion
  10389. (beginning-of-line 1)
  10390. (skip-chars-forward " \t")
  10391. (setq params (plist-put params :indentation-column (current-column))))
  10392. (unless (re-search-forward org-dblock-end-re nil t)
  10393. (error "Dynamic block not terminated"))
  10394. (setq params
  10395. (append params
  10396. (list :content (buffer-substring
  10397. begdel (match-beginning 0)))))
  10398. (delete-region begdel (match-beginning 0))
  10399. (goto-char begdel)
  10400. (open-line 1)
  10401. params))
  10402. (defun org-map-dblocks (&optional command)
  10403. "Apply COMMAND to all dynamic blocks in the current buffer.
  10404. If COMMAND is not given, use `org-update-dblock'."
  10405. (let ((cmd (or command 'org-update-dblock)))
  10406. (save-excursion
  10407. (goto-char (point-min))
  10408. (while (re-search-forward org-dblock-start-re nil t)
  10409. (goto-char (match-beginning 0))
  10410. (save-excursion
  10411. (condition-case nil
  10412. (funcall cmd)
  10413. (error (message "Error during update of dynamic block"))))
  10414. (unless (re-search-forward org-dblock-end-re nil t)
  10415. (error "Dynamic block not terminated"))))))
  10416. (defun org-dblock-update (&optional arg)
  10417. "User command for updating dynamic blocks.
  10418. Update the dynamic block at point. With prefix ARG, update all dynamic
  10419. blocks in the buffer."
  10420. (interactive "P")
  10421. (if arg
  10422. (org-update-all-dblocks)
  10423. (or (looking-at org-dblock-start-re)
  10424. (org-beginning-of-dblock))
  10425. (org-update-dblock)))
  10426. (defun org-update-dblock ()
  10427. "Update the dynamic block at point.
  10428. This means to empty the block, parse for parameters and then call
  10429. the correct writing function."
  10430. (interactive)
  10431. (save-excursion
  10432. (let* ((win (selected-window))
  10433. (pos (point))
  10434. (line (org-current-line))
  10435. (params (org-prepare-dblock))
  10436. (name (plist-get params :name))
  10437. (indent (plist-get params :indentation-column))
  10438. (cmd (intern (concat "org-dblock-write:" name))))
  10439. (message "Updating dynamic block `%s' at line %d..." name line)
  10440. (funcall cmd params)
  10441. (message "Updating dynamic block `%s' at line %d...done" name line)
  10442. (goto-char pos)
  10443. (when (and indent (> indent 0))
  10444. (setq indent (make-string indent ?\ ))
  10445. (save-excursion
  10446. (select-window win)
  10447. (org-beginning-of-dblock)
  10448. (forward-line 1)
  10449. (while (not (looking-at org-dblock-end-re))
  10450. (insert indent)
  10451. (beginning-of-line 2))
  10452. (when (looking-at org-dblock-end-re)
  10453. (and (looking-at "[ \t]+")
  10454. (replace-match ""))
  10455. (insert indent)))))))
  10456. (defun org-beginning-of-dblock ()
  10457. "Find the beginning of the dynamic block at point.
  10458. Error if there is no such block at point."
  10459. (let ((pos (point))
  10460. beg)
  10461. (end-of-line 1)
  10462. (if (and (re-search-backward org-dblock-start-re nil t)
  10463. (setq beg (match-beginning 0))
  10464. (re-search-forward org-dblock-end-re nil t)
  10465. (> (match-end 0) pos))
  10466. (goto-char beg)
  10467. (goto-char pos)
  10468. (error "Not in a dynamic block"))))
  10469. (defun org-update-all-dblocks ()
  10470. "Update all dynamic blocks in the buffer.
  10471. This function can be used in a hook."
  10472. (interactive)
  10473. (when (derived-mode-p 'org-mode)
  10474. (org-map-dblocks 'org-update-dblock)))
  10475. ;;;; Completion
  10476. (declare-function org-export-backend-options "ox" (cl-x) t)
  10477. (defun org-get-export-keywords ()
  10478. "Return a list of all currently understood export keywords.
  10479. Export keywords include options, block names, attributes and
  10480. keywords relative to each registered export back-end."
  10481. (let (keywords)
  10482. (dolist (backend
  10483. (bound-and-true-p org-export-registered-backends)
  10484. (delq nil keywords))
  10485. ;; Back-end name (for keywords, like #+LATEX:)
  10486. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10487. (dolist (option-entry (org-export-backend-options backend))
  10488. ;; Back-end options.
  10489. (push (nth 1 option-entry) keywords)))))
  10490. (defconst org-options-keywords
  10491. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10492. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10493. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10494. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10495. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10496. (defcustom org-structure-template-alist
  10497. '((?a . "export ascii")
  10498. (?c . "center")
  10499. (?C . "comment")
  10500. (?e . "example")
  10501. (?E . "export")
  10502. (?h . "export html")
  10503. (?l . "export latex")
  10504. (?q . "quote")
  10505. (?s . "src")
  10506. (?v . "verse"))
  10507. "Structure completion elements.
  10508. This is an alist of characters and values. When
  10509. `org-insert-structure-template' is called, an additional key is
  10510. read. The key is first looked up in this alist, and the
  10511. corresponding structure is inserted, with \"#+BEGIN_\" and
  10512. \"#+END_\" added automatically."
  10513. :group 'org-edit-structure
  10514. :type '(repeat
  10515. (cons (character :tag "Key")
  10516. (string :tag "Template")))
  10517. :package-version '(Org . "9.2"))
  10518. (defun org-insert-structure-template (type)
  10519. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10520. First read a character, which can be one of the keys in
  10521. `org-structure-template-alist'. When it is <TAB>, prompt the
  10522. user for a string to use. With an active region, wrap the region
  10523. in the block. Otherwise, insert an empty block."
  10524. (interactive
  10525. (list
  10526. (let* ((key (read-key "Key: "))
  10527. (struct-string
  10528. (or (cdr (assq key org-structure-template-alist))
  10529. (and (= key ?\t)
  10530. (read-string "Structure type: "))
  10531. (user-error "`%c' has no structure definition" key))))
  10532. struct-string)))
  10533. (let* ((region? (use-region-p))
  10534. (s (if region? (region-beginning) (point)))
  10535. (e (copy-marker (if region? (region-end) (point)) t))
  10536. column)
  10537. (when (string-match-p
  10538. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10539. type)
  10540. (org-escape-code-in-region s e))
  10541. (goto-char s)
  10542. (setq column (current-indentation))
  10543. (beginning-of-line)
  10544. (indent-to column)
  10545. (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
  10546. (goto-char e)
  10547. (if (bolp)
  10548. (progn
  10549. (skip-chars-backward " \n\t")
  10550. (forward-line))
  10551. (end-of-line)
  10552. (insert "\n"))
  10553. (indent-to column)
  10554. (insert (format "#+end_%s\n"
  10555. (car (split-string type))))
  10556. (when (or (not region?)
  10557. (string-match-p "src\\|\\`export\\'" type))
  10558. (goto-char s)
  10559. (end-of-line))
  10560. (set-marker e nil)))
  10561. ;;;; TODO, DEADLINE, Comments
  10562. (defun org-toggle-comment ()
  10563. "Change the COMMENT state of an entry."
  10564. (interactive)
  10565. (save-excursion
  10566. (org-back-to-heading)
  10567. (let ((case-fold-search nil))
  10568. (looking-at org-complex-heading-regexp))
  10569. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10570. (skip-chars-forward " \t")
  10571. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10572. (if (org-in-commented-heading-p t)
  10573. (delete-region (point)
  10574. (progn (search-forward " " (line-end-position) 'move)
  10575. (skip-chars-forward " \t")
  10576. (point)))
  10577. (insert org-comment-string)
  10578. (unless (eolp) (insert " ")))))
  10579. (defvar org-last-todo-state-is-todo nil
  10580. "This is non-nil when the last TODO state change led to a TODO state.
  10581. If the last change removed the TODO tag or switched to DONE, then
  10582. this is nil.")
  10583. (defvar org-setting-tags nil) ; dynamically skipped
  10584. (defvar org-todo-setup-filter-hook nil
  10585. "Hook for functions that pre-filter todo specs.
  10586. Each function takes a todo spec and returns either nil or the spec
  10587. transformed into canonical form." )
  10588. (defvar org-todo-get-default-hook nil
  10589. "Hook for functions that get a default item for todo.
  10590. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10591. nil or a string to be used for the todo mark." )
  10592. (defvar org-agenda-headline-snapshot-before-repeat)
  10593. (defun org-current-effective-time ()
  10594. "Return current time adjusted for `org-extend-today-until' variable."
  10595. (let* ((ct (org-current-time))
  10596. (dct (decode-time ct))
  10597. (ct1
  10598. (cond
  10599. (org-use-last-clock-out-time-as-effective-time
  10600. (or (org-clock-get-last-clock-out-time) ct))
  10601. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10602. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10603. (t ct))))
  10604. ct1))
  10605. (defun org-todo-yesterday (&optional arg)
  10606. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10607. (interactive "P")
  10608. (if (eq major-mode 'org-agenda-mode)
  10609. (apply 'org-agenda-todo-yesterday arg)
  10610. (let* ((org-use-effective-time t)
  10611. (hour (nth 2 (decode-time (org-current-time))))
  10612. (org-extend-today-until (1+ hour)))
  10613. (org-todo arg))))
  10614. (defvar org-block-entry-blocking ""
  10615. "First entry preventing the TODO state change.")
  10616. (defun org-cancel-repeater ()
  10617. "Cancel a repeater by setting its numeric value to zero."
  10618. (interactive)
  10619. (save-excursion
  10620. (org-back-to-heading t)
  10621. (let ((bound1 (point))
  10622. (bound0 (save-excursion (outline-next-heading) (point))))
  10623. (when (and (re-search-forward
  10624. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10625. org-deadline-time-regexp "\\)\\|\\("
  10626. org-ts-regexp "\\)")
  10627. bound0 t)
  10628. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10629. bound1 t))
  10630. (replace-match "0" t nil nil 1)))))
  10631. (defvar org-state)
  10632. (defvar org-blocked-by-checkboxes)
  10633. (defun org-todo (&optional arg)
  10634. "Change the TODO state of an item.
  10635. The state of an item is given by a keyword at the start of the heading,
  10636. like
  10637. *** TODO Write paper
  10638. *** DONE Call mom
  10639. The different keywords are specified in the variable `org-todo-keywords'.
  10640. By default the available states are \"TODO\" and \"DONE\". So, for this
  10641. example: when the item starts with TODO, it is changed to DONE.
  10642. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10643. DONE are present, add TODO at the beginning of the heading.
  10644. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10645. state.
  10646. With numeric prefix ARG, switch to that state.
  10647. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10648. next set of TODO \
  10649. keywords (nextset).
  10650. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10651. prefix, circumvent any state blocking.
  10652. With a numeric prefix arg of 0, inhibit note taking for the change.
  10653. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10654. When called through ELisp, arg is also interpreted in the following way:
  10655. `none' -> empty state
  10656. \"\" -> switch to empty state
  10657. `done' -> switch to DONE
  10658. `nextset' -> switch to the next set of keywords
  10659. `previousset' -> switch to the previous set of keywords
  10660. \"WAITING\" -> switch to the specified keyword, but only if it
  10661. really is a member of `org-todo-keywords'."
  10662. (interactive "P")
  10663. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10664. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10665. 'region-start-level 'region))
  10666. org-loop-over-headlines-in-active-region)
  10667. (org-map-entries
  10668. `(org-todo ,arg)
  10669. org-loop-over-headlines-in-active-region
  10670. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10671. (when (equal arg '(16)) (setq arg 'nextset))
  10672. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10673. (let ((org-blocker-hook org-blocker-hook)
  10674. commentp
  10675. case-fold-search)
  10676. (when (equal arg '(64))
  10677. (setq arg nil org-blocker-hook nil))
  10678. (when (and org-blocker-hook
  10679. (or org-inhibit-blocking
  10680. (org-entry-get nil "NOBLOCKING")))
  10681. (setq org-blocker-hook nil))
  10682. (save-excursion
  10683. (catch 'exit
  10684. (org-back-to-heading t)
  10685. (when (org-in-commented-heading-p t)
  10686. (org-toggle-comment)
  10687. (setq commentp t))
  10688. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10689. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10690. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10691. (let* ((match-data (match-data))
  10692. (startpos (copy-marker (line-beginning-position)))
  10693. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10694. (org-log-done org-log-done)
  10695. (org-log-repeat org-log-repeat)
  10696. (org-todo-log-states org-todo-log-states)
  10697. (org-inhibit-logging
  10698. (if (equal arg 0)
  10699. (progn (setq arg nil) 'note) org-inhibit-logging))
  10700. (this (match-string 1))
  10701. (hl-pos (match-beginning 0))
  10702. (head (org-get-todo-sequence-head this))
  10703. (ass (assoc head org-todo-kwd-alist))
  10704. (interpret (nth 1 ass))
  10705. (done-word (nth 3 ass))
  10706. (final-done-word (nth 4 ass))
  10707. (org-last-state (or this ""))
  10708. (completion-ignore-case t)
  10709. (member (member this org-todo-keywords-1))
  10710. (tail (cdr member))
  10711. (org-state (cond
  10712. ((and org-todo-key-trigger
  10713. (or (and (equal arg '(4))
  10714. (eq org-use-fast-todo-selection 'prefix))
  10715. (and (not arg) org-use-fast-todo-selection
  10716. (not (eq org-use-fast-todo-selection
  10717. 'prefix)))))
  10718. ;; Use fast selection.
  10719. (org-fast-todo-selection))
  10720. ((and (equal arg '(4))
  10721. (or (not org-use-fast-todo-selection)
  10722. (not org-todo-key-trigger)))
  10723. ;; Read a state with completion.
  10724. (completing-read
  10725. "State: " (mapcar #'list org-todo-keywords-1)
  10726. nil t))
  10727. ((eq arg 'right)
  10728. (if this
  10729. (if tail (car tail) nil)
  10730. (car org-todo-keywords-1)))
  10731. ((eq arg 'left)
  10732. (unless (equal member org-todo-keywords-1)
  10733. (if this
  10734. (nth (- (length org-todo-keywords-1)
  10735. (length tail) 2)
  10736. org-todo-keywords-1)
  10737. (org-last org-todo-keywords-1))))
  10738. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10739. (setq arg nil))) ;hack to fall back to cycling
  10740. (arg
  10741. ;; User or caller requests a specific state.
  10742. (cond
  10743. ((equal arg "") nil)
  10744. ((eq arg 'none) nil)
  10745. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10746. ((eq arg 'nextset)
  10747. (or (car (cdr (member head org-todo-heads)))
  10748. (car org-todo-heads)))
  10749. ((eq arg 'previousset)
  10750. (let ((org-todo-heads (reverse org-todo-heads)))
  10751. (or (car (cdr (member head org-todo-heads)))
  10752. (car org-todo-heads))))
  10753. ((car (member arg org-todo-keywords-1)))
  10754. ((stringp arg)
  10755. (user-error "State `%s' not valid in this file" arg))
  10756. ((nth (1- (prefix-numeric-value arg))
  10757. org-todo-keywords-1))))
  10758. ((null member) (or head (car org-todo-keywords-1)))
  10759. ((equal this final-done-word) nil) ;-> make empty
  10760. ((null tail) nil) ;-> first entry
  10761. ((memq interpret '(type priority))
  10762. (if (eq this-command last-command)
  10763. (car tail)
  10764. (if (> (length tail) 0)
  10765. (or done-word (car org-done-keywords))
  10766. nil)))
  10767. (t
  10768. (car tail))))
  10769. (org-state (or
  10770. (run-hook-with-args-until-success
  10771. 'org-todo-get-default-hook org-state org-last-state)
  10772. org-state))
  10773. (next (if org-state (concat " " org-state " ") " "))
  10774. (change-plist (list :type 'todo-state-change :from this :to org-state
  10775. :position startpos))
  10776. dolog now-done-p)
  10777. (when org-blocker-hook
  10778. (let (org-blocked-by-checkboxes block-reason)
  10779. (setq org-last-todo-state-is-todo
  10780. (not (member this org-done-keywords)))
  10781. (unless (save-excursion
  10782. (save-match-data
  10783. (org-with-wide-buffer
  10784. (run-hook-with-args-until-failure
  10785. 'org-blocker-hook change-plist))))
  10786. (setq block-reason (if org-blocked-by-checkboxes
  10787. "contained checkboxes"
  10788. (format "\"%s\"" org-block-entry-blocking)))
  10789. (if (called-interactively-p 'interactive)
  10790. (user-error "TODO state change from %s to %s blocked (by %s)"
  10791. this org-state block-reason)
  10792. ;; Fail silently.
  10793. (message "TODO state change from %s to %s blocked (by %s)"
  10794. this org-state block-reason)
  10795. (throw 'exit nil)))))
  10796. (store-match-data match-data)
  10797. (replace-match next t t)
  10798. (cond ((equal this org-state)
  10799. (message "TODO state was already %s" (org-trim next)))
  10800. ((not (pos-visible-in-window-p hl-pos))
  10801. (message "TODO state changed to %s" (org-trim next))))
  10802. (unless head
  10803. (setq head (org-get-todo-sequence-head org-state)
  10804. ass (assoc head org-todo-kwd-alist)
  10805. interpret (nth 1 ass)
  10806. done-word (nth 3 ass)
  10807. final-done-word (nth 4 ass)))
  10808. (when (memq arg '(nextset previousset))
  10809. (message "Keyword-Set %d/%d: %s"
  10810. (- (length org-todo-sets) -1
  10811. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10812. (length org-todo-sets)
  10813. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10814. (setq org-last-todo-state-is-todo
  10815. (not (member org-state org-done-keywords)))
  10816. (setq now-done-p (and (member org-state org-done-keywords)
  10817. (not (member this org-done-keywords))))
  10818. (and logging (org-local-logging logging))
  10819. (when (and (or org-todo-log-states org-log-done)
  10820. (not (eq org-inhibit-logging t))
  10821. (not (memq arg '(nextset previousset))))
  10822. ;; We need to look at recording a time and note.
  10823. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10824. (nth 2 (assoc this org-todo-log-states))))
  10825. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10826. (setq dolog 'time))
  10827. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10828. (and org-state
  10829. (member org-state org-not-done-keywords)
  10830. (not (member this org-not-done-keywords))))
  10831. ;; This is now a todo state and was not one before
  10832. ;; If there was a CLOSED time stamp, get rid of it.
  10833. (org-add-planning-info nil nil 'closed))
  10834. (when (and now-done-p org-log-done)
  10835. ;; It is now done, and it was not done before.
  10836. (org-add-planning-info 'closed (org-current-effective-time))
  10837. (when (and (not dolog) (eq 'note org-log-done))
  10838. (org-add-log-setup 'done org-state this 'note)))
  10839. (when (and org-state dolog)
  10840. ;; This is a non-nil state, and we need to log it.
  10841. (org-add-log-setup 'state org-state this dolog)))
  10842. ;; Fixup tag positioning.
  10843. (org-todo-trigger-tag-changes org-state)
  10844. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  10845. (when org-provide-todo-statistics
  10846. (org-update-parent-todo-statistics))
  10847. (run-hooks 'org-after-todo-state-change-hook)
  10848. (when (and arg (not (member org-state org-done-keywords)))
  10849. (setq head (org-get-todo-sequence-head org-state)))
  10850. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10851. ;; Do we need to trigger a repeat?
  10852. (when now-done-p
  10853. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10854. ;; This is for the agenda, take a snapshot of the headline.
  10855. (save-match-data
  10856. (setq org-agenda-headline-snapshot-before-repeat
  10857. (org-get-heading))))
  10858. (org-auto-repeat-maybe org-state))
  10859. ;; Fixup cursor location if close to the keyword.
  10860. (when (and (outline-on-heading-p)
  10861. (not (bolp))
  10862. (save-excursion (beginning-of-line 1)
  10863. (looking-at org-todo-line-regexp))
  10864. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10865. (goto-char (or (match-end 2) (match-end 1)))
  10866. (and (looking-at " ") (just-one-space)))
  10867. (when org-trigger-hook
  10868. (save-excursion
  10869. (run-hook-with-args 'org-trigger-hook change-plist)))
  10870. (when commentp (org-toggle-comment))))))))
  10871. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10872. "Block turning an entry into a TODO, using the hierarchy.
  10873. This checks whether the current task should be blocked from state
  10874. changes. Such blocking occurs when:
  10875. 1. The task has children which are not all in a completed state.
  10876. 2. A task has a parent with the property :ORDERED:, and there
  10877. are siblings prior to the current task with incomplete
  10878. status.
  10879. 3. The parent of the task is blocked because it has siblings that should
  10880. be done first, or is child of a block grandparent TODO entry."
  10881. (if (not org-enforce-todo-dependencies)
  10882. t ; if locally turned off don't block
  10883. (catch 'dont-block
  10884. ;; If this is not a todo state change, or if this entry is already DONE,
  10885. ;; do not block
  10886. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10887. (member (plist-get change-plist :from)
  10888. (cons 'done org-done-keywords))
  10889. (member (plist-get change-plist :to)
  10890. (cons 'todo org-not-done-keywords))
  10891. (not (plist-get change-plist :to)))
  10892. (throw 'dont-block t))
  10893. ;; If this task has children, and any are undone, it's blocked
  10894. (save-excursion
  10895. (org-back-to-heading t)
  10896. (let ((this-level (funcall outline-level)))
  10897. (outline-next-heading)
  10898. (let ((child-level (funcall outline-level)))
  10899. (while (and (not (eobp))
  10900. (> child-level this-level))
  10901. ;; this todo has children, check whether they are all
  10902. ;; completed
  10903. (when (and (not (org-entry-is-done-p))
  10904. (org-entry-is-todo-p))
  10905. (setq org-block-entry-blocking (org-get-heading))
  10906. (throw 'dont-block nil))
  10907. (outline-next-heading)
  10908. (setq child-level (funcall outline-level))))))
  10909. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10910. ;; any previous siblings are undone, it's blocked
  10911. (save-excursion
  10912. (org-back-to-heading t)
  10913. (let* ((pos (point))
  10914. (parent-pos (and (org-up-heading-safe) (point)))
  10915. (case-fold-search nil))
  10916. (unless parent-pos (throw 'dont-block t)) ; no parent
  10917. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10918. (forward-line 1)
  10919. (re-search-forward org-not-done-heading-regexp pos t))
  10920. (setq org-block-entry-blocking (match-string 0))
  10921. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  10922. ;; Search further up the hierarchy, to see if an ancestor is blocked
  10923. (while t
  10924. (goto-char parent-pos)
  10925. (unless (looking-at org-not-done-heading-regexp)
  10926. (throw 'dont-block t)) ; do not block, parent is not a TODO
  10927. (setq pos (point))
  10928. (setq parent-pos (and (org-up-heading-safe) (point)))
  10929. (unless parent-pos (throw 'dont-block t)) ; no parent
  10930. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10931. (forward-line 1)
  10932. (re-search-forward org-not-done-heading-regexp pos t)
  10933. (setq org-block-entry-blocking (org-get-heading)))
  10934. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  10935. (defcustom org-track-ordered-property-with-tag nil
  10936. "Should the ORDERED property also be shown as a tag?
  10937. The ORDERED property decides if an entry should require subtasks to be
  10938. completed in sequence. Since a property is not very visible, setting
  10939. this option means that toggling the ORDERED property with the command
  10940. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  10941. not relevant for the behavior, but it makes things more visible.
  10942. Note that toggling the tag with tags commands will not change the property
  10943. and therefore not influence behavior!
  10944. This can be t, meaning the tag ORDERED should be used, It can also be a
  10945. string to select a different tag for this task."
  10946. :group 'org-todo
  10947. :type '(choice
  10948. (const :tag "No tracking" nil)
  10949. (const :tag "Track with ORDERED tag" t)
  10950. (string :tag "Use other tag")))
  10951. (defun org-toggle-ordered-property ()
  10952. "Toggle the ORDERED property of the current entry.
  10953. For better visibility, you can track the value of this property with a tag.
  10954. See variable `org-track-ordered-property-with-tag'."
  10955. (interactive)
  10956. (let* ((t1 org-track-ordered-property-with-tag)
  10957. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  10958. (save-excursion
  10959. (org-back-to-heading)
  10960. (if (org-entry-get nil "ORDERED")
  10961. (progn
  10962. (org-delete-property "ORDERED")
  10963. (and tag (org-toggle-tag tag 'off))
  10964. (message "Subtasks can be completed in arbitrary order"))
  10965. (org-entry-put nil "ORDERED" "t")
  10966. (and tag (org-toggle-tag tag 'on))
  10967. (message "Subtasks must be completed in sequence")))))
  10968. (defun org-block-todo-from-checkboxes (change-plist)
  10969. "Block turning an entry into a TODO, using checkboxes.
  10970. This checks whether the current task should be blocked from state
  10971. changes because there are unchecked boxes in this entry."
  10972. (if (not org-enforce-todo-checkbox-dependencies)
  10973. t ; if locally turned off don't block
  10974. (catch 'dont-block
  10975. ;; If this is not a todo state change, or if this entry is already DONE,
  10976. ;; do not block
  10977. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10978. (member (plist-get change-plist :from)
  10979. (cons 'done org-done-keywords))
  10980. (member (plist-get change-plist :to)
  10981. (cons 'todo org-not-done-keywords))
  10982. (not (plist-get change-plist :to)))
  10983. (throw 'dont-block t))
  10984. ;; If this task has checkboxes that are not checked, it's blocked
  10985. (save-excursion
  10986. (org-back-to-heading t)
  10987. (let ((beg (point)) end)
  10988. (outline-next-heading)
  10989. (setq end (point))
  10990. (goto-char beg)
  10991. (when (org-list-search-forward
  10992. (concat (org-item-beginning-re)
  10993. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  10994. "\\[[- ]\\]")
  10995. end t)
  10996. (when (boundp 'org-blocked-by-checkboxes)
  10997. (setq org-blocked-by-checkboxes t))
  10998. (throw 'dont-block nil))))
  10999. t))) ; do not block
  11000. (defun org-entry-blocked-p ()
  11001. "Non-nil if entry at point is blocked."
  11002. (and (not (org-entry-get nil "NOBLOCKING"))
  11003. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11004. (not (run-hook-with-args-until-failure
  11005. 'org-blocker-hook
  11006. (list :type 'todo-state-change
  11007. :position (point)
  11008. :from 'todo
  11009. :to 'done)))))
  11010. (defun org-update-statistics-cookies (all)
  11011. "Update the statistics cookie, either from TODO or from checkboxes.
  11012. This should be called with the cursor in a line with a statistics
  11013. cookie. When called with a \\[universal-argument] prefix, update
  11014. all statistics cookies in the buffer."
  11015. (interactive "P")
  11016. (if all
  11017. (progn
  11018. (org-update-checkbox-count 'all)
  11019. (org-map-entries 'org-update-parent-todo-statistics))
  11020. (if (not (org-at-heading-p))
  11021. (org-update-checkbox-count)
  11022. (let ((pos (point-marker))
  11023. end l1 l2)
  11024. (ignore-errors (org-back-to-heading t))
  11025. (if (not (org-at-heading-p))
  11026. (org-update-checkbox-count)
  11027. (setq l1 (org-outline-level))
  11028. (setq end (save-excursion
  11029. (outline-next-heading)
  11030. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11031. (point)))
  11032. (if (and (save-excursion
  11033. (re-search-forward
  11034. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11035. (not (save-excursion (re-search-forward
  11036. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11037. (org-update-checkbox-count)
  11038. (if (and l2 (> l2 l1))
  11039. (progn
  11040. (goto-char end)
  11041. (org-update-parent-todo-statistics))
  11042. (goto-char pos)
  11043. (beginning-of-line 1)
  11044. (while (re-search-forward
  11045. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11046. (point-at-eol) t)
  11047. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11048. (goto-char pos)
  11049. (move-marker pos nil)))))
  11050. (defvar org-entry-property-inherited-from) ;; defined below
  11051. (defun org-update-parent-todo-statistics ()
  11052. "Update any statistics cookie in the parent of the current headline.
  11053. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11054. the entire subtree and this will travel up the hierarchy and update
  11055. statistics everywhere."
  11056. (let* ((prop (save-excursion (org-up-heading-safe)
  11057. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11058. (recursive (or (not org-hierarchical-todo-statistics)
  11059. (and prop (string-match "\\<recursive\\>" prop))))
  11060. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11061. 0))
  11062. (first t)
  11063. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11064. level ltoggle l1 new ndel
  11065. (cnt-all 0) (cnt-done 0) is-percent kwd
  11066. checkbox-beg cookie-present)
  11067. (catch 'exit
  11068. (save-excursion
  11069. (beginning-of-line 1)
  11070. (setq ltoggle (funcall outline-level))
  11071. ;; Three situations are to consider:
  11072. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11073. ;; to the top-level ancestor on the headline;
  11074. ;; 2. If parent has "recursive" property, repeat up to the
  11075. ;; headline setting that property, taking inheritance into
  11076. ;; account;
  11077. ;; 3. Else, move up to direct parent and proceed only once.
  11078. (while (and (setq level (org-up-heading-safe))
  11079. (or recursive first)
  11080. (>= (point) lim))
  11081. (setq first nil cookie-present nil)
  11082. (unless (and level
  11083. (not (string-match
  11084. "\\<checkbox\\>"
  11085. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11086. "")))))
  11087. (throw 'exit nil))
  11088. (while (re-search-forward box-re (point-at-eol) t)
  11089. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11090. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11091. (save-match-data
  11092. (unless (outline-next-heading) (throw 'exit nil))
  11093. (while (and (looking-at org-complex-heading-regexp)
  11094. (> (setq l1 (length (match-string 1))) level))
  11095. (setq kwd (and (or recursive (= l1 ltoggle))
  11096. (match-string 2)))
  11097. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11098. (and (eq org-provide-todo-statistics t)
  11099. (or (member kwd org-done-keywords)))
  11100. (and (listp org-provide-todo-statistics)
  11101. (stringp (car org-provide-todo-statistics))
  11102. (or (member kwd org-provide-todo-statistics)
  11103. (member kwd org-done-keywords)))
  11104. (and (listp org-provide-todo-statistics)
  11105. (listp (car org-provide-todo-statistics))
  11106. (or (member kwd (car org-provide-todo-statistics))
  11107. (and (member kwd org-done-keywords)
  11108. (member kwd (cadr org-provide-todo-statistics))))))
  11109. (setq cnt-all (1+ cnt-all))
  11110. (and (eq org-provide-todo-statistics t)
  11111. kwd
  11112. (setq cnt-all (1+ cnt-all))))
  11113. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11114. (member kwd org-done-keywords))
  11115. (and (listp org-provide-todo-statistics)
  11116. (listp (car org-provide-todo-statistics))
  11117. (member kwd org-done-keywords)
  11118. (member kwd (cadr org-provide-todo-statistics)))
  11119. (and (listp org-provide-todo-statistics)
  11120. (stringp (car org-provide-todo-statistics))
  11121. (member kwd org-done-keywords)))
  11122. (setq cnt-done (1+ cnt-done)))
  11123. (outline-next-heading)))
  11124. (setq new
  11125. (if is-percent
  11126. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11127. (max 1 cnt-all)))
  11128. (format "[%d/%d]" cnt-done cnt-all))
  11129. ndel (- (match-end 0) checkbox-beg))
  11130. (goto-char checkbox-beg)
  11131. (insert new)
  11132. (delete-region (point) (+ (point) ndel))
  11133. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11134. (when cookie-present
  11135. (run-hook-with-args 'org-after-todo-statistics-hook
  11136. cnt-done (- cnt-all cnt-done))))))
  11137. (run-hooks 'org-todo-statistics-hook)))
  11138. (defvar org-after-todo-statistics-hook nil
  11139. "Hook that is called after a TODO statistics cookie has been updated.
  11140. Each function is called with two arguments: the number of not-done entries
  11141. and the number of done entries.
  11142. For example, the following function, when added to this hook, will switch
  11143. an entry to DONE when all children are done, and back to TODO when new
  11144. entries are set to a TODO status. Note that this hook is only called
  11145. when there is a statistics cookie in the headline!
  11146. (defun org-summary-todo (n-done n-not-done)
  11147. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11148. (let (org-log-done org-log-states) ; turn off logging
  11149. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11150. ")
  11151. (defvar org-todo-statistics-hook nil
  11152. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11153. This hook runs even if there is no statistics cookie present, in which case
  11154. `org-after-todo-statistics-hook' would not run.")
  11155. (defun org-todo-trigger-tag-changes (state)
  11156. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11157. (let ((l org-todo-state-tags-triggers)
  11158. changes)
  11159. (when (or (not state) (equal state ""))
  11160. (setq changes (append changes (cdr (assoc "" l)))))
  11161. (when (and (stringp state) (> (length state) 0))
  11162. (setq changes (append changes (cdr (assoc state l)))))
  11163. (when (member state org-not-done-keywords)
  11164. (setq changes (append changes (cdr (assq 'todo l)))))
  11165. (when (member state org-done-keywords)
  11166. (setq changes (append changes (cdr (assq 'done l)))))
  11167. (dolist (c changes)
  11168. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11169. (defun org-local-logging (value)
  11170. "Get logging settings from a property VALUE."
  11171. ;; Directly set the variables, they are already local.
  11172. (setq org-log-done nil
  11173. org-log-repeat nil
  11174. org-todo-log-states nil)
  11175. (dolist (w (split-string value))
  11176. (let (a)
  11177. (cond
  11178. ((setq a (assoc w org-startup-options))
  11179. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11180. (set (nth 1 a) (nth 2 a))))
  11181. ((setq a (org-extract-log-state-settings w))
  11182. (and (member (car a) org-todo-keywords-1)
  11183. (push a org-todo-log-states)))))))
  11184. (defun org-get-todo-sequence-head (kwd)
  11185. "Return the head of the TODO sequence to which KWD belongs.
  11186. If KWD is not set, check if there is a text property remembering the
  11187. right sequence."
  11188. (let (p)
  11189. (cond
  11190. ((not kwd)
  11191. (or (get-text-property (point-at-bol) 'org-todo-head)
  11192. (progn
  11193. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11194. nil (point-at-eol)))
  11195. (get-text-property p 'org-todo-head))))
  11196. ((not (member kwd org-todo-keywords-1))
  11197. (car org-todo-keywords-1))
  11198. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11199. (defun org-fast-todo-selection ()
  11200. "Fast TODO keyword selection with single keys.
  11201. Returns the new TODO keyword, or nil if no state change should occur."
  11202. (let* ((fulltable org-todo-key-alist)
  11203. (done-keywords org-done-keywords) ;; needed for the faces.
  11204. (maxlen (apply 'max (mapcar
  11205. (lambda (x)
  11206. (if (stringp (car x)) (string-width (car x)) 0))
  11207. fulltable)))
  11208. (expert nil)
  11209. (fwidth (+ maxlen 3 1 3))
  11210. (ncol (/ (- (window-width) 4) fwidth))
  11211. tg cnt e c tbl
  11212. groups ingroup)
  11213. (save-excursion
  11214. (save-window-excursion
  11215. (if expert
  11216. (set-buffer (get-buffer-create " *Org todo*"))
  11217. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11218. (erase-buffer)
  11219. (setq-local org-done-keywords done-keywords)
  11220. (setq tbl fulltable cnt 0)
  11221. (while (setq e (pop tbl))
  11222. (cond
  11223. ((equal e '(:startgroup))
  11224. (push '() groups) (setq ingroup t)
  11225. (unless (= cnt 0)
  11226. (setq cnt 0)
  11227. (insert "\n"))
  11228. (insert "{ "))
  11229. ((equal e '(:endgroup))
  11230. (setq ingroup nil cnt 0)
  11231. (insert "}\n"))
  11232. ((equal e '(:newline))
  11233. (unless (= cnt 0)
  11234. (setq cnt 0)
  11235. (insert "\n")
  11236. (setq e (car tbl))
  11237. (while (equal (car tbl) '(:newline))
  11238. (insert "\n")
  11239. (setq tbl (cdr tbl)))))
  11240. (t
  11241. (setq tg (car e) c (cdr e))
  11242. (when ingroup (push tg (car groups)))
  11243. (setq tg (org-add-props tg nil 'face
  11244. (org-get-todo-face tg)))
  11245. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11246. (insert "[" c "] " tg (make-string
  11247. (- fwidth 4 (length tg)) ?\ ))
  11248. (when (= (setq cnt (1+ cnt)) ncol)
  11249. (insert "\n")
  11250. (when ingroup (insert " "))
  11251. (setq cnt 0)))))
  11252. (insert "\n")
  11253. (goto-char (point-min))
  11254. (unless expert (org-fit-window-to-buffer))
  11255. (message "[a-z..]:Set [SPC]:clear")
  11256. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11257. (cond
  11258. ((or (= c ?\C-g)
  11259. (and (= c ?q) (not (rassoc c fulltable))))
  11260. (setq quit-flag t))
  11261. ((= c ?\ ) nil)
  11262. ((setq e (rassoc c fulltable) tg (car e))
  11263. tg)
  11264. (t (setq quit-flag t)))))))
  11265. (defun org-entry-is-todo-p ()
  11266. (member (org-get-todo-state) org-not-done-keywords))
  11267. (defun org-entry-is-done-p ()
  11268. (member (org-get-todo-state) org-done-keywords))
  11269. (defun org-get-todo-state ()
  11270. "Return the TODO keyword of the current subtree."
  11271. (save-excursion
  11272. (org-back-to-heading t)
  11273. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11274. (match-end 2)
  11275. (match-string 2))))
  11276. (defun org-at-date-range-p (&optional inactive-ok)
  11277. "Non-nil if point is inside a date range.
  11278. When optional argument INACTIVE-OK is non-nil, also consider
  11279. inactive time ranges.
  11280. When this function returns a non-nil value, match data is set
  11281. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11282. on INACTIVE-OK."
  11283. (interactive)
  11284. (save-excursion
  11285. (catch 'exit
  11286. (let ((pos (point)))
  11287. (skip-chars-backward "^[<\r\n")
  11288. (skip-chars-backward "<[")
  11289. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11290. (>= (match-end 0) pos)
  11291. (throw 'exit t))
  11292. (skip-chars-backward "^<[\r\n")
  11293. (skip-chars-backward "<[")
  11294. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11295. (>= (match-end 0) pos)
  11296. (throw 'exit t)))
  11297. nil)))
  11298. (defun org-get-repeat (&optional timestamp)
  11299. "Check if there is a time-stamp with repeater in this entry.
  11300. Return the repeater, as a string, or nil. Also return nil when
  11301. this function is called before first heading.
  11302. When optional argument TIMESTAMP is a string, extract the
  11303. repeater from there instead."
  11304. (save-match-data
  11305. (cond (timestamp
  11306. (and (string-match org-repeat-re timestamp)
  11307. (match-string-no-properties 1 timestamp)))
  11308. ((org-before-first-heading-p) nil)
  11309. (t
  11310. (save-excursion
  11311. (org-back-to-heading t)
  11312. (let ((end (org-entry-end-position)))
  11313. (catch :repeat
  11314. (while (re-search-forward org-repeat-re end t)
  11315. (when (save-match-data (org-at-timestamp-p 'agenda))
  11316. (throw :repeat (match-string-no-properties 1)))))))))))
  11317. (defvar org-last-changed-timestamp)
  11318. (defvar org-last-inserted-timestamp)
  11319. (defvar org-log-post-message)
  11320. (defvar org-log-note-purpose)
  11321. (defvar org-log-note-how nil)
  11322. (defvar org-log-note-extra)
  11323. (defun org-auto-repeat-maybe (done-word)
  11324. "Check if the current headline contains a repeated time-stamp.
  11325. If yes, set TODO state back to what it was and change the base date
  11326. of repeating deadline/scheduled time stamps to new date.
  11327. This function is run automatically after each state change to a DONE state."
  11328. (let* ((repeat (org-get-repeat))
  11329. (aa (assoc org-last-state org-todo-kwd-alist))
  11330. (interpret (nth 1 aa))
  11331. (head (nth 2 aa))
  11332. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11333. (msg "Entry repeats: ")
  11334. (org-log-done nil)
  11335. (org-todo-log-states nil)
  11336. (end (copy-marker (org-entry-end-position))))
  11337. (unwind-protect
  11338. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11339. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11340. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11341. (and (stringp org-todo-repeat-to-state)
  11342. org-todo-repeat-to-state)
  11343. (and org-todo-repeat-to-state org-last-state))))
  11344. (org-todo (cond
  11345. ((and to-state (member to-state org-todo-keywords-1))
  11346. to-state)
  11347. ((eq interpret 'type) org-last-state)
  11348. (head)
  11349. (t 'none))))
  11350. (org-back-to-heading t)
  11351. (org-add-planning-info nil nil 'closed)
  11352. ;; When `org-log-repeat' is non-nil or entry contains
  11353. ;; a clock, set LAST_REPEAT property.
  11354. (when (or org-log-repeat
  11355. (catch :clock
  11356. (save-excursion
  11357. (while (re-search-forward org-clock-line-re end t)
  11358. (when (org-at-clock-log-p) (throw :clock t))))))
  11359. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11360. (org-time-stamp-format t t)
  11361. (current-time))))
  11362. (when org-log-repeat
  11363. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11364. (memq 'org-add-log-note post-command-hook))
  11365. ;; We are already setup for some record.
  11366. (when (eq org-log-repeat 'note)
  11367. ;; Make sure we take a note, not only a time stamp.
  11368. (setq org-log-note-how 'note))
  11369. ;; Set up for taking a record.
  11370. (org-add-log-setup 'state
  11371. (or done-word (car org-done-keywords))
  11372. org-last-state
  11373. org-log-repeat)))
  11374. (let ((planning-re (regexp-opt
  11375. (list org-scheduled-string org-deadline-string))))
  11376. (while (re-search-forward org-ts-regexp end t)
  11377. (let* ((ts (match-string 0))
  11378. (planning? (org-at-planning-p))
  11379. (type (if (not planning?) "Plain:"
  11380. (save-excursion
  11381. (re-search-backward
  11382. planning-re (line-beginning-position) t)
  11383. (match-string 0)))))
  11384. (cond
  11385. ;; Ignore fake time-stamps (e.g., within comments).
  11386. ((not (org-at-timestamp-p 'agenda)))
  11387. ;; Time-stamps without a repeater are usually
  11388. ;; skipped. However, a SCHEDULED time-stamp without
  11389. ;; one is removed, as they are no longer relevant.
  11390. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11391. ts))
  11392. (when (equal type org-scheduled-string)
  11393. (org-remove-timestamp-with-keyword type)))
  11394. (t
  11395. (let ((n (string-to-number (match-string 2 ts)))
  11396. (what (match-string 3 ts)))
  11397. (when (equal what "w") (setq n (* n 7) what "d"))
  11398. (when (and (equal what "h")
  11399. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11400. ts)))
  11401. (user-error
  11402. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11403. has been set"
  11404. n))
  11405. ;; Preparation, see if we need to modify the start
  11406. ;; date for the change.
  11407. (when (match-end 1)
  11408. (let ((time (save-match-data
  11409. (org-time-string-to-time ts))))
  11410. (cond
  11411. ((equal (match-string 1 ts) ".")
  11412. ;; Shift starting date to today
  11413. (org-timestamp-change
  11414. (- (org-today) (time-to-days time))
  11415. 'day))
  11416. ((equal (match-string 1 ts) "+")
  11417. (let ((nshiftmax 10)
  11418. (nshift 0))
  11419. (while (or (= nshift 0)
  11420. (not (time-less-p (current-time) time)))
  11421. (when (= (cl-incf nshift) nshiftmax)
  11422. (or (y-or-n-p
  11423. (format "%d repeater intervals were not \
  11424. enough to shift date past today. Continue? "
  11425. nshift))
  11426. (user-error "Abort")))
  11427. (org-timestamp-change n (cdr (assoc what whata)))
  11428. (org-in-regexp org-ts-regexp3)
  11429. (setq ts (match-string 1))
  11430. (setq time
  11431. (save-match-data
  11432. (org-time-string-to-time ts)))))
  11433. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11434. ;; Rematch, so that we have everything in place
  11435. ;; for the real shift.
  11436. (org-in-regexp org-ts-regexp3)
  11437. (setq ts (match-string 1))
  11438. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11439. ts)))))
  11440. (save-excursion
  11441. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11442. (setq msg
  11443. (concat
  11444. msg type " " org-last-changed-timestamp " "))))))))
  11445. (setq org-log-post-message msg)
  11446. (message "%s" msg))
  11447. (set-marker end nil))))
  11448. (defun org-show-todo-tree (arg)
  11449. "Make a compact tree which shows all headlines marked with TODO.
  11450. The tree will show the lines where the regexp matches, and all higher
  11451. headlines above the match.
  11452. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11453. With a numeric prefix N, construct a sparse tree for the Nth element
  11454. of `org-todo-keywords-1'."
  11455. (interactive "P")
  11456. (let ((case-fold-search nil)
  11457. (kwd-re
  11458. (cond ((null arg) org-not-done-regexp)
  11459. ((equal arg '(4))
  11460. (let ((kwd
  11461. (completing-read "Keyword (or KWD1|KWD2|...): "
  11462. (mapcar #'list org-todo-keywords-1))))
  11463. (concat "\\("
  11464. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11465. "\\)\\>")))
  11466. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11467. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11468. org-todo-keywords-1)))
  11469. (t (user-error "Invalid prefix argument: %s" arg)))))
  11470. (message "%d TODO entries found"
  11471. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11472. (defun org--deadline-or-schedule (arg type time)
  11473. "Insert DEADLINE or SCHEDULE information in current entry.
  11474. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11475. `org-schedule' for information about ARG and TIME arguments."
  11476. (let* ((deadline? (eq type 'deadline))
  11477. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11478. (log (if deadline? org-log-redeadline org-log-reschedule))
  11479. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11480. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11481. ;; Save repeater cookie from either TIME or current scheduled
  11482. ;; time stamp. We are going to insert it back at the end of
  11483. ;; the process.
  11484. (repeater (or (and (org-string-nw-p time)
  11485. ;; We use `org-repeat-re' because we need
  11486. ;; to tell the difference between a real
  11487. ;; repeater and a time delta, e.g. "+2d".
  11488. (string-match org-repeat-re time)
  11489. (match-string 1 time))
  11490. (and (org-string-nw-p old-date)
  11491. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11492. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11493. old-date)
  11494. (match-string 1 old-date)))))
  11495. (pcase arg
  11496. (`(4)
  11497. (when (and old-date log)
  11498. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11499. nil old-date log))
  11500. (org-remove-timestamp-with-keyword keyword)
  11501. (message (if deadline? "Item no longer has a deadline."
  11502. "Item is no longer scheduled.")))
  11503. (`(16)
  11504. (save-excursion
  11505. (org-back-to-heading t)
  11506. (let ((regexp (if deadline? org-deadline-time-regexp
  11507. org-scheduled-time-regexp)))
  11508. (if (not (re-search-forward regexp (line-end-position 2) t))
  11509. (user-error (if deadline? "No deadline information to update"
  11510. "No scheduled information to update"))
  11511. (let* ((rpl0 (match-string 1))
  11512. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11513. (msg (if deadline? "Warn starting from" "Delay until")))
  11514. (replace-match
  11515. (concat keyword
  11516. " <" rpl
  11517. (format " -%dd"
  11518. (abs (- (time-to-days
  11519. (save-match-data
  11520. (org-read-date
  11521. nil t nil msg old-date-time)))
  11522. (time-to-days old-date-time))))
  11523. ">") t t))))))
  11524. (_
  11525. (org-add-planning-info type time 'closed)
  11526. (when (and old-date
  11527. log
  11528. (not (equal old-date org-last-inserted-timestamp)))
  11529. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11530. org-last-inserted-timestamp
  11531. old-date
  11532. log))
  11533. (when repeater
  11534. (save-excursion
  11535. (org-back-to-heading t)
  11536. (when (re-search-forward
  11537. (concat keyword " " org-last-inserted-timestamp)
  11538. (line-end-position 2)
  11539. t)
  11540. (goto-char (1- (match-end 0)))
  11541. (insert " " repeater)
  11542. (setq org-last-inserted-timestamp
  11543. (concat (substring org-last-inserted-timestamp 0 -1)
  11544. " " repeater
  11545. (substring org-last-inserted-timestamp -1))))))
  11546. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11547. org-last-inserted-timestamp)))))
  11548. (defun org-deadline (arg &optional time)
  11549. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11550. With one universal prefix argument, remove any deadline from the item.
  11551. With two universal prefix arguments, prompt for a warning delay.
  11552. With argument TIME, set the deadline at the corresponding date. TIME
  11553. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11554. (interactive "P")
  11555. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11556. (org-map-entries
  11557. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11558. nil
  11559. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11560. 'region-start-level
  11561. 'region)
  11562. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11563. (org--deadline-or-schedule arg 'deadline time)))
  11564. (defun org-schedule (arg &optional time)
  11565. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11566. With one universal prefix argument, remove any scheduling date from the item.
  11567. With two universal prefix arguments, prompt for a delay cookie.
  11568. With argument TIME, scheduled at the corresponding date. TIME can
  11569. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11570. (interactive "P")
  11571. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11572. (org-map-entries
  11573. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11574. nil
  11575. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11576. 'region-start-level
  11577. 'region)
  11578. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11579. (org--deadline-or-schedule arg 'scheduled time)))
  11580. (defun org-get-scheduled-time (pom &optional inherit)
  11581. "Get the scheduled time as a time tuple, of a format suitable
  11582. for calling org-schedule with, or if there is no scheduling,
  11583. returns nil."
  11584. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11585. (when time
  11586. (apply 'encode-time (org-parse-time-string time)))))
  11587. (defun org-get-deadline-time (pom &optional inherit)
  11588. "Get the deadline as a time tuple, of a format suitable for
  11589. calling org-deadline with, or if there is no scheduling, returns
  11590. nil."
  11591. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11592. (when time
  11593. (apply 'encode-time (org-parse-time-string time)))))
  11594. (defun org-remove-timestamp-with-keyword (keyword)
  11595. "Remove all time stamps with KEYWORD in the current entry."
  11596. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11597. beg)
  11598. (save-excursion
  11599. (org-back-to-heading t)
  11600. (setq beg (point))
  11601. (outline-next-heading)
  11602. (while (re-search-backward re beg t)
  11603. (replace-match "")
  11604. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11605. (equal (char-before) ?\ ))
  11606. (backward-delete-char 1)
  11607. (when (string-match "^[ \t]*$" (buffer-substring
  11608. (point-at-bol) (point-at-eol)))
  11609. (delete-region (point-at-bol)
  11610. (min (point-max) (1+ (point-at-eol))))))))))
  11611. (defvar org-time-was-given) ; dynamically scoped parameter
  11612. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11613. (defun org-at-planning-p ()
  11614. "Non-nil when point is on a planning info line."
  11615. ;; This is as accurate and faster than `org-element-at-point' since
  11616. ;; planning info location is fixed in the section.
  11617. (org-with-wide-buffer
  11618. (beginning-of-line)
  11619. (and (looking-at-p org-planning-line-re)
  11620. (eq (point)
  11621. (ignore-errors
  11622. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11623. (org-back-to-heading t)
  11624. (org-with-limited-levels (org-back-to-heading t)))
  11625. (line-beginning-position 2))))))
  11626. (defun org-add-planning-info (what &optional time &rest remove)
  11627. "Insert new timestamp with keyword in the planning line.
  11628. WHAT indicates what kind of time stamp to add. It is a symbol
  11629. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11630. the time to use. If none is given, the user is prompted for
  11631. a date. REMOVE indicates what kind of entries to remove. An old
  11632. WHAT entry will also be removed."
  11633. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11634. (catch 'exit
  11635. (when (and (memq what '(scheduled deadline))
  11636. (or (not time)
  11637. (and (stringp time)
  11638. (string-match "^[-+]+[0-9]" time))))
  11639. ;; Try to get a default date/time from existing timestamp
  11640. (save-excursion
  11641. (org-back-to-heading t)
  11642. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11643. (when (re-search-forward (if (eq what 'scheduled)
  11644. org-scheduled-time-regexp
  11645. org-deadline-time-regexp)
  11646. end t)
  11647. (setq ts (match-string 1)
  11648. default-time (apply 'encode-time (org-parse-time-string ts))
  11649. default-input (and ts (org-get-compact-tod ts)))))))
  11650. (when what
  11651. (setq time
  11652. (if (stringp time)
  11653. ;; This is a string (relative or absolute), set
  11654. ;; proper date.
  11655. (apply #'encode-time
  11656. (org-read-date-analyze
  11657. time default-time (decode-time default-time)))
  11658. ;; If necessary, get the time from the user
  11659. (or time (org-read-date nil 'to-time nil nil
  11660. default-time default-input)))))
  11661. (org-with-wide-buffer
  11662. (org-back-to-heading t)
  11663. (forward-line)
  11664. (unless (bolp) (insert "\n"))
  11665. (cond ((looking-at-p org-planning-line-re)
  11666. ;; Move to current indentation.
  11667. (skip-chars-forward " \t")
  11668. ;; Check if we have to remove something.
  11669. (dolist (type (if what (cons what remove) remove))
  11670. (save-excursion
  11671. (when (re-search-forward
  11672. (cl-case type
  11673. (closed org-closed-time-regexp)
  11674. (deadline org-deadline-time-regexp)
  11675. (scheduled org-scheduled-time-regexp)
  11676. (otherwise
  11677. (error "Invalid planning type: %s" type)))
  11678. (line-end-position) t)
  11679. ;; Delete until next keyword or end of line.
  11680. (delete-region
  11681. (match-beginning 0)
  11682. (if (re-search-forward org-keyword-time-not-clock-regexp
  11683. (line-end-position)
  11684. t)
  11685. (match-beginning 0)
  11686. (line-end-position))))))
  11687. ;; If there is nothing more to add and no more keyword
  11688. ;; is left, remove the line completely.
  11689. (if (and (looking-at-p "[ \t]*$") (not what))
  11690. (delete-region (line-beginning-position)
  11691. (line-beginning-position 2))
  11692. ;; If we removed last keyword, do not leave trailing
  11693. ;; white space at the end of line.
  11694. (let ((p (point)))
  11695. (save-excursion
  11696. (end-of-line)
  11697. (unless (= (skip-chars-backward " \t" p) 0)
  11698. (delete-region (point) (line-end-position)))))))
  11699. ((not what) (throw 'exit nil)) ; Nothing to do.
  11700. (t (insert-before-markers "\n")
  11701. (backward-char 1)
  11702. (when org-adapt-indentation
  11703. (indent-to-column (1+ (org-outline-level))))))
  11704. (when what
  11705. ;; Insert planning keyword.
  11706. (insert (cl-case what
  11707. (closed org-closed-string)
  11708. (deadline org-deadline-string)
  11709. (scheduled org-scheduled-string)
  11710. (otherwise (error "Invalid planning type: %s" what)))
  11711. " ")
  11712. ;; Insert associated timestamp.
  11713. (let ((ts (org-insert-time-stamp
  11714. time
  11715. (or org-time-was-given
  11716. (and (eq what 'closed) org-log-done-with-time))
  11717. (eq what 'closed)
  11718. nil nil (list org-end-time-was-given))))
  11719. (unless (eolp) (insert " "))
  11720. ts))))))
  11721. (defvar org-log-note-marker (make-marker)
  11722. "Marker pointing at the entry where the note is to be inserted.")
  11723. (defvar org-log-note-purpose nil)
  11724. (defvar org-log-note-state nil)
  11725. (defvar org-log-note-previous-state nil)
  11726. (defvar org-log-note-extra nil)
  11727. (defvar org-log-note-window-configuration nil)
  11728. (defvar org-log-note-return-to (make-marker))
  11729. (defvar org-log-note-effective-time nil
  11730. "Remembered current time so that dynamically scoped
  11731. `org-extend-today-until' affects timestamps in state change log")
  11732. (defvar org-log-post-message nil
  11733. "Message to be displayed after a log note has been stored.
  11734. The auto-repeater uses this.")
  11735. (defun org-add-note ()
  11736. "Add a note to the current entry.
  11737. This is done in the same way as adding a state change note."
  11738. (interactive)
  11739. (org-add-log-setup 'note))
  11740. (defun org-log-beginning (&optional create)
  11741. "Return expected start of log notes in current entry.
  11742. When optional argument CREATE is non-nil, the function creates
  11743. a drawer to store notes, if necessary. Returned position ignores
  11744. narrowing."
  11745. (org-with-wide-buffer
  11746. (let ((drawer (org-log-into-drawer)))
  11747. (cond
  11748. (drawer
  11749. (org-end-of-meta-data)
  11750. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11751. (end (if (org-at-heading-p) (point)
  11752. (save-excursion (outline-next-heading) (point))))
  11753. (case-fold-search t))
  11754. (catch 'exit
  11755. ;; Try to find existing drawer.
  11756. (while (re-search-forward regexp end t)
  11757. (let ((element (org-element-at-point)))
  11758. (when (eq (org-element-type element) 'drawer)
  11759. (let ((cend (org-element-property :contents-end element)))
  11760. (when (and (not org-log-states-order-reversed) cend)
  11761. (goto-char cend)))
  11762. (throw 'exit nil))))
  11763. ;; No drawer found. Create one, if permitted.
  11764. (when create
  11765. (unless (bolp) (insert "\n"))
  11766. (let ((beg (point)))
  11767. (insert ":" drawer ":\n:END:\n")
  11768. (org-indent-region beg (point))
  11769. (org-flag-region
  11770. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11771. (end-of-line -1)))))
  11772. (t
  11773. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11774. (skip-chars-forward " \t\n")
  11775. (beginning-of-line)
  11776. (unless org-log-states-order-reversed
  11777. (org-skip-over-state-notes)
  11778. (skip-chars-backward " \t\n")
  11779. (forward-line)))))
  11780. (if (bolp) (point) (line-beginning-position 2))))
  11781. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11782. "Set up the post command hook to take a note.
  11783. If this is about to TODO state change, the new state is expected in STATE.
  11784. HOW is an indicator what kind of note should be created.
  11785. EXTRA is additional text that will be inserted into the notes buffer."
  11786. (move-marker org-log-note-marker (point))
  11787. (setq org-log-note-purpose purpose
  11788. org-log-note-state state
  11789. org-log-note-previous-state prev-state
  11790. org-log-note-how how
  11791. org-log-note-extra extra
  11792. org-log-note-effective-time (org-current-effective-time))
  11793. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11794. (defun org-skip-over-state-notes ()
  11795. "Skip past the list of State notes in an entry."
  11796. (when (ignore-errors (goto-char (org-in-item-p)))
  11797. (let* ((struct (org-list-struct))
  11798. (prevs (org-list-prevs-alist struct))
  11799. (regexp
  11800. (concat "[ \t]*- +"
  11801. (replace-regexp-in-string
  11802. " +" " +"
  11803. (org-replace-escapes
  11804. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11805. `(("%d" . ,org-ts-regexp-inactive)
  11806. ("%D" . ,org-ts-regexp)
  11807. ("%s" . "\"\\S-+\"")
  11808. ("%S" . "\"\\S-+\"")
  11809. ("%t" . ,org-ts-regexp-inactive)
  11810. ("%T" . ,org-ts-regexp)
  11811. ("%u" . ".*?")
  11812. ("%U" . ".*?")))))))
  11813. (while (looking-at-p regexp)
  11814. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11815. (org-list-get-item-end (point) struct)))))))
  11816. (defun org-add-log-note (&optional _purpose)
  11817. "Pop up a window for taking a note, and add this note later."
  11818. (remove-hook 'post-command-hook 'org-add-log-note)
  11819. (setq org-log-note-window-configuration (current-window-configuration))
  11820. (delete-other-windows)
  11821. (move-marker org-log-note-return-to (point))
  11822. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11823. (goto-char org-log-note-marker)
  11824. (org-switch-to-buffer-other-window "*Org Note*")
  11825. (erase-buffer)
  11826. (if (memq org-log-note-how '(time state))
  11827. (org-store-log-note)
  11828. (let ((org-inhibit-startup t)) (org-mode))
  11829. (insert (format "# Insert note for %s.
  11830. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11831. (cond
  11832. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11833. ((eq org-log-note-purpose 'done) "closed todo item")
  11834. ((eq org-log-note-purpose 'state)
  11835. (format "state change from \"%s\" to \"%s\""
  11836. (or org-log-note-previous-state "")
  11837. (or org-log-note-state "")))
  11838. ((eq org-log-note-purpose 'reschedule)
  11839. "rescheduling")
  11840. ((eq org-log-note-purpose 'delschedule)
  11841. "no longer scheduled")
  11842. ((eq org-log-note-purpose 'redeadline)
  11843. "changing deadline")
  11844. ((eq org-log-note-purpose 'deldeadline)
  11845. "removing deadline")
  11846. ((eq org-log-note-purpose 'refile)
  11847. "refiling")
  11848. ((eq org-log-note-purpose 'note)
  11849. "this entry")
  11850. (t (error "This should not happen")))))
  11851. (when org-log-note-extra (insert org-log-note-extra))
  11852. (setq-local org-finish-function 'org-store-log-note)
  11853. (run-hooks 'org-log-buffer-setup-hook)))
  11854. (defvar org-note-abort nil) ; dynamically scoped
  11855. (defun org-store-log-note ()
  11856. "Finish taking a log note, and insert it to where it belongs."
  11857. (let ((txt (prog1 (buffer-string)
  11858. (kill-buffer)))
  11859. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11860. lines)
  11861. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11862. (setq txt (replace-match "" t t txt)))
  11863. (when (string-match "\\s-+\\'" txt)
  11864. (setq txt (replace-match "" t t txt)))
  11865. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11866. (when (org-string-nw-p note)
  11867. (setq note
  11868. (org-replace-escapes
  11869. note
  11870. (list (cons "%u" (user-login-name))
  11871. (cons "%U" user-full-name)
  11872. (cons "%t" (format-time-string
  11873. (org-time-stamp-format 'long 'inactive)
  11874. org-log-note-effective-time))
  11875. (cons "%T" (format-time-string
  11876. (org-time-stamp-format 'long nil)
  11877. org-log-note-effective-time))
  11878. (cons "%d" (format-time-string
  11879. (org-time-stamp-format nil 'inactive)
  11880. org-log-note-effective-time))
  11881. (cons "%D" (format-time-string
  11882. (org-time-stamp-format nil nil)
  11883. org-log-note-effective-time))
  11884. (cons "%s" (cond
  11885. ((not org-log-note-state) "")
  11886. ((string-match-p org-ts-regexp
  11887. org-log-note-state)
  11888. (format "\"[%s]\""
  11889. (substring org-log-note-state 1 -1)))
  11890. (t (format "\"%s\"" org-log-note-state))))
  11891. (cons "%S"
  11892. (cond
  11893. ((not org-log-note-previous-state) "")
  11894. ((string-match-p org-ts-regexp
  11895. org-log-note-previous-state)
  11896. (format "\"[%s]\""
  11897. (substring
  11898. org-log-note-previous-state 1 -1)))
  11899. (t (format "\"%s\""
  11900. org-log-note-previous-state)))))))
  11901. (when lines (setq note (concat note " \\\\")))
  11902. (push note lines))
  11903. (when (and lines (not org-note-abort))
  11904. (with-current-buffer (marker-buffer org-log-note-marker)
  11905. (org-with-wide-buffer
  11906. ;; Find location for the new note.
  11907. (goto-char org-log-note-marker)
  11908. (set-marker org-log-note-marker nil)
  11909. ;; Note associated to a clock is to be located right after
  11910. ;; the clock. Do not move point.
  11911. (unless (eq org-log-note-purpose 'clock-out)
  11912. (goto-char (org-log-beginning t)))
  11913. ;; Make sure point is at the beginning of an empty line.
  11914. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11915. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11916. ;; In an existing list, add a new item at the top level.
  11917. ;; Otherwise, indent line like a regular one.
  11918. (let ((itemp (org-in-item-p)))
  11919. (if itemp
  11920. (indent-line-to
  11921. (let ((struct (save-excursion
  11922. (goto-char itemp) (org-list-struct))))
  11923. (org-list-get-ind (org-list-get-top-point struct) struct)))
  11924. (org-indent-line)))
  11925. (insert (org-list-bullet-string "-") (pop lines))
  11926. (let ((ind (org-list-item-body-column (line-beginning-position))))
  11927. (dolist (line lines)
  11928. (insert "\n")
  11929. (indent-line-to ind)
  11930. (insert line)))
  11931. (message "Note stored")
  11932. (org-back-to-heading t))
  11933. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  11934. ;; from within `org-add-log-note' because `buffer-undo-list'
  11935. ;; is then modified outside of `org-with-remote-undo'.
  11936. (when (eq this-command 'org-agenda-todo)
  11937. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  11938. ;; Don't add undo information when called from `org-agenda-todo'.
  11939. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  11940. (set-window-configuration org-log-note-window-configuration)
  11941. (with-current-buffer (marker-buffer org-log-note-return-to)
  11942. (goto-char org-log-note-return-to))
  11943. (move-marker org-log-note-return-to nil)
  11944. (when org-log-post-message (message "%s" org-log-post-message))))
  11945. (defun org-remove-empty-drawer-at (pos)
  11946. "Remove an empty drawer at position POS.
  11947. POS may also be a marker."
  11948. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  11949. (org-with-wide-buffer
  11950. (goto-char pos)
  11951. (let ((drawer (org-element-at-point)))
  11952. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  11953. (not (org-element-property :contents-begin drawer)))
  11954. (delete-region (org-element-property :begin drawer)
  11955. (progn (goto-char (org-element-property :end drawer))
  11956. (skip-chars-backward " \r\t\n")
  11957. (forward-line)
  11958. (point))))))))
  11959. (defvar org-ts-type nil)
  11960. (defun org-sparse-tree (&optional arg type)
  11961. "Create a sparse tree, prompt for the details.
  11962. This command can create sparse trees. You first need to select the type
  11963. of match used to create the tree:
  11964. t Show all TODO entries.
  11965. T Show entries with a specific TODO keyword.
  11966. m Show entries selected by a tags/property match.
  11967. p Enter a property name and its value (both with completion on existing
  11968. names/values) and show entries with that property.
  11969. r Show entries matching a regular expression (`/' can be used as well).
  11970. b Show deadlines and scheduled items before a date.
  11971. a Show deadlines and scheduled items after a date.
  11972. d Show deadlines due within `org-deadline-warning-days'.
  11973. D Show deadlines and scheduled items between a date range."
  11974. (interactive "P")
  11975. (setq type (or type org-sparse-tree-default-date-type))
  11976. (setq org-ts-type type)
  11977. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  11978. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  11979. \[c]ycle through date types: %s"
  11980. (cl-case type
  11981. (all "all timestamps")
  11982. (scheduled "only scheduled")
  11983. (deadline "only deadline")
  11984. (active "only active timestamps")
  11985. (inactive "only inactive timestamps")
  11986. (closed "with a closed time-stamp")
  11987. (otherwise "scheduled/deadline")))
  11988. (let ((answer (read-char-exclusive)))
  11989. (cl-case answer
  11990. (?c
  11991. (org-sparse-tree
  11992. arg
  11993. (cadr
  11994. (memq type '(nil all scheduled deadline active inactive closed)))))
  11995. (?d (call-interactively 'org-check-deadlines))
  11996. (?b (call-interactively 'org-check-before-date))
  11997. (?a (call-interactively 'org-check-after-date))
  11998. (?D (call-interactively 'org-check-dates-range))
  11999. (?t (call-interactively 'org-show-todo-tree))
  12000. (?T (org-show-todo-tree '(4)))
  12001. (?m (call-interactively 'org-match-sparse-tree))
  12002. ((?p ?P)
  12003. (let* ((kwd (completing-read
  12004. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12005. (value (completing-read
  12006. "Value: " (mapcar #'list (org-property-values kwd)))))
  12007. (unless (string-match "\\`{.*}\\'" value)
  12008. (setq value (concat "\"" value "\"")))
  12009. (org-match-sparse-tree arg (concat kwd "=" value))))
  12010. ((?r ?R ?/) (call-interactively 'org-occur))
  12011. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12012. (defvar-local org-occur-highlights nil
  12013. "List of overlays used for occur matches.")
  12014. (defvar-local org-occur-parameters nil
  12015. "Parameters of the active org-occur calls.
  12016. This is a list, each call to org-occur pushes as cons cell,
  12017. containing the regular expression and the callback, onto the list.
  12018. The list can contain several entries if `org-occur' has been called
  12019. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12020. will only contain one set of parameters. When the highlights are
  12021. removed (for example with `C-c C-c', or with the next edit (depending
  12022. on `org-remove-highlights-with-change'), this variable is emptied
  12023. as well.")
  12024. (defun org-occur (regexp &optional keep-previous callback)
  12025. "Make a compact tree which shows all matches of REGEXP.
  12026. The tree will show the lines where the regexp matches, and any other context
  12027. defined in `org-show-context-detail', which see.
  12028. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12029. done by a previous call to `org-occur' will be kept, to allow stacking of
  12030. calls to this command.
  12031. Optional argument CALLBACK can be a function of no argument. In this case,
  12032. it is called with point at the end of the match, match data being set
  12033. accordingly. Current match is shown only if the return value is non-nil.
  12034. The function must neither move point nor alter narrowing."
  12035. (interactive "sRegexp: \nP")
  12036. (when (equal regexp "")
  12037. (user-error "Regexp cannot be empty"))
  12038. (unless keep-previous
  12039. (org-remove-occur-highlights nil nil t))
  12040. (push (cons regexp callback) org-occur-parameters)
  12041. (let ((cnt 0))
  12042. (save-excursion
  12043. (goto-char (point-min))
  12044. (when (or (not keep-previous) ; do not want to keep
  12045. (not org-occur-highlights)) ; no previous matches
  12046. ;; hide everything
  12047. (org-overview))
  12048. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12049. (isearch-no-upper-case-p regexp t)
  12050. org-occur-case-fold-search)))
  12051. (while (re-search-forward regexp nil t)
  12052. (when (or (not callback)
  12053. (save-match-data (funcall callback)))
  12054. (setq cnt (1+ cnt))
  12055. (when org-highlight-sparse-tree-matches
  12056. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12057. (org-show-context 'occur-tree)))))
  12058. (when org-remove-highlights-with-change
  12059. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12060. nil 'local))
  12061. (unless org-sparse-tree-open-archived-trees
  12062. (org-hide-archived-subtrees (point-min) (point-max)))
  12063. (run-hooks 'org-occur-hook)
  12064. (when (called-interactively-p 'interactive)
  12065. (message "%d match(es) for regexp %s" cnt regexp))
  12066. cnt))
  12067. (defun org-occur-next-match (&optional n _reset)
  12068. "Function for `next-error-function' to find sparse tree matches.
  12069. N is the number of matches to move, when negative move backwards.
  12070. This function always goes back to the starting point when no
  12071. match is found."
  12072. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12073. (search-func (if (< n 0)
  12074. 'previous-single-char-property-change
  12075. 'next-single-char-property-change))
  12076. (n (abs n))
  12077. (pos (point))
  12078. p1)
  12079. (catch 'exit
  12080. (while (setq p1 (funcall search-func (point) 'org-type))
  12081. (when (equal p1 limit)
  12082. (goto-char pos)
  12083. (user-error "No more matches"))
  12084. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12085. (setq n (1- n))
  12086. (when (= n 0)
  12087. (goto-char p1)
  12088. (throw 'exit (point))))
  12089. (goto-char p1))
  12090. (goto-char p1)
  12091. (user-error "No more matches"))))
  12092. (defun org-highlight-new-match (beg end)
  12093. "Highlight from BEG to END and mark the highlight is an occur headline."
  12094. (let ((ov (make-overlay beg end)))
  12095. (overlay-put ov 'face 'secondary-selection)
  12096. (overlay-put ov 'org-type 'org-occur)
  12097. (push ov org-occur-highlights)))
  12098. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12099. "Remove the occur highlights from the buffer.
  12100. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12101. from the `before-change-functions' in the current buffer."
  12102. (interactive)
  12103. (unless org-inhibit-highlight-removal
  12104. (mapc #'delete-overlay org-occur-highlights)
  12105. (setq org-occur-highlights nil)
  12106. (setq org-occur-parameters nil)
  12107. (unless noremove
  12108. (remove-hook 'before-change-functions
  12109. 'org-remove-occur-highlights 'local))))
  12110. ;;;; Priorities
  12111. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12112. "Regular expression matching the priority indicator.")
  12113. (defvar org-remove-priority-next-time nil)
  12114. (defun org-priority-up ()
  12115. "Increase the priority of the current item."
  12116. (interactive)
  12117. (org-priority 'up))
  12118. (defun org-priority-down ()
  12119. "Decrease the priority of the current item."
  12120. (interactive)
  12121. (org-priority 'down))
  12122. (defun org-priority (&optional action _show)
  12123. "Change the priority of an item.
  12124. ACTION can be `set', `up', `down', or a character."
  12125. (interactive "P")
  12126. (if (equal action '(4))
  12127. (org-show-priority)
  12128. (unless org-enable-priority-commands
  12129. (user-error "Priority commands are disabled"))
  12130. (setq action (or action 'set))
  12131. (let (current new news have remove)
  12132. (save-excursion
  12133. (org-back-to-heading t)
  12134. (when (looking-at org-priority-regexp)
  12135. (setq current (string-to-char (match-string 2))
  12136. have t))
  12137. (cond
  12138. ((eq action 'remove)
  12139. (setq remove t new ?\ ))
  12140. ((or (eq action 'set)
  12141. (integerp action))
  12142. (if (not (eq action 'set))
  12143. (setq new action)
  12144. (message "Priority %c-%c, SPC to remove: "
  12145. org-highest-priority org-lowest-priority)
  12146. (save-match-data
  12147. (setq new (read-char-exclusive))))
  12148. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12149. (= (upcase org-lowest-priority) org-lowest-priority))
  12150. (setq new (upcase new)))
  12151. (cond ((equal new ?\ ) (setq remove t))
  12152. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12153. (user-error "Priority must be between `%c' and `%c'"
  12154. org-highest-priority org-lowest-priority))))
  12155. ((eq action 'up)
  12156. (setq new (if have
  12157. (1- current) ; normal cycling
  12158. ;; last priority was empty
  12159. (if (eq last-command this-command)
  12160. org-lowest-priority ; wrap around empty to lowest
  12161. ;; default
  12162. (if org-priority-start-cycle-with-default
  12163. org-default-priority
  12164. (1- org-default-priority))))))
  12165. ((eq action 'down)
  12166. (setq new (if have
  12167. (1+ current) ; normal cycling
  12168. ;; last priority was empty
  12169. (if (eq last-command this-command)
  12170. org-highest-priority ; wrap around empty to highest
  12171. ;; default
  12172. (if org-priority-start-cycle-with-default
  12173. org-default-priority
  12174. (1+ org-default-priority))))))
  12175. (t (user-error "Invalid action")))
  12176. (when (or (< (upcase new) org-highest-priority)
  12177. (> (upcase new) org-lowest-priority))
  12178. (if (and (memq action '(up down))
  12179. (not have) (not (eq last-command this-command)))
  12180. ;; `new' is from default priority
  12181. (error
  12182. "The default can not be set, see `org-default-priority' why")
  12183. ;; normal cycling: `new' is beyond highest/lowest priority
  12184. ;; and is wrapped around to the empty priority
  12185. (setq remove t)))
  12186. (setq news (format "%c" new))
  12187. (if have
  12188. (if remove
  12189. (replace-match "" t t nil 1)
  12190. (replace-match news t t nil 2))
  12191. (if remove
  12192. (user-error "No priority cookie found in line")
  12193. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12194. (if (match-end 2)
  12195. (progn
  12196. (goto-char (match-end 2))
  12197. (insert " [#" news "]"))
  12198. (goto-char (match-beginning 3))
  12199. (insert "[#" news "] "))))
  12200. (org-set-tags nil 'align))
  12201. (if remove
  12202. (message "Priority removed")
  12203. (message "Priority of current item set to %s" news)))))
  12204. (defun org-show-priority ()
  12205. "Show the priority of the current item.
  12206. This priority is composed of the main priority given with the [#A] cookies,
  12207. and by additional input from the age of a schedules or deadline entry."
  12208. (interactive)
  12209. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12210. (org-get-at-bol 'priority)
  12211. (save-excursion
  12212. (save-match-data
  12213. (beginning-of-line)
  12214. (and (looking-at org-heading-regexp)
  12215. (org-get-priority (match-string 0))))))))
  12216. (message "Priority is %d" (if pri pri -1000))))
  12217. (defun org-get-priority (s)
  12218. "Find priority cookie and return priority."
  12219. (save-match-data
  12220. (if (functionp org-get-priority-function)
  12221. (funcall org-get-priority-function)
  12222. (if (not (string-match org-priority-regexp s))
  12223. (* 1000 (- org-lowest-priority org-default-priority))
  12224. (* 1000 (- org-lowest-priority
  12225. (string-to-char (match-string 2 s))))))))
  12226. ;;;; Tags
  12227. (defvar org-agenda-archives-mode)
  12228. (defvar org-map-continue-from nil
  12229. "Position from where mapping should continue.
  12230. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12231. (defvar org-scanner-tags nil
  12232. "The current tag list while the tags scanner is running.")
  12233. (defvar org-trust-scanner-tags nil
  12234. "Should `org-get-tags-at' use the tags for the scanner.
  12235. This is for internal dynamical scoping only.
  12236. When this is non-nil, the function `org-get-tags-at' will return the value
  12237. of `org-scanner-tags' instead of building the list by itself. This
  12238. can lead to large speed-ups when the tags scanner is used in a file with
  12239. many entries, and when the list of tags is retrieved, for example to
  12240. obtain a list of properties. Building the tags list for each entry in such
  12241. a file becomes an N^2 operation - but with this variable set, it scales
  12242. as N.")
  12243. (defvar org--matcher-tags-todo-only nil)
  12244. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12245. "Scan headline tags with inheritance and produce output ACTION.
  12246. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12247. or `agenda' to produce an entry list for an agenda view. It can also be
  12248. a Lisp form or a function that should be called at each matched headline, in
  12249. this case the return value is a list of all return values from these calls.
  12250. MATCHER is a function accepting three arguments, returning
  12251. a non-nil value whenever a given set of tags qualifies a headline
  12252. for inclusion. See `org-make-tags-matcher' for more information.
  12253. As a special case, it can also be set to t (respectively nil) in
  12254. order to match all (respectively none) headline.
  12255. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12256. included in the output.
  12257. START-LEVEL can be a string with asterisks, reducing the scope to
  12258. headlines matching this string."
  12259. (require 'org-agenda)
  12260. (let* ((re (concat "^"
  12261. (if start-level
  12262. ;; Get the correct level to match
  12263. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12264. org-outline-regexp)
  12265. " *\\(\\<\\("
  12266. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12267. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12268. (props (list 'face 'default
  12269. 'done-face 'org-agenda-done
  12270. 'undone-face 'default
  12271. 'mouse-face 'highlight
  12272. 'org-not-done-regexp org-not-done-regexp
  12273. 'org-todo-regexp org-todo-regexp
  12274. 'org-complex-heading-regexp org-complex-heading-regexp
  12275. 'help-echo
  12276. (format "mouse-2 or RET jump to org file %s"
  12277. (abbreviate-file-name
  12278. (or (buffer-file-name (buffer-base-buffer))
  12279. (buffer-name (buffer-base-buffer)))))))
  12280. (org-map-continue-from nil)
  12281. lspos tags tags-list
  12282. (tags-alist (list (cons 0 org-file-tags)))
  12283. (llast 0) rtn rtn1 level category i txt
  12284. todo marker entry priority
  12285. ts-date ts-date-type ts-date-pair)
  12286. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12287. (setq action (list 'lambda nil action)))
  12288. (save-excursion
  12289. (goto-char (point-min))
  12290. (when (eq action 'sparse-tree)
  12291. (org-overview)
  12292. (org-remove-occur-highlights))
  12293. (while (let (case-fold-search)
  12294. (re-search-forward re nil t))
  12295. (setq org-map-continue-from nil)
  12296. (catch :skip
  12297. (setq todo
  12298. ;; TODO: is the 1-2 difference a bug?
  12299. (when (match-end 1) (match-string-no-properties 2))
  12300. tags (when (match-end 4) (match-string-no-properties 4)))
  12301. (goto-char (setq lspos (match-beginning 0)))
  12302. (setq level (org-reduced-level (org-outline-level))
  12303. category (org-get-category))
  12304. (when (eq action 'agenda)
  12305. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12306. ts-date (car ts-date-pair)
  12307. ts-date-type (cdr ts-date-pair)))
  12308. (setq i llast llast level)
  12309. ;; remove tag lists from same and sublevels
  12310. (while (>= i level)
  12311. (when (setq entry (assoc i tags-alist))
  12312. (setq tags-alist (delete entry tags-alist)))
  12313. (setq i (1- i)))
  12314. ;; add the next tags
  12315. (when tags
  12316. (setq tags (org-split-string tags ":")
  12317. tags-alist
  12318. (cons (cons level tags) tags-alist)))
  12319. ;; compile tags for current headline
  12320. (setq tags-list
  12321. (if org-use-tag-inheritance
  12322. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12323. tags)
  12324. org-scanner-tags tags-list)
  12325. (when org-use-tag-inheritance
  12326. (setcdr (car tags-alist)
  12327. (mapcar (lambda (x)
  12328. (setq x (copy-sequence x))
  12329. (org-add-prop-inherited x))
  12330. (cdar tags-alist))))
  12331. (when (and tags org-use-tag-inheritance
  12332. (or (not (eq t org-use-tag-inheritance))
  12333. org-tags-exclude-from-inheritance))
  12334. ;; Selective inheritance, remove uninherited ones.
  12335. (setcdr (car tags-alist)
  12336. (org-remove-uninherited-tags (cdar tags-alist))))
  12337. (when (and
  12338. ;; eval matcher only when the todo condition is OK
  12339. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12340. (if (functionp matcher)
  12341. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12342. (funcall matcher todo tags-list level))
  12343. matcher))
  12344. ;; Call the skipper, but return t if it does not
  12345. ;; skip, so that the `and' form continues evaluating.
  12346. (progn
  12347. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12348. t)
  12349. ;; Check if timestamps are deselecting this entry
  12350. (or (not todo-only)
  12351. (and (member todo org-todo-keywords-1)
  12352. (or (not org-agenda-tags-todo-honor-ignore-options)
  12353. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12354. ;; select this headline
  12355. (cond
  12356. ((eq action 'sparse-tree)
  12357. (and org-highlight-sparse-tree-matches
  12358. (org-get-heading) (match-end 0)
  12359. (org-highlight-new-match
  12360. (match-beginning 1) (match-end 1)))
  12361. (org-show-context 'tags-tree))
  12362. ((eq action 'agenda)
  12363. (setq txt (org-agenda-format-item
  12364. ""
  12365. (concat
  12366. (if (eq org-tags-match-list-sublevels 'indented)
  12367. (make-string (1- level) ?.) "")
  12368. (org-get-heading))
  12369. (make-string level ?\s)
  12370. category
  12371. tags-list)
  12372. priority (org-get-priority txt))
  12373. (goto-char lspos)
  12374. (setq marker (org-agenda-new-marker))
  12375. (org-add-props txt props
  12376. 'org-marker marker 'org-hd-marker marker 'org-category category
  12377. 'todo-state todo
  12378. 'ts-date ts-date
  12379. 'priority priority
  12380. 'type (concat "tagsmatch" ts-date-type))
  12381. (push txt rtn))
  12382. ((functionp action)
  12383. (setq org-map-continue-from nil)
  12384. (save-excursion
  12385. (setq rtn1 (funcall action))
  12386. (push rtn1 rtn)))
  12387. (t (user-error "Invalid action")))
  12388. ;; if we are to skip sublevels, jump to end of subtree
  12389. (unless org-tags-match-list-sublevels
  12390. (org-end-of-subtree t)
  12391. (backward-char 1))))
  12392. ;; Get the correct position from where to continue
  12393. (if org-map-continue-from
  12394. (goto-char org-map-continue-from)
  12395. (and (= (point) lspos) (end-of-line 1)))))
  12396. (when (and (eq action 'sparse-tree)
  12397. (not org-sparse-tree-open-archived-trees))
  12398. (org-hide-archived-subtrees (point-min) (point-max)))
  12399. (nreverse rtn)))
  12400. (defun org-remove-uninherited-tags (tags)
  12401. "Remove all tags that are not inherited from the list TAGS."
  12402. (cond
  12403. ((eq org-use-tag-inheritance t)
  12404. (if org-tags-exclude-from-inheritance
  12405. (org-delete-all org-tags-exclude-from-inheritance tags)
  12406. tags))
  12407. ((not org-use-tag-inheritance) nil)
  12408. ((stringp org-use-tag-inheritance)
  12409. (delq nil (mapcar
  12410. (lambda (x)
  12411. (if (and (string-match org-use-tag-inheritance x)
  12412. (not (member x org-tags-exclude-from-inheritance)))
  12413. x nil))
  12414. tags)))
  12415. ((listp org-use-tag-inheritance)
  12416. (delq nil (mapcar
  12417. (lambda (x)
  12418. (if (member x org-use-tag-inheritance) x nil))
  12419. tags)))))
  12420. (defun org-match-sparse-tree (&optional todo-only match)
  12421. "Create a sparse tree according to tags string MATCH.
  12422. MATCH is a string with match syntax. It can contain a selection
  12423. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12424. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12425. those. See the manual for details.
  12426. If optional argument TODO-ONLY is non-nil, only select lines that
  12427. are also TODO tasks."
  12428. (interactive "P")
  12429. (org-agenda-prepare-buffers (list (current-buffer)))
  12430. (let ((org--matcher-tags-todo-only todo-only))
  12431. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12432. org--matcher-tags-todo-only)))
  12433. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12434. (defvar org-cached-props nil)
  12435. (defun org-cached-entry-get (pom property)
  12436. (if (or (eq t org-use-property-inheritance)
  12437. (and (stringp org-use-property-inheritance)
  12438. (let ((case-fold-search t))
  12439. (string-match-p org-use-property-inheritance property)))
  12440. (and (listp org-use-property-inheritance)
  12441. (member-ignore-case property org-use-property-inheritance)))
  12442. ;; Caching is not possible, check it directly.
  12443. (org-entry-get pom property 'inherit)
  12444. ;; Get all properties, so we can do complicated checks easily.
  12445. (cdr (assoc-string property
  12446. (or org-cached-props
  12447. (setq org-cached-props (org-entry-properties pom)))
  12448. t))))
  12449. (defun org-global-tags-completion-table (&optional files)
  12450. "Return the list of all tags in all agenda buffer/files.
  12451. Optional FILES argument is a list of files which can be used
  12452. instead of the agenda files."
  12453. (save-excursion
  12454. (org-uniquify
  12455. (delq nil
  12456. (apply #'append
  12457. (mapcar
  12458. (lambda (file)
  12459. (set-buffer (find-file-noselect file))
  12460. (mapcar (lambda (x)
  12461. (and (stringp (car-safe x))
  12462. (list (car-safe x))))
  12463. (or org-current-tag-alist (org-get-buffer-tags))))
  12464. (if (car-safe files) files
  12465. (org-agenda-files))))))))
  12466. (defun org-make-tags-matcher (match)
  12467. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12468. Returns a cons of the selection string MATCH and a function
  12469. implementing the matcher.
  12470. The matcher is to be called at an Org entry, with point on the
  12471. headline, and returns non-nil if the entry matches the selection
  12472. string MATCH. It must be called with three arguments: the TODO
  12473. keyword at the entry (or nil if none), the list of all tags at
  12474. the entry including inherited ones and the reduced level of the
  12475. headline. Additionally, the category of the entry, if any, must
  12476. be specified as the text property `org-category' on the headline.
  12477. This function sets the variable `org--matcher-tags-todo-only' to
  12478. a non-nil value if the matcher restricts matching to TODO
  12479. entries, otherwise it is not touched.
  12480. See also `org-scan-tags'."
  12481. (unless match
  12482. ;; Get a new match request, with completion against the global
  12483. ;; tags table and the local tags in current buffer.
  12484. (let ((org-last-tags-completion-table
  12485. (org-uniquify
  12486. (delq nil (append (org-get-buffer-tags)
  12487. (org-global-tags-completion-table))))))
  12488. (setq match
  12489. (completing-read
  12490. "Match: "
  12491. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12492. (let ((match0 match)
  12493. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12494. (start 0)
  12495. tagsmatch todomatch tagsmatcher todomatcher)
  12496. ;; Expand group tags.
  12497. (setq match (org-tags-expand match))
  12498. ;; Check if there is a TODO part of this match, which would be the
  12499. ;; part after a "/". To make sure that this slash is not part of
  12500. ;; a property value to be matched against, we also check that
  12501. ;; there is no / after that slash. First, find the last slash.
  12502. (let ((s 0))
  12503. (while (string-match "/+" match s)
  12504. (setq start (match-beginning 0))
  12505. (setq s (match-end 0))))
  12506. (if (and (string-match "/+" match start)
  12507. (not (string-match-p "\"" match start)))
  12508. ;; Match contains also a TODO-matching request.
  12509. (progn
  12510. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12511. (setq todomatch (substring match (match-end 0)))
  12512. (when (string-prefix-p "!" todomatch)
  12513. (setq org--matcher-tags-todo-only t)
  12514. (setq todomatch (substring todomatch 1)))
  12515. (when (string-match "\\`\\s-*\\'" todomatch)
  12516. (setq todomatch nil)))
  12517. ;; Only matching tags.
  12518. (setq tagsmatch match)
  12519. (setq todomatch nil))
  12520. ;; Make the tags matcher.
  12521. (when (org-string-nw-p tagsmatch)
  12522. (let ((orlist nil)
  12523. (orterms (org-split-string tagsmatch "|"))
  12524. term)
  12525. (while (setq term (pop orterms))
  12526. (while (and (equal (substring term -1) "\\") orterms)
  12527. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12528. (while (string-match re term)
  12529. (let* ((rest (substring term (match-end 0)))
  12530. (minus (and (match-end 1)
  12531. (equal (match-string 1 term) "-")))
  12532. (tag (save-match-data
  12533. (replace-regexp-in-string
  12534. "\\\\-" "-" (match-string 2 term))))
  12535. (regexp (eq (string-to-char tag) ?{))
  12536. (levelp (match-end 4))
  12537. (propp (match-end 5))
  12538. (mm
  12539. (cond
  12540. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12541. (levelp
  12542. `(,(org-op-to-function (match-string 3 term))
  12543. level
  12544. ,(string-to-number (match-string 4 term))))
  12545. (propp
  12546. (let* ((gv (pcase (upcase (match-string 5 term))
  12547. ("CATEGORY"
  12548. '(get-text-property (point) 'org-category))
  12549. ("TODO" 'todo)
  12550. (p `(org-cached-entry-get nil ,p))))
  12551. (pv (match-string 7 term))
  12552. (regexp (eq (string-to-char pv) ?{))
  12553. (strp (eq (string-to-char pv) ?\"))
  12554. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12555. (po (org-op-to-function (match-string 6 term)
  12556. (if timep 'time strp))))
  12557. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12558. (when timep (setq pv (org-matcher-time pv)))
  12559. (cond ((and regexp (eq po 'org<>))
  12560. `(not (string-match ,pv (or ,gv ""))))
  12561. (regexp `(string-match ,pv (or ,gv "")))
  12562. (strp `(,po (or ,gv "") ,pv))
  12563. (t
  12564. `(,po
  12565. (string-to-number (or ,gv ""))
  12566. ,(string-to-number pv))))))
  12567. (t `(member ,tag tags-list)))))
  12568. (push (if minus `(not ,mm) mm) tagsmatcher)
  12569. (setq term rest)))
  12570. (push `(and ,@tagsmatcher) orlist)
  12571. (setq tagsmatcher nil))
  12572. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12573. ;; Make the TODO matcher.
  12574. (when (org-string-nw-p todomatch)
  12575. (let ((orlist nil))
  12576. (dolist (term (org-split-string todomatch "|"))
  12577. (while (string-match re term)
  12578. (let* ((minus (and (match-end 1)
  12579. (equal (match-string 1 term) "-")))
  12580. (kwd (match-string 2 term))
  12581. (regexp (eq (string-to-char kwd) ?{))
  12582. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12583. `(equal todo ,kwd))))
  12584. (push (if minus `(not ,mm) mm) todomatcher))
  12585. (setq term (substring term (match-end 0))))
  12586. (push (if (> (length todomatcher) 1)
  12587. (cons 'and todomatcher)
  12588. (car todomatcher))
  12589. orlist)
  12590. (setq todomatcher nil))
  12591. (setq todomatcher (cons 'or orlist))))
  12592. ;; Return the string and function of the matcher. If no
  12593. ;; tags-specific or todo-specific matcher exists, match
  12594. ;; everything.
  12595. (let ((matcher (if (and tagsmatcher todomatcher)
  12596. `(and ,tagsmatcher ,todomatcher)
  12597. (or tagsmatcher todomatcher t))))
  12598. (when org--matcher-tags-todo-only
  12599. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12600. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12601. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12602. "Expand group tags in MATCH.
  12603. This replaces every group tag in MATCH with a regexp tag search.
  12604. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12605. will be replaced like this:
  12606. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12607. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12608. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12609. Replacing by a regexp preserves the structure of the match.
  12610. E.g., this expansion
  12611. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12612. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12613. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12614. A group tag in MATCH can contain regular expressions of its own.
  12615. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12616. will be replaced like this:
  12617. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12618. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12619. assumed to be a single group tag, and the function will return
  12620. the list of tags in this group.
  12621. When DOWNCASE is non-nil, expand downcased TAGS."
  12622. (if org-group-tags
  12623. (let* ((case-fold-search t)
  12624. (stable org-mode-syntax-table)
  12625. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12626. (taggroups (if downcased
  12627. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12628. taggroups)
  12629. taggroups))
  12630. (taggroups-keys (mapcar #'car taggroups))
  12631. (return-match (if downcased (downcase match) match))
  12632. (count 0)
  12633. (work-already-expanded tags-already-expanded)
  12634. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12635. ;; @ and _ are allowed as word-components in tags.
  12636. (modify-syntax-entry ?@ "w" stable)
  12637. (modify-syntax-entry ?_ "w" stable)
  12638. ;; Temporarily replace regexp-expressions in the match-expression.
  12639. (while (string-match "{.+?}" return-match)
  12640. (cl-incf count)
  12641. (push (match-string 0 return-match) regexps-in-match)
  12642. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12643. (while (and taggroups-keys
  12644. (with-syntax-table stable
  12645. (string-match
  12646. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12647. (regexp-opt taggroups-keys) "\\>\\)")
  12648. return-match)))
  12649. (let* ((dir (match-string 1 return-match))
  12650. (tag (match-string 2 return-match))
  12651. (tag (if downcased (downcase tag) tag)))
  12652. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12653. (member tag work-already-expanded))
  12654. (setq tags-in-group (assoc tag taggroups))
  12655. (push tag work-already-expanded)
  12656. ;; Recursively expand each tag in the group, if the tag hasn't
  12657. ;; already been expanded. Restore the match-data after all recursive calls.
  12658. (save-match-data
  12659. (let (tags-expanded)
  12660. (dolist (x (cdr tags-in-group))
  12661. (if (and (member x taggroups-keys)
  12662. (not (member x work-already-expanded)))
  12663. (setq tags-expanded
  12664. (delete-dups
  12665. (append
  12666. (org-tags-expand x t downcased
  12667. work-already-expanded)
  12668. tags-expanded)))
  12669. (setq tags-expanded
  12670. (append (list x) tags-expanded)))
  12671. (setq work-already-expanded
  12672. (delete-dups
  12673. (append tags-expanded
  12674. work-already-expanded))))
  12675. (setq tags-in-group
  12676. (delete-dups (cons (car tags-in-group)
  12677. tags-expanded)))))
  12678. ;; Filter tag-regexps from tags.
  12679. (setq regexp-in-group-escaped
  12680. (delq nil (mapcar (lambda (x)
  12681. (if (stringp x)
  12682. (and (equal "{" (substring x 0 1))
  12683. (equal "}" (substring x -1))
  12684. x)
  12685. x))
  12686. tags-in-group))
  12687. regexp-in-group
  12688. (mapcar (lambda (x)
  12689. (substring x 1 -1))
  12690. regexp-in-group-escaped)
  12691. tags-in-group
  12692. (delq nil (mapcar (lambda (x)
  12693. (if (stringp x)
  12694. (and (not (equal "{" (substring x 0 1)))
  12695. (not (equal "}" (substring x -1)))
  12696. x)
  12697. x))
  12698. tags-in-group)))
  12699. ;; If single-as-list, do no more in the while-loop.
  12700. (if (not single-as-list)
  12701. (progn
  12702. (when regexp-in-group
  12703. (setq regexp-in-group
  12704. (concat "\\|"
  12705. (mapconcat 'identity regexp-in-group
  12706. "\\|"))))
  12707. (setq tags-in-group
  12708. (concat dir
  12709. "{\\<"
  12710. (regexp-opt tags-in-group)
  12711. "\\>"
  12712. regexp-in-group
  12713. "}"))
  12714. (when (stringp tags-in-group)
  12715. (org-add-props tags-in-group '(grouptag t)))
  12716. (setq return-match
  12717. (replace-match tags-in-group t t return-match)))
  12718. (setq tags-in-group
  12719. (append regexp-in-group-escaped tags-in-group))))
  12720. (setq taggroups-keys (delete tag taggroups-keys))))
  12721. ;; Add the regular expressions back into the match-expression again.
  12722. (while regexps-in-match
  12723. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12724. (pop regexps-in-match)
  12725. return-match t t))
  12726. (cl-decf count))
  12727. (if single-as-list
  12728. (if tags-in-group tags-in-group (list return-match))
  12729. return-match))
  12730. (if single-as-list
  12731. (list (if downcased (downcase match) match))
  12732. match)))
  12733. (defun org-op-to-function (op &optional stringp)
  12734. "Turn an operator into the appropriate function."
  12735. (setq op
  12736. (cond
  12737. ((equal op "<" ) '(< string< org-time<))
  12738. ((equal op ">" ) '(> org-string> org-time>))
  12739. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12740. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12741. ((member op '("=" "==")) '(= string= org-time=))
  12742. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  12743. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12744. (defun org<> (a b) (not (= a b)))
  12745. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  12746. (defun org-string>= (a b) (not (string< a b)))
  12747. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  12748. (defun org-string<> (a b) (not (string= a b)))
  12749. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  12750. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  12751. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  12752. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  12753. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  12754. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  12755. (defun org-2ft (s)
  12756. "Convert S to a floating point time.
  12757. If S is already a number, just return it. If it is a string, parse
  12758. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  12759. (cond
  12760. ((numberp s) s)
  12761. ((stringp s)
  12762. (condition-case nil
  12763. (float-time (apply #'encode-time (org-parse-time-string s)))
  12764. (error 0.)))
  12765. (t 0.)))
  12766. (defun org-time-today ()
  12767. "Time in seconds today at 0:00.
  12768. Returns the float number of seconds since the beginning of the
  12769. epoch to the beginning of today (00:00)."
  12770. (float-time (apply 'encode-time
  12771. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  12772. (defun org-matcher-time (s)
  12773. "Interpret a time comparison value."
  12774. (save-match-data
  12775. (cond
  12776. ((string= s "<now>") (float-time))
  12777. ((string= s "<today>") (org-time-today))
  12778. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  12779. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  12780. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  12781. (+ (org-time-today)
  12782. (* (string-to-number (match-string 1 s))
  12783. (cdr (assoc (match-string 2 s)
  12784. '(("d" . 86400.0) ("w" . 604800.0)
  12785. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  12786. (t (org-2ft s)))))
  12787. (defun org-match-any-p (re list)
  12788. "Does re match any element of list?"
  12789. (setq list (mapcar (lambda (x) (string-match re x)) list))
  12790. (delq nil list))
  12791. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12792. (defvar org-tags-overlay (make-overlay 1 1))
  12793. (delete-overlay org-tags-overlay)
  12794. (defun org-get-local-tags-at (&optional pos)
  12795. "Get a list of tags defined in the current headline."
  12796. (org-get-tags-at pos 'local))
  12797. (defun org-get-local-tags ()
  12798. "Get a list of tags defined in the current headline."
  12799. (org-get-tags-at nil 'local))
  12800. (defun org-get-tags-at (&optional pos local)
  12801. "Get a list of all headline tags applicable at POS.
  12802. POS defaults to point. If tags are inherited, the list contains
  12803. the targets in the same sequence as the headlines appear, i.e.
  12804. the tags of the current headline come last.
  12805. When LOCAL is non-nil, only return tags from the current headline,
  12806. ignore inherited ones."
  12807. (interactive)
  12808. (if (and org-trust-scanner-tags
  12809. (or (not pos) (equal pos (point)))
  12810. (not local))
  12811. org-scanner-tags
  12812. (let (tags ltags lastpos parent)
  12813. (save-excursion
  12814. (save-restriction
  12815. (widen)
  12816. (goto-char (or pos (point)))
  12817. (save-match-data
  12818. (catch 'done
  12819. (condition-case nil
  12820. (progn
  12821. (org-back-to-heading t)
  12822. (while (not (equal lastpos (point)))
  12823. (setq lastpos (point))
  12824. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  12825. (setq ltags (org-split-string
  12826. (match-string-no-properties 1) ":"))
  12827. (when parent
  12828. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  12829. (setq tags (append
  12830. (if parent
  12831. (org-remove-uninherited-tags ltags)
  12832. ltags)
  12833. tags)))
  12834. (or org-use-tag-inheritance (throw 'done t))
  12835. (when local (throw 'done t))
  12836. (or (org-up-heading-safe) (error nil))
  12837. (setq parent t)))
  12838. (error nil)))))
  12839. (if local
  12840. tags
  12841. (reverse (delete-dups
  12842. (reverse (append
  12843. (org-remove-uninherited-tags
  12844. org-file-tags)
  12845. tags)))))))))
  12846. (defun org-add-prop-inherited (s)
  12847. (add-text-properties 0 (length s) '(inherited t) s)
  12848. s)
  12849. (defun org-toggle-tag (tag &optional onoff)
  12850. "Toggle the tag TAG for the current line.
  12851. If ONOFF is `on' or `off', don't toggle but set to this state."
  12852. (save-excursion
  12853. (org-back-to-heading t)
  12854. (let ((current
  12855. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  12856. (line-end-position) t)
  12857. (let ((tags (match-string 1)))
  12858. ;; Clear current tags.
  12859. (replace-match "")
  12860. ;; Reverse the tags list so any new tag is appended to
  12861. ;; the current list of tags.
  12862. (nreverse (org-split-string tags ":")))))
  12863. res)
  12864. (pcase onoff
  12865. (`off (setq current (delete tag current)))
  12866. ((or `on (guard (not (member tag current))))
  12867. (setq res t)
  12868. (cl-pushnew tag current :test #'equal))
  12869. (_ (setq current (delete tag current))))
  12870. (end-of-line)
  12871. (if current
  12872. (progn
  12873. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  12874. (org-set-tags nil t))
  12875. (delete-horizontal-space))
  12876. (run-hooks 'org-after-tags-change-hook)
  12877. res)))
  12878. (defun org--align-tags-here (to-col)
  12879. "Align tags on the current headline to TO-COL.
  12880. Assume point is on a headline."
  12881. (let ((pos (point)))
  12882. (beginning-of-line)
  12883. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  12884. (>= pos (match-beginning 2)))
  12885. ;; No tags or point within tags: do not align.
  12886. (goto-char pos)
  12887. (goto-char (match-beginning 1))
  12888. (let ((shift (max (- (if (>= to-col 0) to-col
  12889. (- (abs to-col) (string-width (match-string 2))))
  12890. (current-column))
  12891. 1)))
  12892. (replace-match (make-string shift ?\s) nil nil nil 1)
  12893. ;; Preserve initial position, if possible. In any case, stop
  12894. ;; before tags.
  12895. (when (< pos (point)) (goto-char pos))))))
  12896. (defun org-set-tags-command (&optional arg just-align)
  12897. "Call the set-tags command for the current entry."
  12898. (interactive "P")
  12899. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  12900. (org-set-tags arg just-align)
  12901. (save-excursion
  12902. (unless (and (org-region-active-p)
  12903. org-loop-over-headlines-in-active-region)
  12904. (org-back-to-heading t))
  12905. (org-set-tags arg just-align))))
  12906. (defun org-set-tags-to (data)
  12907. "Set the tags of the current entry to DATA, replacing the current tags.
  12908. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  12909. If DATA is nil or the empty string, any tags will be removed."
  12910. (interactive "sTags: ")
  12911. (setq data
  12912. (cond
  12913. ((eq data nil) "")
  12914. ((equal data "") "")
  12915. ((stringp data)
  12916. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  12917. ":"))
  12918. ((listp data)
  12919. (concat ":" (mapconcat 'identity data ":") ":"))))
  12920. (when data
  12921. (save-excursion
  12922. (org-back-to-heading t)
  12923. (when (let ((case-fold-search nil))
  12924. (looking-at org-complex-heading-regexp))
  12925. (if (match-end 5)
  12926. (progn
  12927. (goto-char (match-beginning 5))
  12928. (insert data)
  12929. (delete-region (point) (point-at-eol))
  12930. (org-set-tags nil 'align))
  12931. (goto-char (point-at-eol))
  12932. (insert " " data)
  12933. (org-set-tags nil 'align)))
  12934. (beginning-of-line 1)
  12935. (when (looking-at ".*?\\([ \t]+\\)$")
  12936. (delete-region (match-beginning 1) (match-end 1))))))
  12937. (defun org-align-all-tags ()
  12938. "Align the tags in all headings."
  12939. (interactive)
  12940. (save-excursion
  12941. (or (ignore-errors (org-back-to-heading t))
  12942. (outline-next-heading))
  12943. (if (org-at-heading-p)
  12944. (org-set-tags t)
  12945. (message "No headings"))))
  12946. (defvar org-indent-indentation-per-level)
  12947. (defun org-set-tags (&optional arg just-align)
  12948. "Set the tags for the current headline.
  12949. With prefix ARG, realign all tags in headings in the current buffer.
  12950. When JUST-ALIGN is non-nil, only align tags."
  12951. (interactive "P")
  12952. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12953. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12954. 'region-start-level
  12955. 'region))
  12956. org-loop-over-headlines-in-active-region)
  12957. (org-map-entries
  12958. ;; We don't use ARG and JUST-ALIGN here because these args
  12959. ;; are not useful when looping over headlines.
  12960. #'org-set-tags
  12961. org-loop-over-headlines-in-active-region
  12962. cl
  12963. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  12964. (let ((org-setting-tags t))
  12965. (if arg
  12966. (save-excursion
  12967. (goto-char (point-min))
  12968. (while (re-search-forward org-outline-regexp-bol nil t)
  12969. (org-set-tags nil t)
  12970. (end-of-line))
  12971. (message "All tags realigned to column %d" org-tags-column))
  12972. (let* ((current (org-get-tags-string))
  12973. (tags
  12974. (if just-align current
  12975. ;; Get a new set of tags from the user.
  12976. (save-excursion
  12977. (let* ((seen)
  12978. (table
  12979. (setq
  12980. org-last-tags-completion-table
  12981. ;; Uniquify tags in alists, yet preserve
  12982. ;; structure (i.e., keywords).
  12983. (delq nil
  12984. (mapcar
  12985. (lambda (pair)
  12986. (let ((head (car pair)))
  12987. (cond ((symbolp head) pair)
  12988. ((member head seen) nil)
  12989. (t (push head seen)
  12990. pair))))
  12991. (append
  12992. (or org-current-tag-alist
  12993. (org-get-buffer-tags))
  12994. (and
  12995. org-complete-tags-always-offer-all-agenda-tags
  12996. (org-global-tags-completion-table
  12997. (org-agenda-files))))))))
  12998. (current-tags (org-split-string current ":"))
  12999. (inherited-tags
  13000. (nreverse (nthcdr (length current-tags)
  13001. (nreverse (org-get-tags-at))))))
  13002. (replace-regexp-in-string
  13003. "\\([-+&]+\\|,\\)"
  13004. ":"
  13005. (if (or (eq t org-use-fast-tag-selection)
  13006. (and org-use-fast-tag-selection
  13007. (delq nil (mapcar #'cdr table))))
  13008. (org-fast-tag-selection
  13009. current-tags inherited-tags table
  13010. (and org-fast-tag-selection-include-todo
  13011. org-todo-key-alist))
  13012. (let ((org-add-colon-after-tag-completion
  13013. (< 1 (length table))))
  13014. (org-trim
  13015. (completing-read
  13016. "Tags: "
  13017. #'org-tags-completion-function
  13018. nil nil current 'org-tags-history))))))))))
  13019. (when org-tags-sort-function
  13020. (setq tags
  13021. (mapconcat
  13022. #'identity
  13023. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13024. org-tags-sort-function)
  13025. ":")))
  13026. (if (or (string= ":" tags)
  13027. (string= "::" tags))
  13028. (setq tags ""))
  13029. (if (not (org-string-nw-p tags)) (setq tags "")
  13030. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13031. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13032. ;; Insert new tags at the correct column.
  13033. (unless (equal current tags)
  13034. (save-excursion
  13035. (beginning-of-line)
  13036. (let ((case-fold-search nil))
  13037. (looking-at org-complex-heading-regexp))
  13038. ;; Remove current tags, if any.
  13039. (when (match-end 5) (replace-match "" nil nil nil 5))
  13040. ;; Insert new tags, if any. Otherwise, remove trailing
  13041. ;; white spaces.
  13042. (end-of-line)
  13043. (if (not (equal tags ""))
  13044. ;; When text is being inserted on an invisible
  13045. ;; region boundary, it can be inadvertently sucked
  13046. ;; into invisibility.
  13047. (org-flag-region (point) (progn (insert " " tags) (point))
  13048. nil
  13049. 'outline)
  13050. (skip-chars-backward " \t")
  13051. (delete-region (point) (line-end-position)))))
  13052. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13053. ;; is on.
  13054. (unless (equal tags "")
  13055. (let* ((level (save-excursion
  13056. (beginning-of-line)
  13057. (skip-chars-forward "\\*")))
  13058. (offset (if (bound-and-true-p org-indent-mode)
  13059. (* (1- org-indent-indentation-per-level)
  13060. (1- level))
  13061. 0))
  13062. (tags-column
  13063. (+ org-tags-column
  13064. (if (> org-tags-column 0) (- offset) offset))))
  13065. (org--align-tags-here tags-column))))
  13066. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13067. (defun org-change-tag-in-region (beg end tag off)
  13068. "Add or remove TAG for each entry in the region.
  13069. This works in the agenda, and also in an Org buffer."
  13070. (interactive
  13071. (list (region-beginning) (region-end)
  13072. (let ((org-last-tags-completion-table
  13073. (if (derived-mode-p 'org-mode)
  13074. (org-uniquify
  13075. (delq nil (append (org-get-buffer-tags)
  13076. (org-global-tags-completion-table))))
  13077. (org-global-tags-completion-table))))
  13078. (completing-read
  13079. "Tag: " 'org-tags-completion-function nil nil nil
  13080. 'org-tags-history))
  13081. (progn
  13082. (message "[s]et or [r]emove? ")
  13083. (equal (read-char-exclusive) ?r))))
  13084. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13085. (let ((agendap (equal major-mode 'org-agenda-mode))
  13086. l1 l2 m buf pos newhead (cnt 0))
  13087. (goto-char end)
  13088. (setq l2 (1- (org-current-line)))
  13089. (goto-char beg)
  13090. (setq l1 (org-current-line))
  13091. (cl-loop for l from l1 to l2 do
  13092. (org-goto-line l)
  13093. (setq m (get-text-property (point) 'org-hd-marker))
  13094. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13095. (and agendap m))
  13096. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13097. pos (if agendap m (point)))
  13098. (with-current-buffer buf
  13099. (save-excursion
  13100. (save-restriction
  13101. (goto-char pos)
  13102. (setq cnt (1+ cnt))
  13103. (org-toggle-tag tag (if off 'off 'on))
  13104. (setq newhead (org-get-heading)))))
  13105. (and agendap (org-agenda-change-all-lines newhead m))))
  13106. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13107. (defun org-tags-completion-function (string _predicate &optional flag)
  13108. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13109. (confirm (lambda (x) (stringp (car x)))))
  13110. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13111. (setq s1 (match-string 1 string)
  13112. s2 (match-string 2 string))
  13113. (setq s1 "" s2 string))
  13114. (cond
  13115. ((eq flag nil)
  13116. ;; try completion
  13117. (setq rtn (try-completion s2 ctable confirm))
  13118. (when (stringp rtn)
  13119. (setq rtn
  13120. (concat s1 s2 (substring rtn (length s2))
  13121. (if (and org-add-colon-after-tag-completion
  13122. (assoc rtn ctable))
  13123. ":" ""))))
  13124. rtn)
  13125. ((eq flag t)
  13126. ;; all-completions
  13127. (all-completions s2 ctable confirm))
  13128. ((eq flag 'lambda)
  13129. ;; exact match?
  13130. (assoc s2 ctable)))))
  13131. (defun org-fast-tag-insert (kwd tags face &optional end)
  13132. "Insert KDW, and the TAGS, the latter with face FACE.
  13133. Also insert END."
  13134. (insert (format "%-12s" (concat kwd ":"))
  13135. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13136. (or end "")))
  13137. (defun org-fast-tag-show-exit (flag)
  13138. (save-excursion
  13139. (org-goto-line 3)
  13140. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13141. (replace-match ""))
  13142. (when flag
  13143. (end-of-line 1)
  13144. (org-move-to-column (- (window-width) 19) t)
  13145. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13146. (defun org-set-current-tags-overlay (current prefix)
  13147. "Add an overlay to CURRENT tag with PREFIX."
  13148. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13149. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13150. (org-overlay-display org-tags-overlay (concat prefix s))))
  13151. (defvar org-last-tag-selection-key nil)
  13152. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13153. "Fast tag selection with single keys.
  13154. CURRENT is the current list of tags in the headline, INHERITED is the
  13155. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13156. possibly with grouping information. TODO-TABLE is a similar table with
  13157. TODO keywords, should these have keys assigned to them.
  13158. If the keys are nil, a-z are automatically assigned.
  13159. Returns the new tags string, or nil to not change the current settings."
  13160. (let* ((fulltable (append table todo-table))
  13161. (maxlen (apply 'max (mapcar
  13162. (lambda (x)
  13163. (if (stringp (car x)) (string-width (car x)) 0))
  13164. fulltable)))
  13165. (buf (current-buffer))
  13166. (expert (eq org-fast-tag-selection-single-key 'expert))
  13167. (buffer-tags nil)
  13168. (fwidth (+ maxlen 3 1 3))
  13169. (ncol (/ (- (window-width) 4) fwidth))
  13170. (i-face 'org-done)
  13171. (c-face 'org-todo)
  13172. tg cnt e c char c1 c2 ntable tbl rtn
  13173. ov-start ov-end ov-prefix
  13174. (exit-after-next org-fast-tag-selection-single-key)
  13175. (done-keywords org-done-keywords)
  13176. groups ingroup intaggroup)
  13177. (save-excursion
  13178. (beginning-of-line 1)
  13179. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13180. (setq ov-start (match-beginning 1)
  13181. ov-end (match-end 1)
  13182. ov-prefix "")
  13183. (setq ov-start (1- (point-at-eol))
  13184. ov-end (1+ ov-start))
  13185. (skip-chars-forward "^\n\r")
  13186. (setq ov-prefix
  13187. (concat
  13188. (buffer-substring (1- (point)) (point))
  13189. (if (> (current-column) org-tags-column)
  13190. " "
  13191. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13192. (move-overlay org-tags-overlay ov-start ov-end)
  13193. (save-window-excursion
  13194. (if expert
  13195. (set-buffer (get-buffer-create " *Org tags*"))
  13196. (delete-other-windows)
  13197. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13198. (org-switch-to-buffer-other-window " *Org tags*"))
  13199. (erase-buffer)
  13200. (setq-local org-done-keywords done-keywords)
  13201. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13202. (org-fast-tag-insert "Current" current c-face "\n\n")
  13203. (org-fast-tag-show-exit exit-after-next)
  13204. (org-set-current-tags-overlay current ov-prefix)
  13205. (setq tbl fulltable char ?a cnt 0)
  13206. (while (setq e (pop tbl))
  13207. (cond
  13208. ((eq (car e) :startgroup)
  13209. (push '() groups) (setq ingroup t)
  13210. (unless (zerop cnt)
  13211. (setq cnt 0)
  13212. (insert "\n"))
  13213. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13214. ((eq (car e) :endgroup)
  13215. (setq ingroup nil cnt 0)
  13216. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13217. ((eq (car e) :startgrouptag)
  13218. (setq intaggroup t)
  13219. (unless (zerop cnt)
  13220. (setq cnt 0)
  13221. (insert "\n"))
  13222. (insert "[ "))
  13223. ((eq (car e) :endgrouptag)
  13224. (setq intaggroup nil cnt 0)
  13225. (insert "]\n"))
  13226. ((equal e '(:newline))
  13227. (unless (zerop cnt)
  13228. (setq cnt 0)
  13229. (insert "\n")
  13230. (setq e (car tbl))
  13231. (while (equal (car tbl) '(:newline))
  13232. (insert "\n")
  13233. (setq tbl (cdr tbl)))))
  13234. ((equal e '(:grouptags)) (insert " : "))
  13235. (t
  13236. (setq tg (copy-sequence (car e)) c2 nil)
  13237. (if (cdr e)
  13238. (setq c (cdr e))
  13239. ;; automatically assign a character.
  13240. (setq c1 (string-to-char
  13241. (downcase (substring
  13242. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13243. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13244. (while (or (rassoc char ntable) (rassoc char table))
  13245. (setq char (1+ char)))
  13246. (setq c2 c1))
  13247. (setq c (or c2 char)))
  13248. (when ingroup (push tg (car groups)))
  13249. (setq tg (org-add-props tg nil 'face
  13250. (cond
  13251. ((not (assoc tg table))
  13252. (org-get-todo-face tg))
  13253. ((member tg current) c-face)
  13254. ((member tg inherited) i-face))))
  13255. (when (equal (caar tbl) :grouptags)
  13256. (org-add-props tg nil 'face 'org-tag-group))
  13257. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13258. (insert "[" c "] " tg (make-string
  13259. (- fwidth 4 (length tg)) ?\ ))
  13260. (push (cons tg c) ntable)
  13261. (when (= (cl-incf cnt) ncol)
  13262. (insert "\n")
  13263. (when (or ingroup intaggroup) (insert " "))
  13264. (setq cnt 0)))))
  13265. (setq ntable (nreverse ntable))
  13266. (insert "\n")
  13267. (goto-char (point-min))
  13268. (unless expert (org-fit-window-to-buffer))
  13269. (setq rtn
  13270. (catch 'exit
  13271. (while t
  13272. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13273. (if (not groups) "no " "")
  13274. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13275. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13276. (setq org-last-tag-selection-key c)
  13277. (cond
  13278. ((= c ?\r) (throw 'exit t))
  13279. ((= c ?!)
  13280. (setq groups (not groups))
  13281. (goto-char (point-min))
  13282. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13283. ((= c ?\C-c)
  13284. (if (not expert)
  13285. (org-fast-tag-show-exit
  13286. (setq exit-after-next (not exit-after-next)))
  13287. (setq expert nil)
  13288. (delete-other-windows)
  13289. (set-window-buffer (split-window-vertically) " *Org tags*")
  13290. (org-switch-to-buffer-other-window " *Org tags*")
  13291. (org-fit-window-to-buffer)))
  13292. ((or (= c ?\C-g)
  13293. (and (= c ?q) (not (rassoc c ntable))))
  13294. (delete-overlay org-tags-overlay)
  13295. (setq quit-flag t))
  13296. ((= c ?\ )
  13297. (setq current nil)
  13298. (when exit-after-next (setq exit-after-next 'now)))
  13299. ((= c ?\t)
  13300. (condition-case nil
  13301. (setq tg (completing-read
  13302. "Tag: "
  13303. (or buffer-tags
  13304. (with-current-buffer buf
  13305. (setq buffer-tags
  13306. (org-get-buffer-tags))))))
  13307. (quit (setq tg "")))
  13308. (when (string-match "\\S-" tg)
  13309. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13310. (if (member tg current)
  13311. (setq current (delete tg current))
  13312. (push tg current)))
  13313. (when exit-after-next (setq exit-after-next 'now)))
  13314. ((setq e (rassoc c todo-table) tg (car e))
  13315. (with-current-buffer buf
  13316. (save-excursion (org-todo tg)))
  13317. (when exit-after-next (setq exit-after-next 'now)))
  13318. ((setq e (rassoc c ntable) tg (car e))
  13319. (if (member tg current)
  13320. (setq current (delete tg current))
  13321. (cl-loop for g in groups do
  13322. (when (member tg g)
  13323. (dolist (x g) (setq current (delete x current)))))
  13324. (push tg current))
  13325. (when exit-after-next (setq exit-after-next 'now))))
  13326. ;; Create a sorted list
  13327. (setq current
  13328. (sort current
  13329. (lambda (a b)
  13330. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13331. (when (eq exit-after-next 'now) (throw 'exit t))
  13332. (goto-char (point-min))
  13333. (beginning-of-line 2)
  13334. (delete-region (point) (point-at-eol))
  13335. (org-fast-tag-insert "Current" current c-face)
  13336. (org-set-current-tags-overlay current ov-prefix)
  13337. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13338. (setq tg (match-string 1))
  13339. (add-text-properties
  13340. (match-beginning 1) (match-end 1)
  13341. (list 'face
  13342. (cond
  13343. ((member tg current) c-face)
  13344. ((member tg inherited) i-face)
  13345. (t (get-text-property (match-beginning 1) 'face))))))
  13346. (goto-char (point-min)))))
  13347. (delete-overlay org-tags-overlay)
  13348. (if rtn
  13349. (mapconcat 'identity current ":")
  13350. nil))))
  13351. (defun org-get-tags-string ()
  13352. "Get the TAGS string in the current headline."
  13353. (unless (org-at-heading-p t)
  13354. (user-error "Not on a heading"))
  13355. (save-excursion
  13356. (beginning-of-line 1)
  13357. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13358. (match-string-no-properties 1)
  13359. "")))
  13360. (defun org-get-tags ()
  13361. "Get the list of tags specified in the current headline."
  13362. (org-split-string (org-get-tags-string) ":"))
  13363. (defun org-get-buffer-tags ()
  13364. "Get a table of all tags used in the buffer, for completion."
  13365. (org-with-wide-buffer
  13366. (goto-char (point-min))
  13367. (let ((tag-re (concat org-outline-regexp-bol
  13368. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13369. tags)
  13370. (while (re-search-forward tag-re nil t)
  13371. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13372. (push tag tags)))
  13373. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13374. ;;;; The mapping API
  13375. (defvar org-agenda-skip-comment-trees)
  13376. (defvar org-agenda-skip-function)
  13377. (defun org-map-entries (func &optional match scope &rest skip)
  13378. "Call FUNC at each headline selected by MATCH in SCOPE.
  13379. FUNC is a function or a lisp form. The function will be called without
  13380. arguments, with the cursor positioned at the beginning of the headline.
  13381. The return values of all calls to the function will be collected and
  13382. returned as a list.
  13383. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13384. does not need to preserve point. After evaluation, the cursor will be
  13385. moved to the end of the line (presumably of the headline of the
  13386. processed entry) and search continues from there. Under some
  13387. circumstances, this may not produce the wanted results. For example,
  13388. if you have removed (e.g. archived) the current (sub)tree it could
  13389. mean that the next entry will be skipped entirely. In such cases, you
  13390. can specify the position from where search should continue by making
  13391. FUNC set the variable `org-map-continue-from' to the desired buffer
  13392. position.
  13393. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13394. Only headlines that are matched by this query will be considered during
  13395. the iteration. When MATCH is nil or t, all headlines will be
  13396. visited by the iteration.
  13397. SCOPE determines the scope of this command. It can be any of:
  13398. nil The current buffer, respecting the restriction if any
  13399. tree The subtree started with the entry at point
  13400. region The entries within the active region, if any
  13401. region-start-level
  13402. The entries within the active region, but only those at
  13403. the same level than the first one.
  13404. file The current buffer, without restriction
  13405. file-with-archives
  13406. The current buffer, and any archives associated with it
  13407. agenda All agenda files
  13408. agenda-with-archives
  13409. All agenda files with any archive files associated with them
  13410. \(file1 file2 ...)
  13411. If this is a list, all files in the list will be scanned
  13412. The remaining args are treated as settings for the skipping facilities of
  13413. the scanner. The following items can be given here:
  13414. archive skip trees with the archive tag
  13415. comment skip trees with the COMMENT keyword
  13416. function or Emacs Lisp form:
  13417. will be used as value for `org-agenda-skip-function', so
  13418. whenever the function returns a position, FUNC will not be
  13419. called for that entry and search will continue from the
  13420. position returned
  13421. If your function needs to retrieve the tags including inherited tags
  13422. at the *current* entry, you can use the value of the variable
  13423. `org-scanner-tags' which will be much faster than getting the value
  13424. with `org-get-tags-at'. If your function gets properties with
  13425. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13426. to t around the call to `org-entry-properties' to get the same speedup.
  13427. Note that if your function moves around to retrieve tags and properties at
  13428. a *different* entry, you cannot use these techniques."
  13429. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13430. (not (org-region-active-p)))
  13431. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13432. (org-agenda-skip-archived-trees (memq 'archive skip))
  13433. (org-agenda-skip-comment-trees (memq 'comment skip))
  13434. (org-agenda-skip-function
  13435. (car (org-delete-all '(comment archive) skip)))
  13436. (org-tags-match-list-sublevels t)
  13437. (start-level (eq scope 'region-start-level))
  13438. matcher res
  13439. org-todo-keywords-for-agenda
  13440. org-done-keywords-for-agenda
  13441. org-todo-keyword-alist-for-agenda
  13442. org-tag-alist-for-agenda
  13443. org--matcher-tags-todo-only)
  13444. (cond
  13445. ((eq match t) (setq matcher t))
  13446. ((eq match nil) (setq matcher t))
  13447. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13448. (save-excursion
  13449. (save-restriction
  13450. (cond ((eq scope 'tree)
  13451. (org-back-to-heading t)
  13452. (org-narrow-to-subtree)
  13453. (setq scope nil))
  13454. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13455. (org-region-active-p))
  13456. ;; If needed, set start-level to a string like "2"
  13457. (when start-level
  13458. (save-excursion
  13459. (goto-char (region-beginning))
  13460. (unless (org-at-heading-p) (outline-next-heading))
  13461. (setq start-level (org-current-level))))
  13462. (narrow-to-region (region-beginning)
  13463. (save-excursion
  13464. (goto-char (region-end))
  13465. (unless (and (bolp) (org-at-heading-p))
  13466. (outline-next-heading))
  13467. (point)))
  13468. (setq scope nil)))
  13469. (if (not scope)
  13470. (progn
  13471. (org-agenda-prepare-buffers
  13472. (and buffer-file-name (list buffer-file-name)))
  13473. (setq res
  13474. (org-scan-tags
  13475. func matcher org--matcher-tags-todo-only start-level)))
  13476. ;; Get the right scope
  13477. (cond
  13478. ((and scope (listp scope) (symbolp (car scope)))
  13479. (setq scope (eval scope)))
  13480. ((eq scope 'agenda)
  13481. (setq scope (org-agenda-files t)))
  13482. ((eq scope 'agenda-with-archives)
  13483. (setq scope (org-agenda-files t))
  13484. (setq scope (org-add-archive-files scope)))
  13485. ((eq scope 'file)
  13486. (setq scope (and buffer-file-name (list buffer-file-name))))
  13487. ((eq scope 'file-with-archives)
  13488. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13489. (org-agenda-prepare-buffers scope)
  13490. (dolist (file scope)
  13491. (with-current-buffer (org-find-base-buffer-visiting file)
  13492. (org-with-wide-buffer
  13493. (goto-char (point-min))
  13494. (setq res
  13495. (append
  13496. res
  13497. (org-scan-tags
  13498. func matcher org--matcher-tags-todo-only)))))))))
  13499. res)))
  13500. ;;; Properties API
  13501. (defconst org-special-properties
  13502. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13503. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13504. "The special properties valid in Org mode.
  13505. These are properties that are not defined in the property drawer,
  13506. but in some other way.")
  13507. (defconst org-default-properties
  13508. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13509. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13510. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13511. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13512. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13513. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13514. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13515. "Some properties that are used by Org mode for various purposes.
  13516. Being in this list makes sure that they are offered for completion.")
  13517. (defun org--valid-property-p (property)
  13518. "Non nil when string PROPERTY is a valid property name."
  13519. (not
  13520. (or (equal property "")
  13521. (string-match-p "\\s-" property))))
  13522. (defun org--update-property-plist (key val props)
  13523. "Associate KEY to VAL in alist PROPS.
  13524. Modifications are made by side-effect. Return new alist."
  13525. (let* ((appending (string= (substring key -1) "+"))
  13526. (key (if appending (substring key 0 -1) key))
  13527. (old (assoc-string key props t)))
  13528. (if (not old) (cons (cons key val) props)
  13529. (setcdr old (if appending (concat (cdr old) " " val) val))
  13530. props)))
  13531. (defun org-get-property-block (&optional beg force)
  13532. "Return the (beg . end) range of the body of the property drawer.
  13533. BEG is the beginning of the current subtree, or of the part
  13534. before the first headline. If it is not given, it will be found.
  13535. If the drawer does not exist, create it if FORCE is non-nil, or
  13536. return nil."
  13537. (org-with-wide-buffer
  13538. (when beg (goto-char beg))
  13539. (unless (org-before-first-heading-p)
  13540. (let ((beg (cond (beg)
  13541. ((or (not (featurep 'org-inlinetask))
  13542. (org-inlinetask-in-task-p))
  13543. (org-back-to-heading t))
  13544. (t (org-with-limited-levels (org-back-to-heading t))))))
  13545. (forward-line)
  13546. (when (looking-at-p org-planning-line-re) (forward-line))
  13547. (cond ((looking-at org-property-drawer-re)
  13548. (forward-line)
  13549. (cons (point) (progn (goto-char (match-end 0))
  13550. (line-beginning-position))))
  13551. (force
  13552. (goto-char beg)
  13553. (org-insert-property-drawer)
  13554. (let ((pos (save-excursion (search-forward ":END:")
  13555. (line-beginning-position))))
  13556. (cons pos pos))))))))
  13557. (defun org-at-property-p ()
  13558. "Non-nil when point is inside a property drawer.
  13559. See `org-property-re' for match data, if applicable."
  13560. (save-excursion
  13561. (beginning-of-line)
  13562. (and (looking-at org-property-re)
  13563. (let ((property-drawer (save-match-data (org-get-property-block))))
  13564. (and property-drawer
  13565. (>= (point) (car property-drawer))
  13566. (< (point) (cdr property-drawer)))))))
  13567. (defun org-property-action ()
  13568. "Do an action on properties."
  13569. (interactive)
  13570. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13571. (let ((c (read-char-exclusive)))
  13572. (cl-case c
  13573. (?s (call-interactively #'org-set-property))
  13574. (?d (call-interactively #'org-delete-property))
  13575. (?D (call-interactively #'org-delete-property-globally))
  13576. (?c (call-interactively #'org-compute-property-at-point))
  13577. (otherwise (user-error "No such property action %c" c)))))
  13578. (defun org-inc-effort ()
  13579. "Increment the value of the effort property in the current entry."
  13580. (interactive)
  13581. (org-set-effort t))
  13582. (defvar org-clock-effort) ; Defined in org-clock.el.
  13583. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13584. (defun org-set-effort (&optional increment value)
  13585. "Set the effort property of the current entry.
  13586. If INCREMENT is non-nil, set the property to the next allowed
  13587. value. Otherwise, if optional argument VALUE is provided, use
  13588. it. Eventually, prompt for the new value if none of the previous
  13589. variables is set."
  13590. (interactive "P")
  13591. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13592. (current (org-entry-get nil org-effort-property))
  13593. (value
  13594. (cond
  13595. (increment
  13596. (unless allowed (user-error "Allowed effort values are not set"))
  13597. (or (cl-caadr (member (list current) allowed))
  13598. (user-error "Unknown value %S among allowed values" current)))
  13599. (value
  13600. (if (stringp value) value
  13601. (error "Invalid effort value: %S" value)))
  13602. (t
  13603. (let ((must-match
  13604. (and allowed
  13605. (not (get-text-property 0 'org-unrestricted
  13606. (caar allowed))))))
  13607. (completing-read "Effort: " allowed nil must-match))))))
  13608. (unless (equal current value)
  13609. (org-entry-put nil org-effort-property value))
  13610. (org-refresh-property '((effort . identity)
  13611. (effort-minutes . org-duration-to-minutes))
  13612. value)
  13613. (when (equal (org-get-heading t t t t)
  13614. (bound-and-true-p org-clock-current-task))
  13615. (setq org-clock-effort (org-get-at-bol 'effort))
  13616. (org-clock-update-mode-line))
  13617. (message "%s is now %s" org-effort-property value)))
  13618. (defun org-entry-properties (&optional pom which)
  13619. "Get all properties of the current entry.
  13620. When POM is a buffer position, get all properties from the entry
  13621. there instead.
  13622. This includes the TODO keyword, the tags, time strings for
  13623. deadline, scheduled, and clocking, and any additional properties
  13624. defined in the entry.
  13625. If WHICH is nil or `all', get all properties. If WHICH is
  13626. `special' or `standard', only get that subclass. If WHICH is
  13627. a string, only get that property.
  13628. Return value is an alist. Keys are properties, as upcased
  13629. strings."
  13630. (org-with-point-at pom
  13631. (when (and (derived-mode-p 'org-mode)
  13632. (ignore-errors (org-back-to-heading t)))
  13633. (catch 'exit
  13634. (let* ((beg (point))
  13635. (specific (and (stringp which) (upcase which)))
  13636. (which (cond ((not specific) which)
  13637. ((member specific org-special-properties) 'special)
  13638. (t 'standard)))
  13639. props)
  13640. ;; Get the special properties, like TODO and TAGS.
  13641. (when (memq which '(nil all special))
  13642. (when (or (not specific) (string= specific "CLOCKSUM"))
  13643. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13644. (when clocksum
  13645. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13646. props)))
  13647. (when specific (throw 'exit props)))
  13648. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13649. (let ((clocksumt (get-text-property (point)
  13650. :org-clock-minutes-today)))
  13651. (when clocksumt
  13652. (push (cons "CLOCKSUM_T"
  13653. (org-duration-from-minutes clocksumt))
  13654. props)))
  13655. (when specific (throw 'exit props)))
  13656. (when (or (not specific) (string= specific "ITEM"))
  13657. (let ((case-fold-search nil))
  13658. (when (looking-at org-complex-heading-regexp)
  13659. (push (cons "ITEM"
  13660. (let ((title (match-string-no-properties 4)))
  13661. (if (org-string-nw-p title)
  13662. (org-remove-tabs title)
  13663. "")))
  13664. props)))
  13665. (when specific (throw 'exit props)))
  13666. (when (or (not specific) (string= specific "TODO"))
  13667. (let ((case-fold-search nil))
  13668. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13669. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13670. (when specific (throw 'exit props)))
  13671. (when (or (not specific) (string= specific "PRIORITY"))
  13672. (push (cons "PRIORITY"
  13673. (if (looking-at org-priority-regexp)
  13674. (match-string-no-properties 2)
  13675. (char-to-string org-default-priority)))
  13676. props)
  13677. (when specific (throw 'exit props)))
  13678. (when (or (not specific) (string= specific "FILE"))
  13679. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13680. props)
  13681. (when specific (throw 'exit props)))
  13682. (when (or (not specific) (string= specific "TAGS"))
  13683. (let ((value (org-string-nw-p (org-get-tags-string))))
  13684. (when value (push (cons "TAGS" value) props)))
  13685. (when specific (throw 'exit props)))
  13686. (when (or (not specific) (string= specific "ALLTAGS"))
  13687. (let ((value (org-get-tags-at)))
  13688. (when value
  13689. (push (cons "ALLTAGS"
  13690. (format ":%s:" (mapconcat #'identity value ":")))
  13691. props)))
  13692. (when specific (throw 'exit props)))
  13693. (when (or (not specific) (string= specific "BLOCKED"))
  13694. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13695. (when specific (throw 'exit props)))
  13696. (when (or (not specific)
  13697. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13698. (forward-line)
  13699. (when (looking-at-p org-planning-line-re)
  13700. (end-of-line)
  13701. (let ((bol (line-beginning-position))
  13702. ;; Backward compatibility: time keywords used to
  13703. ;; be configurable (before 8.3). Make sure we
  13704. ;; get the correct keyword.
  13705. (key-assoc `(("CLOSED" . ,org-closed-string)
  13706. ("DEADLINE" . ,org-deadline-string)
  13707. ("SCHEDULED" . ,org-scheduled-string))))
  13708. (dolist (pair (if specific (list (assoc specific key-assoc))
  13709. key-assoc))
  13710. (save-excursion
  13711. (when (search-backward (cdr pair) bol t)
  13712. (goto-char (match-end 0))
  13713. (skip-chars-forward " \t")
  13714. (and (looking-at org-ts-regexp-both)
  13715. (push (cons (car pair)
  13716. (match-string-no-properties 0))
  13717. props)))))))
  13718. (when specific (throw 'exit props)))
  13719. (when (or (not specific)
  13720. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13721. (let ((find-ts
  13722. (lambda (end ts)
  13723. ;; Fix next time-stamp before END. TS is the
  13724. ;; list of time-stamps found so far.
  13725. (let ((ts ts)
  13726. (regexp (cond
  13727. ((string= specific "TIMESTAMP")
  13728. org-ts-regexp)
  13729. ((string= specific "TIMESTAMP_IA")
  13730. org-ts-regexp-inactive)
  13731. ((assoc "TIMESTAMP_IA" ts)
  13732. org-ts-regexp)
  13733. ((assoc "TIMESTAMP" ts)
  13734. org-ts-regexp-inactive)
  13735. (t org-ts-regexp-both))))
  13736. (catch 'next
  13737. (while (re-search-forward regexp end t)
  13738. (backward-char)
  13739. (let ((object (org-element-context)))
  13740. ;; Accept to match timestamps in node
  13741. ;; properties, too.
  13742. (when (memq (org-element-type object)
  13743. '(node-property timestamp))
  13744. (let ((type
  13745. (org-element-property :type object)))
  13746. (cond
  13747. ((and (memq type '(active active-range))
  13748. (not (equal specific "TIMESTAMP_IA")))
  13749. (unless (assoc "TIMESTAMP" ts)
  13750. (push (cons "TIMESTAMP"
  13751. (org-element-property
  13752. :raw-value object))
  13753. ts)
  13754. (when specific (throw 'exit ts))))
  13755. ((and (memq type '(inactive inactive-range))
  13756. (not (string= specific "TIMESTAMP")))
  13757. (unless (assoc "TIMESTAMP_IA" ts)
  13758. (push (cons "TIMESTAMP_IA"
  13759. (org-element-property
  13760. :raw-value object))
  13761. ts)
  13762. (when specific (throw 'exit ts))))))
  13763. ;; Both timestamp types are found,
  13764. ;; move to next part.
  13765. (when (= (length ts) 2) (throw 'next ts)))))
  13766. ts)))))
  13767. (goto-char beg)
  13768. ;; First look for timestamps within headline.
  13769. (let ((ts (funcall find-ts (line-end-position) nil)))
  13770. (if (= (length ts) 2) (setq props (nconc ts props))
  13771. ;; Then find timestamps in the section, skipping
  13772. ;; planning line.
  13773. (let ((end (save-excursion (outline-next-heading))))
  13774. (forward-line)
  13775. (when (looking-at-p org-planning-line-re) (forward-line))
  13776. (setq props (nconc (funcall find-ts end ts) props))))))))
  13777. ;; Get the standard properties, like :PROP:.
  13778. (when (memq which '(nil all standard))
  13779. ;; If we are looking after a specific property, delegate
  13780. ;; to `org-entry-get', which is faster. However, make an
  13781. ;; exception for "CATEGORY", since it can be also set
  13782. ;; through keywords (i.e. #+CATEGORY).
  13783. (if (and specific (not (equal specific "CATEGORY")))
  13784. (let ((value (org-entry-get beg specific nil t)))
  13785. (throw 'exit (and value (list (cons specific value)))))
  13786. (let ((range (org-get-property-block beg)))
  13787. (when range
  13788. (let ((end (cdr range)) seen-base)
  13789. (goto-char (car range))
  13790. ;; Unlike to `org--update-property-plist', we
  13791. ;; handle the case where base values is found
  13792. ;; after its extension. We also forbid standard
  13793. ;; properties to be named as special properties.
  13794. (while (re-search-forward org-property-re end t)
  13795. (let* ((key (upcase (match-string-no-properties 2)))
  13796. (extendp (string-match-p "\\+\\'" key))
  13797. (key-base (if extendp (substring key 0 -1) key))
  13798. (value (match-string-no-properties 3)))
  13799. (cond
  13800. ((member-ignore-case key-base org-special-properties))
  13801. (extendp
  13802. (setq props
  13803. (org--update-property-plist key value props)))
  13804. ((member key seen-base))
  13805. (t (push key seen-base)
  13806. (let ((p (assoc-string key props t)))
  13807. (if p (setcdr p (concat value " " (cdr p)))
  13808. (push (cons key value) props))))))))))))
  13809. (unless (assoc "CATEGORY" props)
  13810. (push (cons "CATEGORY" (org-get-category beg)) props)
  13811. (when (string= specific "CATEGORY") (throw 'exit props)))
  13812. ;; Return value.
  13813. props)))))
  13814. (defun org--property-local-values (property literal-nil)
  13815. "Return value for PROPERTY in current entry.
  13816. Value is a list whose car is the base value for PROPERTY and cdr
  13817. a list of accumulated values. Return nil if neither is found in
  13818. the entry. Also return nil when PROPERTY is set to \"nil\",
  13819. unless LITERAL-NIL is non-nil."
  13820. (let ((range (org-get-property-block)))
  13821. (when range
  13822. (goto-char (car range))
  13823. (let* ((case-fold-search t)
  13824. (end (cdr range))
  13825. (value
  13826. ;; Base value.
  13827. (save-excursion
  13828. (let ((v (and (re-search-forward
  13829. (org-re-property property nil t) end t)
  13830. (match-string-no-properties 3))))
  13831. (list (if literal-nil v (org-not-nil v)))))))
  13832. ;; Find additional values.
  13833. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13834. (while (re-search-forward property+ end t)
  13835. (push (match-string-no-properties 3) value)))
  13836. ;; Return final values.
  13837. (and (not (equal value '(nil))) (nreverse value))))))
  13838. (defun org--property-global-value (property literal-nil)
  13839. "Return value for PROPERTY in current buffer.
  13840. Return value is a string. Return nil if property is not set
  13841. globally. Also return nil when PROPERTY is set to \"nil\",
  13842. unless LITERAL-NIL is non-nil."
  13843. (let ((global
  13844. (cdr (or (assoc-string property org-file-properties t)
  13845. (assoc-string property org-global-properties t)
  13846. (assoc-string property org-global-properties-fixed t)))))
  13847. (if literal-nil global (org-not-nil global))))
  13848. (defun org-entry-get (pom property &optional inherit literal-nil)
  13849. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13850. If INHERIT is non-nil and the entry does not have the property,
  13851. then also check higher levels of the hierarchy. If INHERIT is
  13852. the symbol `selective', use inheritance only if the setting in
  13853. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13854. If the property is present but empty, the return value is the
  13855. empty string. If the property is not present at all, nil is
  13856. returned. In any other case, return the value as a string.
  13857. Search is case-insensitive.
  13858. If LITERAL-NIL is set, return the string value \"nil\" as
  13859. a string, do not interpret it as the list atom nil. This is used
  13860. for inheritance when a \"nil\" value can supersede a non-nil
  13861. value higher up the hierarchy."
  13862. (org-with-point-at pom
  13863. (cond
  13864. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13865. ;; We need a special property. Use `org-entry-properties' to
  13866. ;; retrieve it, but specify the wanted property.
  13867. (cdr (assoc-string property (org-entry-properties nil property))))
  13868. ((and inherit
  13869. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13870. (org-entry-get-with-inheritance property literal-nil))
  13871. (t
  13872. (let* ((local (org--property-local-values property literal-nil))
  13873. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13874. (if literal-nil value (org-not-nil value)))))))
  13875. (defun org-property-or-variable-value (var &optional inherit)
  13876. "Check if there is a property fixing the value of VAR.
  13877. If yes, return this value. If not, return the current value of the variable."
  13878. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13879. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13880. (read prop)
  13881. (symbol-value var))))
  13882. (defun org-entry-delete (pom property)
  13883. "Delete PROPERTY from entry at point-or-marker POM.
  13884. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13885. non-nil when a property was removed."
  13886. (org-with-point-at pom
  13887. (pcase (org-get-property-block)
  13888. (`(,begin . ,origin)
  13889. (let* ((end (copy-marker origin))
  13890. (re (org-re-property
  13891. (concat (regexp-quote property) "\\+?") t t)))
  13892. (goto-char begin)
  13893. (while (re-search-forward re end t)
  13894. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13895. ;; If drawer is empty, remove it altogether.
  13896. (when (= begin end)
  13897. (delete-region (line-beginning-position 0)
  13898. (line-beginning-position 2)))
  13899. ;; Return non-nil if some property was removed.
  13900. (prog1 (/= end origin) (set-marker end nil))))
  13901. (_ nil))))
  13902. ;; Multi-values properties are properties that contain multiple values
  13903. ;; These values are assumed to be single words, separated by whitespace.
  13904. (defun org-entry-add-to-multivalued-property (pom property value)
  13905. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13906. (let* ((old (org-entry-get pom property))
  13907. (values (and old (split-string old))))
  13908. (setq value (org-entry-protect-space value))
  13909. (unless (member value values)
  13910. (setq values (append values (list value)))
  13911. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13912. (defun org-entry-remove-from-multivalued-property (pom property value)
  13913. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13914. (let* ((old (org-entry-get pom property))
  13915. (values (and old (split-string old))))
  13916. (setq value (org-entry-protect-space value))
  13917. (when (member value values)
  13918. (setq values (delete value values))
  13919. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13920. (defun org-entry-member-in-multivalued-property (pom property value)
  13921. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13922. (let* ((old (org-entry-get pom property))
  13923. (values (and old (split-string old))))
  13924. (setq value (org-entry-protect-space value))
  13925. (member value values)))
  13926. (defun org-entry-get-multivalued-property (pom property)
  13927. "Return a list of values in a multivalued property."
  13928. (let* ((value (org-entry-get pom property))
  13929. (values (and value (split-string value))))
  13930. (mapcar #'org-entry-restore-space values)))
  13931. (defun org-entry-put-multivalued-property (pom property &rest values)
  13932. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13933. VALUES should be a list of strings. Spaces will be protected."
  13934. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13935. (let* ((value (org-entry-get pom property))
  13936. (values (and value (split-string value))))
  13937. (mapcar #'org-entry-restore-space values)))
  13938. (defun org-entry-protect-space (s)
  13939. "Protect spaces and newline in string S."
  13940. (while (string-match " " s)
  13941. (setq s (replace-match "%20" t t s)))
  13942. (while (string-match "\n" s)
  13943. (setq s (replace-match "%0A" t t s)))
  13944. s)
  13945. (defun org-entry-restore-space (s)
  13946. "Restore spaces and newline in string S."
  13947. (while (string-match "%20" s)
  13948. (setq s (replace-match " " t t s)))
  13949. (while (string-match "%0A" s)
  13950. (setq s (replace-match "\n" t t s)))
  13951. s)
  13952. (defvar org-entry-property-inherited-from (make-marker)
  13953. "Marker pointing to the entry from where a property was inherited.
  13954. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13955. location of the entry where the inheritance search matched. If there was
  13956. no match, the marker will point nowhere.
  13957. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13958. is set.")
  13959. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13960. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13961. The search will stop at the first ancestor which has the property defined.
  13962. If the value found is \"nil\", return nil to show that the property
  13963. should be considered as undefined (this is the meaning of nil here).
  13964. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13965. (move-marker org-entry-property-inherited-from nil)
  13966. (org-with-wide-buffer
  13967. (let (value)
  13968. (catch 'exit
  13969. (while t
  13970. (let ((v (org--property-local-values property literal-nil)))
  13971. (when v
  13972. (setq value
  13973. (concat (mapconcat #'identity (delq nil v) " ")
  13974. (and value " ")
  13975. value)))
  13976. (cond
  13977. ((car v)
  13978. (org-back-to-heading t)
  13979. (move-marker org-entry-property-inherited-from (point))
  13980. (throw 'exit nil))
  13981. ((org-up-heading-safe))
  13982. (t
  13983. (let ((global (org--property-global-value property literal-nil)))
  13984. (cond ((not global))
  13985. (value (setq value (concat global " " value)))
  13986. (t (setq value global))))
  13987. (throw 'exit nil))))))
  13988. (if literal-nil value (org-not-nil value)))))
  13989. (defvar org-property-changed-functions nil
  13990. "Hook called when the value of a property has changed.
  13991. Each hook function should accept two arguments, the name of the property
  13992. and the new value.")
  13993. (defun org-entry-put (pom property value)
  13994. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13995. If the value is nil, it is converted to the empty string. If it
  13996. is not a string, an error is raised. Also raise an error on
  13997. invalid property names.
  13998. PROPERTY can be any regular property (see
  13999. `org-special-properties'). It can also be \"TODO\",
  14000. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14001. For the last two properties, VALUE may have any of the special
  14002. values \"earlier\" and \"later\". The function then increases or
  14003. decreases scheduled or deadline date by one day."
  14004. (cond ((null value) (setq value ""))
  14005. ((not (stringp value)) (error "Properties values should be strings"))
  14006. ((not (org--valid-property-p property))
  14007. (user-error "Invalid property name: \"%s\"" property)))
  14008. (org-with-point-at pom
  14009. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14010. (org-back-to-heading t)
  14011. (org-with-limited-levels (org-back-to-heading t)))
  14012. (let ((beg (point)))
  14013. (cond
  14014. ((equal property "TODO")
  14015. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14016. ((not (member value org-todo-keywords-1))
  14017. (user-error "\"%s\" is not a valid TODO state" value)))
  14018. (org-todo value)
  14019. (org-set-tags nil 'align))
  14020. ((equal property "PRIORITY")
  14021. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14022. (org-set-tags nil 'align))
  14023. ((equal property "SCHEDULED")
  14024. (forward-line)
  14025. (if (and (looking-at-p org-planning-line-re)
  14026. (re-search-forward
  14027. org-scheduled-time-regexp (line-end-position) t))
  14028. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14029. ((string= value "later") (org-timestamp-change 1 'day))
  14030. ((string= value "") (org-schedule '(4)))
  14031. (t (org-schedule nil value)))
  14032. (if (member value '("earlier" "later" ""))
  14033. (call-interactively #'org-schedule)
  14034. (org-schedule nil value))))
  14035. ((equal property "DEADLINE")
  14036. (forward-line)
  14037. (if (and (looking-at-p org-planning-line-re)
  14038. (re-search-forward
  14039. org-deadline-time-regexp (line-end-position) t))
  14040. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14041. ((string= value "later") (org-timestamp-change 1 'day))
  14042. ((string= value "") (org-deadline '(4)))
  14043. (t (org-deadline nil value)))
  14044. (if (member value '("earlier" "later" ""))
  14045. (call-interactively #'org-deadline)
  14046. (org-deadline nil value))))
  14047. ((member property org-special-properties)
  14048. (error "The %s property cannot be set with `org-entry-put'" property))
  14049. (t
  14050. (let* ((range (org-get-property-block beg 'force))
  14051. (end (cdr range))
  14052. (case-fold-search t))
  14053. (goto-char (car range))
  14054. (if (re-search-forward (org-re-property property nil t) end t)
  14055. (progn (delete-region (match-beginning 0) (match-end 0))
  14056. (goto-char (match-beginning 0)))
  14057. (goto-char end)
  14058. (insert "\n")
  14059. (backward-char))
  14060. (insert ":" property ":")
  14061. (when value (insert " " value))
  14062. (org-indent-line)))))
  14063. (run-hook-with-args 'org-property-changed-functions property value)))
  14064. (defun org-buffer-property-keys (&optional specials defaults columns)
  14065. "Get all property keys in the current buffer.
  14066. When SPECIALS is non-nil, also list the special properties that
  14067. reflect things like tags and TODO state.
  14068. When DEFAULTS is non-nil, also include properties that has
  14069. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14070. DESCRIPTION, LOCATION, and LOGGING and others.
  14071. When COLUMNS in non-nil, also include property names given in
  14072. COLUMN formats in the current buffer."
  14073. (let ((case-fold-search t)
  14074. (props (append
  14075. (and specials org-special-properties)
  14076. (and defaults (cons org-effort-property org-default-properties))
  14077. nil)))
  14078. (org-with-wide-buffer
  14079. (goto-char (point-min))
  14080. (while (re-search-forward org-property-start-re nil t)
  14081. (catch :skip
  14082. (let ((range (org-get-property-block)))
  14083. (unless range (throw :skip nil))
  14084. (goto-char (car range))
  14085. (let ((begin (car range))
  14086. (end (cdr range)))
  14087. ;; Make sure that found property block is not located
  14088. ;; before current point, as it would generate an infloop.
  14089. ;; It can happen, for example, in the following
  14090. ;; situation:
  14091. ;;
  14092. ;; * Headline
  14093. ;; :PROPERTIES:
  14094. ;; ...
  14095. ;; :END:
  14096. ;; *************** Inlinetask
  14097. ;; #+BEGIN_EXAMPLE
  14098. ;; :PROPERTIES:
  14099. ;; #+END_EXAMPLE
  14100. ;;
  14101. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14102. (while (< (point) end)
  14103. (let ((p (progn (looking-at org-property-re)
  14104. (match-string-no-properties 2))))
  14105. ;; Only add true property name, not extension symbol.
  14106. (push (if (not (string-match-p "\\+\\'" p)) p
  14107. (substring p 0 -1))
  14108. props))
  14109. (forward-line))))
  14110. (outline-next-heading)))
  14111. (when columns
  14112. (goto-char (point-min))
  14113. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14114. (let ((element (org-element-at-point)))
  14115. (when (memq (org-element-type element) '(keyword node-property))
  14116. (let ((value (org-element-property :value element))
  14117. (start 0))
  14118. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14119. \\(?:{[^}]+}\\)?"
  14120. value start)
  14121. (setq start (match-end 0))
  14122. (let ((p (match-string-no-properties 1 value)))
  14123. (unless (member-ignore-case p org-special-properties)
  14124. (push p props))))))))))
  14125. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14126. (defun org-property-values (key)
  14127. "List all non-nil values of property KEY in current buffer."
  14128. (org-with-wide-buffer
  14129. (goto-char (point-min))
  14130. (let ((case-fold-search t)
  14131. (re (org-re-property key))
  14132. values)
  14133. (while (re-search-forward re nil t)
  14134. (push (org-entry-get (point) key) values))
  14135. (delete-dups values))))
  14136. (defun org-insert-property-drawer ()
  14137. "Insert a property drawer into the current entry."
  14138. (org-with-wide-buffer
  14139. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14140. (org-back-to-heading t)
  14141. (org-with-limited-levels (org-back-to-heading t)))
  14142. (forward-line)
  14143. (when (looking-at-p org-planning-line-re) (forward-line))
  14144. (unless (looking-at-p org-property-drawer-re)
  14145. ;; Make sure we start editing a line from current entry, not from
  14146. ;; next one. It prevents extending text properties or overlays
  14147. ;; belonging to the latter.
  14148. (when (bolp) (backward-char))
  14149. (let ((begin (1+ (point)))
  14150. (inhibit-read-only t))
  14151. (insert "\n:PROPERTIES:\n:END:")
  14152. (when (eobp) (insert "\n"))
  14153. (org-indent-region begin (point))))))
  14154. (defun org-insert-drawer (&optional arg drawer)
  14155. "Insert a drawer at point.
  14156. When optional argument ARG is non-nil, insert a property drawer.
  14157. Optional argument DRAWER, when non-nil, is a string representing
  14158. drawer's name. Otherwise, the user is prompted for a name.
  14159. If a region is active, insert the drawer around that region
  14160. instead.
  14161. Point is left between drawer's boundaries."
  14162. (interactive "P")
  14163. (let* ((drawer (if arg "PROPERTIES"
  14164. (or drawer (read-from-minibuffer "Drawer: ")))))
  14165. (cond
  14166. ;; With C-u, fall back on `org-insert-property-drawer'
  14167. (arg (org-insert-property-drawer))
  14168. ;; Check validity of suggested drawer's name.
  14169. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14170. (user-error "Invalid drawer name"))
  14171. ;; With an active region, insert a drawer at point.
  14172. ((not (org-region-active-p))
  14173. (progn
  14174. (unless (bolp) (insert "\n"))
  14175. (insert (format ":%s:\n\n:END:\n" drawer))
  14176. (forward-line -2)))
  14177. ;; Otherwise, insert the drawer at point
  14178. (t
  14179. (let ((rbeg (region-beginning))
  14180. (rend (copy-marker (region-end))))
  14181. (unwind-protect
  14182. (progn
  14183. (goto-char rbeg)
  14184. (beginning-of-line)
  14185. (when (save-excursion
  14186. (re-search-forward org-outline-regexp-bol rend t))
  14187. (user-error "Drawers cannot contain headlines"))
  14188. ;; Position point at the beginning of the first
  14189. ;; non-blank line in region. Insert drawer's opening
  14190. ;; there, then indent it.
  14191. (org-skip-whitespace)
  14192. (beginning-of-line)
  14193. (insert ":" drawer ":\n")
  14194. (forward-line -1)
  14195. (indent-for-tab-command)
  14196. ;; Move point to the beginning of the first blank line
  14197. ;; after the last non-blank line in region. Insert
  14198. ;; drawer's closing, then indent it.
  14199. (goto-char rend)
  14200. (skip-chars-backward " \r\t\n")
  14201. (insert "\n:END:")
  14202. (deactivate-mark t)
  14203. (indent-for-tab-command)
  14204. (unless (eolp) (insert "\n")))
  14205. ;; Clear marker, whatever the outcome of insertion is.
  14206. (set-marker rend nil)))))))
  14207. (defvar org-property-set-functions-alist nil
  14208. "Property set function alist.
  14209. Each entry should have the following format:
  14210. (PROPERTY . READ-FUNCTION)
  14211. The read function will be called with the same argument as
  14212. `org-completing-read'.")
  14213. (defun org-set-property-function (property)
  14214. "Get the function that should be used to set PROPERTY.
  14215. This is computed according to `org-property-set-functions-alist'."
  14216. (or (cdr (assoc property org-property-set-functions-alist))
  14217. 'org-completing-read))
  14218. (defun org-read-property-value (property)
  14219. "Read PROPERTY value from user."
  14220. (let* ((completion-ignore-case t)
  14221. (allowed (org-property-get-allowed-values nil property 'table))
  14222. (cur (org-entry-get nil property))
  14223. (prompt (concat property " value"
  14224. (if (and cur (string-match "\\S-" cur))
  14225. (concat " [" cur "]") "") ": "))
  14226. (set-function (org-set-property-function property))
  14227. (val (if allowed
  14228. (funcall set-function prompt allowed nil
  14229. (not (get-text-property 0 'org-unrestricted
  14230. (caar allowed))))
  14231. (funcall set-function prompt
  14232. (mapcar 'list (org-property-values property))
  14233. nil nil "" nil cur))))
  14234. (org-trim val)))
  14235. (defvar org-last-set-property nil)
  14236. (defvar org-last-set-property-value nil)
  14237. (defun org-read-property-name ()
  14238. "Read a property name."
  14239. (let ((completion-ignore-case t)
  14240. (default-prop (or (and (org-at-property-p)
  14241. (match-string-no-properties 2))
  14242. org-last-set-property)))
  14243. (org-completing-read
  14244. (concat "Property"
  14245. (if default-prop (concat " [" default-prop "]") "")
  14246. ": ")
  14247. (mapcar #'list (org-buffer-property-keys nil t t))
  14248. nil nil nil nil default-prop)))
  14249. (defun org-set-property-and-value (use-last)
  14250. "Allow to set [PROPERTY]: [value] direction from prompt.
  14251. When use-default, don't even ask, just use the last
  14252. \"[PROPERTY]: [value]\" string from the history."
  14253. (interactive "P")
  14254. (let* ((completion-ignore-case t)
  14255. (pv (or (and use-last org-last-set-property-value)
  14256. (org-completing-read
  14257. "Enter a \"[Property]: [value]\" pair: "
  14258. nil nil nil nil nil
  14259. org-last-set-property-value)))
  14260. prop val)
  14261. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14262. (setq prop (match-string 1 pv)
  14263. val (match-string 2 pv))
  14264. (org-set-property prop val))))
  14265. (defun org-set-property (property value)
  14266. "In the current entry, set PROPERTY to VALUE.
  14267. When called interactively, this will prompt for a property name, offering
  14268. completion on existing and default properties. And then it will prompt
  14269. for a value, offering completion either on allowed values (via an inherited
  14270. xxx_ALL property) or on existing values in other instances of this property
  14271. in the current file.
  14272. Throw an error when trying to set a property with an invalid name."
  14273. (interactive (list nil nil))
  14274. (let ((property (or property (org-read-property-name))))
  14275. ;; `org-entry-put' also makes the following check, but this one
  14276. ;; avoids polluting `org-last-set-property' and
  14277. ;; `org-last-set-property-value' needlessly.
  14278. (unless (org--valid-property-p property)
  14279. (user-error "Invalid property name: \"%s\"" property))
  14280. (let ((value (or value (org-read-property-value property)))
  14281. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14282. (setq org-last-set-property property)
  14283. (setq org-last-set-property-value (concat property ": " value))
  14284. ;; Possibly postprocess the inserted value:
  14285. (when fn (setq value (funcall fn value)))
  14286. (unless (equal (org-entry-get nil property) value)
  14287. (org-entry-put nil property value)))))
  14288. (defun org-find-property (property &optional value)
  14289. "Find first entry in buffer that sets PROPERTY.
  14290. When optional argument VALUE is non-nil, only consider an entry
  14291. if it contains PROPERTY set to this value. If PROPERTY should be
  14292. explicitly set to nil, use string \"nil\" for VALUE.
  14293. Return position where the entry begins, or nil if there is no
  14294. such entry. If narrowing is in effect, only search the visible
  14295. part of the buffer."
  14296. (save-excursion
  14297. (goto-char (point-min))
  14298. (let ((case-fold-search t)
  14299. (re (org-re-property property nil (not value) value)))
  14300. (catch 'exit
  14301. (while (re-search-forward re nil t)
  14302. (when (if value (org-at-property-p)
  14303. (org-entry-get (point) property nil t))
  14304. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14305. (defun org-delete-property (property)
  14306. "In the current entry, delete PROPERTY."
  14307. (interactive
  14308. (let* ((completion-ignore-case t)
  14309. (cat (org-entry-get (point) "CATEGORY"))
  14310. (props0 (org-entry-properties nil 'standard))
  14311. (props (if cat props0
  14312. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14313. (prop (if (< 1 (length props))
  14314. (completing-read "Property: " props nil t)
  14315. (caar props))))
  14316. (list prop)))
  14317. (if (not property)
  14318. (message "No property to delete in this entry")
  14319. (org-entry-delete nil property)
  14320. (message "Property \"%s\" deleted" property)))
  14321. (defun org-delete-property-globally (property)
  14322. "Remove PROPERTY globally, from all entries.
  14323. This function ignores narrowing, if any."
  14324. (interactive
  14325. (let* ((completion-ignore-case t)
  14326. (prop (completing-read
  14327. "Globally remove property: "
  14328. (mapcar #'list (org-buffer-property-keys)))))
  14329. (list prop)))
  14330. (org-with-wide-buffer
  14331. (goto-char (point-min))
  14332. (let ((count 0)
  14333. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14334. (while (re-search-forward re nil t)
  14335. (when (org-entry-delete (point) property) (cl-incf count)))
  14336. (message "Property \"%s\" removed from %d entries" property count))))
  14337. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14338. (defun org-compute-property-at-point ()
  14339. "Compute the property at point.
  14340. This looks for an enclosing column format, extracts the operator and
  14341. then applies it to the property in the column format's scope."
  14342. (interactive)
  14343. (unless (org-at-property-p)
  14344. (user-error "Not at a property"))
  14345. (let ((prop (match-string-no-properties 2)))
  14346. (org-columns-get-format-and-top-level)
  14347. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14348. (user-error "No operator defined for property %s" prop))
  14349. (org-columns-compute prop)))
  14350. (defvar org-property-allowed-value-functions nil
  14351. "Hook for functions supplying allowed values for a specific property.
  14352. The functions must take a single argument, the name of the property, and
  14353. return a flat list of allowed values. If \":ETC\" is one of
  14354. the values, this means that these values are intended as defaults for
  14355. completion, but that other values should be allowed too.
  14356. The functions must return nil if they are not responsible for this
  14357. property.")
  14358. (defun org-property-get-allowed-values (pom property &optional table)
  14359. "Get allowed values for the property PROPERTY.
  14360. When TABLE is non-nil, return an alist that can directly be used for
  14361. completion."
  14362. (let (vals)
  14363. (cond
  14364. ((equal property "TODO")
  14365. (setq vals (org-with-point-at pom
  14366. (append org-todo-keywords-1 '("")))))
  14367. ((equal property "PRIORITY")
  14368. (let ((n org-lowest-priority))
  14369. (while (>= n org-highest-priority)
  14370. (push (char-to-string n) vals)
  14371. (setq n (1- n)))))
  14372. ((equal property "CATEGORY"))
  14373. ((member property org-special-properties))
  14374. ((setq vals (run-hook-with-args-until-success
  14375. 'org-property-allowed-value-functions property)))
  14376. (t
  14377. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14378. (when (and vals (string-match "\\S-" vals))
  14379. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14380. (setq vals (mapcar (lambda (x)
  14381. (cond ((stringp x) x)
  14382. ((numberp x) (number-to-string x))
  14383. ((symbolp x) (symbol-name x))
  14384. (t "???")))
  14385. vals)))))
  14386. (when (member ":ETC" vals)
  14387. (setq vals (remove ":ETC" vals))
  14388. (org-add-props (car vals) '(org-unrestricted t)))
  14389. (if table (mapcar 'list vals) vals)))
  14390. (defun org-property-previous-allowed-value (&optional _previous)
  14391. "Switch to the next allowed value for this property."
  14392. (interactive)
  14393. (org-property-next-allowed-value t))
  14394. (defun org-property-next-allowed-value (&optional previous)
  14395. "Switch to the next allowed value for this property."
  14396. (interactive)
  14397. (unless (org-at-property-p)
  14398. (user-error "Not at a property"))
  14399. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14400. (key (match-string 2))
  14401. (value (match-string 3))
  14402. (allowed (or (org-property-get-allowed-values (point) key)
  14403. (and (member value '("[ ]" "[-]" "[X]"))
  14404. '("[ ]" "[X]"))))
  14405. (heading (save-match-data (nth 4 (org-heading-components))))
  14406. nval)
  14407. (unless allowed
  14408. (user-error "Allowed values for this property have not been defined"))
  14409. (when previous (setq allowed (reverse allowed)))
  14410. (when (member value allowed)
  14411. (setq nval (car (cdr (member value allowed)))))
  14412. (setq nval (or nval (car allowed)))
  14413. (when (equal nval value)
  14414. (user-error "Only one allowed value for this property"))
  14415. (org-at-property-p)
  14416. (replace-match (concat " :" key ": " nval) t t)
  14417. (org-indent-line)
  14418. (beginning-of-line 1)
  14419. (skip-chars-forward " \t")
  14420. (when (equal prop org-effort-property)
  14421. (org-refresh-property
  14422. '((effort . identity)
  14423. (effort-minutes . org-duration-to-minutes))
  14424. nval)
  14425. (when (string= org-clock-current-task heading)
  14426. (setq org-clock-effort nval)
  14427. (org-clock-update-mode-line)))
  14428. (run-hook-with-args 'org-property-changed-functions key nval)))
  14429. (defun org-find-olp (path &optional this-buffer)
  14430. "Return a marker pointing to the entry at outline path OLP.
  14431. If anything goes wrong, throw an error.
  14432. You can wrap this call to catch the error like this:
  14433. (condition-case msg
  14434. (org-mobile-locate-entry (match-string 4))
  14435. (error (nth 1 msg)))
  14436. The return value will then be either a string with the error message,
  14437. or a marker if everything is OK.
  14438. If THIS-BUFFER is set, the outline path does not contain a file,
  14439. only headings."
  14440. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14441. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14442. (level 1)
  14443. (lmin 1)
  14444. (lmax 1)
  14445. end found flevel)
  14446. (unless buffer (error "File not found :%s" file))
  14447. (with-current-buffer buffer
  14448. (unless (derived-mode-p 'org-mode)
  14449. (error "Buffer %s needs to be in Org mode" buffer))
  14450. (org-with-wide-buffer
  14451. (goto-char (point-min))
  14452. (dolist (heading path)
  14453. (let ((re (format org-complex-heading-regexp-format
  14454. (regexp-quote heading)))
  14455. (cnt 0))
  14456. (while (re-search-forward re end t)
  14457. (setq level (- (match-end 1) (match-beginning 1)))
  14458. (when (and (>= level lmin) (<= level lmax))
  14459. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14460. (when (= cnt 0)
  14461. (error "Heading not found on level %d: %s" lmax heading))
  14462. (when (> cnt 1)
  14463. (error "Heading not unique on level %d: %s" lmax heading))
  14464. (goto-char found)
  14465. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14466. (setq end (save-excursion (org-end-of-subtree t t)))))
  14467. (when (org-at-heading-p)
  14468. (point-marker))))))
  14469. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14470. "Find node HEADING in BUFFER.
  14471. Return a marker to the heading if it was found, or nil if not.
  14472. If POS-ONLY is set, return just the position instead of a marker.
  14473. The heading text must match exact, but it may have a TODO keyword,
  14474. a priority cookie and tags in the standard locations."
  14475. (with-current-buffer (or buffer (current-buffer))
  14476. (org-with-wide-buffer
  14477. (goto-char (point-min))
  14478. (let (case-fold-search)
  14479. (when (re-search-forward
  14480. (format org-complex-heading-regexp-format
  14481. (regexp-quote heading)) nil t)
  14482. (if pos-only
  14483. (match-beginning 0)
  14484. (move-marker (make-marker) (match-beginning 0))))))))
  14485. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14486. "Find Org node headline HEADING in all .org files in directory DIR.
  14487. When the target headline is found, return a marker to this location."
  14488. (let ((files (directory-files (or dir default-directory)
  14489. t "\\`[^.#].*\\.org\\'"))
  14490. visiting m buffer)
  14491. (catch 'found
  14492. (dolist (file files)
  14493. (message "trying %s" file)
  14494. (setq visiting (org-find-base-buffer-visiting file))
  14495. (setq buffer (or visiting (find-file-noselect file)))
  14496. (setq m (org-find-exact-headline-in-buffer
  14497. heading buffer))
  14498. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14499. (and m (throw 'found m))))))
  14500. (defun org-find-entry-with-id (ident)
  14501. "Locate the entry that contains the ID property with exact value IDENT.
  14502. IDENT can be a string, a symbol or a number, this function will search for
  14503. the string representation of it.
  14504. Return the position where this entry starts, or nil if there is no such entry."
  14505. (interactive "sID: ")
  14506. (let ((id (cond
  14507. ((stringp ident) ident)
  14508. ((symbolp ident) (symbol-name ident))
  14509. ((numberp ident) (number-to-string ident))
  14510. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14511. (org-with-wide-buffer (org-find-property "ID" id))))
  14512. ;;;; Timestamps
  14513. (defvar org-last-changed-timestamp nil)
  14514. (defvar org-last-inserted-timestamp nil
  14515. "The last time stamp inserted with `org-insert-time-stamp'.")
  14516. (defun org-time-stamp (arg &optional inactive)
  14517. "Prompt for a date/time and insert a time stamp.
  14518. If the user specifies a time like HH:MM or if this command is
  14519. called with at least one prefix argument, the time stamp contains
  14520. the date and the time. Otherwise, only the date is included.
  14521. All parts of a date not specified by the user are filled in from
  14522. the timestamp at point, if any, or the current date/time
  14523. otherwise.
  14524. If there is already a timestamp at the cursor, it is replaced.
  14525. With two universal prefix arguments, insert an active timestamp
  14526. with the current time without prompting the user.
  14527. When called from lisp, the timestamp is inactive if INACTIVE is
  14528. non-nil."
  14529. (interactive "P")
  14530. (let* ((ts (cond
  14531. ((org-at-date-range-p t)
  14532. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14533. ((org-at-timestamp-p 'lax) (match-string 0))))
  14534. ;; Default time is either the timestamp at point or today.
  14535. ;; When entering a range, only the range start is considered.
  14536. (default-time (if (not ts) (current-time)
  14537. (apply #'encode-time (org-parse-time-string ts))))
  14538. (default-input (and ts (org-get-compact-tod ts)))
  14539. (repeater (and ts
  14540. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14541. (match-string 0 ts)))
  14542. org-time-was-given
  14543. org-end-time-was-given
  14544. (time
  14545. (and (if (equal arg '(16)) (current-time)
  14546. ;; Preserve `this-command' and `last-command'.
  14547. (let ((this-command this-command)
  14548. (last-command last-command))
  14549. (org-read-date
  14550. arg 'totime nil nil default-time default-input
  14551. inactive))))))
  14552. (cond
  14553. ((and ts
  14554. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14555. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14556. (insert "--")
  14557. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14558. (ts
  14559. ;; Make sure we're on a timestamp. When in the middle of a date
  14560. ;; range, move arbitrarily to range end.
  14561. (unless (org-at-timestamp-p 'lax)
  14562. (skip-chars-forward "-")
  14563. (org-at-timestamp-p 'lax))
  14564. (replace-match "")
  14565. (setq org-last-changed-timestamp
  14566. (org-insert-time-stamp
  14567. time (or org-time-was-given arg)
  14568. inactive nil nil (list org-end-time-was-given)))
  14569. (when repeater
  14570. (backward-char)
  14571. (insert " " repeater)
  14572. (setq org-last-changed-timestamp
  14573. (concat (substring org-last-inserted-timestamp 0 -1)
  14574. " " repeater ">")))
  14575. (message "Timestamp updated"))
  14576. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14577. (t (org-insert-time-stamp
  14578. time (or org-time-was-given arg) inactive nil nil
  14579. (list org-end-time-was-given))))))
  14580. ;; FIXME: can we use this for something else, like computing time differences?
  14581. (defun org-get-compact-tod (s)
  14582. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14583. (let* ((t1 (match-string 1 s))
  14584. (h1 (string-to-number (match-string 2 s)))
  14585. (m1 (string-to-number (match-string 3 s)))
  14586. (t2 (and (match-end 4) (match-string 5 s)))
  14587. (h2 (and t2 (string-to-number (match-string 6 s))))
  14588. (m2 (and t2 (string-to-number (match-string 7 s))))
  14589. dh dm)
  14590. (if (not t2)
  14591. t1
  14592. (setq dh (- h2 h1) dm (- m2 m1))
  14593. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14594. (concat t1 "+" (number-to-string dh)
  14595. (and (/= 0 dm) (format ":%02d" dm)))))))
  14596. (defun org-time-stamp-inactive (&optional arg)
  14597. "Insert an inactive time stamp.
  14598. An inactive time stamp is enclosed in square brackets instead of angle
  14599. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14600. does not link to the calendar and cannot be changed with the S-cursor keys.
  14601. So these are more for recording a certain time/date."
  14602. (interactive "P")
  14603. (org-time-stamp arg 'inactive))
  14604. (defvar org-date-ovl (make-overlay 1 1))
  14605. (overlay-put org-date-ovl 'face 'org-date-selected)
  14606. (delete-overlay org-date-ovl)
  14607. (defvar org-ans1) ; dynamically scoped parameter
  14608. (defvar org-ans2) ; dynamically scoped parameter
  14609. (defvar org-plain-time-of-day-regexp) ; defined below
  14610. (defvar org-overriding-default-time nil) ; dynamically scoped
  14611. (defvar org-read-date-overlay nil)
  14612. (defvar org-dcst nil) ; dynamically scoped
  14613. (defvar org-read-date-history nil)
  14614. (defvar org-read-date-final-answer nil)
  14615. (defvar org-read-date-analyze-futurep nil)
  14616. (defvar org-read-date-analyze-forced-year nil)
  14617. (defvar org-read-date-inactive)
  14618. (defvar org-read-date-minibuffer-local-map
  14619. (let* ((map (make-sparse-keymap)))
  14620. (set-keymap-parent map minibuffer-local-map)
  14621. (org-defkey map (kbd ".")
  14622. (lambda () (interactive)
  14623. ;; Are we at the beginning of the prompt?
  14624. (if (looking-back "^[^:]+: "
  14625. (let ((inhibit-field-text-motion t))
  14626. (line-beginning-position)))
  14627. (org-eval-in-calendar '(calendar-goto-today))
  14628. (insert "."))))
  14629. (org-defkey map (kbd "C-.")
  14630. (lambda () (interactive)
  14631. (org-eval-in-calendar '(calendar-goto-today))))
  14632. (org-defkey map [(meta shift left)]
  14633. (lambda () (interactive)
  14634. (org-eval-in-calendar '(calendar-backward-month 1))))
  14635. (org-defkey map [(meta shift right)]
  14636. (lambda () (interactive)
  14637. (org-eval-in-calendar '(calendar-forward-month 1))))
  14638. (org-defkey map [(meta shift up)]
  14639. (lambda () (interactive)
  14640. (org-eval-in-calendar '(calendar-backward-year 1))))
  14641. (org-defkey map [(meta shift down)]
  14642. (lambda () (interactive)
  14643. (org-eval-in-calendar '(calendar-forward-year 1))))
  14644. (org-defkey map [?\e (shift left)]
  14645. (lambda () (interactive)
  14646. (org-eval-in-calendar '(calendar-backward-month 1))))
  14647. (org-defkey map [?\e (shift right)]
  14648. (lambda () (interactive)
  14649. (org-eval-in-calendar '(calendar-forward-month 1))))
  14650. (org-defkey map [?\e (shift up)]
  14651. (lambda () (interactive)
  14652. (org-eval-in-calendar '(calendar-backward-year 1))))
  14653. (org-defkey map [?\e (shift down)]
  14654. (lambda () (interactive)
  14655. (org-eval-in-calendar '(calendar-forward-year 1))))
  14656. (org-defkey map [(shift up)]
  14657. (lambda () (interactive)
  14658. (org-eval-in-calendar '(calendar-backward-week 1))))
  14659. (org-defkey map [(shift down)]
  14660. (lambda () (interactive)
  14661. (org-eval-in-calendar '(calendar-forward-week 1))))
  14662. (org-defkey map [(shift left)]
  14663. (lambda () (interactive)
  14664. (org-eval-in-calendar '(calendar-backward-day 1))))
  14665. (org-defkey map [(shift right)]
  14666. (lambda () (interactive)
  14667. (org-eval-in-calendar '(calendar-forward-day 1))))
  14668. (org-defkey map "!"
  14669. (lambda () (interactive)
  14670. (org-eval-in-calendar '(diary-view-entries))
  14671. (message "")))
  14672. (org-defkey map ">"
  14673. (lambda () (interactive)
  14674. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14675. (org-defkey map "<"
  14676. (lambda () (interactive)
  14677. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14678. (org-defkey map "\C-v"
  14679. (lambda () (interactive)
  14680. (org-eval-in-calendar
  14681. '(calendar-scroll-left-three-months 1))))
  14682. (org-defkey map "\M-v"
  14683. (lambda () (interactive)
  14684. (org-eval-in-calendar
  14685. '(calendar-scroll-right-three-months 1))))
  14686. map)
  14687. "Keymap for minibuffer commands when using `org-read-date'.")
  14688. (defvar org-def)
  14689. (defvar org-defdecode)
  14690. (defvar org-with-time)
  14691. (defvar calendar-setup) ; Dynamically scoped.
  14692. (defun org-read-date (&optional with-time to-time from-string prompt
  14693. default-time default-input inactive)
  14694. "Read a date, possibly a time, and make things smooth for the user.
  14695. The prompt will suggest to enter an ISO date, but you can also enter anything
  14696. which will at least partially be understood by `parse-time-string'.
  14697. Unrecognized parts of the date will default to the current day, month, year,
  14698. hour and minute. If this command is called to replace a timestamp at point,
  14699. or to enter the second timestamp of a range, the default time is taken
  14700. from the existing stamp. Furthermore, the command prefers the future,
  14701. so if you are giving a date where the year is not given, and the day-month
  14702. combination is already past in the current year, it will assume you
  14703. mean next year. For details, see the manual. A few examples:
  14704. 3-2-5 --> 2003-02-05
  14705. feb 15 --> currentyear-02-15
  14706. 2/15 --> currentyear-02-15
  14707. sep 12 9 --> 2009-09-12
  14708. 12:45 --> today 12:45
  14709. 22 sept 0:34 --> currentyear-09-22 0:34
  14710. 12 --> currentyear-currentmonth-12
  14711. Fri --> nearest Friday after today
  14712. -Tue --> last Tuesday
  14713. etc.
  14714. Furthermore you can specify a relative date by giving, as the *first* thing
  14715. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14716. change in days weeks, months, years.
  14717. With a single plus or minus, the date is relative to today. With a double
  14718. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14719. +4d --> four days from today
  14720. +4 --> same as above
  14721. +2w --> two weeks from today
  14722. ++5 --> five days from default date
  14723. The function understands only English month and weekday abbreviations.
  14724. While prompting, a calendar is popped up - you can also select the
  14725. date with the mouse (button 1). The calendar shows a period of three
  14726. months. To scroll it to other months, use the keys `>' and `<'.
  14727. If you don't like the calendar, turn it off with
  14728. (setq org-read-date-popup-calendar nil)
  14729. With optional argument TO-TIME, the date will immediately be converted
  14730. to an internal time.
  14731. With an optional argument WITH-TIME, the prompt will suggest to
  14732. also insert a time. Note that when WITH-TIME is not set, you can
  14733. still enter a time, and this function will inform the calling routine
  14734. about this change. The calling routine may then choose to change the
  14735. format used to insert the time stamp into the buffer to include the time.
  14736. With optional argument FROM-STRING, read from this string instead from
  14737. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14738. the time/date that is used for everything that is not specified by the
  14739. user."
  14740. (require 'parse-time)
  14741. (let* ((org-with-time with-time)
  14742. (org-time-stamp-rounding-minutes
  14743. (if (equal org-with-time '(16))
  14744. '(0 0)
  14745. org-time-stamp-rounding-minutes))
  14746. (org-dcst org-display-custom-times)
  14747. (ct (org-current-time))
  14748. (org-def (or org-overriding-default-time default-time ct))
  14749. (org-defdecode (decode-time org-def))
  14750. (cur-frame (selected-frame))
  14751. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14752. (calendar-setup
  14753. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14754. (calendar-move-hook nil)
  14755. (calendar-view-diary-initially-flag nil)
  14756. (calendar-view-holidays-initially-flag nil)
  14757. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14758. ;; Rationalize `org-def' and `org-defdecode', if required.
  14759. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14760. (setf (nth 2 org-defdecode) -1)
  14761. (setf (nth 1 org-defdecode) 59)
  14762. (setq org-def (apply #'encode-time org-defdecode))
  14763. (setq org-defdecode (decode-time org-def)))
  14764. (let* ((timestr (format-time-string
  14765. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14766. org-def))
  14767. (prompt (concat (if prompt (concat prompt " ") "")
  14768. (format "Date+time [%s]: " timestr))))
  14769. (cond
  14770. (from-string (setq ans from-string))
  14771. (org-read-date-popup-calendar
  14772. (save-excursion
  14773. (save-window-excursion
  14774. (calendar)
  14775. (when (eq calendar-setup 'calendar-only)
  14776. (setq cal-frame
  14777. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14778. (select-frame cal-frame))
  14779. (org-eval-in-calendar '(setq cursor-type nil) t)
  14780. (unwind-protect
  14781. (progn
  14782. (calendar-forward-day (- (time-to-days org-def)
  14783. (calendar-absolute-from-gregorian
  14784. (calendar-current-date))))
  14785. (org-eval-in-calendar nil t)
  14786. (let* ((old-map (current-local-map))
  14787. (map (copy-keymap calendar-mode-map))
  14788. (minibuffer-local-map
  14789. (copy-keymap org-read-date-minibuffer-local-map)))
  14790. (org-defkey map (kbd "RET") 'org-calendar-select)
  14791. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14792. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14793. (unwind-protect
  14794. (progn
  14795. (use-local-map map)
  14796. (setq org-read-date-inactive inactive)
  14797. (add-hook 'post-command-hook 'org-read-date-display)
  14798. (setq org-ans0
  14799. (read-string prompt
  14800. default-input
  14801. 'org-read-date-history
  14802. nil))
  14803. ;; org-ans0: from prompt
  14804. ;; org-ans1: from mouse click
  14805. ;; org-ans2: from calendar motion
  14806. (setq ans
  14807. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14808. (remove-hook 'post-command-hook 'org-read-date-display)
  14809. (use-local-map old-map)
  14810. (when org-read-date-overlay
  14811. (delete-overlay org-read-date-overlay)
  14812. (setq org-read-date-overlay nil)))))
  14813. (bury-buffer "*Calendar*")
  14814. (when cal-frame
  14815. (delete-frame cal-frame)
  14816. (select-frame-set-input-focus cur-frame))))))
  14817. (t ; Naked prompt only
  14818. (unwind-protect
  14819. (setq ans (read-string prompt default-input
  14820. 'org-read-date-history timestr))
  14821. (when org-read-date-overlay
  14822. (delete-overlay org-read-date-overlay)
  14823. (setq org-read-date-overlay nil))))))
  14824. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14825. (when org-read-date-analyze-forced-year
  14826. (message "Year was forced into %s"
  14827. (if org-read-date-force-compatible-dates
  14828. "compatible range (1970-2037)"
  14829. "range representable on this machine"))
  14830. (ding))
  14831. ;; One round trip to get rid of 34th of August and stuff like that....
  14832. (setq final (decode-time (apply 'encode-time final)))
  14833. (setq org-read-date-final-answer ans)
  14834. (if to-time
  14835. (apply 'encode-time final)
  14836. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14837. (format "%04d-%02d-%02d %02d:%02d"
  14838. (nth 5 final) (nth 4 final) (nth 3 final)
  14839. (nth 2 final) (nth 1 final))
  14840. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14841. (defun org-read-date-display ()
  14842. "Display the current date prompt interpretation in the minibuffer."
  14843. (when org-read-date-display-live
  14844. (when org-read-date-overlay
  14845. (delete-overlay org-read-date-overlay))
  14846. (when (minibufferp (current-buffer))
  14847. (save-excursion
  14848. (end-of-line 1)
  14849. (while (not (equal (buffer-substring
  14850. (max (point-min) (- (point) 4)) (point))
  14851. " "))
  14852. (insert " ")))
  14853. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14854. " " (or org-ans1 org-ans2)))
  14855. (org-end-time-was-given nil)
  14856. (f (org-read-date-analyze ans org-def org-defdecode))
  14857. (fmts (if org-dcst
  14858. org-time-stamp-custom-formats
  14859. org-time-stamp-formats))
  14860. (fmt (if (or org-with-time
  14861. (and (boundp 'org-time-was-given) org-time-was-given))
  14862. (cdr fmts)
  14863. (car fmts)))
  14864. (txt (format-time-string fmt (apply 'encode-time f)))
  14865. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14866. (txt (concat "=> " txt)))
  14867. (when (and org-end-time-was-given
  14868. (string-match org-plain-time-of-day-regexp txt))
  14869. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14870. org-end-time-was-given
  14871. (substring txt (match-end 0)))))
  14872. (when org-read-date-analyze-futurep
  14873. (setq txt (concat txt " (=>F)")))
  14874. (setq org-read-date-overlay
  14875. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14876. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14877. (defun org-read-date-analyze (ans def defdecode)
  14878. "Analyze the combined answer of the date prompt."
  14879. ;; FIXME: cleanup and comment
  14880. ;; Pass `current-time' result to `decode-time' (instead of calling
  14881. ;; without arguments) so that only `current-time' has to be
  14882. ;; overridden in tests.
  14883. (let ((org-def def)
  14884. (org-defdecode defdecode)
  14885. (nowdecode (decode-time (current-time)))
  14886. delta deltan deltaw deltadef year month day
  14887. hour minute second wday pm h2 m2 tl wday1
  14888. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14889. (setq org-read-date-analyze-futurep nil
  14890. org-read-date-analyze-forced-year nil)
  14891. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14892. (setq ans "+0"))
  14893. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14894. (setq ans (replace-match "" t t ans)
  14895. deltan (car delta)
  14896. deltaw (nth 1 delta)
  14897. deltadef (nth 2 delta)))
  14898. ;; Check if there is an iso week date in there. If yes, store the
  14899. ;; info and postpone interpreting it until the rest of the parsing
  14900. ;; is done.
  14901. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14902. (setq iso-year (when (match-end 1)
  14903. (org-small-year-to-year
  14904. (string-to-number (match-string 1 ans))))
  14905. iso-weekday (when (match-end 3)
  14906. (string-to-number (match-string 3 ans)))
  14907. iso-week (string-to-number (match-string 2 ans)))
  14908. (setq ans (replace-match "" t t ans)))
  14909. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14910. (when (string-match
  14911. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14912. (setq year (if (match-end 2)
  14913. (string-to-number (match-string 2 ans))
  14914. (progn (setq kill-year t)
  14915. (string-to-number (format-time-string "%Y"))))
  14916. month (string-to-number (match-string 3 ans))
  14917. day (string-to-number (match-string 4 ans)))
  14918. (setq year (org-small-year-to-year year))
  14919. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14920. t nil ans)))
  14921. ;; Help matching dotted european dates
  14922. (when (string-match
  14923. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14924. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14925. (setq kill-year t)
  14926. (string-to-number (format-time-string "%Y")))
  14927. day (string-to-number (match-string 1 ans))
  14928. month (string-to-number (match-string 2 ans))
  14929. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14930. t nil ans)))
  14931. ;; Help matching american dates, like 5/30 or 5/30/7
  14932. (when (string-match
  14933. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14934. (setq year (if (match-end 4)
  14935. (string-to-number (match-string 4 ans))
  14936. (progn (setq kill-year t)
  14937. (string-to-number (format-time-string "%Y"))))
  14938. month (string-to-number (match-string 1 ans))
  14939. day (string-to-number (match-string 2 ans)))
  14940. (setq year (org-small-year-to-year year))
  14941. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14942. t nil ans)))
  14943. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14944. ;; If there is a time with am/pm, and *no* time without it, we convert
  14945. ;; so that matching will be successful.
  14946. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14947. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14948. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14949. (setq hour (string-to-number (match-string 1 ans))
  14950. minute (if (match-end 3)
  14951. (string-to-number (match-string 3 ans))
  14952. 0)
  14953. pm (equal ?p
  14954. (string-to-char (downcase (match-string 4 ans)))))
  14955. (if (and (= hour 12) (not pm))
  14956. (setq hour 0)
  14957. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14958. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14959. t t ans))))
  14960. ;; Check if a time range is given as a duration
  14961. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14962. (setq hour (string-to-number (match-string 1 ans))
  14963. h2 (+ hour (string-to-number (match-string 3 ans)))
  14964. minute (string-to-number (match-string 2 ans))
  14965. m2 (+ minute (if (match-end 5) (string-to-number
  14966. (match-string 5 ans))0)))
  14967. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14968. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14969. t t ans)))
  14970. ;; Check if there is a time range
  14971. (when (boundp 'org-end-time-was-given)
  14972. (setq org-time-was-given nil)
  14973. (when (and (string-match org-plain-time-of-day-regexp ans)
  14974. (match-end 8))
  14975. (setq org-end-time-was-given (match-string 8 ans))
  14976. (setq ans (concat (substring ans 0 (match-beginning 7))
  14977. (substring ans (match-end 7))))))
  14978. (setq tl (parse-time-string ans)
  14979. day (or (nth 3 tl) (nth 3 org-defdecode))
  14980. month
  14981. (cond ((nth 4 tl))
  14982. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14983. ;; Day was specified. Make sure DAY+MONTH
  14984. ;; combination happens in the future.
  14985. ((nth 3 tl)
  14986. (setq futurep t)
  14987. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14988. (nth 4 nowdecode)))
  14989. (t (nth 4 org-defdecode)))
  14990. year
  14991. (cond ((and (not kill-year) (nth 5 tl)))
  14992. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14993. ;; Month was guessed in the future and is at least
  14994. ;; equal to NOWDECODE's. Fix year accordingly.
  14995. (futurep
  14996. (if (or (> month (nth 4 nowdecode))
  14997. (>= day (nth 3 nowdecode)))
  14998. (nth 5 nowdecode)
  14999. (1+ (nth 5 nowdecode))))
  15000. ;; Month was specified. Make sure MONTH+YEAR
  15001. ;; combination happens in the future.
  15002. ((nth 4 tl)
  15003. (setq futurep t)
  15004. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15005. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15006. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15007. (t (nth 5 nowdecode))))
  15008. (t (nth 5 org-defdecode)))
  15009. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15010. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15011. second (or (nth 0 tl) 0)
  15012. wday (nth 6 tl))
  15013. (when (and (eq org-read-date-prefer-future 'time)
  15014. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15015. (equal day (nth 3 nowdecode))
  15016. (equal month (nth 4 nowdecode))
  15017. (equal year (nth 5 nowdecode))
  15018. (nth 2 tl)
  15019. (or (< (nth 2 tl) (nth 2 nowdecode))
  15020. (and (= (nth 2 tl) (nth 2 nowdecode))
  15021. (nth 1 tl)
  15022. (< (nth 1 tl) (nth 1 nowdecode)))))
  15023. (setq day (1+ day)
  15024. futurep t))
  15025. ;; Special date definitions below
  15026. (cond
  15027. (iso-week
  15028. ;; There was an iso week
  15029. (require 'cal-iso)
  15030. (setq futurep nil)
  15031. (setq year (or iso-year year)
  15032. day (or iso-weekday wday 1)
  15033. wday nil ; to make sure that the trigger below does not match
  15034. iso-date (calendar-gregorian-from-absolute
  15035. (calendar-iso-to-absolute
  15036. (list iso-week day year))))
  15037. ; FIXME: Should we also push ISO weeks into the future?
  15038. ; (when (and org-read-date-prefer-future
  15039. ; (not iso-year)
  15040. ; (< (calendar-absolute-from-gregorian iso-date)
  15041. ; (time-to-days (current-time))))
  15042. ; (setq year (1+ year)
  15043. ; iso-date (calendar-gregorian-from-absolute
  15044. ; (calendar-iso-to-absolute
  15045. ; (list iso-week day year)))))
  15046. (setq month (car iso-date)
  15047. year (nth 2 iso-date)
  15048. day (nth 1 iso-date)))
  15049. (deltan
  15050. (setq futurep nil)
  15051. (unless deltadef
  15052. ;; Pass `current-time' result to `decode-time' (instead of
  15053. ;; calling without arguments) so that only `current-time' has
  15054. ;; to be overridden in tests.
  15055. (let ((now (decode-time (current-time))))
  15056. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15057. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15058. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15059. ((equal deltaw "m") (setq month (+ month deltan)))
  15060. ((equal deltaw "y") (setq year (+ year deltan)))))
  15061. ((and wday (not (nth 3 tl)))
  15062. ;; Weekday was given, but no day, so pick that day in the week
  15063. ;; on or after the derived date.
  15064. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15065. (unless (equal wday wday1)
  15066. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15067. (when (and (boundp 'org-time-was-given)
  15068. (nth 2 tl))
  15069. (setq org-time-was-given t))
  15070. (when (< year 100) (setq year (+ 2000 year)))
  15071. ;; Check of the date is representable
  15072. (if org-read-date-force-compatible-dates
  15073. (progn
  15074. (when (< year 1970)
  15075. (setq year 1970 org-read-date-analyze-forced-year t))
  15076. (when (> year 2037)
  15077. (setq year 2037 org-read-date-analyze-forced-year t)))
  15078. (condition-case nil
  15079. (ignore (encode-time second minute hour day month year))
  15080. (error
  15081. (setq year (nth 5 org-defdecode))
  15082. (setq org-read-date-analyze-forced-year t))))
  15083. (setq org-read-date-analyze-futurep futurep)
  15084. (list second minute hour day month year)))
  15085. (defvar parse-time-weekdays)
  15086. (defun org-read-date-get-relative (s today default)
  15087. "Check string S for special relative date string.
  15088. TODAY and DEFAULT are internal times, for today and for a default.
  15089. Return shift list (N what def-flag)
  15090. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15091. N is the number of WHATs to shift.
  15092. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15093. the DEFAULT date rather than TODAY."
  15094. (require 'parse-time)
  15095. (when (and
  15096. (string-match
  15097. (concat
  15098. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15099. "\\([0-9]+\\)?"
  15100. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15101. "\\([ \t]\\|$\\)") s)
  15102. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15103. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15104. (string-to-char (substring (match-string 1 s) -1))
  15105. ?+))
  15106. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15107. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15108. (what (if (match-end 3) (match-string 3 s) "d"))
  15109. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15110. (date (if rel default today))
  15111. (wday (nth 6 (decode-time date)))
  15112. delta)
  15113. (if wday1
  15114. (progn
  15115. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15116. (when (= delta 0) (setq delta 7))
  15117. (when (= dir ?-)
  15118. (setq delta (- delta 7))
  15119. (when (= delta 0) (setq delta -7)))
  15120. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15121. (list delta "d" rel))
  15122. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15123. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15124. "Turn a user-specified date into the internal representation.
  15125. The internal representation needed by the calendar is (month day year).
  15126. This is a wrapper to handle the brain-dead convention in calendar that
  15127. user function argument order change dependent on argument order."
  15128. (pcase calendar-date-style
  15129. (`american (list arg1 arg2 arg3))
  15130. (`european (list arg2 arg1 arg3))
  15131. (`iso (list arg2 arg3 arg1))))
  15132. (defun org-eval-in-calendar (form &optional keepdate)
  15133. "Eval FORM in the calendar window and return to current window.
  15134. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15135. (let ((sf (selected-frame))
  15136. (sw (selected-window)))
  15137. (select-window (get-buffer-window "*Calendar*" t))
  15138. (eval form)
  15139. (when (and (not keepdate) (calendar-cursor-to-date))
  15140. (let* ((date (calendar-cursor-to-date))
  15141. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15142. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15143. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15144. (select-window sw)
  15145. (select-frame-set-input-focus sf)))
  15146. (defun org-calendar-select ()
  15147. "Return to `org-read-date' with the date currently selected.
  15148. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15149. (interactive)
  15150. (when (calendar-cursor-to-date)
  15151. (let* ((date (calendar-cursor-to-date))
  15152. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15153. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15154. (when (active-minibuffer-window) (exit-minibuffer))))
  15155. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15156. "Insert a date stamp for the date given by the internal TIME.
  15157. See `format-time-string' for the format of TIME.
  15158. WITH-HM means use the stamp format that includes the time of the day.
  15159. INACTIVE means use square brackets instead of angular ones, so that the
  15160. stamp will not contribute to the agenda.
  15161. PRE and POST are optional strings to be inserted before and after the
  15162. stamp.
  15163. The command returns the inserted time stamp."
  15164. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15165. stamp)
  15166. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15167. (insert-before-markers (or pre ""))
  15168. (when (listp extra)
  15169. (setq extra (car extra))
  15170. (if (and (stringp extra)
  15171. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15172. (setq extra (format "-%02d:%02d"
  15173. (string-to-number (match-string 1 extra))
  15174. (string-to-number (match-string 2 extra))))
  15175. (setq extra nil)))
  15176. (when extra
  15177. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15178. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15179. (insert-before-markers (or post ""))
  15180. (setq org-last-inserted-timestamp stamp)))
  15181. (defun org-toggle-time-stamp-overlays ()
  15182. "Toggle the use of custom time stamp formats."
  15183. (interactive)
  15184. (setq org-display-custom-times (not org-display-custom-times))
  15185. (unless org-display-custom-times
  15186. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15187. (while (setq p (next-single-property-change p 'display))
  15188. (when (and (get-text-property p 'display)
  15189. (eq (get-text-property p 'face) 'org-date))
  15190. (remove-text-properties
  15191. p (setq p (next-single-property-change p 'display))
  15192. '(display t))))
  15193. (set-buffer-modified-p bmp)))
  15194. (org-restart-font-lock)
  15195. (setq org-table-may-need-update t)
  15196. (if org-display-custom-times
  15197. (message "Time stamps are overlaid with custom format")
  15198. (message "Time stamp overlays removed")))
  15199. (defun org-display-custom-time (beg end)
  15200. "Overlay modified time stamp format over timestamp between BEG and END."
  15201. (let* ((ts (buffer-substring beg end))
  15202. t1 with-hm tf time str (off 0))
  15203. (save-match-data
  15204. (setq t1 (org-parse-time-string ts t))
  15205. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15206. (setq off (- (match-end 0) (match-beginning 0)))))
  15207. (setq end (- end off))
  15208. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15209. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15210. time (org-fix-decoded-time t1)
  15211. str (org-add-props
  15212. (format-time-string
  15213. (substring tf 1 -1) (apply 'encode-time time))
  15214. nil 'mouse-face 'highlight))
  15215. (put-text-property beg end 'display str)))
  15216. (defun org-fix-decoded-time (time)
  15217. "Set 0 instead of nil for the first 6 elements of time.
  15218. Don't touch the rest."
  15219. (let ((n 0))
  15220. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15221. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15222. "Difference between TIMESTAMP-STRING and now in days.
  15223. If SECONDS is non-nil, return the difference in seconds."
  15224. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15225. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15226. (funcall fdiff (current-time)))))
  15227. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15228. "Is the time in TIMESTAMP-STRING close to the current date?"
  15229. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15230. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15231. (not (org-entry-is-done-p))))
  15232. (defun org-get-wdays (ts &optional delay zero-delay)
  15233. "Get the deadline lead time appropriate for timestring TS.
  15234. When DELAY is non-nil, get the delay time for scheduled items
  15235. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15236. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15237. don't try to find the delay cookie in the scheduled timestamp."
  15238. (let ((tv (if delay org-scheduled-delay-days
  15239. org-deadline-warning-days)))
  15240. (cond
  15241. ((or (and delay (< tv 0))
  15242. (and delay zero-delay (<= tv 0))
  15243. (and (not delay) (<= tv 0)))
  15244. ;; Enforce this value no matter what
  15245. (- tv))
  15246. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15247. ;; lead time is specified.
  15248. (floor (* (string-to-number (match-string 1 ts))
  15249. (cdr (assoc (match-string 2 ts)
  15250. '(("d" . 1) ("w" . 7)
  15251. ("m" . 30.4) ("y" . 365.25)
  15252. ("h" . 0.041667)))))))
  15253. ;; go for the default.
  15254. (t tv))))
  15255. (defun org-calendar-select-mouse (ev)
  15256. "Return to `org-read-date' with the date currently selected.
  15257. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15258. (interactive "e")
  15259. (mouse-set-point ev)
  15260. (when (calendar-cursor-to-date)
  15261. (let* ((date (calendar-cursor-to-date))
  15262. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15263. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15264. (when (active-minibuffer-window) (exit-minibuffer))))
  15265. (defun org-check-deadlines (ndays)
  15266. "Check if there are any deadlines due or past due.
  15267. A deadline is considered due if it happens within `org-deadline-warning-days'
  15268. days from today's date. If the deadline appears in an entry marked DONE,
  15269. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15270. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15271. are shown."
  15272. (interactive "P")
  15273. (let* ((org-warn-days
  15274. (cond
  15275. ((equal ndays '(4)) 100000)
  15276. (ndays (prefix-numeric-value ndays))
  15277. (t (abs org-deadline-warning-days))))
  15278. (case-fold-search nil)
  15279. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15280. (callback
  15281. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15282. (message "%d deadlines past-due or due within %d days"
  15283. (org-occur regexp nil callback)
  15284. org-warn-days)))
  15285. (defsubst org-re-timestamp (type)
  15286. "Return a regexp for timestamp TYPE.
  15287. Allowed values for TYPE are:
  15288. all: all timestamps
  15289. active: only active timestamps (<...>)
  15290. inactive: only inactive timestamps ([...])
  15291. scheduled: only scheduled timestamps
  15292. deadline: only deadline timestamps
  15293. closed: only closed time-stamps
  15294. When TYPE is nil, fall back on returning a regexp that matches
  15295. both scheduled and deadline timestamps."
  15296. (cl-case type
  15297. (all org-ts-regexp-both)
  15298. (active org-ts-regexp)
  15299. (inactive org-ts-regexp-inactive)
  15300. (scheduled org-scheduled-time-regexp)
  15301. (deadline org-deadline-time-regexp)
  15302. (closed org-closed-time-regexp)
  15303. (otherwise
  15304. (concat "\\<"
  15305. (regexp-opt (list org-deadline-string org-scheduled-string))
  15306. " *<\\([^>]+\\)>"))))
  15307. (defun org-check-before-date (d)
  15308. "Check if there are deadlines or scheduled entries before date D."
  15309. (interactive (list (org-read-date)))
  15310. (let* ((case-fold-search nil)
  15311. (regexp (org-re-timestamp org-ts-type))
  15312. (ts-type org-ts-type)
  15313. (callback
  15314. (lambda ()
  15315. (let ((match (match-string 1)))
  15316. (and (if (memq ts-type '(active inactive all))
  15317. (eq (org-element-type (save-excursion
  15318. (backward-char)
  15319. (org-element-context)))
  15320. 'timestamp)
  15321. (org-at-planning-p))
  15322. (time-less-p
  15323. (org-time-string-to-time match)
  15324. (org-time-string-to-time d)))))))
  15325. (message "%d entries before %s"
  15326. (org-occur regexp nil callback)
  15327. d)))
  15328. (defun org-check-after-date (d)
  15329. "Check if there are deadlines or scheduled entries after date D."
  15330. (interactive (list (org-read-date)))
  15331. (let* ((case-fold-search nil)
  15332. (regexp (org-re-timestamp org-ts-type))
  15333. (ts-type org-ts-type)
  15334. (callback
  15335. (lambda ()
  15336. (let ((match (match-string 1)))
  15337. (and (if (memq ts-type '(active inactive all))
  15338. (eq (org-element-type (save-excursion
  15339. (backward-char)
  15340. (org-element-context)))
  15341. 'timestamp)
  15342. (org-at-planning-p))
  15343. (not (time-less-p
  15344. (org-time-string-to-time match)
  15345. (org-time-string-to-time d))))))))
  15346. (message "%d entries after %s"
  15347. (org-occur regexp nil callback)
  15348. d)))
  15349. (defun org-check-dates-range (start-date end-date)
  15350. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15351. (interactive (list (org-read-date nil nil nil "Range starts")
  15352. (org-read-date nil nil nil "Range end")))
  15353. (let ((case-fold-search nil)
  15354. (regexp (org-re-timestamp org-ts-type))
  15355. (callback
  15356. (let ((type org-ts-type))
  15357. (lambda ()
  15358. (let ((match (match-string 1)))
  15359. (and
  15360. (if (memq type '(active inactive all))
  15361. (eq (org-element-type (save-excursion
  15362. (backward-char)
  15363. (org-element-context)))
  15364. 'timestamp)
  15365. (org-at-planning-p))
  15366. (not (time-less-p
  15367. (org-time-string-to-time match)
  15368. (org-time-string-to-time start-date)))
  15369. (time-less-p
  15370. (org-time-string-to-time match)
  15371. (org-time-string-to-time end-date))))))))
  15372. (message "%d entries between %s and %s"
  15373. (org-occur regexp nil callback) start-date end-date)))
  15374. (defun org-evaluate-time-range (&optional to-buffer)
  15375. "Evaluate a time range by computing the difference between start and end.
  15376. Normally the result is just printed in the echo area, but with prefix arg
  15377. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15378. If the time range is actually in a table, the result is inserted into the
  15379. next column.
  15380. For time difference computation, a year is assumed to be exactly 365
  15381. days in order to avoid rounding problems."
  15382. (interactive "P")
  15383. (or
  15384. (org-clock-update-time-maybe)
  15385. (save-excursion
  15386. (unless (org-at-date-range-p t)
  15387. (goto-char (point-at-bol))
  15388. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15389. (unless (org-at-date-range-p t)
  15390. (user-error "Not at a time-stamp range, and none found in current line")))
  15391. (let* ((ts1 (match-string 1))
  15392. (ts2 (match-string 2))
  15393. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15394. (match-end (match-end 0))
  15395. (time1 (org-time-string-to-time ts1))
  15396. (time2 (org-time-string-to-time ts2))
  15397. (t1 (float-time time1))
  15398. (t2 (float-time time2))
  15399. (diff (abs (- t2 t1)))
  15400. (negative (< (- t2 t1) 0))
  15401. ;; (ys (floor (* 365 24 60 60)))
  15402. (ds (* 24 60 60))
  15403. (hs (* 60 60))
  15404. (fy "%dy %dd %02d:%02d")
  15405. (fy1 "%dy %dd")
  15406. (fd "%dd %02d:%02d")
  15407. (fd1 "%dd")
  15408. (fh "%02d:%02d")
  15409. y d h m align)
  15410. (if havetime
  15411. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15412. y 0
  15413. d (floor (/ diff ds)) diff (mod diff ds)
  15414. h (floor (/ diff hs)) diff (mod diff hs)
  15415. m (floor (/ diff 60)))
  15416. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15417. y 0
  15418. d (floor (+ (/ diff ds) 0.5))
  15419. h 0 m 0))
  15420. (if (not to-buffer)
  15421. (message "%s" (org-make-tdiff-string y d h m))
  15422. (if (org-at-table-p)
  15423. (progn
  15424. (goto-char match-end)
  15425. (setq align t)
  15426. (and (looking-at " *|") (goto-char (match-end 0))))
  15427. (goto-char match-end))
  15428. (when (looking-at
  15429. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15430. (replace-match ""))
  15431. (when negative (insert " -"))
  15432. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15433. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15434. (insert " " (format fh h m))))
  15435. (when align (org-table-align))
  15436. (message "Time difference inserted")))))
  15437. (defun org-make-tdiff-string (y d h m)
  15438. (let ((fmt "")
  15439. (l nil))
  15440. (when (> y 0)
  15441. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15442. (push y l))
  15443. (when (> d 0)
  15444. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15445. (push d l))
  15446. (when (> h 0)
  15447. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15448. (push h l))
  15449. (when (> m 0)
  15450. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15451. (push m l))
  15452. (apply 'format fmt (nreverse l))))
  15453. (defun org-time-string-to-time (s)
  15454. "Convert timestamp string S into internal time."
  15455. (apply #'encode-time (org-parse-time-string s)))
  15456. (defun org-time-string-to-seconds (s)
  15457. "Convert a timestamp string S into a number of seconds."
  15458. (float-time (org-time-string-to-time s)))
  15459. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15460. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15461. "Convert time stamp S to an absolute day number.
  15462. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15463. stamp, get the closest date to DAYNR. If PREFER is
  15464. `past' (respectively `future') return a date past (respectively
  15465. after) or equal to DAYNR.
  15466. POS is the location of time stamp S, as a buffer position in
  15467. BUFFER.
  15468. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15469. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15470. signaled."
  15471. (cond
  15472. ((string-match "\\`%%\\((.*)\\)" s)
  15473. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15474. ;; only able to match individual dates. If it fails, raise an
  15475. ;; error.
  15476. (if (and daynr
  15477. (org-diary-sexp-entry
  15478. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15479. daynr
  15480. (signal 'org-diary-sexp-no-match (list s))))
  15481. (daynr (org-closest-date s daynr prefer))
  15482. (t (time-to-days
  15483. (condition-case errdata
  15484. (apply #'encode-time (org-parse-time-string s))
  15485. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15486. s
  15487. (if (not (and buffer pos)) ""
  15488. (format-message " at %d in buffer `%s'" pos buffer))
  15489. (cdr errdata))))))))
  15490. (defun org-days-to-iso-week (days)
  15491. "Return the iso week number."
  15492. (require 'cal-iso)
  15493. (car (calendar-iso-from-absolute days)))
  15494. (defun org-small-year-to-year (year)
  15495. "Convert 2-digit years into 4-digit years.
  15496. YEAR is expanded into one of the 30 next years, if possible, or
  15497. into a past one. Any year larger than 99 is returned unchanged."
  15498. (if (>= year 100) year
  15499. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15500. (century (/ current 100))
  15501. (offset (- year (% current 100))))
  15502. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15503. ((> offset -70) (+ (* century 100) year))
  15504. (t (+ (* (1+ century) 100) year))))))
  15505. (defun org-time-from-absolute (d)
  15506. "Return the time corresponding to date D.
  15507. D may be an absolute day number, or a calendar-type list (month day year)."
  15508. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15509. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15510. (defvar org-agenda-current-date)
  15511. (defun org-calendar-holiday ()
  15512. "List of holidays, for Diary display in Org mode."
  15513. (require 'holidays)
  15514. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15515. (and hl (mapconcat #'identity hl "; "))))
  15516. (defun org-diary-sexp-entry (sexp entry d)
  15517. "Process a SEXP diary ENTRY for date D."
  15518. (require 'diary-lib)
  15519. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15520. ;; dynamically.
  15521. (let* ((sexp `(let ((entry ,entry)
  15522. (date ',d))
  15523. ,(car (read-from-string sexp))))
  15524. (result (if calendar-debug-sexp (eval sexp)
  15525. (condition-case nil
  15526. (eval sexp)
  15527. (error
  15528. (beep)
  15529. (message "Bad sexp at line %d in %s: %s"
  15530. (org-current-line)
  15531. (buffer-file-name) sexp)
  15532. (sleep-for 2))))))
  15533. (cond ((stringp result) (split-string result "; "))
  15534. ((and (consp result)
  15535. (not (consp (cdr result)))
  15536. (stringp (cdr result))) (cdr result))
  15537. ((and (consp result)
  15538. (stringp (car result))) result)
  15539. (result entry))))
  15540. (defun org-diary-to-ical-string (frombuf)
  15541. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15542. This uses the icalendar.el library."
  15543. (let* ((tmpdir temporary-file-directory)
  15544. (tmpfile (make-temp-name
  15545. (expand-file-name "orgics" tmpdir)))
  15546. buf rtn b e)
  15547. (with-current-buffer frombuf
  15548. (icalendar-export-region (point-min) (point-max) tmpfile)
  15549. (setq buf (find-buffer-visiting tmpfile))
  15550. (set-buffer buf)
  15551. (goto-char (point-min))
  15552. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15553. (setq b (match-beginning 0)))
  15554. (goto-char (point-max))
  15555. (when (re-search-backward "^END:VEVENT" nil t)
  15556. (setq e (match-end 0)))
  15557. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15558. (kill-buffer buf)
  15559. (delete-file tmpfile)
  15560. rtn))
  15561. (defun org-closest-date (start current prefer)
  15562. "Return closest date to CURRENT starting from START.
  15563. CURRENT and START are both time stamps.
  15564. When PREFER is `past', return a date that is either CURRENT or
  15565. past. When PREFER is `future', return a date that is either
  15566. CURRENT or future.
  15567. Only time stamps with a repeater are modified. Any other time
  15568. stamp stay unchanged. In any case, return value is an absolute
  15569. day number."
  15570. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15571. ;; No repeater. Do not shift time stamp.
  15572. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15573. (let ((value (string-to-number (match-string 1 start)))
  15574. (type (match-string 2 start)))
  15575. (if (= 0 value)
  15576. ;; Repeater with a 0-value is considered as void.
  15577. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15578. (let* ((base (org-date-to-gregorian start))
  15579. (target (org-date-to-gregorian current))
  15580. (sday (calendar-absolute-from-gregorian base))
  15581. (cday (calendar-absolute-from-gregorian target))
  15582. n1 n2)
  15583. ;; If START is already past CURRENT, just return START.
  15584. (if (<= cday sday) sday
  15585. ;; Compute closest date before (N1) and closest date past
  15586. ;; (N2) CURRENT.
  15587. (pcase type
  15588. ("h"
  15589. (let ((missing-hours
  15590. (mod (+ (- (* 24 (- cday sday))
  15591. (nth 2 (org-parse-time-string start)))
  15592. org-extend-today-until)
  15593. value)))
  15594. (setf n1 (if (= missing-hours 0) cday
  15595. (- cday (1+ (/ missing-hours 24)))))
  15596. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15597. ((or "d" "w")
  15598. (let ((value (if (equal type "w") (* 7 value) value)))
  15599. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15600. (setf n2 (+ n1 value))))
  15601. ("m"
  15602. (let* ((add-months
  15603. (lambda (d n)
  15604. ;; Add N months to gregorian date D, i.e.,
  15605. ;; a list (MONTH DAY YEAR). Return a valid
  15606. ;; gregorian date.
  15607. (let ((m (+ (nth 0 d) n)))
  15608. (list (mod m 12)
  15609. (nth 1 d)
  15610. (+ (/ m 12) (nth 2 d))))))
  15611. (months ; Complete months to TARGET.
  15612. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15613. (- (nth 0 target) (nth 0 base))
  15614. ;; If START's day is greater than
  15615. ;; TARGET's, remove incomplete month.
  15616. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15617. value)
  15618. value))
  15619. (before (funcall add-months base months)))
  15620. (setf n1 (calendar-absolute-from-gregorian before))
  15621. (setf n2
  15622. (calendar-absolute-from-gregorian
  15623. (funcall add-months before value)))))
  15624. (_
  15625. (let* ((d (nth 1 base))
  15626. (m (nth 0 base))
  15627. (y (nth 2 base))
  15628. (years ; Complete years to TARGET.
  15629. (* (/ (- (nth 2 target)
  15630. y
  15631. ;; If START's month and day are
  15632. ;; greater than TARGET's, remove
  15633. ;; incomplete year.
  15634. (if (or (> (nth 0 target) m)
  15635. (and (= (nth 0 target) m)
  15636. (> (nth 1 target) d)))
  15637. 0
  15638. 1))
  15639. value)
  15640. value))
  15641. (before (list m d (+ y years))))
  15642. (setf n1 (calendar-absolute-from-gregorian before))
  15643. (setf n2 (calendar-absolute-from-gregorian
  15644. (list m d (+ (nth 2 before) value)))))))
  15645. ;; Handle PREFER parameter, if any.
  15646. (cond
  15647. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15648. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15649. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15650. (defun org-date-to-gregorian (d)
  15651. "Turn any specification of date D into a Gregorian date for the calendar."
  15652. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15653. ((and (listp d) (= (length d) 3)) d)
  15654. ((stringp d)
  15655. (let ((d (org-parse-time-string d)))
  15656. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15657. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15658. (defun org-parse-time-string (s &optional nodefault)
  15659. "Parse the standard Org time string.
  15660. This should be a lot faster than the normal `parse-time-string'.
  15661. If time is not given, defaults to 0:00. However, with optional
  15662. NODEFAULT, hour and minute fields will be nil if not given."
  15663. (cond ((string-match org-ts-regexp0 s)
  15664. (list 0
  15665. (when (or (match-beginning 8) (not nodefault))
  15666. (string-to-number (or (match-string 8 s) "0")))
  15667. (when (or (match-beginning 7) (not nodefault))
  15668. (string-to-number (or (match-string 7 s) "0")))
  15669. (string-to-number (match-string 4 s))
  15670. (string-to-number (match-string 3 s))
  15671. (string-to-number (match-string 2 s))
  15672. nil nil nil))
  15673. ((string-match "^<[^>]+>$" s)
  15674. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15675. ;; second argument. However, this requires at least Emacs
  15676. ;; 25.1. We can do it when we switch to this version as our
  15677. ;; minimal requirement.
  15678. (decode-time (seconds-to-time (org-matcher-time s))))
  15679. (t (error "Not a standard Org time string: %s" s))))
  15680. (defun org-timestamp-up (&optional arg)
  15681. "Increase the date item at the cursor by one.
  15682. If the cursor is on the year, change the year. If it is on the month,
  15683. the day or the time, change that.
  15684. With prefix ARG, change by that many units."
  15685. (interactive "p")
  15686. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15687. (defun org-timestamp-down (&optional arg)
  15688. "Decrease the date item at the cursor by one.
  15689. If the cursor is on the year, change the year. If it is on the month,
  15690. the day or the time, change that.
  15691. With prefix ARG, change by that many units."
  15692. (interactive "p")
  15693. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15694. (defun org-timestamp-up-day (&optional arg)
  15695. "Increase the date in the time stamp by one day.
  15696. With prefix ARG, change that many days."
  15697. (interactive "p")
  15698. (if (and (not (org-at-timestamp-p 'lax))
  15699. (org-at-heading-p))
  15700. (org-todo 'up)
  15701. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15702. (defun org-timestamp-down-day (&optional arg)
  15703. "Decrease the date in the time stamp by one day.
  15704. With prefix ARG, change that many days."
  15705. (interactive "p")
  15706. (if (and (not (org-at-timestamp-p 'lax))
  15707. (org-at-heading-p))
  15708. (org-todo 'down)
  15709. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15710. (defun org-at-timestamp-p (&optional extended)
  15711. "Non-nil if point is inside a timestamp.
  15712. By default, the function only consider syntactically valid active
  15713. timestamps. However, the caller may have a broader definition
  15714. for timestamps. As a consequence, optional argument EXTENDED can
  15715. be set to the following values
  15716. `inactive'
  15717. Include also syntactically valid inactive timestamps.
  15718. `agenda'
  15719. Include timestamps allowed in Agenda, i.e., those in
  15720. properties drawers, planning lines and clock lines.
  15721. `lax'
  15722. Ignore context. The function matches any part of the
  15723. document looking like a timestamp. This includes comments,
  15724. example blocks...
  15725. For backward-compatibility with Org 9.0, every other non-nil
  15726. value is equivalent to `inactive'.
  15727. When at a timestamp, return the position of the point as a symbol
  15728. among `bracket', `after', `year', `month', `hour', `minute',
  15729. `day' or a number of character from the last know part of the
  15730. time stamp.
  15731. When matching, the match groups are the following:
  15732. group 1: year
  15733. group 2: month
  15734. group 3: day number
  15735. group 4: day name
  15736. group 5: hours, if any
  15737. group 6: minutes, if any"
  15738. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15739. (pos (point))
  15740. (match?
  15741. (let ((boundaries (org-in-regexp regexp)))
  15742. (save-match-data
  15743. (cond ((null boundaries) nil)
  15744. ((eq extended 'lax) t)
  15745. (t
  15746. (or (and (eq extended 'agenda)
  15747. (or (org-at-planning-p)
  15748. (org-at-property-p)
  15749. (and (bound-and-true-p
  15750. org-agenda-include-inactive-timestamps)
  15751. (org-at-clock-log-p))))
  15752. (eq 'timestamp
  15753. (save-excursion
  15754. (when (= pos (cdr boundaries)) (forward-char -1))
  15755. (org-element-type (org-element-context)))))))))))
  15756. (cond
  15757. ((not match?) nil)
  15758. ((= pos (match-beginning 0)) 'bracket)
  15759. ;; Distinguish location right before the closing bracket from
  15760. ;; right after it.
  15761. ((= pos (1- (match-end 0))) 'bracket)
  15762. ((= pos (match-end 0)) 'after)
  15763. ((org-pos-in-match-range pos 2) 'year)
  15764. ((org-pos-in-match-range pos 3) 'month)
  15765. ((org-pos-in-match-range pos 7) 'hour)
  15766. ((org-pos-in-match-range pos 8) 'minute)
  15767. ((or (org-pos-in-match-range pos 4)
  15768. (org-pos-in-match-range pos 5)) 'day)
  15769. ((and (> pos (or (match-end 8) (match-end 5)))
  15770. (< pos (match-end 0)))
  15771. (- pos (or (match-end 8) (match-end 5))))
  15772. (t 'day))))
  15773. (defun org-toggle-timestamp-type ()
  15774. "Toggle the type (<active> or [inactive]) of a time stamp."
  15775. (interactive)
  15776. (when (org-at-timestamp-p 'lax)
  15777. (let ((beg (match-beginning 0)) (end (match-end 0))
  15778. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15779. (save-excursion
  15780. (goto-char beg)
  15781. (while (re-search-forward "[][<>]" end t)
  15782. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15783. t t)))
  15784. (message "Timestamp is now %sactive"
  15785. (if (equal (char-after beg) ?<) "" "in")))))
  15786. (defun org-at-clock-log-p ()
  15787. "Non-nil if point is on a clock log line."
  15788. (and (org-match-line org-clock-line-re)
  15789. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15790. (defvar org-clock-history) ; defined in org-clock.el
  15791. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15792. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15793. "Change the date in the time stamp at point.
  15794. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15795. `year', `minute', `second'. If WHAT is not given, the cursor position
  15796. in the timestamp determines what will be changed.
  15797. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15798. (let ((origin (point))
  15799. (timestamp? (org-at-timestamp-p 'lax))
  15800. origin-cat
  15801. with-hm inactive
  15802. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15803. extra rem
  15804. ts time time0 fixnext clrgx)
  15805. (unless timestamp? (user-error "Not at a timestamp"))
  15806. (if (and (not what) (eq timestamp? 'bracket))
  15807. (org-toggle-timestamp-type)
  15808. ;; Point isn't on brackets. Remember the part of the time-stamp
  15809. ;; the point was in. Indeed, size of time-stamps may change,
  15810. ;; but point must be kept in the same category nonetheless.
  15811. (setq origin-cat timestamp?)
  15812. (when (and (not what) (not (eq timestamp? 'day))
  15813. org-display-custom-times
  15814. (get-text-property (point) 'display)
  15815. (not (get-text-property (1- (point)) 'display)))
  15816. (setq timestamp? 'day))
  15817. (setq timestamp? (or what timestamp?)
  15818. inactive (= (char-after (match-beginning 0)) ?\[)
  15819. ts (match-string 0))
  15820. (replace-match "")
  15821. (when (string-match
  15822. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15823. ts)
  15824. (setq extra (match-string 1 ts))
  15825. (when suppress-tmp-delay
  15826. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15827. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15828. (setq with-hm t))
  15829. (setq time0 (org-parse-time-string ts))
  15830. (when (and updown
  15831. (eq timestamp? 'minute)
  15832. (not current-prefix-arg))
  15833. ;; This looks like s-up and s-down. Change by one rounding step.
  15834. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15835. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15836. (setcar (cdr time0) (+ (nth 1 time0)
  15837. (if (> n 0) (- rem) (- dm rem))))))
  15838. (setq time
  15839. (apply #'encode-time
  15840. (or (car time0) 0)
  15841. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15842. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15843. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15844. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15845. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15846. (nthcdr 6 time0)))
  15847. (when (and (memq timestamp? '(hour minute))
  15848. extra
  15849. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15850. (setq extra (org-modify-ts-extra
  15851. extra
  15852. (if (eq timestamp? 'hour) 2 5)
  15853. n dm)))
  15854. (when (integerp timestamp?)
  15855. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15856. (when (eq what 'calendar)
  15857. (let ((cal-date (org-get-date-from-calendar)))
  15858. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15859. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15860. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15861. (setcar time0 (or (car time0) 0))
  15862. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15863. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15864. (setq time (apply 'encode-time time0))))
  15865. ;; Insert the new time-stamp, and ensure point stays in the same
  15866. ;; category as before (i.e. not after the last position in that
  15867. ;; category).
  15868. (let ((pos (point)))
  15869. ;; Stay before inserted string. `save-excursion' is of no use.
  15870. (setq org-last-changed-timestamp
  15871. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15872. (goto-char pos))
  15873. (save-match-data
  15874. (looking-at org-ts-regexp3)
  15875. (goto-char
  15876. (pcase origin-cat
  15877. ;; `day' category ends before `hour' if any, or at the end
  15878. ;; of the day name.
  15879. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15880. (`hour (min (match-end 7) origin))
  15881. (`minute (min (1- (match-end 8)) origin))
  15882. ((pred integerp) (min (1- (match-end 0)) origin))
  15883. ;; Point was right after the time-stamp. However, the
  15884. ;; time-stamp length might have changed, so refer to
  15885. ;; (match-end 0) instead.
  15886. (`after (match-end 0))
  15887. ;; `year' and `month' have both fixed size: point couldn't
  15888. ;; have moved into another part.
  15889. (_ origin))))
  15890. ;; Update clock if on a CLOCK line.
  15891. (org-clock-update-time-maybe)
  15892. ;; Maybe adjust the closest clock in `org-clock-history'
  15893. (when org-clock-adjust-closest
  15894. (if (not (and (org-at-clock-log-p)
  15895. (< 1 (length (delq nil (mapcar 'marker-position
  15896. org-clock-history))))))
  15897. (message "No clock to adjust")
  15898. (cond ((save-excursion ; fix previous clock?
  15899. (re-search-backward org-ts-regexp0 nil t)
  15900. (looking-back (concat org-clock-string " \\[")
  15901. (line-beginning-position)))
  15902. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15903. ((save-excursion ; fix next clock?
  15904. (re-search-backward org-ts-regexp0 nil t)
  15905. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15906. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15907. (save-window-excursion
  15908. ;; Find closest clock to point, adjust the previous/next one in history
  15909. (let* ((p (save-excursion (org-back-to-heading t)))
  15910. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15911. (clfixnth
  15912. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15913. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15914. (if (not clfixpos)
  15915. (message "No clock to adjust")
  15916. (save-excursion
  15917. (org-goto-marker-or-bmk clfixpos)
  15918. (org-show-subtree)
  15919. (when (re-search-forward clrgx nil t)
  15920. (goto-char (match-beginning 1))
  15921. (let (org-clock-adjust-closest)
  15922. (org-timestamp-change n timestamp? updown))
  15923. (message "Clock adjusted in %s for heading: %s"
  15924. (file-name-nondirectory (buffer-file-name))
  15925. (org-get-heading t t)))))))))
  15926. ;; Try to recenter the calendar window, if any.
  15927. (when (and org-calendar-follow-timestamp-change
  15928. (get-buffer-window "*Calendar*" t)
  15929. (memq timestamp? '(day month year)))
  15930. (org-recenter-calendar (time-to-days time))))))
  15931. (defun org-modify-ts-extra (s pos n dm)
  15932. "Change the different parts of the lead-time and repeat fields in timestamp."
  15933. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15934. ng h m new rem)
  15935. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15936. (cond
  15937. ((or (org-pos-in-match-range pos 2)
  15938. (org-pos-in-match-range pos 3))
  15939. (setq m (string-to-number (match-string 3 s))
  15940. h (string-to-number (match-string 2 s)))
  15941. (if (org-pos-in-match-range pos 2)
  15942. (setq h (+ h n))
  15943. (setq n (* dm (with-no-warnings (signum n))))
  15944. (unless (= 0 (setq rem (% m dm)))
  15945. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15946. (setq m (+ m n)))
  15947. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15948. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15949. (setq h (mod h 24))
  15950. (setq ng 1 new (format "-%02d:%02d" h m)))
  15951. ((org-pos-in-match-range pos 6)
  15952. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15953. ((org-pos-in-match-range pos 5)
  15954. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15955. ((org-pos-in-match-range pos 9)
  15956. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15957. ((org-pos-in-match-range pos 8)
  15958. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15959. (when ng
  15960. (setq s (concat
  15961. (substring s 0 (match-beginning ng))
  15962. new
  15963. (substring s (match-end ng))))))
  15964. s))
  15965. (defun org-recenter-calendar (d)
  15966. "If the calendar is visible, recenter it to date D."
  15967. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15968. (when cwin
  15969. (let ((calendar-move-hook nil))
  15970. (with-selected-window cwin
  15971. (calendar-goto-date
  15972. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15973. (defun org-goto-calendar (&optional arg)
  15974. "Go to the Emacs calendar at the current date.
  15975. If there is a time stamp in the current line, go to that date.
  15976. A prefix ARG can be used to force the current date."
  15977. (interactive "P")
  15978. (let ((calendar-move-hook nil)
  15979. (calendar-view-holidays-initially-flag nil)
  15980. (calendar-view-diary-initially-flag nil)
  15981. diff)
  15982. (when (or (org-at-timestamp-p 'lax)
  15983. (org-match-line (concat ".*" org-ts-regexp)))
  15984. (let ((d1 (time-to-days (current-time)))
  15985. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15986. (setq diff (- d2 d1))))
  15987. (calendar)
  15988. (calendar-goto-today)
  15989. (when (and diff (not arg)) (calendar-forward-day diff))))
  15990. (defun org-get-date-from-calendar ()
  15991. "Return a list (month day year) of date at point in calendar."
  15992. (with-current-buffer "*Calendar*"
  15993. (save-match-data
  15994. (calendar-cursor-to-date))))
  15995. (defun org-date-from-calendar ()
  15996. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15997. If there is already a time stamp at the cursor position, update it."
  15998. (interactive)
  15999. (if (org-at-timestamp-p 'lax)
  16000. (org-timestamp-change 0 'calendar)
  16001. (let ((cal-date (org-get-date-from-calendar)))
  16002. (org-insert-time-stamp
  16003. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16004. (defcustom org-effort-durations
  16005. `(("min" . 1)
  16006. ("h" . 60)
  16007. ("d" . ,(* 60 8))
  16008. ("w" . ,(* 60 8 5))
  16009. ("m" . ,(* 60 8 5 4))
  16010. ("y" . ,(* 60 8 5 40)))
  16011. "Conversion factor to minutes for an effort modifier.
  16012. Each entry has the form (MODIFIER . MINUTES).
  16013. In an effort string, a number followed by MODIFIER is multiplied
  16014. by the specified number of MINUTES to obtain an effort in
  16015. minutes.
  16016. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16017. effort string \"2hours\" is equivalent to 120 minutes."
  16018. :group 'org-agenda
  16019. :version "26.1"
  16020. :package-version '(Org . "8.3")
  16021. :type '(alist :key-type (string :tag "Modifier")
  16022. :value-type (number :tag "Minutes")))
  16023. (defcustom org-image-actual-width t
  16024. "Should we use the actual width of images when inlining them?
  16025. When set to t, always use the image width.
  16026. When set to a number, use imagemagick (when available) to set
  16027. the image's width to this value.
  16028. When set to a number in a list, try to get the width from any
  16029. #+ATTR.* keyword if it matches a width specification like
  16030. #+ATTR_HTML: :width 300px
  16031. and fall back on that number if none is found.
  16032. When set to nil, try to get the width from an #+ATTR.* keyword
  16033. and fall back on the original width if none is found.
  16034. This requires Emacs >= 24.1, build with imagemagick support."
  16035. :group 'org-appearance
  16036. :version "24.4"
  16037. :package-version '(Org . "8.0")
  16038. :type '(choice
  16039. (const :tag "Use the image width" t)
  16040. (integer :tag "Use a number of pixels")
  16041. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16042. (const :tag "Use #+ATTR* or don't resize" nil)))
  16043. (defcustom org-agenda-inhibit-startup nil
  16044. "Inhibit startup when preparing agenda buffers.
  16045. When this variable is t, the initialization of the Org agenda
  16046. buffers is inhibited: e.g. the visibility state is not set, the
  16047. tables are not re-aligned, etc."
  16048. :type 'boolean
  16049. :version "24.3"
  16050. :group 'org-agenda)
  16051. (defcustom org-agenda-ignore-properties nil
  16052. "Avoid updating text properties when building the agenda.
  16053. Properties are used to prepare buffers for effort estimates,
  16054. appointments, statistics and subtree-local categories.
  16055. If you don't use these in the agenda, you can add them to this
  16056. list and agenda building will be a bit faster.
  16057. The value is a list, with zero or more of the symbols `effort', `appt',
  16058. `stats' or `category'."
  16059. :type '(set :greedy t
  16060. (const effort)
  16061. (const appt)
  16062. (const stats)
  16063. (const category))
  16064. :version "26.1"
  16065. :package-version '(Org . "8.3")
  16066. :group 'org-agenda)
  16067. ;;;; Files
  16068. (defun org-save-all-org-buffers ()
  16069. "Save all Org buffers without user confirmation."
  16070. (interactive)
  16071. (message "Saving all Org buffers...")
  16072. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16073. (when (featurep 'org-id) (org-id-locations-save))
  16074. (message "Saving all Org buffers... done"))
  16075. (defun org-revert-all-org-buffers ()
  16076. "Revert all Org buffers.
  16077. Prompt for confirmation when there are unsaved changes.
  16078. Be sure you know what you are doing before letting this function
  16079. overwrite your changes.
  16080. This function is useful in a setup where one tracks org files
  16081. with a version control system, to revert on one machine after pulling
  16082. changes from another. I believe the procedure must be like this:
  16083. 1. M-x org-save-all-org-buffers
  16084. 2. Pull changes from the other machine, resolve conflicts
  16085. 3. M-x org-revert-all-org-buffers"
  16086. (interactive)
  16087. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16088. (user-error "Abort"))
  16089. (save-excursion
  16090. (save-window-excursion
  16091. (dolist (b (buffer-list))
  16092. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16093. (with-current-buffer b buffer-file-name))
  16094. (pop-to-buffer-same-window b)
  16095. (revert-buffer t 'no-confirm)))
  16096. (when (and (featurep 'org-id) org-id-track-globally)
  16097. (org-id-locations-load)))))
  16098. ;;;; Agenda files
  16099. ;;;###autoload
  16100. (defun org-switchb (&optional arg)
  16101. "Switch between Org buffers.
  16102. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16103. With `\\[universal-argument] \\[universal-argument]' \
  16104. prefix, restrict available buffers to agenda files."
  16105. (interactive "P")
  16106. (let ((blist (org-buffer-list
  16107. (cond ((equal arg '(4)) 'files)
  16108. ((equal arg '(16)) 'agenda)))))
  16109. (pop-to-buffer-same-window
  16110. (completing-read "Org buffer: "
  16111. (mapcar #'list (mapcar #'buffer-name blist))
  16112. nil t))))
  16113. (defun org-buffer-list (&optional predicate exclude-tmp)
  16114. "Return a list of Org buffers.
  16115. PREDICATE can be `export', `files' or `agenda'.
  16116. export restrict the list to Export buffers.
  16117. files restrict the list to buffers visiting Org files.
  16118. agenda restrict the list to buffers visiting agenda files.
  16119. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16120. (let* ((bfn nil)
  16121. (agenda-files (and (eq predicate 'agenda)
  16122. (mapcar 'file-truename (org-agenda-files t))))
  16123. (filter
  16124. (cond
  16125. ((eq predicate 'files)
  16126. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16127. ((eq predicate 'export)
  16128. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16129. ((eq predicate 'agenda)
  16130. (lambda (b)
  16131. (with-current-buffer b
  16132. (and (derived-mode-p 'org-mode)
  16133. (setq bfn (buffer-file-name b))
  16134. (member (file-truename bfn) agenda-files)))))
  16135. (t (lambda (b) (with-current-buffer b
  16136. (or (derived-mode-p 'org-mode)
  16137. (string-match "\\*Org .*Export"
  16138. (buffer-name b)))))))))
  16139. (delq nil
  16140. (mapcar
  16141. (lambda(b)
  16142. (if (and (funcall filter b)
  16143. (or (not exclude-tmp)
  16144. (not (string-match "tmp" (buffer-name b)))))
  16145. b
  16146. nil))
  16147. (buffer-list)))))
  16148. (defun org-agenda-files (&optional unrestricted archives)
  16149. "Get the list of agenda files.
  16150. Optional UNRESTRICTED means return the full list even if a restriction
  16151. is currently in place.
  16152. When ARCHIVES is t, include all archive files that are really being
  16153. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16154. `org-agenda-archives-mode' is t."
  16155. (let ((files
  16156. (cond
  16157. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16158. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16159. ((listp org-agenda-files) org-agenda-files)
  16160. (t (error "Invalid value of `org-agenda-files'")))))
  16161. (setq files (apply 'append
  16162. (mapcar (lambda (f)
  16163. (if (file-directory-p f)
  16164. (directory-files
  16165. f t org-agenda-file-regexp)
  16166. (list f)))
  16167. files)))
  16168. (when org-agenda-skip-unavailable-files
  16169. (setq files (delq nil
  16170. (mapcar (function
  16171. (lambda (file)
  16172. (and (file-readable-p file) file)))
  16173. files))))
  16174. (when (or (eq archives t)
  16175. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16176. (setq files (org-add-archive-files files)))
  16177. files))
  16178. (defun org-agenda-file-p (&optional file)
  16179. "Return non-nil, if FILE is an agenda file.
  16180. If FILE is omitted, use the file associated with the current
  16181. buffer."
  16182. (let ((fname (or file (buffer-file-name))))
  16183. (and fname
  16184. (member (file-truename fname)
  16185. (mapcar #'file-truename (org-agenda-files t))))))
  16186. (defun org-edit-agenda-file-list ()
  16187. "Edit the list of agenda files.
  16188. Depending on setup, this either uses customize to edit the variable
  16189. `org-agenda-files', or it visits the file that is holding the list. In the
  16190. latter case, the buffer is set up in a way that saving it automatically kills
  16191. the buffer and restores the previous window configuration."
  16192. (interactive)
  16193. (if (stringp org-agenda-files)
  16194. (let ((cw (current-window-configuration)))
  16195. (find-file org-agenda-files)
  16196. (setq-local org-window-configuration cw)
  16197. (add-hook 'after-save-hook
  16198. (lambda ()
  16199. (set-window-configuration
  16200. (prog1 org-window-configuration
  16201. (kill-buffer (current-buffer))))
  16202. (org-install-agenda-files-menu)
  16203. (message "New agenda file list installed"))
  16204. nil 'local)
  16205. (message "%s" (substitute-command-keys
  16206. "Edit list and finish with \\[save-buffer]")))
  16207. (customize-variable 'org-agenda-files)))
  16208. (defun org-store-new-agenda-file-list (list)
  16209. "Set new value for the agenda file list and save it correctly."
  16210. (if (stringp org-agenda-files)
  16211. (let ((fe (org-read-agenda-file-list t)) b u)
  16212. (while (setq b (find-buffer-visiting org-agenda-files))
  16213. (kill-buffer b))
  16214. (with-temp-file org-agenda-files
  16215. (insert
  16216. (mapconcat
  16217. (lambda (f) ;; Keep un-expanded entries.
  16218. (if (setq u (assoc f fe))
  16219. (cdr u)
  16220. f))
  16221. list "\n")
  16222. "\n")))
  16223. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16224. (org-insert-mode-line-in-empty-file nil))
  16225. (setq org-agenda-files list)
  16226. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16227. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16228. "Read the list of agenda files from a file.
  16229. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16230. filenames, used by `org-store-new-agenda-file-list' to write back
  16231. un-expanded file names."
  16232. (when (file-directory-p org-agenda-files)
  16233. (error "`org-agenda-files' cannot be a single directory"))
  16234. (when (stringp org-agenda-files)
  16235. (with-temp-buffer
  16236. (insert-file-contents org-agenda-files)
  16237. (mapcar
  16238. (lambda (f)
  16239. (let ((e (expand-file-name (substitute-in-file-name f)
  16240. org-directory)))
  16241. (if pair-with-expansion
  16242. (cons e f)
  16243. e)))
  16244. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16245. ;;;###autoload
  16246. (defun org-cycle-agenda-files ()
  16247. "Cycle through the files in `org-agenda-files'.
  16248. If the current buffer visits an agenda file, find the next one in the list.
  16249. If the current buffer does not, find the first agenda file."
  16250. (interactive)
  16251. (let* ((fs (or (org-agenda-files t)
  16252. (user-error "No agenda files")))
  16253. (files (copy-sequence fs))
  16254. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16255. file)
  16256. (when tcf
  16257. (while (and (setq file (pop files))
  16258. (not (equal (file-truename file) tcf)))))
  16259. (find-file (car (or files fs)))
  16260. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16261. (defun org-agenda-file-to-front (&optional to-end)
  16262. "Move/add the current file to the top of the agenda file list.
  16263. If the file is not present in the list, it is added to the front. If it is
  16264. present, it is moved there. With optional argument TO-END, add/move to the
  16265. end of the list."
  16266. (interactive "P")
  16267. (let ((org-agenda-skip-unavailable-files nil)
  16268. (file-alist (mapcar (lambda (x)
  16269. (cons (file-truename x) x))
  16270. (org-agenda-files t)))
  16271. (ctf (file-truename
  16272. (or buffer-file-name
  16273. (user-error "Please save the current buffer to a file"))))
  16274. x had)
  16275. (setq x (assoc ctf file-alist) had x)
  16276. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16277. (if to-end
  16278. (setq file-alist (append (delq x file-alist) (list x)))
  16279. (setq file-alist (cons x (delq x file-alist))))
  16280. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16281. (org-install-agenda-files-menu)
  16282. (message "File %s to %s of agenda file list"
  16283. (if had "moved" "added") (if to-end "end" "front"))))
  16284. (defun org-remove-file (&optional file)
  16285. "Remove current file from the list of files in variable `org-agenda-files'.
  16286. These are the files which are being checked for agenda entries.
  16287. Optional argument FILE means use this file instead of the current."
  16288. (interactive)
  16289. (let* ((org-agenda-skip-unavailable-files nil)
  16290. (file (or file buffer-file-name
  16291. (user-error "Current buffer does not visit a file")))
  16292. (true-file (file-truename file))
  16293. (afile (abbreviate-file-name file))
  16294. (files (delq nil (mapcar
  16295. (lambda (x)
  16296. (unless (equal true-file
  16297. (file-truename x))
  16298. x))
  16299. (org-agenda-files t)))))
  16300. (if (not (= (length files) (length (org-agenda-files t))))
  16301. (progn
  16302. (org-store-new-agenda-file-list files)
  16303. (org-install-agenda-files-menu)
  16304. (message "Removed from Org Agenda list: %s" afile))
  16305. (message "File was not in list: %s (not removed)" afile))))
  16306. (defun org-file-menu-entry (file)
  16307. (vector file (list 'find-file file) t))
  16308. (defun org-check-agenda-file (file)
  16309. "Make sure FILE exists. If not, ask user what to do."
  16310. (unless (file-exists-p file)
  16311. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16312. (abbreviate-file-name file))
  16313. (let ((r (downcase (read-char-exclusive))))
  16314. (cond
  16315. ((equal r ?r)
  16316. (org-remove-file file)
  16317. (throw 'nextfile t))
  16318. (t (user-error "Abort"))))))
  16319. (defun org-get-agenda-file-buffer (file)
  16320. "Get an agenda buffer visiting FILE.
  16321. If the buffer needs to be created, add it to the list of buffers
  16322. which might be released later."
  16323. (let ((buf (org-find-base-buffer-visiting file)))
  16324. (if buf
  16325. buf ; just return it
  16326. ;; Make a new buffer and remember it
  16327. (setq buf (find-file-noselect file))
  16328. (when buf (push buf org-agenda-new-buffers))
  16329. buf)))
  16330. (defun org-release-buffers (blist)
  16331. "Release all buffers in list, asking the user for confirmation when needed.
  16332. When a buffer is unmodified, it is just killed. When modified, it is saved
  16333. \(if the user agrees) and then killed."
  16334. (let (file)
  16335. (dolist (buf blist)
  16336. (setq file (buffer-file-name buf))
  16337. (when (and (buffer-modified-p buf)
  16338. file
  16339. (y-or-n-p (format "Save file %s? " file)))
  16340. (with-current-buffer buf (save-buffer)))
  16341. (kill-buffer buf))))
  16342. (defun org-agenda-prepare-buffers (files)
  16343. "Create buffers for all agenda files, protect archived trees and comments."
  16344. (interactive)
  16345. (let ((pa '(:org-archived t))
  16346. (pc '(:org-comment t))
  16347. (pall '(:org-archived t :org-comment t))
  16348. (inhibit-read-only t)
  16349. (org-inhibit-startup org-agenda-inhibit-startup)
  16350. (rea (concat ":" org-archive-tag ":"))
  16351. re pos)
  16352. (setq org-tag-alist-for-agenda nil
  16353. org-tag-groups-alist-for-agenda nil)
  16354. (save-excursion
  16355. (save-restriction
  16356. (dolist (file files)
  16357. (catch 'nextfile
  16358. (if (bufferp file)
  16359. (set-buffer file)
  16360. (org-check-agenda-file file)
  16361. (set-buffer (org-get-agenda-file-buffer file)))
  16362. (widen)
  16363. (org-set-regexps-and-options 'tags-only)
  16364. (setq pos (point))
  16365. (or (memq 'category org-agenda-ignore-properties)
  16366. (org-refresh-category-properties))
  16367. (or (memq 'stats org-agenda-ignore-properties)
  16368. (org-refresh-stats-properties))
  16369. (or (memq 'effort org-agenda-ignore-properties)
  16370. (org-refresh-effort-properties))
  16371. (or (memq 'appt org-agenda-ignore-properties)
  16372. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16373. (setq org-todo-keywords-for-agenda
  16374. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16375. (setq org-done-keywords-for-agenda
  16376. (append org-done-keywords-for-agenda org-done-keywords))
  16377. (setq org-todo-keyword-alist-for-agenda
  16378. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16379. (setq org-tag-alist-for-agenda
  16380. (org-uniquify
  16381. (append org-tag-alist-for-agenda
  16382. org-current-tag-alist)))
  16383. ;; Merge current file's tag groups into global
  16384. ;; `org-tag-groups-alist-for-agenda'.
  16385. (when org-group-tags
  16386. (dolist (alist org-tag-groups-alist)
  16387. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16388. (if old
  16389. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16390. (push alist org-tag-groups-alist-for-agenda)))))
  16391. (org-with-silent-modifications
  16392. (save-excursion
  16393. (remove-text-properties (point-min) (point-max) pall)
  16394. (when org-agenda-skip-archived-trees
  16395. (goto-char (point-min))
  16396. (while (re-search-forward rea nil t)
  16397. (when (org-at-heading-p t)
  16398. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16399. (goto-char (point-min))
  16400. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16401. (while (re-search-forward re nil t)
  16402. (when (save-match-data (org-in-commented-heading-p t))
  16403. (add-text-properties
  16404. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16405. (goto-char pos)))))
  16406. (setq org-todo-keywords-for-agenda
  16407. (org-uniquify org-todo-keywords-for-agenda))
  16408. (setq org-todo-keyword-alist-for-agenda
  16409. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16410. ;;;; CDLaTeX minor mode
  16411. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16412. "Keymap for the minor `org-cdlatex-mode'.")
  16413. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16414. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16415. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16416. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16417. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16418. (defvar org-cdlatex-texmathp-advice-is-done nil
  16419. "Flag remembering if we have applied the advice to texmathp already.")
  16420. (define-minor-mode org-cdlatex-mode
  16421. "Toggle the minor `org-cdlatex-mode'.
  16422. This mode supports entering LaTeX environment and math in LaTeX fragments
  16423. in Org mode.
  16424. \\{org-cdlatex-mode-map}"
  16425. nil " OCDL" nil
  16426. (when org-cdlatex-mode
  16427. (require 'cdlatex)
  16428. (run-hooks 'cdlatex-mode-hook)
  16429. (cdlatex-compute-tables))
  16430. (unless org-cdlatex-texmathp-advice-is-done
  16431. (setq org-cdlatex-texmathp-advice-is-done t)
  16432. (defadvice texmathp (around org-math-always-on activate)
  16433. "Always return t in Org buffers.
  16434. This is because we want to insert math symbols without dollars even outside
  16435. the LaTeX math segments. If Org mode thinks that point is actually inside
  16436. an embedded LaTeX fragment, let `texmathp' do its job.
  16437. `\\[org-cdlatex-mode-map]'"
  16438. (interactive)
  16439. (let (p)
  16440. (cond
  16441. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16442. ((eq this-command 'cdlatex-math-symbol)
  16443. (setq ad-return-value t
  16444. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16445. (t
  16446. (let ((p (org-inside-LaTeX-fragment-p)))
  16447. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16448. (setq ad-return-value t
  16449. texmathp-why '("Org mode embedded math" . 0))
  16450. (when p ad-do-it)))))))))
  16451. (defun turn-on-org-cdlatex ()
  16452. "Unconditionally turn on `org-cdlatex-mode'."
  16453. (org-cdlatex-mode 1))
  16454. (defun org-try-cdlatex-tab ()
  16455. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16456. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16457. - inside a LaTeX fragment, or
  16458. - after the first word in a line, where an abbreviation expansion could
  16459. insert a LaTeX environment."
  16460. (when org-cdlatex-mode
  16461. (cond
  16462. ;; Before any word on the line: No expansion possible.
  16463. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16464. ;; Just after first word on the line: Expand it. Make sure it
  16465. ;; cannot happen on headlines, though.
  16466. ((save-excursion
  16467. (skip-chars-backward "a-zA-Z0-9*")
  16468. (skip-chars-backward " \t")
  16469. (and (bolp) (not (org-at-heading-p))))
  16470. (cdlatex-tab) t)
  16471. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16472. (defun org-cdlatex-underscore-caret (&optional _arg)
  16473. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16474. Revert to the normal definition outside of these fragments."
  16475. (interactive "P")
  16476. (if (org-inside-LaTeX-fragment-p)
  16477. (call-interactively 'cdlatex-sub-superscript)
  16478. (let (org-cdlatex-mode)
  16479. (call-interactively (key-binding (vector last-input-event))))))
  16480. (defun org-cdlatex-math-modify (&optional _arg)
  16481. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16482. Revert to the normal definition outside of these fragments."
  16483. (interactive "P")
  16484. (if (org-inside-LaTeX-fragment-p)
  16485. (call-interactively 'cdlatex-math-modify)
  16486. (let (org-cdlatex-mode)
  16487. (call-interactively (key-binding (vector last-input-event))))))
  16488. (defun org-cdlatex-environment-indent (&optional environment item)
  16489. "Execute `cdlatex-environment' and indent the inserted environment.
  16490. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16491. The inserted environment is indented to current indentation
  16492. unless point is at the beginning of the line, in which the
  16493. environment remains unintended."
  16494. (interactive)
  16495. ;; cdlatex-environment always return nil. Therefore, capture output
  16496. ;; first and determine if an environment was selected.
  16497. (let* ((beg (point-marker))
  16498. (end (copy-marker (point) t))
  16499. (inserted (progn
  16500. (ignore-errors (cdlatex-environment environment item))
  16501. (< beg end)))
  16502. ;; Figure out how many lines to move forward after the
  16503. ;; environment has been inserted.
  16504. (lines (when inserted
  16505. (save-excursion
  16506. (- (cl-loop while (< beg (point))
  16507. with x = 0
  16508. do (forward-line -1)
  16509. (cl-incf x)
  16510. finally return x)
  16511. (if (progn (goto-char beg)
  16512. (and (progn (skip-chars-forward " \t") (eolp))
  16513. (progn (skip-chars-backward " \t") (bolp))))
  16514. 1 0)))))
  16515. (env (org-trim (delete-and-extract-region beg end))))
  16516. (when inserted
  16517. ;; Get indentation of next line unless at column 0.
  16518. (let ((ind (if (bolp) 0
  16519. (save-excursion
  16520. (org-return-indent)
  16521. (prog1 (org-get-indentation)
  16522. (when (progn (skip-chars-forward " \t") (eolp))
  16523. (delete-region beg (point)))))))
  16524. (bol (progn (skip-chars-backward " \t") (bolp))))
  16525. ;; Insert a newline before environment unless at column zero
  16526. ;; to "escape" the current line. Insert a newline if
  16527. ;; something is one the same line as \end{ENVIRONMENT}.
  16528. (insert
  16529. (concat (unless bol "\n") env
  16530. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16531. (unless (zerop ind)
  16532. (save-excursion
  16533. (goto-char beg)
  16534. (while (< (point) end)
  16535. (unless (eolp) (indent-line-to ind))
  16536. (forward-line))))
  16537. (goto-char beg)
  16538. (forward-line lines)
  16539. (indent-line-to ind)))
  16540. (set-marker beg nil)
  16541. (set-marker end nil)))
  16542. ;;;; LaTeX fragments
  16543. (defun org-inside-LaTeX-fragment-p ()
  16544. "Test if point is inside a LaTeX fragment.
  16545. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16546. sequence appearing also before point.
  16547. Even though the matchers for math are configurable, this function assumes
  16548. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16549. delimiters are skipped when they have been removed by customization.
  16550. The return value is nil, or a cons cell with the delimiter and the
  16551. position of this delimiter.
  16552. This function does a reasonably good job, but can locally be fooled by
  16553. for example currency specifications. For example it will assume being in
  16554. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16555. fragments that are properly closed, but during editing, we have to live
  16556. with the uncertainty caused by missing closing delimiters. This function
  16557. looks only before point, not after."
  16558. (catch 'exit
  16559. (let ((pos (point))
  16560. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16561. (lim (save-excursion (org-backward-paragraph) (point)))
  16562. dd-on str (start 0) m re)
  16563. (goto-char pos)
  16564. (when dodollar
  16565. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16566. re (nth 1 (assoc "$" org-latex-regexps)))
  16567. (while (string-match re str start)
  16568. (cond
  16569. ((= (match-end 0) (length str))
  16570. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16571. ((= (match-end 0) (- (length str) 5))
  16572. (throw 'exit nil))
  16573. (t (setq start (match-end 0))))))
  16574. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16575. (goto-char pos)
  16576. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16577. (and (match-beginning 2) (throw 'exit nil))
  16578. ;; count $$
  16579. (while (re-search-backward "\\$\\$" lim t)
  16580. (setq dd-on (not dd-on)))
  16581. (goto-char pos)
  16582. (when dd-on (cons "$$" m))))))
  16583. (defun org-inside-latex-macro-p ()
  16584. "Is point inside a LaTeX macro or its arguments?"
  16585. (save-match-data
  16586. (org-in-regexp
  16587. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16588. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16589. "Build an overlay between BEG and END using IMAGE file.
  16590. Argument IMAGETYPE is the extension of the displayed image,
  16591. as a string. It defaults to \"png\"."
  16592. (let ((ov (make-overlay beg end))
  16593. (imagetype (or (intern imagetype) 'png)))
  16594. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16595. (overlay-put ov 'evaporate t)
  16596. (overlay-put ov
  16597. 'modification-hooks
  16598. (list (lambda (o _flag _beg _end &optional _l)
  16599. (delete-overlay o))))
  16600. (overlay-put ov
  16601. 'display
  16602. (list 'image :type imagetype :file image :ascent 'center))))
  16603. (defun org--list-latex-overlays (&optional beg end)
  16604. "List all Org LaTeX overlays in current buffer.
  16605. Limit to overlays between BEG and END when those are provided."
  16606. (cl-remove-if-not
  16607. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16608. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16609. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16610. "Remove all overlays with LaTeX fragment images in current buffer.
  16611. When optional arguments BEG and END are non-nil, remove all
  16612. overlays between them instead. Return a non-nil value when some
  16613. overlays were removed, nil otherwise."
  16614. (let ((overlays (org--list-latex-overlays beg end)))
  16615. (mapc #'delete-overlay overlays)
  16616. overlays))
  16617. (defun org-toggle-latex-fragment (&optional arg)
  16618. "Preview the LaTeX fragment at point, or all locally or globally.
  16619. If the cursor is on a LaTeX fragment, create the image and overlay
  16620. it over the source code, if there is none. Remove it otherwise.
  16621. If there is no fragment at point, display all fragments in the
  16622. current section.
  16623. With prefix ARG, preview or clear image for all fragments in the
  16624. current subtree or in the whole buffer when used before the first
  16625. headline. With a prefix ARG `\\[universal-argument] \
  16626. \\[universal-argument]' preview or clear images
  16627. for all fragments in the buffer."
  16628. (interactive "P")
  16629. (when (display-graphic-p)
  16630. (catch 'exit
  16631. (save-excursion
  16632. (let (beg end msg)
  16633. (cond
  16634. ((or (equal arg '(16))
  16635. (and (equal arg '(4))
  16636. (org-with-limited-levels (org-before-first-heading-p))))
  16637. (if (org-remove-latex-fragment-image-overlays)
  16638. (progn (message "LaTeX fragments images removed from buffer")
  16639. (throw 'exit nil))
  16640. (setq msg "Creating images for buffer...")))
  16641. ((equal arg '(4))
  16642. (org-with-limited-levels (org-back-to-heading t))
  16643. (setq beg (point))
  16644. (setq end (progn (org-end-of-subtree t) (point)))
  16645. (if (org-remove-latex-fragment-image-overlays beg end)
  16646. (progn
  16647. (message "LaTeX fragment images removed from subtree")
  16648. (throw 'exit nil))
  16649. (setq msg "Creating images for subtree...")))
  16650. ((let ((datum (org-element-context)))
  16651. (when (memq (org-element-type datum)
  16652. '(latex-environment latex-fragment))
  16653. (setq beg (org-element-property :begin datum))
  16654. (setq end (org-element-property :end datum))
  16655. (if (org-remove-latex-fragment-image-overlays beg end)
  16656. (progn (message "LaTeX fragment image removed")
  16657. (throw 'exit nil))
  16658. (setq msg "Creating image...")))))
  16659. (t
  16660. (org-with-limited-levels
  16661. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16662. (outline-previous-heading)
  16663. (point)))
  16664. (setq end (progn (outline-next-heading) (point)))
  16665. (if (org-remove-latex-fragment-image-overlays beg end)
  16666. (progn
  16667. (message "LaTeX fragment images removed from section")
  16668. (throw 'exit nil))
  16669. (setq msg "Creating images for section...")))))
  16670. (let ((file (buffer-file-name (buffer-base-buffer))))
  16671. (org-format-latex
  16672. (concat org-preview-latex-image-directory "org-ltximg")
  16673. beg end
  16674. ;; Emacs cannot overlay images from remote hosts. Create
  16675. ;; it in `temporary-file-directory' instead.
  16676. (if (or (not file) (file-remote-p file))
  16677. temporary-file-directory
  16678. default-directory)
  16679. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16680. (message (concat msg "done")))))))
  16681. (defun org-format-latex
  16682. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16683. "Replace LaTeX fragments with links to an image.
  16684. The function takes care of creating the replacement image.
  16685. Only consider fragments between BEG and END when those are
  16686. provided.
  16687. When optional argument OVERLAYS is non-nil, display the image on
  16688. top of the fragment instead of replacing it.
  16689. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16690. Some of the options can be changed using the variable
  16691. `org-format-latex-options', which see."
  16692. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16693. (unless (eq processing-type 'verbatim)
  16694. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16695. (cnt 0)
  16696. checkdir-flag)
  16697. (goto-char (or beg (point-min)))
  16698. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16699. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16700. (overlay-recenter (or end (point-max))))
  16701. (while (re-search-forward math-regexp end t)
  16702. (unless (and overlays
  16703. (eq (get-char-property (point) 'org-overlay-type)
  16704. 'org-latex-overlay))
  16705. (let* ((context (org-element-context))
  16706. (type (org-element-type context)))
  16707. (when (memq type '(latex-environment latex-fragment))
  16708. (let ((block-type (eq type 'latex-environment))
  16709. (value (org-element-property :value context))
  16710. (beg (org-element-property :begin context))
  16711. (end (save-excursion
  16712. (goto-char (org-element-property :end context))
  16713. (skip-chars-backward " \r\t\n")
  16714. (point))))
  16715. (cond
  16716. ((eq processing-type 'mathjax)
  16717. ;; Prepare for MathJax processing.
  16718. (if (not (string-match "\\`\\$\\$?" value))
  16719. (goto-char end)
  16720. (delete-region beg end)
  16721. (if (string= (match-string 0 value) "$$")
  16722. (insert "\\[" (substring value 2 -2) "\\]")
  16723. (insert "\\(" (substring value 1 -1) "\\)"))))
  16724. ((assq processing-type org-preview-latex-process-alist)
  16725. ;; Process to an image.
  16726. (cl-incf cnt)
  16727. (goto-char beg)
  16728. (let* ((processing-info
  16729. (cdr (assq processing-type org-preview-latex-process-alist)))
  16730. (face (face-at-point))
  16731. ;; Get the colors from the face at point.
  16732. (fg
  16733. (let ((color (plist-get org-format-latex-options
  16734. :foreground)))
  16735. (if (and forbuffer (eq color 'auto))
  16736. (face-attribute face :foreground nil 'default)
  16737. color)))
  16738. (bg
  16739. (let ((color (plist-get org-format-latex-options
  16740. :background)))
  16741. (if (and forbuffer (eq color 'auto))
  16742. (face-attribute face :background nil 'default)
  16743. color)))
  16744. (hash (sha1 (prin1-to-string
  16745. (list org-format-latex-header
  16746. org-latex-default-packages-alist
  16747. org-latex-packages-alist
  16748. org-format-latex-options
  16749. forbuffer value fg bg))))
  16750. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16751. (absprefix (expand-file-name prefix dir))
  16752. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16753. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16754. (sep (and block-type "\n\n"))
  16755. (link (concat sep "[[file:" linkfile "]]" sep))
  16756. (options
  16757. (org-combine-plists
  16758. org-format-latex-options
  16759. `(:foreground ,fg :background ,bg))))
  16760. (when msg (message msg cnt))
  16761. (unless checkdir-flag ; Ensure the directory exists.
  16762. (setq checkdir-flag t)
  16763. (let ((todir (file-name-directory absprefix)))
  16764. (unless (file-directory-p todir)
  16765. (make-directory todir t))))
  16766. (unless (file-exists-p movefile)
  16767. (org-create-formula-image
  16768. value movefile options forbuffer processing-type))
  16769. (if overlays
  16770. (progn
  16771. (dolist (o (overlays-in beg end))
  16772. (when (eq (overlay-get o 'org-overlay-type)
  16773. 'org-latex-overlay)
  16774. (delete-overlay o)))
  16775. (org--format-latex-make-overlay beg end movefile imagetype)
  16776. (goto-char end))
  16777. (delete-region beg end)
  16778. (insert
  16779. (org-add-props link
  16780. (list 'org-latex-src
  16781. (replace-regexp-in-string "\"" "" value)
  16782. 'org-latex-src-embed-type
  16783. (if block-type 'paragraph 'character)))))))
  16784. ((eq processing-type 'mathml)
  16785. ;; Process to MathML.
  16786. (unless (org-format-latex-mathml-available-p)
  16787. (user-error "LaTeX to MathML converter not configured"))
  16788. (cl-incf cnt)
  16789. (when msg (message msg cnt))
  16790. (goto-char beg)
  16791. (delete-region beg end)
  16792. (insert (org-format-latex-as-mathml
  16793. value block-type prefix dir)))
  16794. (t
  16795. (error "Unknown conversion process %s for LaTeX fragments"
  16796. processing-type)))))))))))
  16797. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16798. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16799. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16800. sucessful, return the portion between \"<math...> </math>\"
  16801. elements otherwise return nil. When MATHML-FILE is specified,
  16802. write the results in to that file. When invoked as an
  16803. interactive command, prompt for LATEX-FRAG, with initial value
  16804. set to the current active region and echo the results for user
  16805. inspection."
  16806. (interactive (list (let ((frag (when (org-region-active-p)
  16807. (buffer-substring-no-properties
  16808. (region-beginning) (region-end)))))
  16809. (read-string "LaTeX Fragment: " frag nil frag))))
  16810. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16811. (let* ((tmp-in-file
  16812. (let ((file (file-relative-name
  16813. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16814. (write-region latex-frag nil file)
  16815. file))
  16816. (tmp-out-file (file-relative-name
  16817. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16818. (cmd (format-spec
  16819. org-latex-to-mathml-convert-command
  16820. `((?j . ,(and org-latex-to-mathml-jar-file
  16821. (shell-quote-argument
  16822. (expand-file-name
  16823. org-latex-to-mathml-jar-file))))
  16824. (?I . ,(shell-quote-argument tmp-in-file))
  16825. (?i . ,latex-frag)
  16826. (?o . ,(shell-quote-argument tmp-out-file)))))
  16827. mathml shell-command-output)
  16828. (when (called-interactively-p 'any)
  16829. (unless (org-format-latex-mathml-available-p)
  16830. (user-error "LaTeX to MathML converter not configured")))
  16831. (message "Running %s" cmd)
  16832. (setq shell-command-output (shell-command-to-string cmd))
  16833. (setq mathml
  16834. (when (file-readable-p tmp-out-file)
  16835. (with-current-buffer (find-file-noselect tmp-out-file t)
  16836. (goto-char (point-min))
  16837. (when (re-search-forward
  16838. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16839. (regexp-quote
  16840. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16841. nil t)
  16842. (prog1 (match-string 0) (kill-buffer))))))
  16843. (cond
  16844. (mathml
  16845. (setq mathml
  16846. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16847. (when mathml-file
  16848. (write-region mathml nil mathml-file))
  16849. (when (called-interactively-p 'any)
  16850. (message mathml)))
  16851. ((message "LaTeX to MathML conversion failed")
  16852. (message shell-command-output)))
  16853. (delete-file tmp-in-file)
  16854. (when (file-exists-p tmp-out-file)
  16855. (delete-file tmp-out-file))
  16856. mathml))
  16857. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16858. prefix &optional dir)
  16859. "Use `org-create-math-formula' but check local cache first."
  16860. (let* ((absprefix (expand-file-name prefix dir))
  16861. (print-length nil) (print-level nil)
  16862. (formula-id (concat
  16863. "formula-"
  16864. (sha1
  16865. (prin1-to-string
  16866. (list latex-frag
  16867. org-latex-to-mathml-convert-command)))))
  16868. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16869. (formula-cache-dir (file-name-directory formula-cache)))
  16870. (unless (file-directory-p formula-cache-dir)
  16871. (make-directory formula-cache-dir t))
  16872. (unless (file-exists-p formula-cache)
  16873. (org-create-math-formula latex-frag formula-cache))
  16874. (if (file-exists-p formula-cache)
  16875. ;; Successful conversion. Return the link to MathML file.
  16876. (org-add-props
  16877. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16878. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16879. 'org-latex-src-embed-type (if latex-frag-type
  16880. 'paragraph 'character)))
  16881. ;; Failed conversion. Return the LaTeX fragment verbatim
  16882. latex-frag)))
  16883. (defun org--get-display-dpi ()
  16884. "Get the DPI of the display.
  16885. The function assumes that the display has the same pixel width in
  16886. the horizontal and vertical directions."
  16887. (if (display-graphic-p)
  16888. (round (/ (display-pixel-height)
  16889. (/ (display-mm-height) 25.4)))
  16890. (error "Attempt to calculate the dpi of a non-graphic display")))
  16891. (defun org-create-formula-image
  16892. (string tofile options buffer &optional processing-type)
  16893. "Create an image from LaTeX source using external processes.
  16894. The LaTeX STRING is saved to a temporary LaTeX file, then
  16895. converted to an image file by process PROCESSING-TYPE defined in
  16896. `org-preview-latex-process-alist'. A nil value defaults to
  16897. `org-preview-latex-default-process'.
  16898. The generated image file is eventually moved to TOFILE.
  16899. The OPTIONS argument controls the size, foreground color and
  16900. background color of the generated image.
  16901. When BUFFER non-nil, this function is used for LaTeX previewing.
  16902. Otherwise, it is used to deal with LaTeX snippets showed in
  16903. a HTML file."
  16904. (let* ((processing-type (or processing-type
  16905. org-preview-latex-default-process))
  16906. (processing-info
  16907. (cdr (assq processing-type org-preview-latex-process-alist)))
  16908. (programs (plist-get processing-info :programs))
  16909. (error-message (or (plist-get processing-info :message) ""))
  16910. (use-xcolor (plist-get processing-info :use-xcolor))
  16911. (image-input-type (plist-get processing-info :image-input-type))
  16912. (image-output-type (plist-get processing-info :image-output-type))
  16913. (post-clean (or (plist-get processing-info :post-clean)
  16914. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16915. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16916. (latex-header
  16917. (or (plist-get processing-info :latex-header)
  16918. (org-latex-make-preamble
  16919. (org-export-get-environment (org-export-get-backend 'latex))
  16920. org-format-latex-header
  16921. 'snippet)))
  16922. (latex-compiler (plist-get processing-info :latex-compiler))
  16923. (image-converter (plist-get processing-info :image-converter))
  16924. (tmpdir temporary-file-directory)
  16925. (texfilebase (make-temp-name
  16926. (expand-file-name "orgtex" tmpdir)))
  16927. (texfile (concat texfilebase ".tex"))
  16928. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16929. '(1.0 . 1.0)))
  16930. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16931. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16932. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16933. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16934. "Black"))
  16935. (bg (or (plist-get options (if buffer :background :html-background))
  16936. "Transparent"))
  16937. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16938. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16939. (dolist (program programs)
  16940. (org-check-external-command program error-message))
  16941. (if use-xcolor
  16942. (progn (if (eq fg 'default)
  16943. (setq fg (org-latex-color :foreground))
  16944. (setq fg (org-latex-color-format fg)))
  16945. (if (eq bg 'default)
  16946. (setq bg (org-latex-color :background))
  16947. (setq bg (org-latex-color-format
  16948. (if (string= bg "Transparent") "white" bg))))
  16949. (with-temp-file texfile
  16950. (insert latex-header)
  16951. (insert "\n\\begin{document}\n"
  16952. "\\definecolor{fg}{rgb}{" fg "}\n"
  16953. "\\definecolor{bg}{rgb}{" bg "}\n"
  16954. "\n\\pagecolor{bg}\n"
  16955. "\n{\\color{fg}\n"
  16956. string
  16957. "\n}\n"
  16958. "\n\\end{document}\n")))
  16959. (if (eq fg 'default)
  16960. (setq fg (org-dvipng-color :foreground))
  16961. (unless (string= fg "Transparent")
  16962. (setq fg (org-dvipng-color-format fg))))
  16963. (if (eq bg 'default)
  16964. (setq bg (org-dvipng-color :background))
  16965. (unless (string= bg "Transparent")
  16966. (setq bg (org-dvipng-color-format bg))))
  16967. (with-temp-file texfile
  16968. (insert latex-header)
  16969. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16970. (let* ((err-msg (format "Please adjust `%s' part of \
  16971. `org-preview-latex-process-alist'."
  16972. processing-type))
  16973. (image-input-file
  16974. (org-compile-file
  16975. texfile latex-compiler image-input-type err-msg log-buf))
  16976. (image-output-file
  16977. (org-compile-file
  16978. image-input-file image-converter image-output-type err-msg log-buf
  16979. `((?F . ,(shell-quote-argument fg))
  16980. (?B . ,(shell-quote-argument bg))
  16981. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16982. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16983. (copy-file image-output-file tofile 'replace)
  16984. (dolist (e post-clean)
  16985. (when (file-exists-p (concat texfilebase e))
  16986. (delete-file (concat texfilebase e))))
  16987. image-output-file)))
  16988. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16989. "Fill a LaTeX header template TPL.
  16990. In the template, the following place holders will be recognized:
  16991. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16992. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16993. [PACKAGES] \\usepackage statements for PKG
  16994. [NO-PACKAGES] do not include PKG
  16995. [EXTRA] the string EXTRA
  16996. [NO-EXTRA] do not include EXTRA
  16997. For backward compatibility, if both the positive and the negative place
  16998. holder is missing, the positive one (without the \"NO-\") will be
  16999. assumed to be present at the end of the template.
  17000. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17001. EXTRA is a string.
  17002. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17003. (let (rpl (end ""))
  17004. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17005. (setq rpl (if (or (match-end 1) (not def-pkg))
  17006. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17007. tpl (replace-match rpl t t tpl))
  17008. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17009. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17010. (setq rpl (if (or (match-end 1) (not pkg))
  17011. "" (org-latex-packages-to-string pkg snippets-p t))
  17012. tpl (replace-match rpl t t tpl))
  17013. (when pkg (setq end
  17014. (concat end "\n"
  17015. (org-latex-packages-to-string pkg snippets-p)))))
  17016. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17017. (setq rpl (if (or (match-end 1) (not extra))
  17018. "" (concat extra "\n"))
  17019. tpl (replace-match rpl t t tpl))
  17020. (when (and extra (string-match "\\S-" extra))
  17021. (setq end (concat end "\n" extra))))
  17022. (if (string-match "\\S-" end)
  17023. (concat tpl "\n" end)
  17024. tpl)))
  17025. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17026. "Turn an alist of packages into a string with the \\usepackage macros."
  17027. (setq pkg (mapconcat (lambda(p)
  17028. (cond
  17029. ((stringp p) p)
  17030. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17031. (format "%% Package %s omitted" (cadr p)))
  17032. ((equal "" (car p))
  17033. (format "\\usepackage{%s}" (cadr p)))
  17034. (t
  17035. (format "\\usepackage[%s]{%s}"
  17036. (car p) (cadr p)))))
  17037. pkg
  17038. "\n"))
  17039. (if newline (concat pkg "\n") pkg))
  17040. (defun org-dvipng-color (attr)
  17041. "Return a RGB color specification for dvipng."
  17042. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17043. (defun org-dvipng-color-format (color-name)
  17044. "Convert COLOR-NAME to a RGB color value for dvipng."
  17045. (apply #'format "rgb %s %s %s"
  17046. (mapcar 'org-normalize-color
  17047. (color-values color-name))))
  17048. (defun org-latex-color (attr)
  17049. "Return a RGB color for the LaTeX color package."
  17050. (org-latex-color-format (face-attribute 'default attr nil)))
  17051. (defun org-latex-color-format (color-name)
  17052. "Convert COLOR-NAME to a RGB color value."
  17053. (apply #'format "%s,%s,%s"
  17054. (mapcar 'org-normalize-color
  17055. (color-values color-name))))
  17056. (defun org-normalize-color (value)
  17057. "Return string to be used as color value for an RGB component."
  17058. (format "%g" (/ value 65535.0)))
  17059. ;; Image display
  17060. (defvar-local org-inline-image-overlays nil)
  17061. (defun org-toggle-inline-images (&optional include-linked)
  17062. "Toggle the display of inline images.
  17063. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17064. (interactive "P")
  17065. (if org-inline-image-overlays
  17066. (progn
  17067. (org-remove-inline-images)
  17068. (when (called-interactively-p 'interactive)
  17069. (message "Inline image display turned off")))
  17070. (org-display-inline-images include-linked)
  17071. (when (called-interactively-p 'interactive)
  17072. (message (if org-inline-image-overlays
  17073. (format "%d images displayed inline"
  17074. (length org-inline-image-overlays))
  17075. "No images to display inline")))))
  17076. (defun org-redisplay-inline-images ()
  17077. "Refresh the display of inline images."
  17078. (interactive)
  17079. (if (not org-inline-image-overlays)
  17080. (org-toggle-inline-images)
  17081. (org-toggle-inline-images)
  17082. (org-toggle-inline-images)))
  17083. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17084. "Display inline images.
  17085. An inline image is a link which follows either of these
  17086. conventions:
  17087. 1. Its path is a file with an extension matching return value
  17088. from `image-file-name-regexp' and it has no contents.
  17089. 2. Its description consists in a single link of the previous
  17090. type.
  17091. When optional argument INCLUDE-LINKED is non-nil, also links with
  17092. a text description part will be inlined. This can be nice for
  17093. a quick look at those images, but it does not reflect what
  17094. exported files will look like.
  17095. When optional argument REFRESH is non-nil, refresh existing
  17096. images between BEG and END. This will create new image displays
  17097. only if necessary. BEG and END default to the buffer
  17098. boundaries."
  17099. (interactive "P")
  17100. (when (display-graphic-p)
  17101. (unless refresh
  17102. (org-remove-inline-images)
  17103. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17104. (org-with-wide-buffer
  17105. (goto-char (or beg (point-min)))
  17106. (let* ((case-fold-search t)
  17107. (file-extension-re (image-file-name-regexp))
  17108. (link-abbrevs (mapcar #'car
  17109. (append org-link-abbrev-alist-local
  17110. org-link-abbrev-alist)))
  17111. ;; Check absolute, relative file names and explicit
  17112. ;; "file:" links. Also check link abbreviations since
  17113. ;; some might expand to "file" links.
  17114. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17115. (if (not link-abbrevs) ""
  17116. (format "\\|\\(?:%s:\\)"
  17117. (regexp-opt link-abbrevs))))))
  17118. (while (re-search-forward file-types-re end t)
  17119. (let ((link (save-match-data (org-element-context))))
  17120. ;; Check if we're at an inline image, i.e., an image file
  17121. ;; link without a description (unless INCLUDE-LINKED is
  17122. ;; non-nil).
  17123. (when (and (equal "file" (org-element-property :type link))
  17124. (or include-linked
  17125. (null (org-element-contents link)))
  17126. (string-match-p file-extension-re
  17127. (org-element-property :path link)))
  17128. (let ((file (expand-file-name
  17129. (org-link-unescape
  17130. (org-element-property :path link)))))
  17131. (when (file-exists-p file)
  17132. (let ((width
  17133. ;; Apply `org-image-actual-width' specifications.
  17134. (cond
  17135. ((not (image-type-available-p 'imagemagick)) nil)
  17136. ((eq org-image-actual-width t) nil)
  17137. ((listp org-image-actual-width)
  17138. (or
  17139. ;; First try to find a width among
  17140. ;; attributes associated to the paragraph
  17141. ;; containing link.
  17142. (let ((paragraph
  17143. (let ((e link))
  17144. (while (and (setq e (org-element-property
  17145. :parent e))
  17146. (not (eq (org-element-type e)
  17147. 'paragraph))))
  17148. e)))
  17149. (when paragraph
  17150. (save-excursion
  17151. (goto-char (org-element-property :begin paragraph))
  17152. (when
  17153. (re-search-forward
  17154. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17155. (org-element-property
  17156. :post-affiliated paragraph)
  17157. t)
  17158. (string-to-number (match-string 1))))))
  17159. ;; Otherwise, fall-back to provided number.
  17160. (car org-image-actual-width)))
  17161. ((numberp org-image-actual-width)
  17162. org-image-actual-width)))
  17163. (old (get-char-property-and-overlay
  17164. (org-element-property :begin link)
  17165. 'org-image-overlay)))
  17166. (if (and (car-safe old) refresh)
  17167. (image-refresh (overlay-get (cdr old) 'display))
  17168. (let ((image (create-image file
  17169. (and width 'imagemagick)
  17170. nil
  17171. :width width)))
  17172. (when image
  17173. (let ((ov (make-overlay
  17174. (org-element-property :begin link)
  17175. (progn
  17176. (goto-char
  17177. (org-element-property :end link))
  17178. (skip-chars-backward " \t")
  17179. (point)))))
  17180. (overlay-put ov 'display image)
  17181. (overlay-put ov 'face 'default)
  17182. (overlay-put ov 'org-image-overlay t)
  17183. (overlay-put
  17184. ov 'modification-hooks
  17185. (list 'org-display-inline-remove-overlay))
  17186. (push ov org-inline-image-overlays)))))))))))))))
  17187. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17188. "Remove inline-display overlay if a corresponding region is modified."
  17189. (let ((inhibit-modification-hooks t))
  17190. (when (and ov after)
  17191. (delete ov org-inline-image-overlays)
  17192. (delete-overlay ov))))
  17193. (defun org-remove-inline-images ()
  17194. "Remove inline display of images."
  17195. (interactive)
  17196. (mapc #'delete-overlay org-inline-image-overlays)
  17197. (setq org-inline-image-overlays nil))
  17198. ;;;; Key bindings
  17199. (defun org-remap (map &rest commands)
  17200. "In MAP, remap the functions given in COMMANDS.
  17201. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17202. (let (new old)
  17203. (while commands
  17204. (setq old (pop commands) new (pop commands))
  17205. (org-defkey map (vector 'remap old) new))))
  17206. ;; Outline functions from `outline-mode-prefix-map'
  17207. ;; that can be remapped in Org:
  17208. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17209. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17210. (define-key org-mode-map [remap outline-forward-same-level]
  17211. 'org-forward-heading-same-level)
  17212. (define-key org-mode-map [remap outline-backward-same-level]
  17213. 'org-backward-heading-same-level)
  17214. (define-key org-mode-map [remap outline-show-branches]
  17215. 'org-kill-note-or-show-branches)
  17216. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17217. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17218. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17219. (define-key org-mode-map [remap outline-next-visible-heading]
  17220. 'org-next-visible-heading)
  17221. (define-key org-mode-map [remap outline-previous-visible-heading]
  17222. 'org-previous-visible-heading)
  17223. (define-key org-mode-map [remap show-children] 'org-show-children)
  17224. ;; Outline functions from `outline-mode-prefix-map' that can not
  17225. ;; be remapped in Org:
  17226. ;; - the column "key binding" shows whether the Outline function is still
  17227. ;; available in Org mode on the same key that it has been bound to in
  17228. ;; Outline mode:
  17229. ;; - "overridden": key used for a different functionality in Org mode
  17230. ;; - else: key still bound to the same Outline function in Org mode
  17231. ;; | Outline function | key binding | Org replacement |
  17232. ;; |------------------------------------+-------------+--------------------------|
  17233. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17234. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17235. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17236. ;; | `show-entry' | overridden | no replacement |
  17237. ;; | `show-branches' | `C-c C-k' | still same function |
  17238. ;; | `show-subtree' | overridden | visibility cycling |
  17239. ;; | `show-all' | overridden | no replacement |
  17240. ;; | `hide-subtree' | overridden | visibility cycling |
  17241. ;; | `hide-body' | overridden | no replacement |
  17242. ;; | `hide-entry' | overridden | visibility cycling |
  17243. ;; | `hide-leaves' | overridden | no replacement |
  17244. ;; | `hide-sublevels' | overridden | no replacement |
  17245. ;; | `hide-other' | overridden | no replacement |
  17246. ;; Make `C-c C-x' a prefix key
  17247. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17248. ;; TAB key with modifiers
  17249. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17250. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17251. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17252. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17253. ;; The following line is necessary under Suse GNU/Linux
  17254. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17255. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17256. (define-key org-mode-map [backtab] 'org-shifttab)
  17257. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17258. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17259. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17260. ;; Cursor keys with modifiers
  17261. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17262. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17263. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17264. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17265. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17266. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17267. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17268. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17269. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17270. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17271. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17272. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17273. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17274. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17275. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17276. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17277. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17278. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17279. ;; Babel keys
  17280. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17281. (dolist (pair org-babel-key-bindings)
  17282. (define-key org-babel-map (car pair) (cdr pair)))
  17283. ;;; Extra keys for tty access.
  17284. ;; We only set them when really needed because otherwise the
  17285. ;; menus don't show the simple keys
  17286. (when (or org-use-extra-keys (not window-system))
  17287. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17288. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17289. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17290. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17291. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17292. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17293. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17294. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17295. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17296. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17297. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17298. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17299. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17300. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17301. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17302. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17303. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17304. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17305. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17306. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17307. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17308. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17309. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17310. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17311. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17312. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17313. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17314. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17315. ;; All the other keys
  17316. (org-remap org-mode-map
  17317. 'self-insert-command 'org-self-insert-command
  17318. 'delete-char 'org-delete-char
  17319. 'delete-backward-char 'org-delete-backward-char)
  17320. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17321. (org-defkey org-mode-map "\C-c\C-a" 'org-show-all)
  17322. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17323. (if (boundp 'narrow-map)
  17324. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17325. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17326. (if (boundp 'narrow-map)
  17327. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17328. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17329. (if (boundp 'narrow-map)
  17330. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17331. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17332. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17333. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17334. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17335. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17336. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17337. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17338. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17339. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17340. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17341. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17342. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17343. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17344. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17345. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17346. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17347. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17348. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17349. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17350. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17351. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17352. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17353. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17354. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17355. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17356. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17357. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17358. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17359. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17360. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17361. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17362. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17363. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17364. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17365. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17366. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17367. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17368. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17369. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17370. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17371. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17372. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17373. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17374. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17375. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17376. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17377. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17378. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17379. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17380. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17381. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17382. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17383. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17384. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17385. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17386. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17387. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17388. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17389. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17390. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17391. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17392. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17393. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17394. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17395. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17396. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17397. (org-defkey org-mode-map "\C-m" 'org-return)
  17398. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17399. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17400. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17401. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17402. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17403. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17404. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17405. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17406. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17407. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17408. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17409. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17410. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17411. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17412. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17413. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17414. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17415. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17416. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17417. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17418. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17419. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17420. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17421. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17422. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17423. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17424. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17425. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17426. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17427. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17428. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17429. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17430. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17431. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17432. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17433. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17434. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17435. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17436. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17437. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17438. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17439. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17440. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17441. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17442. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17443. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17444. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17445. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17446. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17447. (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
  17448. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17449. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17450. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17451. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17452. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17453. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17454. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17455. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17456. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17457. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17458. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17459. (defconst org-speed-commands-default
  17460. '(
  17461. ("Outline Navigation")
  17462. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17463. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17464. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17465. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17466. ("F" . org-next-block)
  17467. ("B" . org-previous-block)
  17468. ("u" . (org-speed-move-safe 'outline-up-heading))
  17469. ("j" . org-goto)
  17470. ("g" . (org-refile t))
  17471. ("Outline Visibility")
  17472. ("c" . org-cycle)
  17473. ("C" . org-shifttab)
  17474. (" " . org-display-outline-path)
  17475. ("s" . org-narrow-to-subtree)
  17476. ("=" . org-columns)
  17477. ("Outline Structure Editing")
  17478. ("U" . org-metaup)
  17479. ("D" . org-metadown)
  17480. ("r" . org-metaright)
  17481. ("l" . org-metaleft)
  17482. ("R" . org-shiftmetaright)
  17483. ("L" . org-shiftmetaleft)
  17484. ("i" . (progn (forward-char 1) (call-interactively
  17485. 'org-insert-heading-respect-content)))
  17486. ("^" . org-sort)
  17487. ("w" . org-refile)
  17488. ("a" . org-archive-subtree-default-with-confirmation)
  17489. ("@" . org-mark-subtree)
  17490. ("#" . org-toggle-comment)
  17491. ("Clock Commands")
  17492. ("I" . org-clock-in)
  17493. ("O" . org-clock-out)
  17494. ("Meta Data Editing")
  17495. ("t" . org-todo)
  17496. ("," . (org-priority))
  17497. ("0" . (org-priority ?\ ))
  17498. ("1" . (org-priority ?A))
  17499. ("2" . (org-priority ?B))
  17500. ("3" . (org-priority ?C))
  17501. (":" . org-set-tags-command)
  17502. ("e" . org-set-effort)
  17503. ("E" . org-inc-effort)
  17504. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17505. (org-entry-put (point) "APPT_WARNTIME" m)))
  17506. ("Agenda Views etc")
  17507. ("v" . org-agenda)
  17508. ("/" . org-sparse-tree)
  17509. ("Misc")
  17510. ("o" . org-open-at-point)
  17511. ("?" . org-speed-command-help)
  17512. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17513. (">" . (org-agenda-remove-restriction-lock))
  17514. )
  17515. "The default speed commands.")
  17516. (defun org-print-speed-command (e)
  17517. (if (> (length (car e)) 1)
  17518. (progn
  17519. (princ "\n")
  17520. (princ (car e))
  17521. (princ "\n")
  17522. (princ (make-string (length (car e)) ?-))
  17523. (princ "\n"))
  17524. (princ (car e))
  17525. (princ " ")
  17526. (if (symbolp (cdr e))
  17527. (princ (symbol-name (cdr e)))
  17528. (prin1 (cdr e)))
  17529. (princ "\n")))
  17530. (defun org-speed-command-help ()
  17531. "Show the available speed commands."
  17532. (interactive)
  17533. (if (not org-use-speed-commands)
  17534. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17535. (with-output-to-temp-buffer "*Help*"
  17536. (princ "User-defined Speed commands\n===========================\n")
  17537. (mapc #'org-print-speed-command org-speed-commands-user)
  17538. (princ "\n")
  17539. (princ "Built-in Speed commands\n=======================\n")
  17540. (mapc #'org-print-speed-command org-speed-commands-default))
  17541. (with-current-buffer "*Help*"
  17542. (setq truncate-lines t))))
  17543. (defun org-speed-move-safe (cmd)
  17544. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17545. If not, return to the original position and throw an error."
  17546. (interactive)
  17547. (let ((pos (point)))
  17548. (call-interactively cmd)
  17549. (unless (and (bolp) (org-at-heading-p))
  17550. (goto-char pos)
  17551. (error "Boundary reached while executing %s" cmd))))
  17552. (defvar org-self-insert-command-undo-counter 0)
  17553. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17554. (defvar org-speed-command nil)
  17555. (defun org-speed-command-activate (keys)
  17556. "Hook for activating single-letter speed commands.
  17557. `org-speed-commands-default' specifies a minimal command set.
  17558. Use `org-speed-commands-user' for further customization."
  17559. (when (or (and (bolp) (looking-at org-outline-regexp))
  17560. (and (functionp org-use-speed-commands)
  17561. (funcall org-use-speed-commands)))
  17562. (cdr (assoc keys (append org-speed-commands-user
  17563. org-speed-commands-default)))))
  17564. (defun org-babel-speed-command-activate (keys)
  17565. "Hook for activating single-letter code block commands."
  17566. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17567. (cdr (assoc keys org-babel-key-bindings))))
  17568. (defcustom org-speed-command-hook
  17569. '(org-speed-command-activate org-babel-speed-command-activate)
  17570. "Hook for activating speed commands at strategic locations.
  17571. Hook functions are called in sequence until a valid handler is
  17572. found.
  17573. Each hook takes a single argument, a user-pressed command key
  17574. which is also a `self-insert-command' from the global map.
  17575. Within the hook, examine the cursor position and the command key
  17576. and return nil or a valid handler as appropriate. Handler could
  17577. be one of an interactive command, a function, or a form.
  17578. Set `org-use-speed-commands' to non-nil value to enable this
  17579. hook. The default setting is `org-speed-command-activate'."
  17580. :group 'org-structure
  17581. :version "24.1"
  17582. :type 'hook)
  17583. (defun org-self-insert-command (N)
  17584. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17585. If the cursor is in a table looking at whitespace, the whitespace is
  17586. overwritten, and the table is not marked as requiring realignment."
  17587. (interactive "p")
  17588. (org-check-before-invisible-edit 'insert)
  17589. (cond
  17590. ((and org-use-speed-commands
  17591. (let ((kv (this-command-keys-vector)))
  17592. (setq org-speed-command
  17593. (run-hook-with-args-until-success
  17594. 'org-speed-command-hook
  17595. (make-string 1 (aref kv (1- (length kv))))))))
  17596. (cond
  17597. ((commandp org-speed-command)
  17598. (setq this-command org-speed-command)
  17599. (call-interactively org-speed-command))
  17600. ((functionp org-speed-command)
  17601. (funcall org-speed-command))
  17602. ((and org-speed-command (listp org-speed-command))
  17603. (eval org-speed-command))
  17604. (t (let (org-use-speed-commands)
  17605. (call-interactively 'org-self-insert-command)))))
  17606. ((and
  17607. (org-at-table-p)
  17608. (eq N 1)
  17609. (not (org-region-active-p))
  17610. (progn
  17611. ;; Check if we blank the field, and if that triggers align.
  17612. (and (featurep 'org-table) org-table-auto-blank-field
  17613. (memq last-command
  17614. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17615. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17616. ;; Got extra space, this field does not determine
  17617. ;; column width.
  17618. (let (org-table-may-need-update) (org-table-blank-field))
  17619. ;; No extra space, this field may determine column
  17620. ;; width.
  17621. (org-table-blank-field)))
  17622. t)
  17623. (looking-at "[^|\n]* \\( \\)|"))
  17624. ;; There is room for insertion without re-aligning the table.
  17625. (delete-region (match-beginning 1) (match-end 1))
  17626. (self-insert-command N))
  17627. (t
  17628. (setq org-table-may-need-update t)
  17629. (self-insert-command N)
  17630. (org-fix-tags-on-the-fly)
  17631. (when org-self-insert-cluster-for-undo
  17632. (if (not (eq last-command 'org-self-insert-command))
  17633. (setq org-self-insert-command-undo-counter 1)
  17634. (if (>= org-self-insert-command-undo-counter 20)
  17635. (setq org-self-insert-command-undo-counter 1)
  17636. (and (> org-self-insert-command-undo-counter 0)
  17637. buffer-undo-list (listp buffer-undo-list)
  17638. (not (cadr buffer-undo-list)) ; remove nil entry
  17639. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17640. (setq org-self-insert-command-undo-counter
  17641. (1+ org-self-insert-command-undo-counter))))))))
  17642. (defun org-check-before-invisible-edit (kind)
  17643. "Check is editing if kind KIND would be dangerous with invisible text around.
  17644. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17645. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17646. (when (and org-catch-invisible-edits
  17647. (or (not (boundp 'visible-mode)) (not visible-mode))
  17648. (or (get-char-property (point) 'invisible)
  17649. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17650. ;; OK, we need to take a closer look. Do not consider
  17651. ;; invisibility obtained through text properties (e.g., link
  17652. ;; fontification), as it cannot be toggled.
  17653. (let* ((invisible-at-point
  17654. (pcase (get-char-property-and-overlay (point) 'invisible)
  17655. (`(,_ . ,(and (pred overlayp) o)) o)))
  17656. ;; Assume that point cannot land in the middle of an
  17657. ;; overlay, or between two overlays.
  17658. (invisible-before-point
  17659. (and (not invisible-at-point)
  17660. (not (bobp))
  17661. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17662. (`(,_ . ,(and (pred overlayp) o)) o))))
  17663. (border-and-ok-direction
  17664. (or
  17665. ;; Check if we are acting predictably before invisible
  17666. ;; text.
  17667. (and invisible-at-point
  17668. (memq kind '(insert delete-backward)))
  17669. ;; Check if we are acting predictably after invisible text
  17670. ;; This works not well, and I have turned it off. It seems
  17671. ;; better to always show and stop after invisible text.
  17672. ;; (and (not invisible-at-point) invisible-before-point
  17673. ;; (memq kind '(insert delete)))
  17674. )))
  17675. (when (or invisible-at-point invisible-before-point)
  17676. (when (eq org-catch-invisible-edits 'error)
  17677. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17678. (if (and org-custom-properties-overlays
  17679. (y-or-n-p "Display invisible properties in this buffer? "))
  17680. (org-toggle-custom-properties-visibility)
  17681. ;; Make the area visible
  17682. (save-excursion
  17683. (when invisible-before-point
  17684. (goto-char
  17685. (previous-single-char-property-change (point) 'invisible)))
  17686. ;; Remove whatever overlay is currently making yet-to-be
  17687. ;; edited text invisible. Also remove nested invisibility
  17688. ;; related overlays.
  17689. (delete-overlay (or invisible-at-point invisible-before-point))
  17690. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17691. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17692. (`(,_ . ,(and (pred overlayp) o))
  17693. (delete-overlay o)
  17694. t)))))
  17695. (cond
  17696. ((eq org-catch-invisible-edits 'show)
  17697. ;; That's it, we do the edit after showing
  17698. (message
  17699. "Unfolding invisible region around point before editing")
  17700. (sit-for 1))
  17701. ((and (eq org-catch-invisible-edits 'smart)
  17702. border-and-ok-direction)
  17703. (message "Unfolding invisible region around point before editing"))
  17704. (t
  17705. ;; Don't do the edit, make the user repeat it in full visibility
  17706. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17707. (defun org-fix-tags-on-the-fly ()
  17708. "Align tags in headline at point.
  17709. Unlike to `org-set-tags', it ignores region and sorting."
  17710. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17711. (org-at-heading-p))
  17712. (let ((org-ignore-region t)
  17713. (org-tags-sort-function nil))
  17714. (org-set-tags nil t))))
  17715. (defun org-delete-backward-char (N)
  17716. "Like `delete-backward-char', insert whitespace at field end in tables.
  17717. When deleting backwards, in tables this function will insert whitespace in
  17718. front of the next \"|\" separator, to keep the table aligned. The table will
  17719. still be marked for re-alignment if the field did fill the entire column,
  17720. because, in this case the deletion might narrow the column."
  17721. (interactive "p")
  17722. (save-match-data
  17723. (org-check-before-invisible-edit 'delete-backward)
  17724. (if (and (org-at-table-p)
  17725. (eq N 1)
  17726. (not (org-region-active-p))
  17727. (string-match "|" (buffer-substring (point-at-bol) (point)))
  17728. (looking-at ".*?|"))
  17729. (let ((pos (point))
  17730. (noalign (looking-at "[^|\n\r]* |"))
  17731. (c org-table-may-need-update))
  17732. (backward-delete-char N)
  17733. (unless overwrite-mode
  17734. (skip-chars-forward "^|")
  17735. (insert " ")
  17736. (goto-char (1- pos)))
  17737. ;; noalign: if there were two spaces at the end, this field
  17738. ;; does not determine the width of the column.
  17739. (when noalign (setq org-table-may-need-update c)))
  17740. (backward-delete-char N)
  17741. (org-fix-tags-on-the-fly))))
  17742. (defun org-delete-char (N)
  17743. "Like `delete-char', but insert whitespace at field end in tables.
  17744. When deleting characters, in tables this function will insert whitespace in
  17745. front of the next \"|\" separator, to keep the table aligned. The table will
  17746. still be marked for re-alignment if the field did fill the entire column,
  17747. because, in this case the deletion might narrow the column."
  17748. (interactive "p")
  17749. (save-match-data
  17750. (org-check-before-invisible-edit 'delete)
  17751. (if (and (org-at-table-p)
  17752. (not (bolp))
  17753. (not (= (char-after) ?|))
  17754. (eq N 1))
  17755. (if (looking-at ".*?|")
  17756. (let ((pos (point))
  17757. (noalign (looking-at "[^|\n\r]* |"))
  17758. (c org-table-may-need-update))
  17759. (replace-match
  17760. (concat (substring (match-string 0) 1 -1) " |") nil t)
  17761. (goto-char pos)
  17762. ;; noalign: if there were two spaces at the end, this field
  17763. ;; does not determine the width of the column.
  17764. (when noalign (setq org-table-may-need-update c)))
  17765. (delete-char N))
  17766. (delete-char N)
  17767. (org-fix-tags-on-the-fly))))
  17768. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17769. (put 'org-self-insert-command 'delete-selection
  17770. (lambda ()
  17771. (not (run-hook-with-args-until-success
  17772. 'self-insert-uses-region-functions))))
  17773. (put 'orgtbl-self-insert-command 'delete-selection
  17774. (lambda ()
  17775. (not (run-hook-with-args-until-success
  17776. 'self-insert-uses-region-functions))))
  17777. (put 'org-delete-char 'delete-selection 'supersede)
  17778. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17779. (put 'org-yank 'delete-selection 'yank)
  17780. ;; Make `flyspell-mode' delay after some commands
  17781. (put 'org-self-insert-command 'flyspell-delayed t)
  17782. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17783. (put 'org-delete-char 'flyspell-delayed t)
  17784. (put 'org-delete-backward-char 'flyspell-delayed t)
  17785. ;; Make pabbrev-mode expand after Org mode commands
  17786. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17787. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17788. (defun org-transpose-words ()
  17789. "Transpose words for Org.
  17790. This uses the `org-mode-transpose-word-syntax-table' syntax
  17791. table, which interprets characters in `org-emphasis-alist' as
  17792. word constituents."
  17793. (interactive)
  17794. (with-syntax-table org-mode-transpose-word-syntax-table
  17795. (call-interactively 'transpose-words)))
  17796. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  17797. (defvar org-ctrl-c-ctrl-c-hook nil
  17798. "Hook for functions attaching themselves to `C-c C-c'.
  17799. This can be used to add additional functionality to the C-c C-c
  17800. key which executes context-dependent commands. This hook is run
  17801. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17802. run after the last test.
  17803. Each function will be called with no arguments. The function
  17804. must check if the context is appropriate for it to act. If yes,
  17805. it should do its thing and then return a non-nil value. If the
  17806. context is wrong, just do nothing and return nil.")
  17807. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17808. "Hook for functions attaching themselves to `C-c C-c'.
  17809. This can be used to add additional functionality to the C-c C-c
  17810. key which executes context-dependent commands. This hook is run
  17811. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17812. before the first test.
  17813. Each function will be called with no arguments. The function
  17814. must check if the context is appropriate for it to act. If yes,
  17815. it should do its thing and then return a non-nil value. If the
  17816. context is wrong, just do nothing and return nil.")
  17817. (defvar org-tab-first-hook nil
  17818. "Hook for functions to attach themselves to TAB.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.
  17820. This hook runs as the first action when TAB is pressed, even before
  17821. `org-cycle' messes around with the `outline-regexp' to cater for
  17822. inline tasks and plain list item folding.
  17823. If any function in this hook returns t, any other actions that
  17824. would have been caused by TAB (such as table field motion or visibility
  17825. cycling) will not occur.")
  17826. (defvar org-tab-after-check-for-table-hook nil
  17827. "Hook for functions to attach themselves to TAB.
  17828. See `org-ctrl-c-ctrl-c-hook' for more information.
  17829. This hook runs after it has been established that the cursor is not in a
  17830. table, but before checking if the cursor is in a headline or if global cycling
  17831. should be done.
  17832. If any function in this hook returns t, not other actions like visibility
  17833. cycling will be done.")
  17834. (defvar org-tab-after-check-for-cycling-hook nil
  17835. "Hook for functions to attach themselves to TAB.
  17836. See `org-ctrl-c-ctrl-c-hook' for more information.
  17837. This hook runs after it has been established that not table field motion and
  17838. not visibility should be done because of current context. This is probably
  17839. the place where a package like yasnippets can hook in.")
  17840. (defvar org-tab-before-tab-emulation-hook nil
  17841. "Hook for functions to attach themselves to TAB.
  17842. See `org-ctrl-c-ctrl-c-hook' for more information.
  17843. This hook runs after every other options for TAB have been exhausted, but
  17844. before indentation and \t insertion takes place.")
  17845. (defvar org-metaleft-hook nil
  17846. "Hook for functions attaching themselves to `M-left'.
  17847. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17848. (defvar org-metaright-hook nil
  17849. "Hook for functions attaching themselves to `M-right'.
  17850. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17851. (defvar org-metaup-hook nil
  17852. "Hook for functions attaching themselves to `M-up'.
  17853. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17854. (defvar org-metadown-hook nil
  17855. "Hook for functions attaching themselves to `M-down'.
  17856. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17857. (defvar org-shiftmetaleft-hook nil
  17858. "Hook for functions attaching themselves to `M-S-left'.
  17859. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17860. (defvar org-shiftmetaright-hook nil
  17861. "Hook for functions attaching themselves to `M-S-right'.
  17862. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17863. (defvar org-shiftmetaup-hook nil
  17864. "Hook for functions attaching themselves to `M-S-up'.
  17865. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17866. (defvar org-shiftmetadown-hook nil
  17867. "Hook for functions attaching themselves to `M-S-down'.
  17868. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17869. (defvar org-metareturn-hook nil
  17870. "Hook for functions attaching themselves to `M-RET'.
  17871. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17872. (defvar org-shiftup-hook nil
  17873. "Hook for functions attaching themselves to `S-up'.
  17874. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17875. (defvar org-shiftup-final-hook nil
  17876. "Hook for functions attaching themselves to `S-up'.
  17877. This one runs after all other options except shift-select have been excluded.
  17878. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17879. (defvar org-shiftdown-hook nil
  17880. "Hook for functions attaching themselves to `S-down'.
  17881. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17882. (defvar org-shiftdown-final-hook nil
  17883. "Hook for functions attaching themselves to `S-down'.
  17884. This one runs after all other options except shift-select have been excluded.
  17885. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17886. (defvar org-shiftleft-hook nil
  17887. "Hook for functions attaching themselves to `S-left'.
  17888. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17889. (defvar org-shiftleft-final-hook nil
  17890. "Hook for functions attaching themselves to `S-left'.
  17891. This one runs after all other options except shift-select have been excluded.
  17892. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17893. (defvar org-shiftright-hook nil
  17894. "Hook for functions attaching themselves to `S-right'.
  17895. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17896. (defvar org-shiftright-final-hook nil
  17897. "Hook for functions attaching themselves to `S-right'.
  17898. This one runs after all other options except shift-select have been excluded.
  17899. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17900. (defun org-modifier-cursor-error ()
  17901. "Throw an error, a modified cursor command was applied in wrong context."
  17902. (user-error "This command is active in special context like tables, headlines or items"))
  17903. (defun org-shiftselect-error ()
  17904. "Throw an error because Shift-Cursor command was applied in wrong context."
  17905. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17906. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17907. (user-error "This command works only in special context like headlines or timestamps")))
  17908. (defun org-call-for-shift-select (cmd)
  17909. (let ((this-command-keys-shift-translated t))
  17910. (call-interactively cmd)))
  17911. (defun org-shifttab (&optional arg)
  17912. "Global visibility cycling or move to previous table field.
  17913. Call `org-table-previous-field' within a table.
  17914. When ARG is nil, cycle globally through visibility states.
  17915. When ARG is a numeric prefix, show contents of this level."
  17916. (interactive "P")
  17917. (cond
  17918. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17919. ((integerp arg)
  17920. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17921. (message "Content view to level: %d" arg)
  17922. (org-content (prefix-numeric-value arg2))
  17923. (org-cycle-show-empty-lines t)
  17924. (setq org-cycle-global-status 'overview)))
  17925. (t (call-interactively 'org-global-cycle))))
  17926. (defun org-shiftmetaleft ()
  17927. "Promote subtree or delete table column.
  17928. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17929. `org-table-delete-column', depending on context. See the
  17930. individual commands for more information."
  17931. (interactive)
  17932. (cond
  17933. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17934. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17935. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17936. ((if (not (org-region-active-p)) (org-at-item-p)
  17937. (save-excursion (goto-char (region-beginning))
  17938. (org-at-item-p)))
  17939. (call-interactively 'org-outdent-item-tree))
  17940. (t (org-modifier-cursor-error))))
  17941. (defun org-shiftmetaright ()
  17942. "Demote subtree or insert table column.
  17943. Calls `org-demote-subtree', `org-indent-item-tree', or
  17944. `org-table-insert-column', depending on context. See the
  17945. individual commands for more information."
  17946. (interactive)
  17947. (cond
  17948. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17949. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17950. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17951. ((if (not (org-region-active-p)) (org-at-item-p)
  17952. (save-excursion (goto-char (region-beginning))
  17953. (org-at-item-p)))
  17954. (call-interactively 'org-indent-item-tree))
  17955. (t (org-modifier-cursor-error))))
  17956. (defun org-shiftmetaup (&optional _arg)
  17957. "Drag the line at point up.
  17958. In a table, kill the current row.
  17959. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17960. but also adjust the previous clocked item in the clock history.
  17961. Everywhere else, drag the line at point up."
  17962. (interactive "P")
  17963. (cond
  17964. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17965. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17966. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17967. (call-interactively 'org-timestamp-up)))
  17968. (t (call-interactively 'org-drag-line-backward))))
  17969. (defun org-shiftmetadown (&optional _arg)
  17970. "Drag the line at point down.
  17971. In a table, insert an empty row at the current line.
  17972. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17973. but also adjust the previous clocked item in the clock history.
  17974. Everywhere else, drag the line at point down."
  17975. (interactive "P")
  17976. (cond
  17977. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17978. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17979. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17980. (call-interactively 'org-timestamp-down)))
  17981. (t (call-interactively 'org-drag-line-forward))))
  17982. (defsubst org-hidden-tree-error ()
  17983. (user-error
  17984. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17985. (defun org-metaleft (&optional _arg)
  17986. "Promote heading, list item at point or move table column left.
  17987. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17988. depending on context. With no specific context, calls the Emacs
  17989. default `backward-word'. See the individual commands for more
  17990. information.
  17991. This function runs the hook `org-metaleft-hook' as a first step,
  17992. and returns at first non-nil value."
  17993. (interactive "P")
  17994. (cond
  17995. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17996. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17997. ((org-with-limited-levels
  17998. (or (org-at-heading-p)
  17999. (and (org-region-active-p)
  18000. (save-excursion
  18001. (goto-char (region-beginning))
  18002. (org-at-heading-p)))))
  18003. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18004. (call-interactively 'org-do-promote))
  18005. ;; At an inline task.
  18006. ((org-at-heading-p)
  18007. (call-interactively 'org-inlinetask-promote))
  18008. ((or (org-at-item-p)
  18009. (and (org-region-active-p)
  18010. (save-excursion
  18011. (goto-char (region-beginning))
  18012. (org-at-item-p))))
  18013. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18014. (call-interactively 'org-outdent-item))
  18015. (t (call-interactively 'backward-word))))
  18016. (defun org-metaright (&optional _arg)
  18017. "Demote heading, list item at point or move table column right.
  18018. In front of a drawer or a block keyword, indent it correctly.
  18019. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18020. `org-indent-drawer' or `org-indent-block' depending on context.
  18021. With no specific context, calls the Emacs default `forward-word'.
  18022. See the individual commands for more information.
  18023. This function runs the hook `org-metaright-hook' as a first step,
  18024. and returns at first non-nil value."
  18025. (interactive "P")
  18026. (cond
  18027. ((run-hook-with-args-until-success 'org-metaright-hook))
  18028. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18029. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18030. ((org-at-block-p) (call-interactively 'org-indent-block))
  18031. ((org-with-limited-levels
  18032. (or (org-at-heading-p)
  18033. (and (org-region-active-p)
  18034. (save-excursion
  18035. (goto-char (region-beginning))
  18036. (org-at-heading-p)))))
  18037. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18038. (call-interactively 'org-do-demote))
  18039. ;; At an inline task.
  18040. ((org-at-heading-p)
  18041. (call-interactively 'org-inlinetask-demote))
  18042. ((or (org-at-item-p)
  18043. (and (org-region-active-p)
  18044. (save-excursion
  18045. (goto-char (region-beginning))
  18046. (org-at-item-p))))
  18047. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18048. (call-interactively 'org-indent-item))
  18049. (t (call-interactively 'forward-word))))
  18050. (defun org-check-for-hidden (what)
  18051. "Check if there are hidden headlines/items in the current visual line.
  18052. WHAT can be either `headlines' or `items'. If the current line is
  18053. an outline or item heading and it has a folded subtree below it,
  18054. this function returns t, nil otherwise."
  18055. (let ((re (cond
  18056. ((eq what 'headlines) org-outline-regexp-bol)
  18057. ((eq what 'items) (org-item-beginning-re))
  18058. (t (error "This should not happen"))))
  18059. beg end)
  18060. (save-excursion
  18061. (catch 'exit
  18062. (unless (org-region-active-p)
  18063. (setq beg (point-at-bol))
  18064. (beginning-of-line 2)
  18065. (while (and (not (eobp)) ;; this is like `next-line'
  18066. (get-char-property (1- (point)) 'invisible))
  18067. (beginning-of-line 2))
  18068. (setq end (point))
  18069. (goto-char beg)
  18070. (goto-char (point-at-eol))
  18071. (setq end (max end (point)))
  18072. (while (re-search-forward re end t)
  18073. (when (get-char-property (match-beginning 0) 'invisible)
  18074. (throw 'exit t))))
  18075. nil))))
  18076. (defun org-metaup (&optional _arg)
  18077. "Move subtree up or move table row up.
  18078. Calls `org-move-subtree-up' or `org-table-move-row' or
  18079. `org-move-item-up', depending on context. See the individual commands
  18080. for more information."
  18081. (interactive "P")
  18082. (cond
  18083. ((run-hook-with-args-until-success 'org-metaup-hook))
  18084. ((org-region-active-p)
  18085. (let* ((a (min (region-beginning) (region-end)))
  18086. (b (1- (max (region-beginning) (region-end))))
  18087. (c (save-excursion (goto-char a)
  18088. (move-beginning-of-line 0)))
  18089. (d (save-excursion (goto-char a)
  18090. (move-end-of-line 0) (point))))
  18091. (transpose-regions a b c d)
  18092. (goto-char c)))
  18093. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18094. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18095. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18096. (t (org-drag-element-backward))))
  18097. (defun org-metadown (&optional _arg)
  18098. "Move subtree down or move table row down.
  18099. Calls `org-move-subtree-down' or `org-table-move-row' or
  18100. `org-move-item-down', depending on context. See the individual
  18101. commands for more information."
  18102. (interactive "P")
  18103. (cond
  18104. ((run-hook-with-args-until-success 'org-metadown-hook))
  18105. ((org-region-active-p)
  18106. (let* ((a (min (region-beginning) (region-end)))
  18107. (b (max (region-beginning) (region-end)))
  18108. (c (save-excursion (goto-char b)
  18109. (move-beginning-of-line 1)))
  18110. (d (save-excursion (goto-char b)
  18111. (move-end-of-line 1) (1+ (point)))))
  18112. (transpose-regions a b c d)
  18113. (goto-char d)))
  18114. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18115. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18116. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18117. (t (org-drag-element-forward))))
  18118. (defun org-shiftup (&optional arg)
  18119. "Increase item in timestamp or increase priority of current headline.
  18120. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18121. depending on context. See the individual commands for more information."
  18122. (interactive "P")
  18123. (cond
  18124. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18125. ((and org-support-shift-select (org-region-active-p))
  18126. (org-call-for-shift-select 'previous-line))
  18127. ((org-at-timestamp-p 'lax)
  18128. (call-interactively (if org-edit-timestamp-down-means-later
  18129. 'org-timestamp-down 'org-timestamp-up)))
  18130. ((and (not (eq org-support-shift-select 'always))
  18131. org-enable-priority-commands
  18132. (org-at-heading-p))
  18133. (call-interactively 'org-priority-up))
  18134. ((and (not org-support-shift-select) (org-at-item-p))
  18135. (call-interactively 'org-previous-item))
  18136. ((org-clocktable-try-shift 'up arg))
  18137. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18138. (org-support-shift-select
  18139. (org-call-for-shift-select 'previous-line))
  18140. (t (org-shiftselect-error))))
  18141. (defun org-shiftdown (&optional arg)
  18142. "Decrease item in timestamp or decrease priority of current headline.
  18143. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18144. depending on context. See the individual commands for more information."
  18145. (interactive "P")
  18146. (cond
  18147. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18148. ((and org-support-shift-select (org-region-active-p))
  18149. (org-call-for-shift-select 'next-line))
  18150. ((org-at-timestamp-p 'lax)
  18151. (call-interactively (if org-edit-timestamp-down-means-later
  18152. 'org-timestamp-up 'org-timestamp-down)))
  18153. ((and (not (eq org-support-shift-select 'always))
  18154. org-enable-priority-commands
  18155. (org-at-heading-p))
  18156. (call-interactively 'org-priority-down))
  18157. ((and (not org-support-shift-select) (org-at-item-p))
  18158. (call-interactively 'org-next-item))
  18159. ((org-clocktable-try-shift 'down arg))
  18160. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18161. (org-support-shift-select
  18162. (org-call-for-shift-select 'next-line))
  18163. (t (org-shiftselect-error))))
  18164. (defun org-shiftright (&optional arg)
  18165. "Cycle the thing at point or in the current line, depending on context.
  18166. Depending on context, this does one of the following:
  18167. - switch a timestamp at point one day into the future
  18168. - on a headline, switch to the next TODO keyword.
  18169. - on an item, switch entire list to the next bullet type
  18170. - on a property line, switch to the next allowed value
  18171. - on a clocktable definition line, move time block into the future"
  18172. (interactive "P")
  18173. (cond
  18174. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18175. ((and org-support-shift-select (org-region-active-p))
  18176. (org-call-for-shift-select 'forward-char))
  18177. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18178. ((and (not (eq org-support-shift-select 'always))
  18179. (org-at-heading-p))
  18180. (let ((org-inhibit-logging
  18181. (not org-treat-S-cursor-todo-selection-as-state-change))
  18182. (org-inhibit-blocking
  18183. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18184. (org-call-with-arg 'org-todo 'right)))
  18185. ((or (and org-support-shift-select
  18186. (not (eq org-support-shift-select 'always))
  18187. (org-at-item-bullet-p))
  18188. (and (not org-support-shift-select) (org-at-item-p)))
  18189. (org-call-with-arg 'org-cycle-list-bullet nil))
  18190. ((and (not (eq org-support-shift-select 'always))
  18191. (org-at-property-p))
  18192. (call-interactively 'org-property-next-allowed-value))
  18193. ((org-clocktable-try-shift 'right arg))
  18194. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18195. (org-support-shift-select
  18196. (org-call-for-shift-select 'forward-char))
  18197. (t (org-shiftselect-error))))
  18198. (defun org-shiftleft (&optional arg)
  18199. "Cycle the thing at point or in the current line, depending on context.
  18200. Depending on context, this does one of the following:
  18201. - switch a timestamp at point one day into the past
  18202. - on a headline, switch to the previous TODO keyword.
  18203. - on an item, switch entire list to the previous bullet type
  18204. - on a property line, switch to the previous allowed value
  18205. - on a clocktable definition line, move time block into the past"
  18206. (interactive "P")
  18207. (cond
  18208. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18209. ((and org-support-shift-select (org-region-active-p))
  18210. (org-call-for-shift-select 'backward-char))
  18211. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18212. ((and (not (eq org-support-shift-select 'always))
  18213. (org-at-heading-p))
  18214. (let ((org-inhibit-logging
  18215. (not org-treat-S-cursor-todo-selection-as-state-change))
  18216. (org-inhibit-blocking
  18217. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18218. (org-call-with-arg 'org-todo 'left)))
  18219. ((or (and org-support-shift-select
  18220. (not (eq org-support-shift-select 'always))
  18221. (org-at-item-bullet-p))
  18222. (and (not org-support-shift-select) (org-at-item-p)))
  18223. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18224. ((and (not (eq org-support-shift-select 'always))
  18225. (org-at-property-p))
  18226. (call-interactively 'org-property-previous-allowed-value))
  18227. ((org-clocktable-try-shift 'left arg))
  18228. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18229. (org-support-shift-select
  18230. (org-call-for-shift-select 'backward-char))
  18231. (t (org-shiftselect-error))))
  18232. (defun org-shiftcontrolright ()
  18233. "Switch to next TODO set."
  18234. (interactive)
  18235. (cond
  18236. ((and org-support-shift-select (org-region-active-p))
  18237. (org-call-for-shift-select 'forward-word))
  18238. ((and (not (eq org-support-shift-select 'always))
  18239. (org-at-heading-p))
  18240. (org-call-with-arg 'org-todo 'nextset))
  18241. (org-support-shift-select
  18242. (org-call-for-shift-select 'forward-word))
  18243. (t (org-shiftselect-error))))
  18244. (defun org-shiftcontrolleft ()
  18245. "Switch to previous TODO set."
  18246. (interactive)
  18247. (cond
  18248. ((and org-support-shift-select (org-region-active-p))
  18249. (org-call-for-shift-select 'backward-word))
  18250. ((and (not (eq org-support-shift-select 'always))
  18251. (org-at-heading-p))
  18252. (org-call-with-arg 'org-todo 'previousset))
  18253. (org-support-shift-select
  18254. (org-call-for-shift-select 'backward-word))
  18255. (t (org-shiftselect-error))))
  18256. (defun org-shiftcontrolup (&optional n)
  18257. "Change timestamps synchronously up in CLOCK log lines.
  18258. Optional argument N tells to change by that many units."
  18259. (interactive "P")
  18260. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18261. (let (org-support-shift-select)
  18262. (org-clock-timestamps-up n))
  18263. (user-error "Not at a clock log")))
  18264. (defun org-shiftcontroldown (&optional n)
  18265. "Change timestamps synchronously down in CLOCK log lines.
  18266. Optional argument N tells to change by that many units."
  18267. (interactive "P")
  18268. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18269. (let (org-support-shift-select)
  18270. (org-clock-timestamps-down n))
  18271. (user-error "Not at a clock log")))
  18272. (defun org-increase-number-at-point (&optional inc)
  18273. "Increment the number at point.
  18274. With an optional prefix numeric argument INC, increment using
  18275. this numeric value."
  18276. (interactive "p")
  18277. (if (not (number-at-point))
  18278. (user-error "Not on a number")
  18279. (unless inc (setq inc 1))
  18280. (let ((pos (point))
  18281. (beg (skip-chars-backward "-+^/*0-9eE."))
  18282. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18283. (setq nap (buffer-substring-no-properties
  18284. (+ pos beg) (+ pos beg end)))
  18285. (delete-region (+ pos beg) (+ pos beg end))
  18286. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18287. (when (org-at-table-p)
  18288. (org-table-align)
  18289. (org-table-end-of-field 1))))
  18290. (defun org-decrease-number-at-point (&optional inc)
  18291. "Decrement the number at point.
  18292. With an optional prefix numeric argument INC, decrement using
  18293. this numeric value."
  18294. (interactive "p")
  18295. (org-increase-number-at-point (- (or inc 1))))
  18296. (defun org-ctrl-c-ret ()
  18297. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18298. (interactive)
  18299. (cond
  18300. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18301. (t (call-interactively 'org-insert-heading))))
  18302. (defun org-find-visible ()
  18303. (let ((s (point)))
  18304. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18305. (get-char-property s 'invisible)))
  18306. s))
  18307. (defun org-find-invisible ()
  18308. (let ((s (point)))
  18309. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18310. (not (get-char-property s 'invisible))))
  18311. s))
  18312. (defun org-copy-visible (beg end)
  18313. "Copy the visible parts of the region."
  18314. (interactive "r")
  18315. (let ((result ""))
  18316. (while (/= beg end)
  18317. (when (get-char-property beg 'invisible)
  18318. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18319. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18320. (setq result (concat result (buffer-substring beg next)))
  18321. (setq beg next)))
  18322. (kill-new result)))
  18323. (defun org-copy-special ()
  18324. "Copy region in table or copy current subtree.
  18325. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18326. context. See the individual commands for more information."
  18327. (interactive)
  18328. (call-interactively
  18329. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18330. (defun org-cut-special ()
  18331. "Cut region in table or cut current subtree.
  18332. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18333. context. See the individual commands for more information."
  18334. (interactive)
  18335. (call-interactively
  18336. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18337. (defun org-paste-special (arg)
  18338. "Paste rectangular region into table, or past subtree relative to level.
  18339. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18340. See the individual commands for more information."
  18341. (interactive "P")
  18342. (if (org-at-table-p)
  18343. (org-table-paste-rectangle)
  18344. (org-paste-subtree arg)))
  18345. (defun org-edit-special (&optional arg)
  18346. "Call a special editor for the element at point.
  18347. When at a table, call the formula editor with `org-table-edit-formulas'.
  18348. When in a source code block, call `org-edit-src-code'.
  18349. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18350. When in an export block, call `org-edit-export-block'.
  18351. When in a LaTeX environment, call `org-edit-latex-environment'.
  18352. When at an #+INCLUDE keyword, visit the included file.
  18353. When at a footnote reference, call `org-edit-footnote-reference'
  18354. On a link, call `ffap' to visit the link at point.
  18355. Otherwise, return a user error."
  18356. (interactive "P")
  18357. (let ((element (org-element-at-point)))
  18358. (barf-if-buffer-read-only)
  18359. (pcase (org-element-type element)
  18360. (`src-block
  18361. (if (not arg) (org-edit-src-code)
  18362. (let* ((info (org-babel-get-src-block-info))
  18363. (lang (nth 0 info))
  18364. (params (nth 2 info))
  18365. (session (cdr (assq :session params))))
  18366. (if (not session) (org-edit-src-code)
  18367. ;; At a src-block with a session and function called with
  18368. ;; an ARG: switch to the buffer related to the inferior
  18369. ;; process.
  18370. (switch-to-buffer
  18371. (funcall (intern (concat "org-babel-prep-session:" lang))
  18372. session params))))))
  18373. (`keyword
  18374. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18375. (org-open-link-from-string
  18376. (format "[[%s]]"
  18377. (expand-file-name
  18378. (let ((value (org-element-property :value element)))
  18379. (cond ((org-file-url-p value)
  18380. (user-error "The file is specified as a URL, cannot be edited"))
  18381. ((not (org-string-nw-p value))
  18382. (user-error "No file to edit"))
  18383. ((string-match "\\`\"\\(.*?\\)\"" value)
  18384. (match-string 1 value))
  18385. ((string-match "\\`[^ \t\"]\\S-*" value)
  18386. (match-string 0 value))
  18387. (t (user-error "No valid file specified")))))))
  18388. (user-error "No special environment to edit here")))
  18389. (`table
  18390. (if (eq (org-element-property :type element) 'table.el)
  18391. (org-edit-table.el)
  18392. (call-interactively 'org-table-edit-formulas)))
  18393. ;; Only Org tables contain `table-row' type elements.
  18394. (`table-row (call-interactively 'org-table-edit-formulas))
  18395. (`example-block (org-edit-src-code))
  18396. (`export-block (org-edit-export-block))
  18397. (`fixed-width (org-edit-fixed-width-region))
  18398. (`latex-environment (org-edit-latex-environment))
  18399. (_
  18400. ;; No notable element at point. Though, we may be at a link or
  18401. ;; a footnote reference, which are objects. Thus, scan deeper.
  18402. (let ((context (org-element-context element)))
  18403. (pcase (org-element-type context)
  18404. (`footnote-reference (org-edit-footnote-reference))
  18405. (`inline-src-block (org-edit-inline-src-code))
  18406. (`link (call-interactively #'ffap))
  18407. (_ (user-error "No special environment to edit here"))))))))
  18408. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18409. (defun org-ctrl-c-ctrl-c (&optional arg)
  18410. "Set tags in headline, or update according to changed information at point.
  18411. This command does many different things, depending on context:
  18412. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18413. this is what we do.
  18414. - If the cursor is on a statistics cookie, update it.
  18415. - If the cursor is in a headline, prompt for tags and insert them
  18416. into the current line, aligned to `org-tags-column'. When called
  18417. with prefix arg, realign all tags in the current buffer.
  18418. - If the cursor is in one of the special #+KEYWORD lines, this
  18419. triggers scanning the buffer for these lines and updating the
  18420. information.
  18421. - If the cursor is inside a table, realign the table. This command
  18422. works even if the automatic table editor has been turned off.
  18423. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18424. the entire table.
  18425. - If the cursor is at a footnote reference or definition, jump to
  18426. the corresponding definition or references, respectively.
  18427. - If the cursor is a the beginning of a dynamic block, update it.
  18428. - If the current buffer is a capture buffer, close note and file it.
  18429. - If the cursor is on a <<<target>>>, update radio targets and
  18430. corresponding links in this buffer.
  18431. - If the cursor is on a numbered item in a plain list, renumber the
  18432. ordered list.
  18433. - If the cursor is on a checkbox, toggle it.
  18434. - If the cursor is on a code block, evaluate it. The variable
  18435. `org-confirm-babel-evaluate' can be used to control prompting
  18436. before code block evaluation, by default every code block
  18437. evaluation requires confirmation. Code block evaluation can be
  18438. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18439. (interactive "P")
  18440. (cond
  18441. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18442. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18443. (org-remove-occur-highlights)
  18444. (message "Temporary highlights/overlays removed from current buffer"))
  18445. ((and (local-variable-p 'org-finish-function)
  18446. (fboundp org-finish-function))
  18447. (funcall org-finish-function))
  18448. ((org-babel-hash-at-point))
  18449. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18450. (t
  18451. (let* ((context
  18452. (org-element-lineage
  18453. (org-element-context)
  18454. ;; Limit to supported contexts.
  18455. '(babel-call clock dynamic-block footnote-definition
  18456. footnote-reference inline-babel-call inline-src-block
  18457. inlinetask item keyword node-property paragraph
  18458. plain-list planning property-drawer radio-target
  18459. src-block statistics-cookie table table-cell table-row
  18460. timestamp)
  18461. t))
  18462. (type (org-element-type context)))
  18463. ;; For convenience: at the first line of a paragraph on the same
  18464. ;; line as an item, apply function on that item instead.
  18465. (when (eq type 'paragraph)
  18466. (let ((parent (org-element-property :parent context)))
  18467. (when (and (eq (org-element-type parent) 'item)
  18468. (= (line-beginning-position)
  18469. (org-element-property :begin parent)))
  18470. (setq context parent)
  18471. (setq type 'item))))
  18472. ;; Act according to type of element or object at point.
  18473. ;;
  18474. ;; Do nothing on a blank line, except if it is contained in
  18475. ;; a src block. Hence, we first check if point is in such
  18476. ;; a block and then if it is at a blank line.
  18477. (pcase type
  18478. ((or `inline-src-block `src-block)
  18479. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18480. (org-babel-eval-wipe-error-buffer)
  18481. (org-babel-execute-src-block
  18482. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18483. ((guard (org-match-line "[ \t]*$"))
  18484. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18485. (user-error
  18486. (substitute-command-keys
  18487. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18488. ((or `babel-call `inline-babel-call)
  18489. (let ((info (org-babel-lob-get-info context)))
  18490. (when info (org-babel-execute-src-block nil info))))
  18491. (`clock (org-clock-update-time-maybe))
  18492. (`dynamic-block
  18493. (save-excursion
  18494. (goto-char (org-element-property :post-affiliated context))
  18495. (org-update-dblock)))
  18496. (`footnote-definition
  18497. (goto-char (org-element-property :post-affiliated context))
  18498. (call-interactively 'org-footnote-action))
  18499. (`footnote-reference (call-interactively #'org-footnote-action))
  18500. ((or `headline `inlinetask)
  18501. (save-excursion (goto-char (org-element-property :begin context))
  18502. (call-interactively #'org-set-tags)))
  18503. (`item
  18504. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18505. ;; unconditionally, whereas `C-u' will toggle its presence.
  18506. ;; Without a universal argument, if the item has a checkbox,
  18507. ;; toggle it. Otherwise repair the list.
  18508. (let* ((box (org-element-property :checkbox context))
  18509. (struct (org-element-property :structure context))
  18510. (old-struct (copy-tree struct))
  18511. (parents (org-list-parents-alist struct))
  18512. (prevs (org-list-prevs-alist struct))
  18513. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18514. (org-list-set-checkbox
  18515. (org-element-property :begin context) struct
  18516. (cond ((equal arg '(16)) "[-]")
  18517. ((and (not box) (equal arg '(4))) "[ ]")
  18518. ((or (not box) (equal arg '(4))) nil)
  18519. ((eq box 'on) "[ ]")
  18520. (t "[X]")))
  18521. ;; Mimic `org-list-write-struct' but with grabbing a return
  18522. ;; value from `org-list-struct-fix-box'.
  18523. (org-list-struct-fix-ind struct parents 2)
  18524. (org-list-struct-fix-item-end struct)
  18525. (org-list-struct-fix-bul struct prevs)
  18526. (org-list-struct-fix-ind struct parents)
  18527. (let ((block-item
  18528. (org-list-struct-fix-box struct parents prevs orderedp)))
  18529. (if (and box (equal struct old-struct))
  18530. (if (equal arg '(16))
  18531. (message "Checkboxes already reset")
  18532. (user-error "Cannot toggle this checkbox: %s"
  18533. (if (eq box 'on)
  18534. "all subitems checked"
  18535. "unchecked subitems")))
  18536. (org-list-struct-apply-struct struct old-struct)
  18537. (org-update-checkbox-count-maybe))
  18538. (when block-item
  18539. (message "Checkboxes were removed due to empty box at line %d"
  18540. (org-current-line block-item))))))
  18541. (`keyword
  18542. (let ((org-inhibit-startup-visibility-stuff t)
  18543. (org-startup-align-all-tables nil))
  18544. (when (boundp 'org-table-coordinate-overlays)
  18545. (mapc #'delete-overlay org-table-coordinate-overlays)
  18546. (setq org-table-coordinate-overlays nil))
  18547. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18548. (message "Local setup has been refreshed"))
  18549. (`plain-list
  18550. ;; At a plain list, with a double C-u argument, set
  18551. ;; checkboxes of each item to "[-]", whereas a single one
  18552. ;; will toggle their presence according to the state of the
  18553. ;; first item in the list. Without an argument, repair the
  18554. ;; list.
  18555. (let* ((begin (org-element-property :contents-begin context))
  18556. (struct (org-element-property :structure context))
  18557. (old-struct (copy-tree struct))
  18558. (first-box (save-excursion
  18559. (goto-char begin)
  18560. (looking-at org-list-full-item-re)
  18561. (match-string-no-properties 3)))
  18562. (new-box (cond ((equal arg '(16)) "[-]")
  18563. ((equal arg '(4)) (unless first-box "[ ]"))
  18564. ((equal first-box "[X]") "[ ]")
  18565. (t "[X]"))))
  18566. (cond
  18567. (arg
  18568. (dolist (pos
  18569. (org-list-get-all-items
  18570. begin struct (org-list-prevs-alist struct)))
  18571. (org-list-set-checkbox pos struct new-box)))
  18572. ((and first-box (eq (point) begin))
  18573. ;; For convenience, when point is at bol on the first
  18574. ;; item of the list and no argument is provided, simply
  18575. ;; toggle checkbox of that item, if any.
  18576. (org-list-set-checkbox begin struct new-box)))
  18577. (org-list-write-struct
  18578. struct (org-list-parents-alist struct) old-struct)
  18579. (org-update-checkbox-count-maybe)))
  18580. ((or `property-drawer `node-property)
  18581. (call-interactively #'org-property-action))
  18582. (`radio-target
  18583. (call-interactively #'org-update-radio-target-regexp))
  18584. (`statistics-cookie
  18585. (call-interactively #'org-update-statistics-cookies))
  18586. ((or `table `table-cell `table-row)
  18587. ;; At a table, recalculate every field and align it. Also
  18588. ;; send the table if necessary. If the table has
  18589. ;; a `table.el' type, just give up. At a table row or cell,
  18590. ;; maybe recalculate line but always align table.
  18591. (if (eq (org-element-property :type context) 'table.el)
  18592. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18593. Use `\\[org-edit-special]' to edit table.el tables"))
  18594. (if (or (eq type 'table)
  18595. ;; Check if point is at a TBLFM line.
  18596. (and (eq type 'table-row)
  18597. (= (point) (org-element-property :end context))))
  18598. (save-excursion
  18599. (if (org-at-TBLFM-p)
  18600. (progn (require 'org-table)
  18601. (org-table-calc-current-TBLFM))
  18602. (goto-char (org-element-property :contents-begin context))
  18603. (org-call-with-arg 'org-table-recalculate (or arg t))
  18604. (orgtbl-send-table 'maybe)))
  18605. (org-table-maybe-eval-formula)
  18606. (cond (arg (call-interactively #'org-table-recalculate))
  18607. ((org-table-maybe-recalculate-line))
  18608. (t (org-table-align))))))
  18609. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18610. (org-timestamp-change 0 'day))
  18611. ((and `nil (guard (org-at-heading-p)))
  18612. ;; When point is on an unsupported object type, we can miss
  18613. ;; the fact that it also is at a heading. Handle it here.
  18614. (call-interactively #'org-set-tags))
  18615. ((guard
  18616. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18617. (_
  18618. (user-error
  18619. (substitute-command-keys
  18620. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18621. (defun org-mode-restart ()
  18622. (interactive)
  18623. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18624. (funcall major-mode)
  18625. (hack-local-variables)
  18626. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18627. (org-indent-mode -1))
  18628. (org-reset-file-cache))
  18629. (message "%s restarted" major-mode))
  18630. (defun org-kill-note-or-show-branches ()
  18631. "Abort storing current note, or call `outline-show-branches'."
  18632. (interactive)
  18633. (if (not org-finish-function)
  18634. (progn
  18635. (outline-hide-subtree)
  18636. (call-interactively 'outline-show-branches))
  18637. (let ((org-note-abort t))
  18638. (funcall org-finish-function))))
  18639. (defun org-delete-indentation (&optional arg)
  18640. "Join current line to previous and fix whitespace at join.
  18641. If previous line is a headline add to headline title. Otherwise
  18642. the function calls `delete-indentation'.
  18643. With a non-nil optional argument, join it to the following one."
  18644. (interactive "*P")
  18645. (if (save-excursion
  18646. (beginning-of-line (if arg 1 0))
  18647. (let ((case-fold-search nil))
  18648. (looking-at org-complex-heading-regexp)))
  18649. ;; At headline.
  18650. (let ((tags-column (when (match-beginning 5)
  18651. (save-excursion (goto-char (match-beginning 5))
  18652. (current-column))))
  18653. (string (concat " " (progn (when arg (forward-line 1))
  18654. (org-trim (delete-and-extract-region
  18655. (line-beginning-position)
  18656. (line-end-position)))))))
  18657. (unless (bobp) (delete-region (point) (1- (point))))
  18658. (goto-char (or (match-end 4)
  18659. (match-beginning 5)
  18660. (match-end 0)))
  18661. (skip-chars-backward " \t")
  18662. (save-excursion (insert string))
  18663. ;; Adjust alignment of tags.
  18664. (cond
  18665. ((not tags-column)) ;no tags
  18666. (org-auto-align-tags (org-set-tags nil t))
  18667. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18668. (delete-indentation arg)))
  18669. (defun org-open-line (n)
  18670. "Insert a new row in tables, call `open-line' elsewhere.
  18671. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18672. As a special case, when a document starts with a table, allow to
  18673. call `open-line' on the very first character."
  18674. (interactive "*p")
  18675. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18676. (org-table-insert-row)
  18677. (open-line n)))
  18678. (defun org-return (&optional indent)
  18679. "Goto next table row or insert a newline.
  18680. Calls `org-table-next-row' or `newline', depending on context.
  18681. When optional INDENT argument is non-nil, call
  18682. `newline-and-indent' instead of `newline'.
  18683. When `org-return-follows-link' is non-nil and point is on
  18684. a timestamp or a link, call `org-open-at-point'. However, it
  18685. will not happen if point is in a table or on a \"dead\"
  18686. object (e.g., within a comment). In these case, you need to use
  18687. `org-open-at-point' directly."
  18688. (interactive)
  18689. (let ((context (if org-return-follows-link (org-element-context)
  18690. (org-element-at-point))))
  18691. (cond
  18692. ;; In a table, call `org-table-next-row'. However, before first
  18693. ;; column or after last one, split the table.
  18694. ((or (and (eq (org-element-type context) 'table)
  18695. (>= (point) (org-element-property :contents-begin context))
  18696. (< (point) (org-element-property :contents-end context)))
  18697. (org-element-lineage context '(table-row table-cell) t))
  18698. (if (or (looking-at-p "[ \t]*$")
  18699. (save-excursion (skip-chars-backward " \t") (bolp)))
  18700. (insert "\n")
  18701. (org-table-justify-field-maybe)
  18702. (call-interactively #'org-table-next-row)))
  18703. ;; On a link or a timestamp, call `org-open-at-point' if
  18704. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18705. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18706. ((and org-return-follows-link
  18707. (or (org-in-regexp org-ts-regexp-both nil t)
  18708. (org-in-regexp org-tsr-regexp-both nil t)
  18709. (org-in-regexp org-any-link-re nil t)))
  18710. (call-interactively #'org-open-at-point))
  18711. ;; Insert newline in heading, but preserve tags.
  18712. ((and (not (bolp))
  18713. (save-excursion (beginning-of-line)
  18714. (let ((case-fold-search nil))
  18715. (looking-at org-complex-heading-regexp))))
  18716. ;; At headline. Split line. However, if point is on keyword,
  18717. ;; priority cookie or tags, do not break any of them: add
  18718. ;; a newline after the headline instead.
  18719. (let ((tags-column (and (match-beginning 5)
  18720. (save-excursion (goto-char (match-beginning 5))
  18721. (current-column))))
  18722. (string
  18723. (when (and (match-end 4) (org-point-in-group (point) 4))
  18724. (delete-and-extract-region (point) (match-end 4)))))
  18725. ;; Adjust tag alignment.
  18726. (cond
  18727. ((not (and tags-column string)))
  18728. (org-auto-align-tags (org-set-tags nil t))
  18729. (t (org--align-tags-here tags-column))) ;preserve tags column
  18730. (end-of-line)
  18731. (org-show-entry)
  18732. (if indent (newline-and-indent) (newline))
  18733. (when string (save-excursion (insert (org-trim string))))))
  18734. ;; In a list, make sure indenting keeps trailing text within.
  18735. ((and indent
  18736. (not (eolp))
  18737. (org-element-lineage context '(item)))
  18738. (let ((trailing-data
  18739. (delete-and-extract-region (point) (line-end-position))))
  18740. (newline-and-indent)
  18741. (save-excursion (insert trailing-data))))
  18742. (t (if indent (newline-and-indent) (newline))))))
  18743. (defun org-return-indent ()
  18744. "Goto next table row or insert a newline and indent.
  18745. Calls `org-table-next-row' or `newline-and-indent', depending on
  18746. context. See the individual commands for more information."
  18747. (interactive)
  18748. (org-return t))
  18749. (defun org-ctrl-c-tab (&optional _arg)
  18750. "Toggle columns width in a table, or show children.
  18751. Call `org-table-toggle-column-width' if point is in a table.
  18752. Otherwise, call `org-show-children'."
  18753. (interactive "p")
  18754. (call-interactively
  18755. (if (org-at-table-p) #'org-table-toggle-column-width
  18756. #'org-show-children)))
  18757. (defun org-ctrl-c-star ()
  18758. "Compute table, or change heading status of lines.
  18759. Calls `org-table-recalculate' or `org-toggle-heading',
  18760. depending on context."
  18761. (interactive)
  18762. (cond
  18763. ((org-at-table-p)
  18764. (call-interactively 'org-table-recalculate))
  18765. (t
  18766. ;; Convert all lines in region to list items
  18767. (call-interactively 'org-toggle-heading))))
  18768. (defun org-ctrl-c-minus ()
  18769. "Insert separator line in table or modify bullet status of line.
  18770. Also turns a plain line or a region of lines into list items.
  18771. Calls `org-table-insert-hline', `org-toggle-item', or
  18772. `org-cycle-list-bullet', depending on context."
  18773. (interactive)
  18774. (cond
  18775. ((org-at-table-p)
  18776. (call-interactively 'org-table-insert-hline))
  18777. ((org-region-active-p)
  18778. (call-interactively 'org-toggle-item))
  18779. ((org-in-item-p)
  18780. (call-interactively 'org-cycle-list-bullet))
  18781. (t
  18782. (call-interactively 'org-toggle-item))))
  18783. (defun org-toggle-heading (&optional nstars)
  18784. "Convert headings to normal text, or items or text to headings.
  18785. If there is no active region, only convert the current line.
  18786. With a `\\[universal-argument]' prefix, convert the whole list at
  18787. point into heading.
  18788. In a region:
  18789. - If the first non blank line is a headline, remove the stars
  18790. from all headlines in the region.
  18791. - If it is a normal line, turn each and every normal line (i.e.,
  18792. not an heading or an item) in the region into headings. If you
  18793. want to convert only the first line of this region, use one
  18794. universal prefix argument.
  18795. - If it is a plain list item, turn all plain list items into headings.
  18796. When converting a line into a heading, the number of stars is chosen
  18797. such that the lines become children of the current entry. However,
  18798. when a numeric prefix argument is given, its value determines the
  18799. number of stars to add."
  18800. (interactive "P")
  18801. (let ((skip-blanks
  18802. (function
  18803. ;; Return beginning of first non-blank line, starting from
  18804. ;; line at POS.
  18805. (lambda (pos)
  18806. (save-excursion
  18807. (goto-char pos)
  18808. (while (org-at-comment-p) (forward-line))
  18809. (skip-chars-forward " \r\t\n")
  18810. (point-at-bol)))))
  18811. beg end toggled)
  18812. ;; Determine boundaries of changes. If a universal prefix has
  18813. ;; been given, put the list in a region. If region ends at a bol,
  18814. ;; do not consider the last line to be in the region.
  18815. (when (and current-prefix-arg (org-at-item-p))
  18816. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18817. (org-mark-element))
  18818. (if (org-region-active-p)
  18819. (setq beg (funcall skip-blanks (region-beginning))
  18820. end (copy-marker (save-excursion
  18821. (goto-char (region-end))
  18822. (if (bolp) (point) (point-at-eol)))))
  18823. (setq beg (funcall skip-blanks (point-at-bol))
  18824. end (copy-marker (point-at-eol))))
  18825. ;; Ensure inline tasks don't count as headings.
  18826. (org-with-limited-levels
  18827. (save-excursion
  18828. (goto-char beg)
  18829. (cond
  18830. ;; Case 1. Started at an heading: de-star headings.
  18831. ((org-at-heading-p)
  18832. (while (< (point) end)
  18833. (when (org-at-heading-p t)
  18834. (looking-at org-outline-regexp) (replace-match "")
  18835. (setq toggled t))
  18836. (forward-line)))
  18837. ;; Case 2. Started at an item: change items into headlines.
  18838. ;; One star will be added by `org-list-to-subtree'.
  18839. ((org-at-item-p)
  18840. (while (< (point) end)
  18841. (when (org-at-item-p)
  18842. ;; Pay attention to cases when region ends before list.
  18843. (let* ((struct (org-list-struct))
  18844. (list-end
  18845. (min (org-list-get-bottom-point struct) (1+ end))))
  18846. (save-restriction
  18847. (narrow-to-region (point) list-end)
  18848. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18849. (setq toggled t))
  18850. (forward-line)))
  18851. ;; Case 3. Started at normal text: make every line an heading,
  18852. ;; skipping headlines and items.
  18853. (t (let* ((stars
  18854. (make-string
  18855. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18856. (add-stars
  18857. (cond (nstars "") ; stars from prefix only
  18858. ((equal stars "") "*") ; before first heading
  18859. (org-odd-levels-only "**") ; inside heading, odd
  18860. (t "*"))) ; inside heading, oddeven
  18861. (rpl (concat stars add-stars " "))
  18862. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18863. (while (< (point) (if (equal nstars '(4)) lend end))
  18864. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18865. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18866. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18867. (forward-line)))))))
  18868. (unless toggled (message "Cannot toggle heading from here"))))
  18869. (defun org-meta-return (&optional arg)
  18870. "Insert a new heading or wrap a region in a table.
  18871. Calls `org-insert-heading', `org-insert-item' or
  18872. `org-table-wrap-region', depending on context. When called with
  18873. an argument, unconditionally call `org-insert-heading'."
  18874. (interactive "P")
  18875. (org-check-before-invisible-edit 'insert)
  18876. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18877. (call-interactively (cond (arg #'org-insert-heading)
  18878. ((org-at-table-p) #'org-table-wrap-region)
  18879. ((org-in-item-p) #'org-insert-item)
  18880. (t #'org-insert-heading)))))
  18881. ;;; Menu entries
  18882. (defsubst org-in-subtree-not-table-p ()
  18883. "Are we in a subtree and not in a table?"
  18884. (and (not (org-before-first-heading-p))
  18885. (not (org-at-table-p))))
  18886. ;; Define the Org mode menus
  18887. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18888. '("Tbl"
  18889. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18890. ["Next Field" org-cycle (org-at-table-p)]
  18891. ["Previous Field" org-shifttab (org-at-table-p)]
  18892. ["Next Row" org-return (org-at-table-p)]
  18893. "--"
  18894. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18895. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18896. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18897. "--"
  18898. ("Column"
  18899. ["Move Column Left" org-metaleft (org-at-table-p)]
  18900. ["Move Column Right" org-metaright (org-at-table-p)]
  18901. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18902. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18903. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18904. ("Row"
  18905. ["Move Row Up" org-metaup (org-at-table-p)]
  18906. ["Move Row Down" org-metadown (org-at-table-p)]
  18907. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18908. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18909. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18910. "--"
  18911. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18912. ("Rectangle"
  18913. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18914. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18915. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18916. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18917. "--"
  18918. ("Calculate"
  18919. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18920. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18921. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18922. "--"
  18923. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18924. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18925. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18926. "--"
  18927. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18928. "--"
  18929. ["Sum Column/Rectangle" org-table-sum
  18930. (or (org-at-table-p) (org-region-active-p))]
  18931. ["Which Column?" org-table-current-column (org-at-table-p)])
  18932. ["Debug Formulas"
  18933. org-table-toggle-formula-debugger
  18934. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18935. ["Show Col/Row Numbers"
  18936. org-table-toggle-coordinate-overlays
  18937. :style toggle
  18938. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18939. "--"
  18940. ["Create" org-table-create (not (org-at-table-p))]
  18941. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18942. ["Import from File" org-table-import (not (org-at-table-p))]
  18943. ["Export to File" org-table-export (org-at-table-p)]
  18944. "--"
  18945. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18946. "--"
  18947. ("Plot"
  18948. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18949. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18950. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18951. '("Org"
  18952. ("Show/Hide"
  18953. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18954. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18955. ["Sparse Tree..." org-sparse-tree t]
  18956. ["Reveal Context" org-reveal t]
  18957. ["Show All" org-show-all t]
  18958. "--"
  18959. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18960. "--"
  18961. ["New Heading" org-insert-heading t]
  18962. ("Navigate Headings"
  18963. ["Up" outline-up-heading t]
  18964. ["Next" outline-next-visible-heading t]
  18965. ["Previous" outline-previous-visible-heading t]
  18966. ["Next Same Level" outline-forward-same-level t]
  18967. ["Previous Same Level" outline-backward-same-level t]
  18968. "--"
  18969. ["Jump" org-goto t])
  18970. ("Edit Structure"
  18971. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18972. "--"
  18973. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18974. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18975. "--"
  18976. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18977. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18978. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18979. "--"
  18980. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18981. "--"
  18982. ["Copy visible text" org-copy-visible t]
  18983. "--"
  18984. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18985. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18986. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18987. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18988. "--"
  18989. ["Sort Region/Children" org-sort t]
  18990. "--"
  18991. ["Convert to odd levels" org-convert-to-odd-levels t]
  18992. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18993. ("Editing"
  18994. ["Emphasis..." org-emphasize t]
  18995. ["Edit Source Example" org-edit-special t]
  18996. "--"
  18997. ["Footnote new/jump" org-footnote-action t]
  18998. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18999. ("Archive"
  19000. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19001. "--"
  19002. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19003. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19004. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19005. )
  19006. "--"
  19007. ("Hyperlinks"
  19008. ["Store Link (Global)" org-store-link t]
  19009. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19010. ["Insert Link" org-insert-link t]
  19011. ["Follow Link" org-open-at-point t]
  19012. "--"
  19013. ["Next link" org-next-link t]
  19014. ["Previous link" org-previous-link t]
  19015. "--"
  19016. ["Descriptive Links"
  19017. org-toggle-link-display
  19018. :style radio
  19019. :selected org-descriptive-links
  19020. ]
  19021. ["Literal Links"
  19022. org-toggle-link-display
  19023. :style radio
  19024. :selected (not org-descriptive-links)])
  19025. "--"
  19026. ("TODO Lists"
  19027. ["TODO/DONE/-" org-todo t]
  19028. ("Select keyword"
  19029. ["Next keyword" org-shiftright (org-at-heading-p)]
  19030. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19031. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19032. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19033. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19034. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19035. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19036. "--"
  19037. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19038. :selected org-enforce-todo-dependencies :style toggle :active t]
  19039. "Settings for tree at point"
  19040. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19041. :selected (org-entry-get nil "ORDERED")
  19042. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19043. ["Do Children parallel" org-toggle-ordered-property :style radio
  19044. :selected (not (org-entry-get nil "ORDERED"))
  19045. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19046. "--"
  19047. ["Set Priority" org-priority t]
  19048. ["Priority Up" org-shiftup t]
  19049. ["Priority Down" org-shiftdown t]
  19050. "--"
  19051. ["Get news from all feeds" org-feed-update-all t]
  19052. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19053. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19054. ("TAGS and Properties"
  19055. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19056. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19057. "--"
  19058. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19059. ["Column view of properties" org-columns t]
  19060. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19061. ("Dates and Scheduling"
  19062. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19063. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19064. ("Change Date"
  19065. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19066. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19067. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19068. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19069. ["Compute Time Range" org-evaluate-time-range t]
  19070. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19071. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19072. "--"
  19073. ["Custom time format" org-toggle-time-stamp-overlays
  19074. :style radio :selected org-display-custom-times]
  19075. "--"
  19076. ["Goto Calendar" org-goto-calendar t]
  19077. ["Date from Calendar" org-date-from-calendar t]
  19078. "--"
  19079. ["Start/Restart Timer" org-timer-start t]
  19080. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19081. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19082. ["Insert Timer String" org-timer t]
  19083. ["Insert Timer Item" org-timer-item t])
  19084. ("Logging work"
  19085. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19086. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19087. ["Clock out" org-clock-out t]
  19088. ["Clock cancel" org-clock-cancel t]
  19089. "--"
  19090. ["Mark as default task" org-clock-mark-default-task t]
  19091. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19092. ["Goto running clock" org-clock-goto t]
  19093. "--"
  19094. ["Display times" org-clock-display t]
  19095. ["Create clock table" org-clock-report t]
  19096. "--"
  19097. ["Record DONE time"
  19098. (progn (setq org-log-done (not org-log-done))
  19099. (message "Switching to %s will %s record a timestamp"
  19100. (car org-done-keywords)
  19101. (if org-log-done "automatically" "not")))
  19102. :style toggle :selected org-log-done])
  19103. "--"
  19104. ["Agenda Command..." org-agenda t]
  19105. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19106. ("File List for Agenda")
  19107. ("Special views current file"
  19108. ["TODO Tree" org-show-todo-tree t]
  19109. ["Check Deadlines" org-check-deadlines t]
  19110. ["Tags/Property tree" org-match-sparse-tree t])
  19111. "--"
  19112. ["Export/Publish..." org-export-dispatch t]
  19113. ("LaTeX"
  19114. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19115. :style toggle :selected org-cdlatex-mode]
  19116. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19117. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19118. ["Modify math symbol" org-cdlatex-math-modify
  19119. (org-inside-LaTeX-fragment-p)]
  19120. ["Insert citation" org-reftex-citation t])
  19121. "--"
  19122. ("MobileOrg"
  19123. ["Push Files and Views" org-mobile-push t]
  19124. ["Get Captured and Flagged" org-mobile-pull t]
  19125. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19126. "--"
  19127. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19128. "--"
  19129. ("Documentation"
  19130. ["Show Version" org-version t]
  19131. ["Info Documentation" org-info t])
  19132. ("Customize"
  19133. ["Browse Org Group" org-customize t]
  19134. "--"
  19135. ["Expand This Menu" org-create-customize-menu
  19136. (fboundp 'customize-menu-create)])
  19137. ["Send bug report" org-submit-bug-report t]
  19138. "--"
  19139. ("Refresh/Reload"
  19140. ["Refresh setup current buffer" org-mode-restart t]
  19141. ["Reload Org (after update)" org-reload t]
  19142. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19143. ))
  19144. (defun org-info (&optional node)
  19145. "Read documentation for Org in the info system.
  19146. With optional NODE, go directly to that node."
  19147. (interactive)
  19148. (info (format "(org)%s" (or node ""))))
  19149. ;;;###autoload
  19150. (defun org-submit-bug-report ()
  19151. "Submit a bug report on Org via mail.
  19152. Don't hesitate to report any problems or inaccurate documentation.
  19153. If you don't have setup sending mail from (X)Emacs, please copy the
  19154. output buffer into your mail program, as it gives us important
  19155. information about your Org version and configuration."
  19156. (interactive)
  19157. (require 'reporter)
  19158. (defvar reporter-prompt-for-summary-p)
  19159. (org-load-modules-maybe)
  19160. (org-require-autoloaded-modules)
  19161. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19162. (reporter-submit-bug-report
  19163. "emacs-orgmode@gnu.org"
  19164. (org-version nil 'full)
  19165. (let (list)
  19166. (save-window-excursion
  19167. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19168. (delete-other-windows)
  19169. (erase-buffer)
  19170. (insert "You are about to submit a bug report to the Org mailing list.
  19171. We would like to add your full Org and Outline configuration to the
  19172. bug report. This greatly simplifies the work of the maintainer and
  19173. other experts on the mailing list.
  19174. HOWEVER, some variables you have customized may contain private
  19175. information. The names of customers, colleagues, or friends, might
  19176. appear in the form of file names, tags, todo states, or search strings.
  19177. If you answer yes to the prompt, you might want to check and remove
  19178. such private information before sending the email.")
  19179. (add-text-properties (point-min) (point-max) '(face org-warning))
  19180. (when (yes-or-no-p "Include your Org configuration ")
  19181. (mapatoms
  19182. (lambda (v)
  19183. (and (boundp v)
  19184. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19185. (or (and (symbol-value v)
  19186. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19187. (and
  19188. (get v 'custom-type) (get v 'standard-value)
  19189. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19190. (push v list)))))
  19191. (kill-buffer (get-buffer "*Warn about privacy*"))
  19192. list))
  19193. nil nil
  19194. "Remember to cover the basics, that is, what you expected to happen and
  19195. what in fact did happen. You don't know how to make a good report? See
  19196. http://orgmode.org/manual/Feedback.html#Feedback
  19197. Your bug report will be posted to the Org mailing list.
  19198. ------------------------------------------------------------------------")
  19199. (save-excursion
  19200. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19201. (replace-match "\\1Bug: \\3 [\\2]")))))
  19202. (defun org-install-agenda-files-menu ()
  19203. (let ((bl (buffer-list)))
  19204. (save-excursion
  19205. (while bl
  19206. (set-buffer (pop bl))
  19207. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19208. (when (derived-mode-p 'org-mode)
  19209. (easy-menu-change
  19210. '("Org") "File List for Agenda"
  19211. (append
  19212. (list
  19213. ["Edit File List" (org-edit-agenda-file-list) t]
  19214. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19215. ["Remove Current File from List" org-remove-file t]
  19216. ["Cycle through agenda files" org-cycle-agenda-files t]
  19217. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19218. "--")
  19219. (mapcar 'org-file-menu-entry
  19220. ;; Prevent initialization from failing.
  19221. (ignore-errors (org-agenda-files t)))))))))
  19222. ;;;; Documentation
  19223. (defun org-require-autoloaded-modules ()
  19224. (interactive)
  19225. (mapc #'require
  19226. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19227. org-table org-timer)))
  19228. ;;;###autoload
  19229. (defun org-reload (&optional uncompiled)
  19230. "Reload all org lisp files.
  19231. With prefix arg UNCOMPILED, load the uncompiled versions."
  19232. (interactive "P")
  19233. (require 'loadhist)
  19234. (let* ((org-dir (org-find-library-dir "org"))
  19235. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19236. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19237. (remove-re (format "\\`%s\\'"
  19238. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19239. (feats (delete-dups
  19240. (mapcar 'file-name-sans-extension
  19241. (mapcar 'file-name-nondirectory
  19242. (delq nil
  19243. (mapcar 'feature-file
  19244. features))))))
  19245. (lfeat (append
  19246. (sort
  19247. (setq feats
  19248. (delq nil (mapcar
  19249. (lambda (f)
  19250. (if (and (string-match feature-re f)
  19251. (not (string-match remove-re f)))
  19252. f nil))
  19253. feats)))
  19254. 'string-lessp)
  19255. (list "org-version" "org")))
  19256. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19257. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19258. load-uncore load-misses)
  19259. (setq load-misses
  19260. (delq 't
  19261. (mapcar (lambda (f)
  19262. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19263. (and (string= org-dir contrib-dir)
  19264. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19265. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19266. (add-to-list 'load-uncore f 'append)
  19267. 't)
  19268. f))
  19269. lfeat)))
  19270. (when load-uncore
  19271. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19272. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19273. (if load-misses
  19274. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19275. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19276. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19277. ;;;###autoload
  19278. (defun org-customize ()
  19279. "Call the customize function with org as argument."
  19280. (interactive)
  19281. (org-load-modules-maybe)
  19282. (org-require-autoloaded-modules)
  19283. (customize-browse 'org))
  19284. (defun org-create-customize-menu ()
  19285. "Create a full customization menu for Org mode, insert it into the menu."
  19286. (interactive)
  19287. (org-load-modules-maybe)
  19288. (org-require-autoloaded-modules)
  19289. (if (fboundp 'customize-menu-create)
  19290. (progn
  19291. (easy-menu-change
  19292. '("Org") "Customize"
  19293. `(["Browse Org group" org-customize t]
  19294. "--"
  19295. ,(customize-menu-create 'org)
  19296. ["Set" Custom-set t]
  19297. ["Save" Custom-save t]
  19298. ["Reset to Current" Custom-reset-current t]
  19299. ["Reset to Saved" Custom-reset-saved t]
  19300. ["Reset to Standard Settings" Custom-reset-standard t]))
  19301. (message "\"Org\"-menu now contains full customization menu"))
  19302. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19303. ;;;; Miscellaneous stuff
  19304. ;;; Generally useful functions
  19305. (defun org-link-display-format (s)
  19306. "Replace links in string S with their description.
  19307. If there is no description, use the link target."
  19308. (save-match-data
  19309. (replace-regexp-in-string
  19310. org-bracket-link-analytic-regexp
  19311. (lambda (m)
  19312. (if (match-end 5) (match-string 5 m)
  19313. (concat (match-string 1 m) (match-string 3 m))))
  19314. s nil t)))
  19315. (defun org-toggle-link-display ()
  19316. "Toggle the literal or descriptive display of links."
  19317. (interactive)
  19318. (if org-descriptive-links
  19319. (progn (org-remove-from-invisibility-spec '(org-link))
  19320. (org-restart-font-lock)
  19321. (setq org-descriptive-links nil))
  19322. (progn (add-to-invisibility-spec '(org-link))
  19323. (org-restart-font-lock)
  19324. (setq org-descriptive-links t))))
  19325. (defun org-in-clocktable-p ()
  19326. "Check if the cursor is in a clocktable."
  19327. (let ((pos (point)) start)
  19328. (save-excursion
  19329. (end-of-line 1)
  19330. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19331. (setq start (match-beginning 0))
  19332. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19333. (>= (match-end 0) pos)
  19334. start))))
  19335. (defun org-in-verbatim-emphasis ()
  19336. (save-match-data
  19337. (and (org-in-regexp org-verbatim-re 2)
  19338. (>= (point) (match-beginning 3))
  19339. (<= (point) (match-end 4)))))
  19340. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19341. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19342. (if (and marker (marker-buffer marker)
  19343. (buffer-live-p (marker-buffer marker)))
  19344. (progn
  19345. (pop-to-buffer-same-window (marker-buffer marker))
  19346. (when (or (> marker (point-max)) (< marker (point-min)))
  19347. (widen))
  19348. (goto-char marker)
  19349. (org-show-context 'org-goto))
  19350. (if bookmark
  19351. (bookmark-jump bookmark)
  19352. (error "Cannot find location"))))
  19353. (defun org-quote-csv-field (s)
  19354. "Quote field for inclusion in CSV material."
  19355. (if (string-match "[\",]" s)
  19356. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19357. s))
  19358. (defun org-force-self-insert (N)
  19359. "Needed to enforce self-insert under remapping."
  19360. (interactive "p")
  19361. (self-insert-command N))
  19362. (defun org-get-indentation (&optional line)
  19363. "Get the indentation of the current line, interpreting tabs.
  19364. When LINE is given, assume it represents a line and compute its indentation."
  19365. (if line
  19366. (when (string-match "^ *" (org-remove-tabs line))
  19367. (match-end 0))
  19368. (save-excursion
  19369. (beginning-of-line 1)
  19370. (skip-chars-forward " \t")
  19371. (current-column))))
  19372. (defun org-get-string-indentation (s)
  19373. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19374. (let ((n -1) (i 0) (w tab-width) c)
  19375. (catch 'exit
  19376. (while (< (setq n (1+ n)) (length s))
  19377. (setq c (aref s n))
  19378. (cond ((= c ?\ ) (setq i (1+ i)))
  19379. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19380. (t (throw 'exit t)))))
  19381. i))
  19382. (defun org-fix-indentation (line ind)
  19383. "Fix indentation in LINE.
  19384. IND is a cons cell with target and minimum indentation.
  19385. If the current indentation in LINE is smaller than the minimum,
  19386. leave it alone. If it is larger than ind, set it to the target."
  19387. (let* ((l (org-remove-tabs line))
  19388. (i (org-get-indentation l))
  19389. (i1 (car ind)) (i2 (cdr ind)))
  19390. (when (>= i i2) (setq l (substring line i2)))
  19391. (if (> i1 0)
  19392. (concat (make-string i1 ?\ ) l)
  19393. l)))
  19394. (defun org-fill-template (template alist)
  19395. "Find each %key of ALIST in TEMPLATE and replace it."
  19396. (let ((case-fold-search nil))
  19397. (dolist (entry (sort (copy-sequence alist)
  19398. (lambda (a b) (< (length (car a)) (length (car b))))))
  19399. (setq template
  19400. (replace-regexp-in-string
  19401. (concat "%" (regexp-quote (car entry)))
  19402. (or (cdr entry) "") template t t)))
  19403. template))
  19404. (defun org-quote-vert (s)
  19405. "Replace \"|\" with \"\\vert\"."
  19406. (while (string-match "|" s)
  19407. (setq s (replace-match "\\vert" t t s)))
  19408. s)
  19409. (defun org-uuidgen-p (s)
  19410. "Is S an ID created by UUIDGEN?"
  19411. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19412. (defun org-in-src-block-p (&optional inside)
  19413. "Whether point is in a code source block.
  19414. When INSIDE is non-nil, don't consider we are within a src block
  19415. when point is at #+BEGIN_SRC or #+END_SRC."
  19416. (let ((case-fold-search t))
  19417. (or (and (eq (get-char-property (point) 'src-block) t))
  19418. (and (not inside)
  19419. (save-match-data
  19420. (save-excursion
  19421. (beginning-of-line)
  19422. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19423. (defun org-context ()
  19424. "Return a list of contexts of the current cursor position.
  19425. If several contexts apply, all are returned.
  19426. Each context entry is a list with a symbol naming the context, and
  19427. two positions indicating start and end of the context. Possible
  19428. contexts are:
  19429. :headline anywhere in a headline
  19430. :headline-stars on the leading stars in a headline
  19431. :todo-keyword on a TODO keyword (including DONE) in a headline
  19432. :tags on the TAGS in a headline
  19433. :priority on the priority cookie in a headline
  19434. :item on the first line of a plain list item
  19435. :item-bullet on the bullet/number of a plain list item
  19436. :checkbox on the checkbox in a plain list item
  19437. :table in an Org table
  19438. :table-special on a special filed in a table
  19439. :table-table in a table.el table
  19440. :clocktable in a clocktable
  19441. :src-block in a source block
  19442. :link on a hyperlink
  19443. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19444. :target on a <<target>>
  19445. :radio-target on a <<<radio-target>>>
  19446. :latex-fragment on a LaTeX fragment
  19447. :latex-preview on a LaTeX fragment with overlaid preview image
  19448. This function expects the position to be visible because it uses font-lock
  19449. faces as a help to recognize the following contexts: :table-special, :link,
  19450. and :keyword."
  19451. (let* ((f (get-text-property (point) 'face))
  19452. (faces (if (listp f) f (list f)))
  19453. (case-fold-search t)
  19454. (p (point)) clist o)
  19455. ;; First the large context
  19456. (cond
  19457. ((org-at-heading-p t)
  19458. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19459. (when (progn
  19460. (beginning-of-line 1)
  19461. (looking-at org-todo-line-tags-regexp))
  19462. (push (org-point-in-group p 1 :headline-stars) clist)
  19463. (push (org-point-in-group p 2 :todo-keyword) clist)
  19464. (push (org-point-in-group p 4 :tags) clist))
  19465. (goto-char p)
  19466. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19467. (when (looking-at "\\[#[A-Z0-9]\\]")
  19468. (push (org-point-in-group p 0 :priority) clist)))
  19469. ((org-at-item-p)
  19470. (push (org-point-in-group p 2 :item-bullet) clist)
  19471. (push (list :item (point-at-bol)
  19472. (save-excursion (org-end-of-item) (point)))
  19473. clist)
  19474. (and (org-at-item-checkbox-p)
  19475. (push (org-point-in-group p 0 :checkbox) clist)))
  19476. ((org-at-table-p)
  19477. (push (list :table (org-table-begin) (org-table-end)) clist)
  19478. (when (memq 'org-formula faces)
  19479. (push (list :table-special
  19480. (previous-single-property-change p 'face)
  19481. (next-single-property-change p 'face)) clist)))
  19482. ((org-at-table-p 'any)
  19483. (push (list :table-table) clist)))
  19484. (goto-char p)
  19485. (let ((case-fold-search t))
  19486. ;; New the "medium" contexts: clocktables, source blocks
  19487. (cond ((org-in-clocktable-p)
  19488. (push (list :clocktable
  19489. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19490. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19491. (match-beginning 1))
  19492. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19493. (match-end 0))) clist))
  19494. ((org-in-src-block-p)
  19495. (push (list :src-block
  19496. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19497. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19498. (match-beginning 1))
  19499. (and (search-forward "#+END_SRC" nil t)
  19500. (match-beginning 0))) clist))))
  19501. (goto-char p)
  19502. ;; Now the small context
  19503. (cond
  19504. ((org-at-timestamp-p)
  19505. (push (org-point-in-group p 0 :timestamp) clist))
  19506. ((memq 'org-link faces)
  19507. (push (list :link
  19508. (previous-single-property-change p 'face)
  19509. (next-single-property-change p 'face)) clist))
  19510. ((memq 'org-special-keyword faces)
  19511. (push (list :keyword
  19512. (previous-single-property-change p 'face)
  19513. (next-single-property-change p 'face)) clist))
  19514. ((org-at-target-p)
  19515. (push (org-point-in-group p 0 :target) clist)
  19516. (goto-char (1- (match-beginning 0)))
  19517. (when (looking-at org-radio-target-regexp)
  19518. (push (org-point-in-group p 0 :radio-target) clist))
  19519. (goto-char p))
  19520. ((setq o (cl-some
  19521. (lambda (o)
  19522. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19523. o))
  19524. (overlays-at (point))))
  19525. (push (list :latex-fragment
  19526. (overlay-start o) (overlay-end o)) clist)
  19527. (push (list :latex-preview
  19528. (overlay-start o) (overlay-end o)) clist))
  19529. ((org-inside-LaTeX-fragment-p)
  19530. ;; FIXME: positions wrong.
  19531. (push (list :latex-fragment (point) (point)) clist)))
  19532. (setq clist (nreverse (delq nil clist)))
  19533. clist))
  19534. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19535. "Non-nil when point is between matches of START-RE and END-RE.
  19536. Also return a non-nil value when point is on one of the matches.
  19537. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19538. buffer positions. Default values are the positions of headlines
  19539. surrounding the point.
  19540. The functions returns a cons cell whose car (resp. cdr) is the
  19541. position before START-RE (resp. after END-RE)."
  19542. (save-match-data
  19543. (let ((pos (point))
  19544. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19545. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19546. beg end)
  19547. (save-excursion
  19548. ;; Point is on a block when on START-RE or if START-RE can be
  19549. ;; found before it...
  19550. (and (or (org-in-regexp start-re)
  19551. (re-search-backward start-re limit-up t))
  19552. (setq beg (match-beginning 0))
  19553. ;; ... and END-RE after it...
  19554. (goto-char (match-end 0))
  19555. (re-search-forward end-re limit-down t)
  19556. (> (setq end (match-end 0)) pos)
  19557. ;; ... without another START-RE in-between.
  19558. (goto-char (match-beginning 0))
  19559. (not (re-search-backward start-re (1+ beg) t))
  19560. ;; Return value.
  19561. (cons beg end))))))
  19562. (defun org-in-block-p (names)
  19563. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19564. NAMES is a list of strings containing names of blocks.
  19565. Return first block name matched, or nil. Beware that in case of
  19566. nested blocks, the returned name may not belong to the closest
  19567. block from point."
  19568. (save-match-data
  19569. (catch 'exit
  19570. (let ((case-fold-search t)
  19571. (lim-up (save-excursion (outline-previous-heading)))
  19572. (lim-down (save-excursion (outline-next-heading))))
  19573. (dolist (name names)
  19574. (let ((n (regexp-quote name)))
  19575. (when (org-between-regexps-p
  19576. (concat "^[ \t]*#\\+begin_" n)
  19577. (concat "^[ \t]*#\\+end_" n)
  19578. lim-up lim-down)
  19579. (throw 'exit n)))))
  19580. nil)))
  19581. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19582. "Call `multi-occur' with buffers for all agenda files."
  19583. (interactive "sOrg-files matching: ")
  19584. (let* ((files (org-agenda-files))
  19585. (tnames (mapcar #'file-truename files))
  19586. (extra org-agenda-text-search-extra-files))
  19587. (when (eq (car extra) 'agenda-archives)
  19588. (setq extra (cdr extra))
  19589. (setq files (org-add-archive-files files)))
  19590. (dolist (f extra)
  19591. (unless (member (file-truename f) tnames)
  19592. (unless (member f files) (setq files (append files (list f))))
  19593. (setq tnames (append tnames (list (file-truename f))))))
  19594. (multi-occur
  19595. (mapcar (lambda (x)
  19596. (with-current-buffer
  19597. ;; FIXME: Why not just (find-file-noselect x)?
  19598. ;; Is it to avoid the "revert buffer" prompt?
  19599. (or (get-file-buffer x) (find-file-noselect x))
  19600. (widen)
  19601. (current-buffer)))
  19602. files)
  19603. regexp)))
  19604. (add-hook 'occur-mode-find-occurrence-hook
  19605. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19606. (defun org-occur-link-in-agenda-files ()
  19607. "Create a link and search for it in the agendas.
  19608. The link is not stored in `org-stored-links', it is just created
  19609. for the search purpose."
  19610. (interactive)
  19611. (let ((link (condition-case nil
  19612. (org-store-link nil)
  19613. (error "Unable to create a link to here"))))
  19614. (org-occur-in-agenda-files (regexp-quote link))))
  19615. (defun org-back-over-empty-lines ()
  19616. "Move backwards over whitespace, to the beginning of the first empty line.
  19617. Returns the number of empty lines passed."
  19618. (let ((pos (point)))
  19619. (if (cdr (assq 'heading org-blank-before-new-entry))
  19620. (skip-chars-backward " \t\n\r")
  19621. (unless (eobp)
  19622. (forward-line -1)))
  19623. (beginning-of-line 2)
  19624. (goto-char (min (point) pos))
  19625. (count-lines (point) pos)))
  19626. (defun org-switch-to-buffer-other-window (&rest args)
  19627. "Switch to buffer in a second window on the current frame.
  19628. In particular, do not allow pop-up frames.
  19629. Returns the newly created buffer."
  19630. (org-no-popups
  19631. (apply 'switch-to-buffer-other-window args)))
  19632. (defun org-replace-escapes (string table)
  19633. "Replace %-escapes in STRING with values in TABLE.
  19634. TABLE is an association list with keys like \"%a\" and string values.
  19635. The sequences in STRING may contain normal field width and padding information,
  19636. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19637. so values can contain further %-escapes if they are define later in TABLE."
  19638. (let ((tbl (copy-alist table))
  19639. (case-fold-search nil)
  19640. (pchg 0)
  19641. re rpl)
  19642. (dolist (e tbl)
  19643. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19644. (when (and (cdr e) (string-match re (cdr e)))
  19645. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19646. (safe "SREF"))
  19647. (add-text-properties 0 3 (list 'sref sref) safe)
  19648. (setcdr e (replace-match safe t t (cdr e)))))
  19649. (while (string-match re string)
  19650. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19651. (cdr e)))
  19652. (setq string (replace-match rpl t t string))))
  19653. (while (setq pchg (next-property-change pchg string))
  19654. (let ((sref (get-text-property pchg 'sref string)))
  19655. (when (and sref (string-match "SREF" string pchg))
  19656. (setq string (replace-match sref t t string)))))
  19657. string))
  19658. ;;; TODO: Only called once, from ox-odt which should probably use
  19659. ;;; org-export-inline-image-p or something.
  19660. (defun org-file-image-p (file)
  19661. "Return non-nil if FILE is an image."
  19662. (save-match-data
  19663. (string-match (image-file-name-regexp) file)))
  19664. (defun org-get-cursor-date (&optional with-time)
  19665. "Return the date at cursor in as a time.
  19666. This works in the calendar and in the agenda, anywhere else it just
  19667. returns the current time.
  19668. If WITH-TIME is non-nil, returns the time of the event at point (in
  19669. the agenda) or the current time of the day."
  19670. (let (date day defd tp hod mod)
  19671. (when with-time
  19672. (setq tp (get-text-property (point) 'time))
  19673. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19674. (setq hod (string-to-number (match-string 1 tp))
  19675. mod (string-to-number (match-string 2 tp))))
  19676. (or tp (let ((now (decode-time)))
  19677. (setq hod (nth 2 now)
  19678. mod (nth 1 now)))))
  19679. (cond
  19680. ((eq major-mode 'calendar-mode)
  19681. (setq date (calendar-cursor-to-date)
  19682. defd (encode-time 0 (or mod 0) (or hod 0)
  19683. (nth 1 date) (nth 0 date) (nth 2 date))))
  19684. ((eq major-mode 'org-agenda-mode)
  19685. (setq day (get-text-property (point) 'day))
  19686. (when day
  19687. (setq date (calendar-gregorian-from-absolute day)
  19688. defd (encode-time 0 (or mod 0) (or hod 0)
  19689. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19690. (or defd (current-time))))
  19691. (defun org-mark-subtree (&optional up)
  19692. "Mark the current subtree.
  19693. This puts point at the start of the current subtree, and mark at
  19694. the end. If a numeric prefix UP is given, move up into the
  19695. hierarchy of headlines by UP levels before marking the subtree."
  19696. (interactive "P")
  19697. (org-with-limited-levels
  19698. (cond ((org-at-heading-p) (beginning-of-line))
  19699. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19700. (t (outline-previous-visible-heading 1))))
  19701. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19702. (if (called-interactively-p 'any)
  19703. (call-interactively 'org-mark-element)
  19704. (org-mark-element)))
  19705. (defun org-file-newer-than-p (file time)
  19706. "Non-nil if FILE is newer than TIME.
  19707. FILE is a filename, as a string, TIME is a list of integers, as
  19708. returned by, e.g., `current-time'."
  19709. (and (file-exists-p file)
  19710. ;; Only compare times up to whole seconds as some file-systems
  19711. ;; (e.g. HFS+) do not retain any finer granularity. As
  19712. ;; a consequence, make sure we return non-nil when the two
  19713. ;; times are equal.
  19714. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19715. (cl-subseq time 0 2)))))
  19716. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19717. "Compile a SOURCE file using PROCESS.
  19718. PROCESS is either a function or a list of shell commands, as
  19719. strings. EXT is a file extension, without the leading dot, as
  19720. a string. It is used to check if the process actually succeeded.
  19721. PROCESS must create a file with the same base name and directory
  19722. as SOURCE, but ending with EXT. The function then returns its
  19723. filename. Otherwise, it raises an error. The error message can
  19724. then be refined by providing string ERR-MSG, which is appended to
  19725. the standard message.
  19726. If PROCESS is a function, it is called with a single argument:
  19727. the SOURCE file.
  19728. If it is a list of commands, each of them is called using
  19729. `shell-command'. By default, in each command, %b, %f, %F, %o and
  19730. %O are replaced with, respectively, SOURCE base name, name, full
  19731. name, directory and absolute output file name. It is possible,
  19732. however, to use more place-holders by specifying them in optional
  19733. argument SPEC, as an alist following the pattern
  19734. (CHARACTER . REPLACEMENT-STRING).
  19735. When PROCESS is a list of commands, optional argument LOG-BUF can
  19736. be set to a buffer or a buffer name. `shell-command' then uses
  19737. it for output."
  19738. (let* ((base-name (file-name-base source))
  19739. (full-name (file-truename source))
  19740. (out-dir (or (file-name-directory source) "./"))
  19741. (output (expand-file-name (concat base-name "." ext) out-dir))
  19742. (time (current-time))
  19743. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  19744. (save-window-excursion
  19745. (pcase process
  19746. ((pred functionp) (funcall process (shell-quote-argument source)))
  19747. ((pred consp)
  19748. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  19749. (spec (append spec
  19750. `((?b . ,(shell-quote-argument base-name))
  19751. (?f . ,(shell-quote-argument source))
  19752. (?F . ,(shell-quote-argument full-name))
  19753. (?o . ,(shell-quote-argument out-dir))
  19754. (?O . ,(shell-quote-argument output))))))
  19755. (dolist (command process)
  19756. (shell-command (format-spec command spec) log-buf))
  19757. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  19758. (_ (error "No valid command to process %S%s" source err-msg))))
  19759. ;; Check for process failure. Output file is expected to be
  19760. ;; located in the same directory as SOURCE.
  19761. (unless (org-file-newer-than-p output time)
  19762. (error (format "File %S wasn't produced%s" output err-msg)))
  19763. output))
  19764. ;;; Indentation
  19765. (defvar org-element-greater-elements)
  19766. (defun org--get-expected-indentation (element contentsp)
  19767. "Expected indentation column for current line, according to ELEMENT.
  19768. ELEMENT is an element containing point. CONTENTSP is non-nil
  19769. when indentation is to be computed according to contents of
  19770. ELEMENT."
  19771. (let ((type (org-element-type element))
  19772. (start (org-element-property :begin element))
  19773. (post-affiliated (org-element-property :post-affiliated element)))
  19774. (org-with-wide-buffer
  19775. (cond
  19776. (contentsp
  19777. (cl-case type
  19778. ((diary-sexp footnote-definition) 0)
  19779. ((headline inlinetask nil)
  19780. (if (not org-adapt-indentation) 0
  19781. (let ((level (org-current-level)))
  19782. (if level (1+ level) 0))))
  19783. ((item plain-list) (org-list-item-body-column post-affiliated))
  19784. (t
  19785. (goto-char start)
  19786. (org-get-indentation))))
  19787. ((memq type '(headline inlinetask nil))
  19788. (if (org-match-line "[ \t]*$")
  19789. (org--get-expected-indentation element t)
  19790. 0))
  19791. ((memq type '(diary-sexp footnote-definition)) 0)
  19792. ;; First paragraph of a footnote definition or an item.
  19793. ;; Indent like parent.
  19794. ((< (line-beginning-position) start)
  19795. (org--get-expected-indentation
  19796. (org-element-property :parent element) t))
  19797. ;; At first line: indent according to previous sibling, if any,
  19798. ;; ignoring footnote definitions and inline tasks, or parent's
  19799. ;; contents.
  19800. ((= (line-beginning-position) start)
  19801. (catch 'exit
  19802. (while t
  19803. (if (= (point-min) start) (throw 'exit 0)
  19804. (goto-char (1- start))
  19805. (let* ((previous (org-element-at-point))
  19806. (parent previous))
  19807. (while (and parent (<= (org-element-property :end parent) start))
  19808. (setq previous parent
  19809. parent (org-element-property :parent parent)))
  19810. (cond
  19811. ((not previous) (throw 'exit 0))
  19812. ((> (org-element-property :end previous) start)
  19813. (throw 'exit (org--get-expected-indentation previous t)))
  19814. ((memq (org-element-type previous)
  19815. '(footnote-definition inlinetask))
  19816. (setq start (org-element-property :begin previous)))
  19817. (t (goto-char (org-element-property :begin previous))
  19818. (throw 'exit
  19819. (if (bolp) (org-get-indentation)
  19820. ;; At first paragraph in an item or
  19821. ;; a footnote definition.
  19822. (org--get-expected-indentation
  19823. (org-element-property :parent previous) t))))))))))
  19824. ;; Otherwise, move to the first non-blank line above.
  19825. (t
  19826. (beginning-of-line)
  19827. (let ((pos (point)))
  19828. (skip-chars-backward " \r\t\n")
  19829. (cond
  19830. ;; Two blank lines end a footnote definition or a plain
  19831. ;; list. When we indent an empty line after them, the
  19832. ;; containing list or footnote definition is over, so it
  19833. ;; qualifies as a previous sibling. Therefore, we indent
  19834. ;; like its first line.
  19835. ((and (memq type '(footnote-definition plain-list))
  19836. (> (count-lines (point) pos) 2))
  19837. (goto-char start)
  19838. (org-get-indentation))
  19839. ;; Line above is the first one of a paragraph at the
  19840. ;; beginning of an item or a footnote definition. Indent
  19841. ;; like parent.
  19842. ((< (line-beginning-position) start)
  19843. (org--get-expected-indentation
  19844. (org-element-property :parent element) t))
  19845. ;; Line above is the beginning of an element, i.e., point
  19846. ;; was originally on the blank lines between element's start
  19847. ;; and contents.
  19848. ((= (line-beginning-position) post-affiliated)
  19849. (org--get-expected-indentation element t))
  19850. ;; POS is after contents in a greater element. Indent like
  19851. ;; the beginning of the element.
  19852. ((and (memq type org-element-greater-elements)
  19853. (let ((cend (org-element-property :contents-end element)))
  19854. (and cend (<= cend pos))))
  19855. ;; As a special case, if point is at the end of a footnote
  19856. ;; definition or an item, indent like the very last element
  19857. ;; within. If that last element is an item, indent like
  19858. ;; its contents.
  19859. (if (memq type '(footnote-definition item plain-list))
  19860. (let ((last (org-element-at-point)))
  19861. (goto-char pos)
  19862. (org--get-expected-indentation
  19863. last (eq (org-element-type last) 'item)))
  19864. (goto-char start)
  19865. (org-get-indentation)))
  19866. ;; In any other case, indent like the current line.
  19867. (t (org-get-indentation)))))))))
  19868. (defun org--align-node-property ()
  19869. "Align node property at point.
  19870. Alignment is done according to `org-property-format', which see."
  19871. (when (save-excursion
  19872. (beginning-of-line)
  19873. (looking-at org-property-re))
  19874. (replace-match
  19875. (concat (match-string 4)
  19876. (org-trim
  19877. (format org-property-format (match-string 1) (match-string 3))))
  19878. t t)))
  19879. (defun org-indent-line ()
  19880. "Indent line depending on context.
  19881. Indentation is done according to the following rules:
  19882. - Footnote definitions, diary sexps, headlines and inline tasks
  19883. have to start at column 0.
  19884. - On the very first line of an element, consider, in order, the
  19885. next rules until one matches:
  19886. 1. If there's a sibling element before, ignoring footnote
  19887. definitions and inline tasks, indent like its first line.
  19888. 2. If element has a parent, indent like its contents. More
  19889. precisely, if parent is an item, indent after the
  19890. description part, if any, or the bullet (see
  19891. `org-list-description-max-indent'). Else, indent like
  19892. parent's first line.
  19893. 3. Otherwise, indent relatively to current level, if
  19894. `org-adapt-indentation' is non-nil, or to left margin.
  19895. - On a blank line at the end of an element, indent according to
  19896. the type of the element. More precisely
  19897. 1. If element is a plain list, an item, or a footnote
  19898. definition, indent like the very last element within.
  19899. 2. If element is a paragraph, indent like its last non blank
  19900. line.
  19901. 3. Otherwise, indent like its very first line.
  19902. - In the code part of a source block, use language major mode
  19903. to indent current line if `org-src-tab-acts-natively' is
  19904. non-nil. If it is nil, do nothing.
  19905. - Otherwise, indent like the first non-blank line above.
  19906. The function doesn't indent an item as it could break the whole
  19907. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19908. `\\[org-shiftmetaright]'.
  19909. Also align node properties according to `org-property-format'."
  19910. (interactive)
  19911. (cond
  19912. ((org-at-heading-p) 'noindent)
  19913. (t
  19914. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19915. (type (org-element-type element)))
  19916. (cond ((and (memq type '(plain-list item))
  19917. (= (line-beginning-position)
  19918. (org-element-property :post-affiliated element)))
  19919. 'noindent)
  19920. ((and (eq type 'latex-environment)
  19921. (>= (point) (org-element-property :post-affiliated element))
  19922. (< (point) (org-with-wide-buffer
  19923. (goto-char (org-element-property :end element))
  19924. (skip-chars-backward " \r\t\n")
  19925. (line-beginning-position 2))))
  19926. 'noindent)
  19927. ((and (eq type 'src-block)
  19928. org-src-tab-acts-natively
  19929. (> (line-beginning-position)
  19930. (org-element-property :post-affiliated element))
  19931. (< (line-beginning-position)
  19932. (org-with-wide-buffer
  19933. (goto-char (org-element-property :end element))
  19934. (skip-chars-backward " \r\t\n")
  19935. (line-beginning-position))))
  19936. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19937. (t
  19938. (let ((column (org--get-expected-indentation element nil)))
  19939. ;; Preserve current column.
  19940. (if (<= (current-column) (current-indentation))
  19941. (indent-line-to column)
  19942. (save-excursion (indent-line-to column))))
  19943. ;; Align node property. Also preserve current column.
  19944. (when (eq type 'node-property)
  19945. (let ((column (current-column)))
  19946. (org--align-node-property)
  19947. (org-move-to-column column)))))))))
  19948. (defun org-indent-region (start end)
  19949. "Indent each non-blank line in the region.
  19950. Called from a program, START and END specify the region to
  19951. indent. The function will not indent contents of example blocks,
  19952. verse blocks and export blocks as leading white spaces are
  19953. assumed to be significant there."
  19954. (interactive "r")
  19955. (save-excursion
  19956. (goto-char start)
  19957. (skip-chars-forward " \r\t\n")
  19958. (unless (eobp) (beginning-of-line))
  19959. (let ((indent-to
  19960. (lambda (ind pos)
  19961. ;; Set IND as indentation for all lines between point and
  19962. ;; POS. Blank lines are ignored. Leave point after POS
  19963. ;; once done.
  19964. (let ((limit (copy-marker pos)))
  19965. (while (< (point) limit)
  19966. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19967. (forward-line))
  19968. (set-marker limit nil))))
  19969. (end (copy-marker end)))
  19970. (while (< (point) end)
  19971. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19972. (let* ((element (org-element-at-point))
  19973. (type (org-element-type element))
  19974. (element-end (copy-marker (org-element-property :end element)))
  19975. (ind (org--get-expected-indentation element nil)))
  19976. (cond
  19977. ;; Element indented as a single block. Example blocks
  19978. ;; preserving indentation are a special case since the
  19979. ;; "contents" must not be indented whereas the block
  19980. ;; boundaries can.
  19981. ((or (memq type '(export-block latex-environment))
  19982. (and (eq type 'example-block)
  19983. (not
  19984. (or org-src-preserve-indentation
  19985. (org-element-property :preserve-indent element)))))
  19986. (let ((offset (- ind (org-get-indentation))))
  19987. (unless (zerop offset)
  19988. (indent-rigidly (org-element-property :begin element)
  19989. (org-element-property :end element)
  19990. offset)))
  19991. (goto-char element-end))
  19992. ;; Elements indented line wise. Be sure to exclude
  19993. ;; example blocks (preserving indentation) and source
  19994. ;; blocks from this category as they are treated
  19995. ;; specially later.
  19996. ((or (memq type '(paragraph table table-row))
  19997. (not (or (org-element-property :contents-begin element)
  19998. (memq type '(example-block src-block)))))
  19999. (when (eq type 'node-property)
  20000. (org--align-node-property)
  20001. (beginning-of-line))
  20002. (funcall indent-to ind (min element-end end)))
  20003. ;; Elements consisting of three parts: before the
  20004. ;; contents, the contents, and after the contents. The
  20005. ;; contents are treated specially, according to the
  20006. ;; element type, or not indented at all. Other parts are
  20007. ;; indented as a single block.
  20008. (t
  20009. (let* ((post (copy-marker
  20010. (org-element-property :post-affiliated element)))
  20011. (cbeg
  20012. (copy-marker
  20013. (cond
  20014. ((not (org-element-property :contents-begin element))
  20015. ;; Fake contents for source blocks.
  20016. (org-with-wide-buffer
  20017. (goto-char post)
  20018. (line-beginning-position 2)))
  20019. ((memq type '(footnote-definition item plain-list))
  20020. ;; Contents in these elements could start on
  20021. ;; the same line as the beginning of the
  20022. ;; element. Make sure we start indenting
  20023. ;; from the second line.
  20024. (org-with-wide-buffer
  20025. (goto-char post)
  20026. (end-of-line)
  20027. (skip-chars-forward " \r\t\n")
  20028. (if (eobp) (point) (line-beginning-position))))
  20029. (t (org-element-property :contents-begin element)))))
  20030. (cend (copy-marker
  20031. (or (org-element-property :contents-end element)
  20032. ;; Fake contents for source blocks.
  20033. (org-with-wide-buffer
  20034. (goto-char element-end)
  20035. (skip-chars-backward " \r\t\n")
  20036. (line-beginning-position)))
  20037. t)))
  20038. ;; Do not change items indentation individually as it
  20039. ;; might break the list as a whole. On the other
  20040. ;; hand, when at a plain list, indent it as a whole.
  20041. (cond ((eq type 'plain-list)
  20042. (let ((offset (- ind (org-get-indentation))))
  20043. (unless (zerop offset)
  20044. (indent-rigidly (org-element-property :begin element)
  20045. (org-element-property :end element)
  20046. offset))
  20047. (goto-char cbeg)))
  20048. ((eq type 'item) (goto-char cbeg))
  20049. (t (funcall indent-to ind (min cbeg end))))
  20050. (when (< (point) end)
  20051. (cl-case type
  20052. ((example-block verse-block))
  20053. (src-block
  20054. ;; In a source block, indent source code
  20055. ;; according to language major mode, but only if
  20056. ;; `org-src-tab-acts-natively' is non-nil.
  20057. (when (and (< (point) end) org-src-tab-acts-natively)
  20058. (ignore-errors
  20059. (org-babel-do-in-edit-buffer
  20060. (indent-region (point-min) (point-max))))))
  20061. (t (org-indent-region (point) (min cend end))))
  20062. (goto-char (min cend end))
  20063. (when (< (point) end)
  20064. (funcall indent-to ind (min element-end end))))
  20065. (set-marker post nil)
  20066. (set-marker cbeg nil)
  20067. (set-marker cend nil))))
  20068. (set-marker element-end nil))))
  20069. (set-marker end nil))))
  20070. (defun org-indent-drawer ()
  20071. "Indent the drawer at point."
  20072. (interactive)
  20073. (unless (save-excursion
  20074. (beginning-of-line)
  20075. (looking-at-p org-drawer-regexp))
  20076. (user-error "Not at a drawer"))
  20077. (let ((element (org-element-at-point)))
  20078. (unless (memq (org-element-type element) '(drawer property-drawer))
  20079. (user-error "Not at a drawer"))
  20080. (org-with-wide-buffer
  20081. (org-indent-region (org-element-property :begin element)
  20082. (org-element-property :end element))))
  20083. (message "Drawer at point indented"))
  20084. (defun org-indent-block ()
  20085. "Indent the block at point."
  20086. (interactive)
  20087. (unless (save-excursion
  20088. (beginning-of-line)
  20089. (let ((case-fold-search t))
  20090. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20091. (user-error "Not at a block"))
  20092. (let ((element (org-element-at-point)))
  20093. (unless (memq (org-element-type element)
  20094. '(comment-block center-block dynamic-block example-block
  20095. export-block quote-block special-block
  20096. src-block verse-block))
  20097. (user-error "Not at a block"))
  20098. (org-with-wide-buffer
  20099. (org-indent-region (org-element-property :begin element)
  20100. (org-element-property :end element))))
  20101. (message "Block at point indented"))
  20102. ;;; Filling
  20103. ;; We use our own fill-paragraph and auto-fill functions.
  20104. ;; `org-fill-paragraph' relies on adaptive filling and context
  20105. ;; checking. Appropriate `fill-prefix' is computed with
  20106. ;; `org-adaptive-fill-function'.
  20107. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20108. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20109. ;; `org-adaptive-fill-function' value. Internally,
  20110. ;; `org-comment-line-break-function' breaks the line.
  20111. ;; `org-setup-filling' installs filling and auto-filling related
  20112. ;; variables during `org-mode' initialization.
  20113. (defun org-setup-filling ()
  20114. (require 'org-element)
  20115. ;; Prevent auto-fill from inserting unwanted new items.
  20116. (when (boundp 'fill-nobreak-predicate)
  20117. (setq-local
  20118. fill-nobreak-predicate
  20119. (org-uniquify
  20120. (append fill-nobreak-predicate
  20121. '(org-fill-line-break-nobreak-p
  20122. org-fill-n-macro-as-item-nobreak-p
  20123. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20124. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20125. (setq-local paragraph-start paragraph-ending)
  20126. (setq-local paragraph-separate paragraph-ending))
  20127. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20128. (setq-local auto-fill-inhibit-regexp nil)
  20129. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20130. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20131. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20132. (defun org-fill-line-break-nobreak-p ()
  20133. "Non-nil when a new line at point would create an Org line break."
  20134. (save-excursion
  20135. (skip-chars-backward "[ \t]")
  20136. (skip-chars-backward "\\\\")
  20137. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20138. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20139. "Non-nil when a new line at point would split a timestamp."
  20140. (and (org-at-timestamp-p 'lax)
  20141. (not (looking-at org-ts-regexp-both))))
  20142. (defun org-fill-n-macro-as-item-nobreak-p ()
  20143. "Non-nil when a new line at point would create a new list."
  20144. ;; During export, a "n" macro followed by a dot or a closing
  20145. ;; parenthesis can end up being parsed as a new list item.
  20146. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20147. (declare-function message-in-body-p "message" ())
  20148. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20149. (defun org-adaptive-fill-function ()
  20150. "Compute a fill prefix for the current line.
  20151. Return fill prefix, as a string, or nil if current line isn't
  20152. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20153. matches in paragraphs or comments, use it."
  20154. (org-with-wide-buffer
  20155. (unless (org-at-heading-p)
  20156. (let* ((p (line-beginning-position))
  20157. (element (save-excursion
  20158. (beginning-of-line)
  20159. (org-element-at-point)))
  20160. (type (org-element-type element))
  20161. (post-affiliated (org-element-property :post-affiliated element)))
  20162. (unless (< p post-affiliated)
  20163. (cl-case type
  20164. (comment
  20165. (save-excursion
  20166. (beginning-of-line)
  20167. (looking-at "[ \t]*")
  20168. (concat (match-string 0) "# ")))
  20169. (footnote-definition "")
  20170. ((item plain-list)
  20171. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20172. (paragraph
  20173. ;; Fill prefix is usually the same as the current line,
  20174. ;; unless the paragraph is at the beginning of an item.
  20175. (let ((parent (org-element-property :parent element)))
  20176. (save-excursion
  20177. (beginning-of-line)
  20178. (cond ((eq (org-element-type parent) 'item)
  20179. (make-string (org-list-item-body-column
  20180. (org-element-property :begin parent))
  20181. ?\s))
  20182. ((and adaptive-fill-regexp
  20183. ;; Locally disable
  20184. ;; `adaptive-fill-function' to let
  20185. ;; `fill-context-prefix' handle
  20186. ;; `adaptive-fill-regexp' variable.
  20187. (let (adaptive-fill-function)
  20188. (fill-context-prefix
  20189. post-affiliated
  20190. (org-element-property :end element)))))
  20191. ((looking-at "[ \t]+") (match-string 0))
  20192. (t "")))))
  20193. (comment-block
  20194. ;; Only fill contents if P is within block boundaries.
  20195. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20196. (forward-line)
  20197. (point)))
  20198. (cend (save-excursion
  20199. (goto-char (org-element-property :end element))
  20200. (skip-chars-backward " \r\t\n")
  20201. (line-beginning-position))))
  20202. (when (and (>= p cbeg) (< p cend))
  20203. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20204. (match-string 0)
  20205. ""))))))))))
  20206. (declare-function message-goto-body "message" ())
  20207. (defvar message-cite-prefix-regexp) ; From message.el
  20208. (defun org-fill-element (&optional justify)
  20209. "Fill element at point, when applicable.
  20210. This function only applies to comment blocks, comments, example
  20211. blocks and paragraphs. Also, as a special case, re-align table
  20212. when point is at one.
  20213. If JUSTIFY is non-nil (interactively, with prefix argument),
  20214. justify as well. If `sentence-end-double-space' is non-nil, then
  20215. period followed by one space does not end a sentence, so don't
  20216. break a line there. The variable `fill-column' controls the
  20217. width for filling.
  20218. For convenience, when point is at a plain list, an item or
  20219. a footnote definition, try to fill the first paragraph within."
  20220. (with-syntax-table org-mode-transpose-word-syntax-table
  20221. ;; Move to end of line in order to get the first paragraph within
  20222. ;; a plain list or a footnote definition.
  20223. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20224. ;; First check if point is in a blank line at the beginning of
  20225. ;; the buffer. In that case, ignore filling.
  20226. (cl-case (org-element-type element)
  20227. ;; Use major mode filling function is src blocks.
  20228. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20229. ;; Align Org tables, leave table.el tables as-is.
  20230. (table-row (org-table-align) t)
  20231. (table
  20232. (when (eq (org-element-property :type element) 'org)
  20233. (save-excursion
  20234. (goto-char (org-element-property :post-affiliated element))
  20235. (org-table-align)))
  20236. t)
  20237. (paragraph
  20238. ;; Paragraphs may contain `line-break' type objects.
  20239. (let ((beg (max (point-min)
  20240. (org-element-property :contents-begin element)))
  20241. (end (min (point-max)
  20242. (org-element-property :contents-end element))))
  20243. ;; Do nothing if point is at an affiliated keyword.
  20244. (if (< (line-end-position) beg) t
  20245. ;; Fill paragraph, taking line breaks into account.
  20246. (save-excursion
  20247. (goto-char beg)
  20248. (let ((cuts (list beg)))
  20249. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20250. (when (eq 'line-break
  20251. (org-element-type
  20252. (save-excursion (backward-char)
  20253. (org-element-context))))
  20254. (push (point) cuts)))
  20255. (dolist (c (delq end cuts))
  20256. (fill-region-as-paragraph c end justify)
  20257. (setq end c))))
  20258. t)))
  20259. ;; Contents of `comment-block' type elements should be
  20260. ;; filled as plain text, but only if point is within block
  20261. ;; markers.
  20262. (comment-block
  20263. (let* ((case-fold-search t)
  20264. (beg (save-excursion
  20265. (goto-char (org-element-property :begin element))
  20266. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20267. (forward-line)
  20268. (point)))
  20269. (end (save-excursion
  20270. (goto-char (org-element-property :end element))
  20271. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20272. (line-beginning-position))))
  20273. (if (or (< (point) beg) (> (point) end)) t
  20274. (fill-region-as-paragraph
  20275. (save-excursion (end-of-line)
  20276. (re-search-backward "^[ \t]*$" beg 'move)
  20277. (line-beginning-position))
  20278. (save-excursion (beginning-of-line)
  20279. (re-search-forward "^[ \t]*$" end 'move)
  20280. (line-beginning-position))
  20281. justify))))
  20282. ;; Fill comments.
  20283. (comment
  20284. (let ((begin (org-element-property :post-affiliated element))
  20285. (end (org-element-property :end element)))
  20286. (when (and (>= (point) begin) (<= (point) end))
  20287. (let ((begin (save-excursion
  20288. (end-of-line)
  20289. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20290. (progn (forward-line) (point))
  20291. begin)))
  20292. (end (save-excursion
  20293. (end-of-line)
  20294. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20295. (1- (line-beginning-position))
  20296. (skip-chars-backward " \r\t\n")
  20297. (line-end-position)))))
  20298. ;; Do not fill comments when at a blank line.
  20299. (when (> end begin)
  20300. (let ((fill-prefix
  20301. (save-excursion
  20302. (beginning-of-line)
  20303. (looking-at "[ \t]*#")
  20304. (let ((comment-prefix (match-string 0)))
  20305. (goto-char (match-end 0))
  20306. (if (looking-at adaptive-fill-regexp)
  20307. (concat comment-prefix (match-string 0))
  20308. (concat comment-prefix " "))))))
  20309. (save-excursion
  20310. (fill-region-as-paragraph begin end justify))))))
  20311. t))
  20312. ;; Ignore every other element.
  20313. (otherwise t)))))
  20314. (defun org-fill-paragraph (&optional justify region)
  20315. "Fill element at point, when applicable.
  20316. This function only applies to comment blocks, comments, example
  20317. blocks and paragraphs. Also, as a special case, re-align table
  20318. when point is at one.
  20319. For convenience, when point is at a plain list, an item or
  20320. a footnote definition, try to fill the first paragraph within.
  20321. If JUSTIFY is non-nil (interactively, with prefix argument),
  20322. justify as well. If `sentence-end-double-space' is non-nil, then
  20323. period followed by one space does not end a sentence, so don't
  20324. break a line there. The variable `fill-column' controls the
  20325. width for filling.
  20326. The REGION argument is non-nil if called interactively; in that
  20327. case, if Transient Mark mode is enabled and the mark is active,
  20328. fill each of the elements in the active region, instead of just
  20329. filling the current element."
  20330. (interactive (progn
  20331. (barf-if-buffer-read-only)
  20332. (list (if current-prefix-arg 'full) t)))
  20333. (cond
  20334. ((and region transient-mark-mode mark-active
  20335. (not (eq (region-beginning) (region-end))))
  20336. (let ((origin (point-marker))
  20337. (start (region-beginning)))
  20338. (unwind-protect
  20339. (progn
  20340. (goto-char (region-end))
  20341. (while (> (point) start)
  20342. (org-backward-paragraph)
  20343. (org-fill-element justify)))
  20344. (goto-char origin)
  20345. (set-marker origin nil))))
  20346. (t (org-fill-element justify))))
  20347. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20348. (defun org-auto-fill-function ()
  20349. "Auto-fill function."
  20350. ;; Check if auto-filling is meaningful.
  20351. (let ((fc (current-fill-column)))
  20352. (when (and fc (> (current-column) fc))
  20353. (let* ((fill-prefix (org-adaptive-fill-function))
  20354. ;; Enforce empty fill prefix, if required. Otherwise, it
  20355. ;; will be computed again.
  20356. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20357. (when fill-prefix (do-auto-fill))))))
  20358. (defun org-comment-line-break-function (&optional soft)
  20359. "Break line at point and indent, continuing comment if within one.
  20360. The inserted newline is marked hard if variable
  20361. `use-hard-newlines' is true, unless optional argument SOFT is
  20362. non-nil."
  20363. (if soft (insert-and-inherit ?\n) (newline 1))
  20364. (save-excursion (forward-char -1) (delete-horizontal-space))
  20365. (delete-horizontal-space)
  20366. (indent-to-left-margin)
  20367. (insert-before-markers-and-inherit fill-prefix))
  20368. ;;; Fixed Width Areas
  20369. (defun org-toggle-fixed-width ()
  20370. "Toggle fixed-width markup.
  20371. Add or remove fixed-width markup on current line, whenever it
  20372. makes sense. Return an error otherwise.
  20373. If a region is active and if it contains only fixed-width areas
  20374. or blank lines, remove all fixed-width markup in it. If the
  20375. region contains anything else, convert all non-fixed-width lines
  20376. to fixed-width ones.
  20377. Blank lines at the end of the region are ignored unless the
  20378. region only contains such lines."
  20379. (interactive)
  20380. (if (not (org-region-active-p))
  20381. ;; No region:
  20382. ;;
  20383. ;; Remove fixed width marker only in a fixed-with element.
  20384. ;;
  20385. ;; Add fixed width maker in paragraphs, in blank lines after
  20386. ;; elements or at the beginning of a headline or an inlinetask,
  20387. ;; and before any one-line elements (e.g., a clock).
  20388. (progn
  20389. (beginning-of-line)
  20390. (let* ((element (org-element-at-point))
  20391. (type (org-element-type element)))
  20392. (cond
  20393. ((and (eq type 'fixed-width)
  20394. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20395. (replace-match
  20396. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20397. ((and (memq type '(babel-call clock comment diary-sexp headline
  20398. horizontal-rule keyword paragraph
  20399. planning))
  20400. (<= (org-element-property :post-affiliated element) (point)))
  20401. (skip-chars-forward " \t")
  20402. (insert ": "))
  20403. ((and (looking-at-p "[ \t]*$")
  20404. (or (eq type 'inlinetask)
  20405. (save-excursion
  20406. (skip-chars-forward " \r\t\n")
  20407. (<= (org-element-property :end element) (point)))))
  20408. (delete-region (point) (line-end-position))
  20409. (org-indent-line)
  20410. (insert ": "))
  20411. (t (user-error "Cannot insert a fixed-width line here")))))
  20412. ;; Region active.
  20413. (let* ((begin (save-excursion
  20414. (goto-char (region-beginning))
  20415. (line-beginning-position)))
  20416. (end (copy-marker
  20417. (save-excursion
  20418. (goto-char (region-end))
  20419. (unless (eolp) (beginning-of-line))
  20420. (if (save-excursion (re-search-backward "\\S-" begin t))
  20421. (progn (skip-chars-backward " \r\t\n") (point))
  20422. (point)))))
  20423. (all-fixed-width-p
  20424. (catch 'not-all-p
  20425. (save-excursion
  20426. (goto-char begin)
  20427. (skip-chars-forward " \r\t\n")
  20428. (when (eobp) (throw 'not-all-p nil))
  20429. (while (< (point) end)
  20430. (let ((element (org-element-at-point)))
  20431. (if (eq (org-element-type element) 'fixed-width)
  20432. (goto-char (org-element-property :end element))
  20433. (throw 'not-all-p nil))))
  20434. t))))
  20435. (if all-fixed-width-p
  20436. (save-excursion
  20437. (goto-char begin)
  20438. (while (< (point) end)
  20439. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20440. (replace-match
  20441. "" nil nil nil
  20442. (if (= (line-end-position) (match-end 0)) 0 1)))
  20443. (forward-line)))
  20444. (let ((min-ind (point-max)))
  20445. ;; Find minimum indentation across all lines.
  20446. (save-excursion
  20447. (goto-char begin)
  20448. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20449. (setq min-ind 0)
  20450. (catch 'zerop
  20451. (while (< (point) end)
  20452. (unless (looking-at-p "[ \t]*$")
  20453. (let ((ind (org-get-indentation)))
  20454. (setq min-ind (min min-ind ind))
  20455. (when (zerop ind) (throw 'zerop t))))
  20456. (forward-line)))))
  20457. ;; Loop over all lines and add fixed-width markup everywhere
  20458. ;; but in fixed-width lines.
  20459. (save-excursion
  20460. (goto-char begin)
  20461. (while (< (point) end)
  20462. (cond
  20463. ((org-at-heading-p)
  20464. (insert ": ")
  20465. (forward-line)
  20466. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20467. (insert ":")
  20468. (forward-line)))
  20469. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20470. (let* ((element (org-element-at-point))
  20471. (element-end (org-element-property :end element)))
  20472. (if (eq (org-element-type element) 'fixed-width)
  20473. (progn (goto-char element-end)
  20474. (skip-chars-backward " \r\t\n")
  20475. (forward-line))
  20476. (let ((limit (min end element-end)))
  20477. (while (< (point) limit)
  20478. (org-move-to-column min-ind t)
  20479. (insert ": ")
  20480. (forward-line))))))
  20481. (t
  20482. (org-move-to-column min-ind t)
  20483. (insert ": ")
  20484. (forward-line)))))))
  20485. (set-marker end nil))))
  20486. ;;; Blocks
  20487. (defun org-block-map (function &optional start end)
  20488. "Call FUNCTION at the head of all source blocks in the current buffer.
  20489. Optional arguments START and END can be used to limit the range."
  20490. (let ((start (or start (point-min)))
  20491. (end (or end (point-max))))
  20492. (save-excursion
  20493. (goto-char start)
  20494. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20495. (save-excursion
  20496. (save-match-data
  20497. (goto-char (match-beginning 0))
  20498. (funcall function)))))))
  20499. (defun org-next-block (arg &optional backward block-regexp)
  20500. "Jump to the next block.
  20501. With a prefix argument ARG, jump forward ARG many blocks.
  20502. When BACKWARD is non-nil, jump to the previous block.
  20503. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20504. Match data is set according to this regexp when the function
  20505. returns.
  20506. Return point at beginning of the opening line of found block.
  20507. Throw an error if no block is found."
  20508. (interactive "p")
  20509. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20510. (case-fold-search t)
  20511. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20512. (count (or arg 1))
  20513. (origin (point))
  20514. last-element)
  20515. (if backward (beginning-of-line) (end-of-line))
  20516. (while (and (> count 0) (funcall search-fn re nil t))
  20517. (let ((element (save-excursion
  20518. (goto-char (match-beginning 0))
  20519. (save-match-data (org-element-at-point)))))
  20520. (when (and (memq (org-element-type element)
  20521. '(center-block comment-block dynamic-block
  20522. example-block export-block quote-block
  20523. special-block src-block verse-block))
  20524. (<= (match-beginning 0)
  20525. (org-element-property :post-affiliated element)))
  20526. (setq last-element element)
  20527. (cl-decf count))))
  20528. (if (= count 0)
  20529. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20530. (save-match-data (org-show-context)))
  20531. (goto-char origin)
  20532. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20533. (defun org-previous-block (arg &optional block-regexp)
  20534. "Jump to the previous block.
  20535. With a prefix argument ARG, jump backward ARG many source blocks.
  20536. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20537. (interactive "p")
  20538. (org-next-block arg t block-regexp))
  20539. ;;; Comments
  20540. ;; Org comments syntax is quite complex. It requires the entire line
  20541. ;; to be just a comment. Also, even with the right syntax at the
  20542. ;; beginning of line, some elements (e.g., verse-block or
  20543. ;; example-block) don't accept comments. Usual Emacs comment commands
  20544. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20545. ;; Org still relies on `comment-dwim', but cannot trust
  20546. ;; `comment-only-p'. So, `comment-region-function' and
  20547. ;; `uncomment-region-function' both point
  20548. ;; to`org-comment-or-uncomment-region'. Eventually,
  20549. ;; `org-insert-comment' takes care of insertion of comments at the
  20550. ;; beginning of line.
  20551. ;; `org-setup-comments-handling' install comments related variables
  20552. ;; during `org-mode' initialization.
  20553. (defun org-setup-comments-handling ()
  20554. (interactive)
  20555. (setq-local comment-use-syntax nil)
  20556. (setq-local comment-start "# ")
  20557. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20558. (setq-local comment-insert-comment-function 'org-insert-comment)
  20559. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20560. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20561. (defun org-insert-comment ()
  20562. "Insert an empty comment above current line.
  20563. If the line is empty, insert comment at its beginning. When
  20564. point is within a source block, comment according to the related
  20565. major mode."
  20566. (if (let ((element (org-element-at-point)))
  20567. (and (eq (org-element-type element) 'src-block)
  20568. (< (save-excursion
  20569. (goto-char (org-element-property :post-affiliated element))
  20570. (line-end-position))
  20571. (point))
  20572. (> (save-excursion
  20573. (goto-char (org-element-property :end element))
  20574. (skip-chars-backward " \r\t\n")
  20575. (line-beginning-position))
  20576. (point))))
  20577. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20578. (beginning-of-line)
  20579. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20580. (open-line 1))
  20581. (org-indent-line)
  20582. (insert "# ")))
  20583. (defvar comment-empty-lines) ; From newcomment.el.
  20584. (defun org-comment-or-uncomment-region (beg end &rest _)
  20585. "Comment or uncomment each non-blank line in the region.
  20586. Uncomment each non-blank line between BEG and END if it only
  20587. contains commented lines. Otherwise, comment them. If region is
  20588. strictly within a source block, use appropriate comment syntax."
  20589. (if (let ((element (org-element-at-point)))
  20590. (and (eq (org-element-type element) 'src-block)
  20591. (< (save-excursion
  20592. (goto-char (org-element-property :post-affiliated element))
  20593. (line-end-position))
  20594. beg)
  20595. (>= (save-excursion
  20596. (goto-char (org-element-property :end element))
  20597. (skip-chars-backward " \r\t\n")
  20598. (line-beginning-position))
  20599. end)))
  20600. ;; Translate region boundaries for the Org buffer to the source
  20601. ;; buffer.
  20602. (let ((offset (- end beg)))
  20603. (save-excursion
  20604. (goto-char beg)
  20605. (org-babel-do-in-edit-buffer
  20606. (comment-or-uncomment-region (point) (+ offset (point))))))
  20607. (save-restriction
  20608. ;; Restrict region
  20609. (narrow-to-region (save-excursion (goto-char beg)
  20610. (skip-chars-forward " \r\t\n" end)
  20611. (line-beginning-position))
  20612. (save-excursion (goto-char end)
  20613. (skip-chars-backward " \r\t\n" beg)
  20614. (line-end-position)))
  20615. (let ((uncommentp
  20616. ;; UNCOMMENTP is non-nil when every non blank line between
  20617. ;; BEG and END is a comment.
  20618. (save-excursion
  20619. (goto-char (point-min))
  20620. (while (and (not (eobp))
  20621. (let ((element (org-element-at-point)))
  20622. (and (eq (org-element-type element) 'comment)
  20623. (goto-char (min (point-max)
  20624. (org-element-property
  20625. :end element)))))))
  20626. (eobp))))
  20627. (if uncommentp
  20628. ;; Only blank lines and comments in region: uncomment it.
  20629. (save-excursion
  20630. (goto-char (point-min))
  20631. (while (not (eobp))
  20632. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20633. (replace-match "" nil nil nil 1))
  20634. (forward-line)))
  20635. ;; Comment each line in region.
  20636. (let ((min-indent (point-max)))
  20637. ;; First find the minimum indentation across all lines.
  20638. (save-excursion
  20639. (goto-char (point-min))
  20640. (while (and (not (eobp)) (not (zerop min-indent)))
  20641. (unless (looking-at "[ \t]*$")
  20642. (setq min-indent (min min-indent (current-indentation))))
  20643. (forward-line)))
  20644. ;; Then loop over all lines.
  20645. (save-excursion
  20646. (goto-char (point-min))
  20647. (while (not (eobp))
  20648. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20649. ;; Don't get fooled by invisible text (e.g. link path)
  20650. ;; when moving to column MIN-INDENT.
  20651. (let ((buffer-invisibility-spec nil))
  20652. (org-move-to-column min-indent t))
  20653. (insert comment-start))
  20654. (forward-line)))))))))
  20655. (defun org-comment-dwim (_arg)
  20656. "Call the comment command you mean.
  20657. Call `org-toggle-comment' if on a heading, otherwise call
  20658. `comment-dwim', within a source edit buffer if needed."
  20659. (interactive "*P")
  20660. (cond ((org-at-heading-p)
  20661. (call-interactively #'org-toggle-comment))
  20662. ((org-in-src-block-p)
  20663. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20664. (t (call-interactively #'comment-dwim))))
  20665. ;;; Timestamps API
  20666. ;; This section contains tools to operate on, or create, timestamp
  20667. ;; objects, as returned by, e.g. `org-element-context'.
  20668. (defun org-timestamp-from-string (s)
  20669. "Convert Org timestamp S, as a string, into a timestamp object.
  20670. Return nil if S is not a valid timestamp string."
  20671. (when (org-string-nw-p s)
  20672. (with-temp-buffer
  20673. (save-excursion (insert s))
  20674. (org-element-timestamp-parser))))
  20675. (defun org-timestamp-from-time (time &optional with-time inactive)
  20676. "Convert a time value into a timestamp object.
  20677. TIME is an Emacs internal time representation, as returned, e.g.,
  20678. by `current-time'.
  20679. When optional argument WITH-TIME is non-nil, return a timestamp
  20680. object with a time part, i.e., with hours and minutes.
  20681. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20682. return an active timestamp."
  20683. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20684. (org-element-create 'timestamp
  20685. (list :type (if inactive 'inactive 'active)
  20686. :year-start year
  20687. :month-start month
  20688. :day-start day
  20689. :hour-start (and with-time hour)
  20690. :minute-start (and with-time minute)))))
  20691. (defun org-timestamp-to-time (timestamp &optional end)
  20692. "Convert TIMESTAMP object into an Emacs internal time value.
  20693. Use end of date range or time range when END is non-nil.
  20694. Otherwise, use its start."
  20695. (apply #'encode-time
  20696. (cons 0
  20697. (mapcar
  20698. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20699. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20700. '(:minute-start :hour-start :day-start :month-start
  20701. :year-start))))))
  20702. (defun org-timestamp-has-time-p (timestamp)
  20703. "Non-nil when TIMESTAMP has a time specified."
  20704. (org-element-property :hour-start timestamp))
  20705. (defun org-timestamp-format (timestamp format &optional end utc)
  20706. "Format a TIMESTAMP object into a string.
  20707. FORMAT is a format specifier to be passed to
  20708. `format-time-string'.
  20709. When optional argument END is non-nil, use end of date-range or
  20710. time-range, if possible.
  20711. When optional argument UTC is non-nil, time is be expressed as
  20712. Universal Time."
  20713. (format-time-string format (org-timestamp-to-time timestamp end)
  20714. (and utc t)))
  20715. (defun org-timestamp-split-range (timestamp &optional end)
  20716. "Extract a TIMESTAMP object from a date or time range.
  20717. END, when non-nil, means extract the end of the range.
  20718. Otherwise, extract its start.
  20719. Return a new timestamp object."
  20720. (let ((type (org-element-property :type timestamp)))
  20721. (if (memq type '(active inactive diary)) timestamp
  20722. (let ((split-ts (org-element-copy timestamp)))
  20723. ;; Set new type.
  20724. (org-element-put-property
  20725. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20726. ;; Copy start properties over end properties if END is
  20727. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20728. (let ((p-alist '((:minute-start . :minute-end)
  20729. (:hour-start . :hour-end)
  20730. (:day-start . :day-end)
  20731. (:month-start . :month-end)
  20732. (:year-start . :year-end))))
  20733. (dolist (p-cell p-alist)
  20734. (org-element-put-property
  20735. split-ts
  20736. (funcall (if end #'car #'cdr) p-cell)
  20737. (org-element-property
  20738. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20739. ;; Eventually refresh `:raw-value'.
  20740. (org-element-put-property split-ts :raw-value nil)
  20741. (org-element-put-property
  20742. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20743. (defun org-timestamp-translate (timestamp &optional boundary)
  20744. "Translate TIMESTAMP object to custom format.
  20745. Format string is defined in `org-time-stamp-custom-formats',
  20746. which see.
  20747. When optional argument BOUNDARY is non-nil, it is either the
  20748. symbol `start' or `end'. In this case, only translate the
  20749. starting or ending part of TIMESTAMP if it is a date or time
  20750. range. Otherwise, translate both parts.
  20751. Return timestamp as-is if `org-display-custom-times' is nil or if
  20752. it has a `diary' type."
  20753. (let ((type (org-element-property :type timestamp)))
  20754. (if (or (not org-display-custom-times) (eq type 'diary))
  20755. (org-element-interpret-data timestamp)
  20756. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20757. org-time-stamp-custom-formats)))
  20758. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20759. (concat (org-timestamp-format timestamp fmt)
  20760. "--"
  20761. (org-timestamp-format timestamp fmt t))
  20762. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20763. ;;; Other stuff.
  20764. (defvar reftex-docstruct-symbol)
  20765. (defvar org--rds)
  20766. (defun org-reftex-citation ()
  20767. "Use reftex-citation to insert a citation into the buffer.
  20768. This looks for a line like
  20769. #+BIBLIOGRAPHY: foo plain option:-d
  20770. and derives from it that foo.bib is the bibliography file relevant
  20771. for this document. It then installs the necessary environment for RefTeX
  20772. to work in this buffer and calls `reftex-citation' to insert a citation
  20773. into the buffer.
  20774. Export of such citations to both LaTeX and HTML is handled by the contributed
  20775. package ox-bibtex by Taru Karttunen."
  20776. (interactive)
  20777. (let ((reftex-docstruct-symbol 'org--rds)
  20778. org--rds bib)
  20779. (org-with-wide-buffer
  20780. (let ((case-fold-search t)
  20781. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20782. (if (not (save-excursion
  20783. (or (re-search-forward re nil t)
  20784. (re-search-backward re nil t))))
  20785. (user-error "No bibliography defined in file")
  20786. (setq bib (concat (match-string 1) ".bib")
  20787. org--rds (list (list 'bib bib))))))
  20788. (call-interactively 'reftex-citation)))
  20789. ;;;; Functions extending outline functionality
  20790. (defun org-beginning-of-line (&optional n)
  20791. "Go to the beginning of the current visible line.
  20792. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  20793. tags on the first attempt, and only move to after the tags when
  20794. the cursor is already beyond the end of the headline.
  20795. With argument N not nil or 1, move forward N - 1 lines first."
  20796. (interactive "^p")
  20797. (let ((origin (point))
  20798. (special (pcase org-special-ctrl-a/e
  20799. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20800. deactivate-mark)
  20801. ;; First move to a visible line.
  20802. (if (bound-and-true-p visual-line-mode)
  20803. (beginning-of-visual-line n)
  20804. (move-beginning-of-line n)
  20805. ;; `move-beginning-of-line' may leave point after invisible
  20806. ;; characters if line starts with such of these (e.g., with
  20807. ;; a link at column 0). Really move to the beginning of the
  20808. ;; current visible line.
  20809. (beginning-of-line))
  20810. (cond
  20811. ;; No special behavior. Point is already at the beginning of
  20812. ;; a line, logical or visual.
  20813. ((not special))
  20814. ;; `beginning-of-visual-line' left point before logical beginning
  20815. ;; of line: point is at the beginning of a visual line. Bail
  20816. ;; out.
  20817. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20818. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20819. ;; At a headline, special position is before the title, but
  20820. ;; after any TODO keyword or priority cookie.
  20821. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20822. (line-end-position)))
  20823. (bol (point)))
  20824. (if (eq special 'reversed)
  20825. (when (and (= origin bol) (eq last-command this-command))
  20826. (goto-char refpos))
  20827. (when (or (> origin refpos) (= origin bol))
  20828. (goto-char refpos)))))
  20829. ((and (looking-at org-list-full-item-re)
  20830. (memq (org-element-type (save-match-data (org-element-at-point)))
  20831. '(item plain-list)))
  20832. ;; Set special position at first white space character after
  20833. ;; bullet, and check-box, if any.
  20834. (let ((after-bullet
  20835. (let ((box (match-end 3)))
  20836. (cond ((not box) (match-end 1))
  20837. ((eq (char-after box) ?\s) (1+ box))
  20838. (t box)))))
  20839. (if (eq special 'reversed)
  20840. (when (and (= (point) origin) (eq last-command this-command))
  20841. (goto-char after-bullet))
  20842. (when (or (> origin after-bullet) (= (point) origin))
  20843. (goto-char after-bullet)))))
  20844. ;; No special context. Point is already at beginning of line.
  20845. (t nil))))
  20846. (defun org-end-of-line (&optional n)
  20847. "Go to the end of the line, but before ellipsis, if any.
  20848. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  20849. tags on the first attempt, and only move to after the tags when
  20850. the cursor is already beyond the end of the headline.
  20851. With argument N not nil or 1, move forward N - 1 lines first."
  20852. (interactive "^p")
  20853. (let ((origin (point))
  20854. (special (pcase org-special-ctrl-a/e
  20855. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20856. deactivate-mark)
  20857. ;; First move to a visible line.
  20858. (if (bound-and-true-p visual-line-mode)
  20859. (beginning-of-visual-line n)
  20860. (move-beginning-of-line n))
  20861. (cond
  20862. ;; At a headline, with tags.
  20863. ((and special
  20864. (save-excursion
  20865. (beginning-of-line)
  20866. (let ((case-fold-search nil))
  20867. (looking-at org-complex-heading-regexp)))
  20868. (match-end 5))
  20869. (let ((tags (save-excursion
  20870. (goto-char (match-beginning 5))
  20871. (skip-chars-backward " \t")
  20872. (point)))
  20873. (visual-end (and (bound-and-true-p visual-line-mode)
  20874. (save-excursion
  20875. (end-of-visual-line)
  20876. (point)))))
  20877. ;; If `end-of-visual-line' brings us before end of line or
  20878. ;; even tags, i.e., the headline spans over multiple visual
  20879. ;; lines, move there.
  20880. (cond ((and visual-end
  20881. (< visual-end tags)
  20882. (<= origin visual-end))
  20883. (goto-char visual-end))
  20884. ((eq special 'reversed)
  20885. (if (and (= origin (line-end-position))
  20886. (eq this-command last-command))
  20887. (goto-char tags)
  20888. (end-of-line)))
  20889. (t
  20890. (if (or (< origin tags) (= origin (line-end-position)))
  20891. (goto-char tags)
  20892. (end-of-line))))))
  20893. ((bound-and-true-p visual-line-mode)
  20894. (let ((bol (line-beginning-position)))
  20895. (end-of-visual-line)
  20896. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20897. ;; end of a line, backtrack and use `end-of-line' instead.
  20898. (when (/= bol (line-beginning-position))
  20899. (goto-char bol)
  20900. (end-of-line))))
  20901. (t (end-of-line)))))
  20902. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  20903. (define-key org-mode-map "\C-e" 'org-end-of-line)
  20904. (defun org-backward-sentence (&optional _arg)
  20905. "Go to beginning of sentence, or beginning of table field.
  20906. This will call `backward-sentence' or `org-table-beginning-of-field',
  20907. depending on context."
  20908. (interactive)
  20909. (let* ((element (org-element-at-point))
  20910. (contents-begin (org-element-property :contents-begin element))
  20911. (table (org-element-lineage element '(table) t)))
  20912. (if (and table
  20913. (> (point) contents-begin)
  20914. (<= (point) (org-element-property :contents-end table)))
  20915. (call-interactively #'org-table-beginning-of-field)
  20916. (save-restriction
  20917. (when (and contents-begin
  20918. (< (point-min) contents-begin)
  20919. (> (point) contents-begin))
  20920. (narrow-to-region contents-begin
  20921. (org-element-property :contents-end element)))
  20922. (call-interactively #'backward-sentence)))))
  20923. (defun org-forward-sentence (&optional _arg)
  20924. "Go to end of sentence, or end of table field.
  20925. This will call `forward-sentence' or `org-table-end-of-field',
  20926. depending on context."
  20927. (interactive)
  20928. (if (and (org-at-heading-p)
  20929. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20930. (save-restriction
  20931. (narrow-to-region (line-beginning-position) (line-end-position))
  20932. (call-interactively #'forward-sentence))
  20933. (let* ((element (org-element-at-point))
  20934. (contents-end (org-element-property :contents-end element))
  20935. (table (org-element-lineage element '(table) t)))
  20936. (if (and table
  20937. (>= (point) (org-element-property :contents-begin table))
  20938. (< (point) contents-end))
  20939. (call-interactively #'org-table-end-of-field)
  20940. (save-restriction
  20941. (when (and contents-end
  20942. (> (point-max) contents-end)
  20943. ;; Skip blank lines between elements.
  20944. (< (org-element-property :end element)
  20945. (save-excursion (goto-char contents-end)
  20946. (skip-chars-forward " \r\t\n"))))
  20947. (narrow-to-region (org-element-property :contents-begin element)
  20948. contents-end))
  20949. ;; End of heading is considered as the end of a sentence.
  20950. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20951. (call-interactively #'forward-sentence)))))))
  20952. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  20953. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  20954. (defun org-kill-line (&optional _arg)
  20955. "Kill line, to tags or end of line."
  20956. (interactive)
  20957. (cond
  20958. ((or (not org-special-ctrl-k)
  20959. (bolp)
  20960. (not (org-at-heading-p)))
  20961. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  20962. org-ctrl-k-protect-subtree
  20963. (or (eq org-ctrl-k-protect-subtree 'error)
  20964. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20965. (user-error "C-k aborted as it would kill a hidden subtree"))
  20966. (call-interactively
  20967. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20968. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  20969. (kill-region (point) (match-beginning 1))
  20970. (org-set-tags nil t))
  20971. (t (kill-region (point) (point-at-eol)))))
  20972. (define-key org-mode-map "\C-k" 'org-kill-line)
  20973. (defun org-yank (&optional arg)
  20974. "Yank. If the kill is a subtree, treat it specially.
  20975. This command will look at the current kill and check if is a single
  20976. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20977. cursor is at the beginning of a line or after the stars of a currently
  20978. empty headline, then the yank is handled specially. How exactly depends
  20979. on the value of the following variables.
  20980. `org-yank-folded-subtrees'
  20981. By default, this variable is non-nil, which results in
  20982. subtree(s) being folded after insertion, except if doing so
  20983. would swallow text after the yanked text.
  20984. `org-yank-adjusted-subtrees'
  20985. When non-nil (the default value is nil), the subtree will be
  20986. promoted or demoted in order to fit into the local outline tree
  20987. structure, which means that the level will be adjusted so that it
  20988. becomes the smaller one of the two *visible* surrounding headings.
  20989. Any prefix to this command will cause `yank' to be called directly with
  20990. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20991. will just
  20992. plainly yank the text as it is.
  20993. \[1] The test checks if the first non-white line is a heading
  20994. and if there are no other headings with fewer stars."
  20995. (interactive "P")
  20996. (org-yank-generic 'yank arg))
  20997. (defun org-yank-generic (command arg)
  20998. "Perform some yank-like command.
  20999. This function implements the behavior described in the `org-yank'
  21000. documentation. However, it has been generalized to work for any
  21001. interactive command with similar behavior."
  21002. ;; pretend to be command COMMAND
  21003. (setq this-command command)
  21004. (if arg
  21005. (call-interactively command)
  21006. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21007. (and (org-kill-is-subtree-p)
  21008. (or (bolp)
  21009. (and (looking-at "[ \t]*$")
  21010. (string-match
  21011. "\\`\\*+\\'"
  21012. (buffer-substring (point-at-bol) (point)))))))
  21013. swallowp)
  21014. (cond
  21015. ((and subtreep org-yank-folded-subtrees)
  21016. (let ((beg (point))
  21017. end)
  21018. (if (and subtreep org-yank-adjusted-subtrees)
  21019. (org-paste-subtree nil nil 'for-yank)
  21020. (call-interactively command))
  21021. (setq end (point))
  21022. (goto-char beg)
  21023. (when (and (bolp) subtreep
  21024. (not (setq swallowp
  21025. (org-yank-folding-would-swallow-text beg end))))
  21026. (org-with-limited-levels
  21027. (or (looking-at org-outline-regexp)
  21028. (re-search-forward org-outline-regexp-bol end t))
  21029. (while (and (< (point) end) (looking-at org-outline-regexp))
  21030. (outline-hide-subtree)
  21031. (org-cycle-show-empty-lines 'folded)
  21032. (condition-case nil
  21033. (outline-forward-same-level 1)
  21034. (error (goto-char end))))))
  21035. (when swallowp
  21036. (message
  21037. "Inserted text not folded because that would swallow text"))
  21038. (goto-char end)
  21039. (skip-chars-forward " \t\n\r")
  21040. (beginning-of-line 1)
  21041. (push-mark beg 'nomsg)))
  21042. ((and subtreep org-yank-adjusted-subtrees)
  21043. (let ((beg (point-at-bol)))
  21044. (org-paste-subtree nil nil 'for-yank)
  21045. (push-mark beg 'nomsg)))
  21046. (t
  21047. (call-interactively command))))))
  21048. (defun org-yank-folding-would-swallow-text (beg end)
  21049. "Would hide-subtree at BEG swallow any text after END?"
  21050. (let (level)
  21051. (org-with-limited-levels
  21052. (save-excursion
  21053. (goto-char beg)
  21054. (when (or (looking-at org-outline-regexp)
  21055. (re-search-forward org-outline-regexp-bol end t))
  21056. (setq level (org-outline-level)))
  21057. (goto-char end)
  21058. (skip-chars-forward " \t\r\n\v\f")
  21059. (not (or (eobp)
  21060. (and (bolp) (looking-at-p org-outline-regexp)
  21061. (<= (org-outline-level) level))))))))
  21062. (define-key org-mode-map "\C-y" 'org-yank)
  21063. (defun org-back-to-heading (&optional invisible-ok)
  21064. "Call `outline-back-to-heading', but provide a better error message."
  21065. (condition-case nil
  21066. (outline-back-to-heading invisible-ok)
  21067. (error (error "Before first headline at position %d in buffer %s"
  21068. (point) (current-buffer)))))
  21069. (defun org-before-first-heading-p ()
  21070. "Before first heading?"
  21071. (save-excursion
  21072. (end-of-line)
  21073. (null (re-search-backward org-outline-regexp-bol nil t))))
  21074. (defun org-at-heading-p (&optional ignored)
  21075. (outline-on-heading-p t))
  21076. (defun org-in-commented-heading-p (&optional no-inheritance)
  21077. "Non-nil if point is under a commented heading.
  21078. This function also checks ancestors of the current headline,
  21079. unless optional argument NO-INHERITANCE is non-nil."
  21080. (cond
  21081. ((org-before-first-heading-p) nil)
  21082. ((let ((headline (nth 4 (org-heading-components))))
  21083. (and headline
  21084. (let ((case-fold-search nil))
  21085. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21086. headline)))))
  21087. (no-inheritance nil)
  21088. (t
  21089. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21090. (defun org-at-comment-p nil
  21091. "Is cursor in a commented line?"
  21092. (save-excursion
  21093. (save-match-data
  21094. (beginning-of-line)
  21095. (looking-at "^[ \t]*# "))))
  21096. (defun org-at-drawer-p nil
  21097. "Is cursor at a drawer keyword?"
  21098. (save-excursion
  21099. (move-beginning-of-line 1)
  21100. (looking-at org-drawer-regexp)))
  21101. (defun org-at-block-p nil
  21102. "Is cursor at a block keyword?"
  21103. (save-excursion
  21104. (move-beginning-of-line 1)
  21105. (looking-at org-block-regexp)))
  21106. (defun org-point-at-end-of-empty-headline ()
  21107. "If point is at the end of an empty headline, return t, else nil.
  21108. If the heading only contains a TODO keyword, it is still still considered
  21109. empty."
  21110. (let ((case-fold-search nil))
  21111. (and (looking-at "[ \t]*$")
  21112. org-todo-line-regexp
  21113. (save-excursion
  21114. (beginning-of-line)
  21115. (looking-at org-todo-line-regexp)
  21116. (string= (match-string 3) "")))))
  21117. (defun org-at-heading-or-item-p ()
  21118. (or (org-at-heading-p) (org-at-item-p)))
  21119. (defun org-at-target-p ()
  21120. (or (org-in-regexp org-radio-target-regexp)
  21121. (org-in-regexp org-target-regexp)))
  21122. ;; Compatibility alias with Org versions < 7.8.03
  21123. (defalias 'org-on-target-p 'org-at-target-p)
  21124. (defun org-up-heading-all (arg)
  21125. "Move to the heading line of which the present line is a subheading.
  21126. This function considers both visible and invisible heading lines.
  21127. With argument, move up ARG levels."
  21128. (outline-up-heading arg t))
  21129. (defun org-up-heading-safe ()
  21130. "Move to the heading line of which the present line is a subheading.
  21131. This version will not throw an error. It will return the level of the
  21132. headline found, or nil if no higher level is found.
  21133. Also, this function will be a lot faster than `outline-up-heading',
  21134. because it relies on stars being the outline starters. This can really
  21135. make a significant difference in outlines with very many siblings."
  21136. (when (ignore-errors (org-back-to-heading t))
  21137. (let ((level-up (1- (funcall outline-level))))
  21138. (and (> level-up 0)
  21139. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21140. (funcall outline-level)))))
  21141. (defun org-first-sibling-p ()
  21142. "Is this heading the first child of its parents?"
  21143. (interactive)
  21144. (let ((re org-outline-regexp-bol)
  21145. level l)
  21146. (unless (org-at-heading-p t)
  21147. (user-error "Not at a heading"))
  21148. (setq level (funcall outline-level))
  21149. (save-excursion
  21150. (if (not (re-search-backward re nil t))
  21151. t
  21152. (setq l (funcall outline-level))
  21153. (< l level)))))
  21154. (defun org-goto-sibling (&optional previous)
  21155. "Goto the next sibling, even if it is invisible.
  21156. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21157. when a sibling was found. When none is found, return nil and don't
  21158. move point."
  21159. (let ((fun (if previous 're-search-backward 're-search-forward))
  21160. (pos (point))
  21161. (re org-outline-regexp-bol)
  21162. level l)
  21163. (when (ignore-errors (org-back-to-heading t))
  21164. (setq level (funcall outline-level))
  21165. (catch 'exit
  21166. (or previous (forward-char 1))
  21167. (while (funcall fun re nil t)
  21168. (setq l (funcall outline-level))
  21169. (when (< l level) (goto-char pos) (throw 'exit nil))
  21170. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21171. (goto-char pos)
  21172. nil))))
  21173. (defun org-show-siblings ()
  21174. "Show all siblings of the current headline."
  21175. (save-excursion
  21176. (while (org-goto-sibling) (org-flag-heading nil)))
  21177. (save-excursion
  21178. (while (org-goto-sibling 'previous)
  21179. (org-flag-heading nil))))
  21180. (defun org-goto-first-child ()
  21181. "Goto the first child, even if it is invisible.
  21182. Return t when a child was found. Otherwise don't move point and
  21183. return nil."
  21184. (let (level (pos (point)) (re org-outline-regexp-bol))
  21185. (when (ignore-errors (org-back-to-heading t))
  21186. (setq level (outline-level))
  21187. (forward-char 1)
  21188. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21189. (progn (goto-char (match-beginning 0)) t)
  21190. (goto-char pos) nil))))
  21191. (defun org-show-hidden-entry ()
  21192. "Show an entry where even the heading is hidden."
  21193. (save-excursion
  21194. (org-show-entry)))
  21195. (defun org-flag-heading (flag &optional entry)
  21196. "Flag the current heading. FLAG non-nil means make invisible.
  21197. When ENTRY is non-nil, show the entire entry."
  21198. (save-excursion
  21199. (org-back-to-heading t)
  21200. ;; Check if we should show the entire entry
  21201. (if (not entry)
  21202. (org-flag-region
  21203. (line-end-position 0) (line-end-position) flag 'outline)
  21204. (org-show-entry)
  21205. (save-excursion
  21206. (and (outline-next-heading)
  21207. (org-flag-heading nil))))))
  21208. (defun org-get-next-sibling ()
  21209. "Move to next heading of the same level, and return point.
  21210. If there is no such heading, return nil.
  21211. This is like outline-next-sibling, but invisible headings are ok."
  21212. (let ((level (funcall outline-level)))
  21213. (outline-next-heading)
  21214. (while (and (not (eobp)) (> (funcall outline-level) level))
  21215. (outline-next-heading))
  21216. (unless (or (eobp) (< (funcall outline-level) level))
  21217. (point))))
  21218. (defun org-get-last-sibling ()
  21219. "Move to previous heading of the same level, and return point.
  21220. If there is no such heading, return nil."
  21221. (let ((opoint (point))
  21222. (level (funcall outline-level)))
  21223. (outline-previous-heading)
  21224. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21225. (while (and (> (funcall outline-level) level)
  21226. (not (bobp)))
  21227. (outline-previous-heading))
  21228. (unless (< (funcall outline-level) level)
  21229. (point)))))
  21230. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21231. "Goto to the end of a subtree."
  21232. ;; This contains an exact copy of the original function, but it uses
  21233. ;; `org-back-to-heading', to make it work also in invisible
  21234. ;; trees. And is uses an invisible-ok argument.
  21235. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21236. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21237. ;; with many children and grandchildren etc, this can be much faster
  21238. ;; than the outline version.
  21239. (org-back-to-heading invisible-ok)
  21240. (let ((first t)
  21241. (level (funcall outline-level)))
  21242. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21243. ;; A true heading (not a plain list item), in Org
  21244. ;; This means we can easily find the end by looking
  21245. ;; only for the right number of stars. Using a regexp to do
  21246. ;; this is so much faster than using a Lisp loop.
  21247. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21248. (forward-char 1)
  21249. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21250. ;; something else, do it the slow way
  21251. (while (and (not (eobp))
  21252. (or first (> (funcall outline-level) level)))
  21253. (setq first nil)
  21254. (outline-next-heading)))
  21255. (unless to-heading
  21256. (when (memq (preceding-char) '(?\n ?\^M))
  21257. ;; Go to end of line before heading
  21258. (forward-char -1)
  21259. (when (memq (preceding-char) '(?\n ?\^M))
  21260. ;; leave blank line before heading
  21261. (forward-char -1)))))
  21262. (point))
  21263. (defun org-end-of-meta-data (&optional full)
  21264. "Skip planning line and properties drawer in current entry.
  21265. When optional argument FULL is non-nil, also skip empty lines,
  21266. clocking lines and regular drawers at the beginning of the
  21267. entry."
  21268. (org-back-to-heading t)
  21269. (forward-line)
  21270. (when (looking-at-p org-planning-line-re) (forward-line))
  21271. (when (looking-at org-property-drawer-re)
  21272. (goto-char (match-end 0))
  21273. (forward-line))
  21274. (when (and full (not (org-at-heading-p)))
  21275. (catch 'exit
  21276. (let ((end (save-excursion (outline-next-heading) (point)))
  21277. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21278. (while (not (eobp))
  21279. (cond ((looking-at-p org-drawer-regexp)
  21280. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21281. (forward-line)
  21282. (throw 'exit t)))
  21283. ((looking-at-p re) (forward-line))
  21284. (t (throw 'exit t))))))))
  21285. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21286. "Move forward to the ARG'th subheading at same level as this one.
  21287. Stop at the first and last subheadings of a superior heading.
  21288. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21289. non-nil it will also look at invisible ones."
  21290. (interactive "p")
  21291. (let ((backward? (and arg (< arg 0))))
  21292. (if (org-before-first-heading-p)
  21293. (if backward? (goto-char (point-min)) (outline-next-heading))
  21294. (org-back-to-heading invisible-ok)
  21295. (unless backward? (end-of-line)) ;do not match current headline
  21296. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21297. (f (if backward? #'re-search-backward #'re-search-forward))
  21298. (count (if arg (abs arg) 1))
  21299. (result (point)))
  21300. (while (and (> count 0)
  21301. (funcall f org-outline-regexp-bol nil 'move))
  21302. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21303. (cond ((< l level) (setq count 0))
  21304. ((and (= l level)
  21305. (or invisible-ok
  21306. (not (org-invisible-p
  21307. (line-beginning-position)))))
  21308. (cl-decf count)
  21309. (when (= l level) (setq result (point)))))))
  21310. (goto-char result))
  21311. (beginning-of-line))))
  21312. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21313. "Move backward to the ARG'th subheading at same level as this one.
  21314. Stop at the first and last subheadings of a superior heading."
  21315. (interactive "p")
  21316. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21317. (defun org-next-visible-heading (arg)
  21318. "Move to the next visible heading.
  21319. This function wraps `outline-next-visible-heading' with
  21320. `org-with-limited-levels' in order to skip over inline tasks and
  21321. respect customization of `org-odd-levels-only'."
  21322. (interactive "p")
  21323. (org-with-limited-levels
  21324. (outline-next-visible-heading arg)))
  21325. (defun org-previous-visible-heading (arg)
  21326. "Move to the previous visible heading.
  21327. This function wraps `outline-previous-visible-heading' with
  21328. `org-with-limited-levels' in order to skip over inline tasks and
  21329. respect customization of `org-odd-levels-only'."
  21330. (interactive "p")
  21331. (org-with-limited-levels
  21332. (outline-previous-visible-heading arg)))
  21333. (defun org-forward-paragraph ()
  21334. "Move forward to beginning of next paragraph or equivalent.
  21335. The function moves point to the beginning of the next visible
  21336. structural element, which can be a paragraph, a table, a list
  21337. item, etc. It also provides some special moves for convenience:
  21338. - On an affiliated keyword, jump to the beginning of the
  21339. relative element.
  21340. - On an item or a footnote definition, move to the second
  21341. element inside, if any.
  21342. - On a table or a property drawer, jump after it.
  21343. - On a verse or source block, stop after blank lines."
  21344. (interactive)
  21345. (unless (eobp)
  21346. (let* ((deactivate-mark nil)
  21347. (element (org-element-at-point))
  21348. (type (org-element-type element))
  21349. (post-affiliated (org-element-property :post-affiliated element))
  21350. (contents-begin (org-element-property :contents-begin element))
  21351. (contents-end (org-element-property :contents-end element))
  21352. (end (let ((end (org-element-property :end element)) (parent element))
  21353. (while (and (setq parent (org-element-property :parent parent))
  21354. (= (org-element-property :contents-end parent) end))
  21355. (setq end (org-element-property :end parent)))
  21356. end)))
  21357. (cond ((not element)
  21358. (skip-chars-forward " \r\t\n")
  21359. (or (eobp) (beginning-of-line)))
  21360. ;; On affiliated keywords, move to element's beginning.
  21361. ((< (point) post-affiliated)
  21362. (goto-char post-affiliated))
  21363. ;; At a table row, move to the end of the table. Similarly,
  21364. ;; at a node property, move to the end of the property
  21365. ;; drawer.
  21366. ((memq type '(node-property table-row))
  21367. (goto-char (org-element-property
  21368. :end (org-element-property :parent element))))
  21369. ((memq type '(property-drawer table)) (goto-char end))
  21370. ;; Consider blank lines as separators in verse and source
  21371. ;; blocks to ease editing.
  21372. ((memq type '(src-block verse-block))
  21373. (when (eq type 'src-block)
  21374. (setq contents-end
  21375. (save-excursion (goto-char end)
  21376. (skip-chars-backward " \r\t\n")
  21377. (line-beginning-position))))
  21378. (beginning-of-line)
  21379. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21380. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21381. (goto-char end)
  21382. (skip-chars-forward " \r\t\n")
  21383. (if (= (point) contents-end) (goto-char end)
  21384. (beginning-of-line))))
  21385. ;; With no contents, just skip element.
  21386. ((not contents-begin) (goto-char end))
  21387. ;; If contents are invisible, skip the element altogether.
  21388. ((org-invisible-p (line-end-position))
  21389. (cl-case type
  21390. (headline
  21391. (org-with-limited-levels (outline-next-visible-heading 1)))
  21392. ;; At a plain list, make sure we move to the next item
  21393. ;; instead of skipping the whole list.
  21394. (plain-list (forward-char)
  21395. (org-forward-paragraph))
  21396. (otherwise (goto-char end))))
  21397. ((>= (point) contents-end) (goto-char end))
  21398. ((>= (point) contents-begin)
  21399. ;; This can only happen on paragraphs and plain lists.
  21400. (cl-case type
  21401. (paragraph (goto-char end))
  21402. ;; At a plain list, try to move to second element in
  21403. ;; first item, if possible.
  21404. (plain-list (end-of-line)
  21405. (org-forward-paragraph))))
  21406. ;; When contents start on the middle of a line (e.g. in
  21407. ;; items and footnote definitions), try to reach first
  21408. ;; element starting after current line.
  21409. ((> (line-end-position) contents-begin)
  21410. (end-of-line)
  21411. (org-forward-paragraph))
  21412. (t (goto-char contents-begin))))))
  21413. (defun org-backward-paragraph ()
  21414. "Move backward to start of previous paragraph or equivalent.
  21415. The function moves point to the beginning of the current
  21416. structural element, which can be a paragraph, a table, a list
  21417. item, etc., or to the beginning of the previous visible one if
  21418. point is already there. It also provides some special moves for
  21419. convenience:
  21420. - On an affiliated keyword, jump to the first one.
  21421. - On a table or a property drawer, move to its beginning.
  21422. - On comment, example, export, src and verse blocks, stop
  21423. before blank lines."
  21424. (interactive)
  21425. (unless (bobp)
  21426. (let* ((deactivate-mark nil)
  21427. (element (org-element-at-point))
  21428. (type (org-element-type element))
  21429. (contents-end (org-element-property :contents-end element))
  21430. (post-affiliated (org-element-property :post-affiliated element))
  21431. (begin (org-element-property :begin element))
  21432. (special? ;blocks handled specially
  21433. (memq type '(comment-block example-block export-block src-block
  21434. verse-block)))
  21435. (contents-begin
  21436. (if special?
  21437. ;; These types have no proper contents. Fake line
  21438. ;; below the block opening line as contents beginning.
  21439. (save-excursion (goto-char begin) (line-beginning-position 2))
  21440. (org-element-property :contents-begin element))))
  21441. (cond
  21442. ((not element) (goto-char (point-min)))
  21443. ((= (point) begin)
  21444. (backward-char)
  21445. (org-backward-paragraph))
  21446. ((<= (point) post-affiliated) (goto-char begin))
  21447. ;; Special behavior: on a table or a property drawer, move to
  21448. ;; its beginning.
  21449. ((memq type '(node-property table-row))
  21450. (goto-char (org-element-property
  21451. :post-affiliated (org-element-property :parent element))))
  21452. (special?
  21453. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21454. ;; Inside a verse block, see blank lines as paragraph
  21455. ;; separators.
  21456. (let ((origin (point)))
  21457. (skip-chars-backward " \r\t\n" contents-begin)
  21458. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21459. (skip-chars-forward " \r\t\n" origin)
  21460. (if (= (point) origin) (goto-char contents-begin)
  21461. (beginning-of-line))))))
  21462. ((eq type 'paragraph) (goto-char contents-begin)
  21463. ;; When at first paragraph in an item or a footnote definition,
  21464. ;; move directly to beginning of line.
  21465. (let ((parent-contents
  21466. (org-element-property
  21467. :contents-begin (org-element-property :parent element))))
  21468. (when (and parent-contents (= parent-contents contents-begin))
  21469. (beginning-of-line))))
  21470. ;; At the end of a greater element, move to the beginning of
  21471. ;; the last element within.
  21472. ((and contents-end (>= (point) contents-end))
  21473. (goto-char (1- contents-end))
  21474. (org-backward-paragraph))
  21475. (t (goto-char (or post-affiliated begin))))
  21476. ;; Ensure we never leave point invisible.
  21477. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21478. (defun org-forward-element ()
  21479. "Move forward by one element.
  21480. Move to the next element at the same level, when possible."
  21481. (interactive)
  21482. (cond ((eobp) (user-error "Cannot move further down"))
  21483. ((org-with-limited-levels (org-at-heading-p))
  21484. (let ((origin (point)))
  21485. (goto-char (org-end-of-subtree nil t))
  21486. (unless (org-with-limited-levels (org-at-heading-p))
  21487. (goto-char origin)
  21488. (user-error "Cannot move further down"))))
  21489. (t
  21490. (let* ((elem (org-element-at-point))
  21491. (end (org-element-property :end elem))
  21492. (parent (org-element-property :parent elem)))
  21493. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21494. (goto-char (org-element-property :end parent)))
  21495. ((integer-or-marker-p end) (goto-char end))
  21496. (t (message "No element at point")))))))
  21497. (defun org-backward-element ()
  21498. "Move backward by one element.
  21499. Move to the previous element at the same level, when possible."
  21500. (interactive)
  21501. (cond ((bobp) (user-error "Cannot move further up"))
  21502. ((org-with-limited-levels (org-at-heading-p))
  21503. ;; At a headline, move to the previous one, if any, or stay
  21504. ;; here.
  21505. (let ((origin (point)))
  21506. (org-with-limited-levels (org-backward-heading-same-level 1))
  21507. ;; When current headline has no sibling above, move to its
  21508. ;; parent.
  21509. (when (= (point) origin)
  21510. (or (org-with-limited-levels (org-up-heading-safe))
  21511. (progn (goto-char origin)
  21512. (user-error "Cannot move further up"))))))
  21513. (t
  21514. (let* ((elem (org-element-at-point))
  21515. (beg (org-element-property :begin elem)))
  21516. (cond
  21517. ;; Move to beginning of current element if point isn't
  21518. ;; there already.
  21519. ((null beg) (message "No element at point"))
  21520. ((/= (point) beg) (goto-char beg))
  21521. (t (goto-char beg)
  21522. (skip-chars-backward " \r\t\n")
  21523. (unless (bobp)
  21524. (let ((prev (org-element-at-point)))
  21525. (goto-char (org-element-property :begin prev))
  21526. (while (and (setq prev (org-element-property :parent prev))
  21527. (<= (org-element-property :end prev) beg))
  21528. (goto-char (org-element-property :begin prev)))))))))))
  21529. (defun org-up-element ()
  21530. "Move to upper element."
  21531. (interactive)
  21532. (if (org-with-limited-levels (org-at-heading-p))
  21533. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21534. (let* ((elem (org-element-at-point))
  21535. (parent (org-element-property :parent elem)))
  21536. (if parent (goto-char (org-element-property :begin parent))
  21537. (if (org-with-limited-levels (org-before-first-heading-p))
  21538. (user-error "No surrounding element")
  21539. (org-with-limited-levels (org-back-to-heading)))))))
  21540. (defun org-down-element ()
  21541. "Move to inner element."
  21542. (interactive)
  21543. (let ((element (org-element-at-point)))
  21544. (cond
  21545. ((memq (org-element-type element) '(plain-list table))
  21546. (goto-char (org-element-property :contents-begin element))
  21547. (forward-char))
  21548. ((memq (org-element-type element) org-element-greater-elements)
  21549. ;; If contents are hidden, first disclose them.
  21550. (when (org-invisible-p (line-end-position)) (org-cycle))
  21551. (goto-char (or (org-element-property :contents-begin element)
  21552. (user-error "No content for this element"))))
  21553. (t (user-error "No inner element")))))
  21554. (defun org-drag-element-backward ()
  21555. "Move backward element at point."
  21556. (interactive)
  21557. (let ((elem (or (org-element-at-point)
  21558. (user-error "No element at point"))))
  21559. (if (eq (org-element-type elem) 'headline)
  21560. ;; Preserve point when moving a whole tree, even if point was
  21561. ;; on blank lines below the headline.
  21562. (let ((offset (skip-chars-backward " \t\n")))
  21563. (unwind-protect (org-move-subtree-up)
  21564. (forward-char (- offset))))
  21565. (let ((prev-elem
  21566. (save-excursion
  21567. (goto-char (org-element-property :begin elem))
  21568. (skip-chars-backward " \r\t\n")
  21569. (unless (bobp)
  21570. (let* ((beg (org-element-property :begin elem))
  21571. (prev (org-element-at-point))
  21572. (up prev))
  21573. (while (and (setq up (org-element-property :parent up))
  21574. (<= (org-element-property :end up) beg))
  21575. (setq prev up))
  21576. prev)))))
  21577. ;; Error out if no previous element or previous element is
  21578. ;; a parent of the current one.
  21579. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21580. (user-error "Cannot drag element backward")
  21581. (let ((pos (point)))
  21582. (org-element-swap-A-B prev-elem elem)
  21583. (goto-char (+ (org-element-property :begin prev-elem)
  21584. (- pos (org-element-property :begin elem))))))))))
  21585. (defun org-drag-element-forward ()
  21586. "Move forward element at point."
  21587. (interactive)
  21588. (let* ((pos (point))
  21589. (elem (or (org-element-at-point)
  21590. (user-error "No element at point"))))
  21591. (when (= (point-max) (org-element-property :end elem))
  21592. (user-error "Cannot drag element forward"))
  21593. (goto-char (org-element-property :end elem))
  21594. (let ((next-elem (org-element-at-point)))
  21595. (when (or (org-element-nested-p elem next-elem)
  21596. (and (eq (org-element-type next-elem) 'headline)
  21597. (not (eq (org-element-type elem) 'headline))))
  21598. (goto-char pos)
  21599. (user-error "Cannot drag element forward"))
  21600. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21601. ;; body's length (without final blanks) and by the length of
  21602. ;; blanks between ELEM and NEXT-ELEM.
  21603. (let ((size-next (- (save-excursion
  21604. (goto-char (org-element-property :end next-elem))
  21605. (skip-chars-backward " \r\t\n")
  21606. (forward-line)
  21607. ;; Small correction if buffer doesn't end
  21608. ;; with a newline character.
  21609. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21610. (org-element-property :begin next-elem)))
  21611. (size-blank (- (org-element-property :end elem)
  21612. (save-excursion
  21613. (goto-char (org-element-property :end elem))
  21614. (skip-chars-backward " \r\t\n")
  21615. (forward-line)
  21616. (point)))))
  21617. (org-element-swap-A-B elem next-elem)
  21618. (goto-char (+ pos size-next size-blank))))))
  21619. (defun org-drag-line-forward (arg)
  21620. "Drag the line at point ARG lines forward."
  21621. (interactive "p")
  21622. (dotimes (_ (abs arg))
  21623. (let ((c (current-column)))
  21624. (if (< 0 arg)
  21625. (progn
  21626. (beginning-of-line 2)
  21627. (transpose-lines 1)
  21628. (beginning-of-line 0))
  21629. (transpose-lines 1)
  21630. (beginning-of-line -1))
  21631. (org-move-to-column c))))
  21632. (defun org-drag-line-backward (arg)
  21633. "Drag the line at point ARG lines backward."
  21634. (interactive "p")
  21635. (org-drag-line-forward (- arg)))
  21636. (defun org-mark-element ()
  21637. "Put point at beginning of this element, mark at end.
  21638. Interactively, if this command is repeated or (in Transient Mark
  21639. mode) if the mark is active, it marks the next element after the
  21640. ones already marked."
  21641. (interactive)
  21642. (let (deactivate-mark)
  21643. (if (and (called-interactively-p 'any)
  21644. (or (and (eq last-command this-command) (mark t))
  21645. (and transient-mark-mode mark-active)))
  21646. (set-mark
  21647. (save-excursion
  21648. (goto-char (mark))
  21649. (goto-char (org-element-property :end (org-element-at-point)))))
  21650. (let ((element (org-element-at-point)))
  21651. (end-of-line)
  21652. (push-mark (org-element-property :end element) t t)
  21653. (goto-char (org-element-property :begin element))))))
  21654. (defun org-narrow-to-element ()
  21655. "Narrow buffer to current element."
  21656. (interactive)
  21657. (let ((elem (org-element-at-point)))
  21658. (cond
  21659. ((eq (car elem) 'headline)
  21660. (narrow-to-region
  21661. (org-element-property :begin elem)
  21662. (org-element-property :end elem)))
  21663. ((memq (car elem) org-element-greater-elements)
  21664. (narrow-to-region
  21665. (org-element-property :contents-begin elem)
  21666. (org-element-property :contents-end elem)))
  21667. (t
  21668. (narrow-to-region
  21669. (org-element-property :begin elem)
  21670. (org-element-property :end elem))))))
  21671. (defun org-transpose-element ()
  21672. "Transpose current and previous elements, keeping blank lines between.
  21673. Point is moved after both elements."
  21674. (interactive)
  21675. (org-skip-whitespace)
  21676. (let ((end (org-element-property :end (org-element-at-point))))
  21677. (org-drag-element-backward)
  21678. (goto-char end)))
  21679. (defun org-unindent-buffer ()
  21680. "Un-indent the visible part of the buffer.
  21681. Relative indentation (between items, inside blocks, etc.) isn't
  21682. modified."
  21683. (interactive)
  21684. (unless (eq major-mode 'org-mode)
  21685. (user-error "Cannot un-indent a buffer not in Org mode"))
  21686. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21687. (unindent-tree
  21688. (lambda (contents)
  21689. (dolist (element (reverse contents))
  21690. (if (memq (org-element-type element) '(headline section))
  21691. (funcall unindent-tree (org-element-contents element))
  21692. (save-excursion
  21693. (save-restriction
  21694. (narrow-to-region
  21695. (org-element-property :begin element)
  21696. (org-element-property :end element))
  21697. (org-do-remove-indentation))))))))
  21698. (funcall unindent-tree (org-element-contents parse-tree))))
  21699. (defun org-make-options-regexp (kwds &optional extra)
  21700. "Make a regular expression for keyword lines.
  21701. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21702. when non-nil, is a regexp matching keywords names."
  21703. (concat "^[ \t]*#\\+\\("
  21704. (regexp-opt kwds)
  21705. (and extra (concat (and kwds "\\|") extra))
  21706. "\\):[ \t]*\\(.*\\)"))
  21707. ;;; Finish up
  21708. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21709. (lambda () (add-hook 'change-major-mode-hook
  21710. 'org-show-all 'append 'local)))
  21711. (provide 'org)
  21712. (run-hooks 'org-load-hook)
  21713. ;;; org.el ends here