org.el 941 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function org-element-at-point "org-element" ())
  119. (declare-function org-element-cache-refresh "org-element" (pos))
  120. (declare-function org-element-cache-reset "org-element" (&optional all))
  121. (declare-function org-element-contents "org-element" (element))
  122. (declare-function org-element-context "org-element" (&optional element))
  123. (declare-function org-element-copy "org-element" (datum))
  124. (declare-function org-element-interpret-data "org-element" (data))
  125. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  126. (declare-function org-element-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 org-table-wrap-region "org-table" (arg))
  157. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  158. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  159. (declare-function orgtbl-mode "org-table" (&optional arg))
  160. (declare-function org-export-get-backend "ox" (name))
  161. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (defsubst org-uniquify (list)
  164. "Non-destructively remove duplicate elements from LIST."
  165. (let ((res (copy-sequence list))) (delete-dups res)))
  166. (defsubst org-get-at-bol (property)
  167. "Get text property PROPERTY at the beginning of line."
  168. (get-text-property (point-at-bol) property))
  169. (defsubst org-trim (s &optional keep-lead)
  170. "Remove whitespace at the beginning and the end of string S.
  171. When optional argument KEEP-LEAD is non-nil, removing blank lines
  172. at the beginning of the string does not affect leading indentation."
  173. (replace-regexp-in-string
  174. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  175. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  176. ;; load languages based on value of `org-babel-load-languages'
  177. (defvar org-babel-load-languages)
  178. ;;;###autoload
  179. (defun org-babel-do-load-languages (sym value)
  180. "Load the languages defined in `org-babel-load-languages'."
  181. (set-default sym value)
  182. (dolist (pair org-babel-load-languages)
  183. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  184. (if active
  185. (require (intern (concat "ob-" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-execute:" lang)))
  188. (funcall 'fmakunbound
  189. (intern (concat "org-babel-expand-body:" lang)))))))
  190. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  191. ;;;###autoload
  192. (defun org-babel-load-file (file &optional compile)
  193. "Load Emacs Lisp source code blocks in the Org FILE.
  194. This function exports the source code using `org-babel-tangle'
  195. and then loads the resulting file using `load-file'. With prefix
  196. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  197. file to byte-code before it is loaded."
  198. (interactive "fFile to load: \nP")
  199. (let* ((age (lambda (file)
  200. (float-time
  201. (time-subtract (current-time)
  202. (nth 5 (or (file-attributes (file-truename file))
  203. (file-attributes file)))))))
  204. (base-name (file-name-sans-extension file))
  205. (exported-file (concat base-name ".el")))
  206. ;; tangle if the Org file is newer than the elisp file
  207. (unless (and (file-exists-p exported-file)
  208. (> (funcall age file) (funcall age exported-file)))
  209. ;; Tangle-file traversal returns reversed list of tangled files
  210. ;; and we want to evaluate the first target.
  211. (setq exported-file
  212. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  213. (message "%s %s"
  214. (if compile
  215. (progn (byte-compile-file exported-file 'load)
  216. "Compiled and loaded")
  217. (progn (load-file exported-file) "Loaded"))
  218. exported-file)))
  219. (defcustom org-babel-load-languages '((emacs-lisp . t))
  220. "Languages which can be evaluated in Org buffers.
  221. This list can be used to load support for any of the languages
  222. below, note that each language will depend on a different set of
  223. system executables and/or Emacs modes. When a language is
  224. \"loaded\", then code blocks in that language can be evaluated
  225. with `org-babel-execute-src-block' bound by default to C-c
  226. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  227. be set to remove code block evaluation from the C-c C-c
  228. keybinding. By default only Emacs Lisp (which has no
  229. requirements) is loaded."
  230. :group 'org-babel
  231. :set 'org-babel-do-load-languages
  232. :version "24.1"
  233. :type '(alist :tag "Babel Languages"
  234. :key-type
  235. (choice
  236. (const :tag "Awk" awk)
  237. (const :tag "C" C)
  238. (const :tag "R" R)
  239. (const :tag "Asymptote" asymptote)
  240. (const :tag "Calc" calc)
  241. (const :tag "Clojure" clojure)
  242. (const :tag "CSS" css)
  243. (const :tag "Ditaa" ditaa)
  244. (const :tag "Dot" dot)
  245. (const :tag "Emacs Lisp" emacs-lisp)
  246. (const :tag "Forth" forth)
  247. (const :tag "Fortran" fortran)
  248. (const :tag "Gnuplot" gnuplot)
  249. (const :tag "Haskell" haskell)
  250. (const :tag "IO" io)
  251. (const :tag "J" J)
  252. (const :tag "Java" java)
  253. (const :tag "Javascript" js)
  254. (const :tag "LaTeX" latex)
  255. (const :tag "Ledger" ledger)
  256. (const :tag "Lilypond" lilypond)
  257. (const :tag "Lisp" lisp)
  258. (const :tag "Makefile" makefile)
  259. (const :tag "Maxima" maxima)
  260. (const :tag "Matlab" matlab)
  261. (const :tag "Mscgen" mscgen)
  262. (const :tag "Ocaml" ocaml)
  263. (const :tag "Octave" octave)
  264. (const :tag "Org" org)
  265. (const :tag "Perl" perl)
  266. (const :tag "Pico Lisp" picolisp)
  267. (const :tag "PlantUML" plantuml)
  268. (const :tag "Python" python)
  269. (const :tag "Ruby" ruby)
  270. (const :tag "Sass" sass)
  271. (const :tag "Scala" scala)
  272. (const :tag "Scheme" scheme)
  273. (const :tag "Screen" screen)
  274. (const :tag "Shell Script" shell)
  275. (const :tag "Shen" shen)
  276. (const :tag "Sql" sql)
  277. (const :tag "Sqlite" sqlite)
  278. (const :tag "Stan" stan)
  279. (const :tag "ebnf2ps" ebnf2ps))
  280. :value-type (boolean :tag "Activate" :value t)))
  281. ;;;; Customization variables
  282. (defcustom org-clone-delete-id nil
  283. "Remove ID property of clones of a subtree.
  284. When non-nil, clones of a subtree don't inherit the ID property.
  285. Otherwise they inherit the ID property with a new unique
  286. identifier."
  287. :type 'boolean
  288. :version "24.1"
  289. :group 'org-id)
  290. ;;; Version
  291. (org-check-version)
  292. ;;;###autoload
  293. (defun org-version (&optional here full message)
  294. "Show the Org version.
  295. Interactively, or when MESSAGE is non-nil, show it in echo area.
  296. With prefix argument, or when HERE is non-nil, insert it at point.
  297. In non-interactive uses, a reduced version string is output unless
  298. FULL is given."
  299. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  300. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  301. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  302. (load-suffixes (list ".el"))
  303. (org-install-dir
  304. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  305. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  306. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  307. (let* ((load-suffixes save-load-suffixes)
  308. (release (org-release))
  309. (git-version (org-git-version))
  310. (version (format "Org mode version %s (%s @ %s)"
  311. release
  312. git-version
  313. (if org-install-dir
  314. (if (string= org-dir org-install-dir)
  315. org-install-dir
  316. (concat "mixed installation! "
  317. org-install-dir
  318. " and "
  319. org-dir))
  320. "org-loaddefs.el can not be found!")))
  321. (version1 (if full version release)))
  322. (when here (insert version1))
  323. (when message (message "%s" version1))
  324. version1)))
  325. (defconst org-version (org-version))
  326. ;;; Syntax Constants
  327. ;;;; Block
  328. (defconst org-block-regexp
  329. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  330. "Regular expression for hiding blocks.")
  331. (defconst org-dblock-start-re
  332. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  333. "Matches the start line of a dynamic block, with parameters.")
  334. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  335. "Matches the end of a dynamic block.")
  336. ;;;; Clock and Planning
  337. (defconst org-clock-string "CLOCK:"
  338. "String used as prefix for timestamps clocking work hours on an item.")
  339. (defvar org-closed-string "CLOSED:"
  340. "String used as the prefix for timestamps logging closing a TODO entry.")
  341. (defvar org-deadline-string "DEADLINE:"
  342. "String to mark deadline entries.
  343. \\<org-mode-map>
  344. A deadline is this string, followed by a time stamp. It must be
  345. a word, terminated by a colon. You can insert a schedule keyword
  346. and a timestamp with `\\[org-deadline]'.")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. \\<org-mode-map>
  350. A schedule is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-schedule]'.")
  353. (defconst org-ds-keyword-length
  354. (+ 2
  355. (apply #'max
  356. (mapcar #'length
  357. (list org-deadline-string org-scheduled-string
  358. org-clock-string org-closed-string))))
  359. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  360. (defconst org-planning-line-re
  361. (concat "^[ \t]*"
  362. (regexp-opt
  363. (list org-closed-string org-deadline-string org-scheduled-string)
  364. t))
  365. "Matches a line with planning info.
  366. Matched keyword is in group 1.")
  367. (defconst org-clock-line-re
  368. (concat "^[ \t]*" org-clock-string)
  369. "Matches a line with clock info.")
  370. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  371. "Matches the DEADLINE keyword.")
  372. (defconst org-deadline-time-regexp
  373. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  374. "Matches the DEADLINE keyword together with a time stamp.")
  375. (defconst org-deadline-time-hour-regexp
  376. (concat "\\<" org-deadline-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  378. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  379. (defconst org-deadline-line-regexp
  380. (concat "\\<\\(" org-deadline-string "\\).*")
  381. "Matches the DEADLINE keyword and the rest of the line.")
  382. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  383. "Matches the SCHEDULED keyword.")
  384. (defconst org-scheduled-time-regexp
  385. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  386. "Matches the SCHEDULED keyword together with a time stamp.")
  387. (defconst org-scheduled-time-hour-regexp
  388. (concat "\\<" org-scheduled-string
  389. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  390. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  391. (defconst org-closed-time-regexp
  392. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  393. "Matches the CLOSED keyword together with a time stamp.")
  394. (defconst org-keyword-time-regexp
  395. (concat "\\<"
  396. (regexp-opt
  397. (list org-scheduled-string org-deadline-string org-closed-string
  398. org-clock-string)
  399. t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 4 keywords, together with the time stamp.")
  402. (defconst org-keyword-time-not-clock-regexp
  403. (concat
  404. "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string) t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 3 keywords, together with the time stamp.")
  409. (defconst org-maybe-keyword-time-regexp
  410. (concat "\\(\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string
  413. org-clock-string)
  414. t)
  415. "\\)?"
  416. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  417. "\\|"
  418. "<%%([^\r\n>]*>\\)")
  419. "Matches a timestamp, possibly preceded by a keyword.")
  420. (defconst org-all-time-keywords
  421. (mapcar (lambda (w) (substring w 0 -1))
  422. (list org-scheduled-string org-deadline-string
  423. org-clock-string org-closed-string))
  424. "List of time keywords.")
  425. ;;;; Drawer
  426. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  427. "Matches first or last line of a hidden block.
  428. Group 1 contains drawer's name or \"END\".")
  429. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  430. "Regular expression matching the first line of a property drawer.")
  431. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a property drawer.")
  433. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  434. "Regular expression matching the first line of a clock drawer.")
  435. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  436. "Regular expression matching the last line of a clock drawer.")
  437. (defconst org-property-drawer-re
  438. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  439. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  440. "[ \t]*:END:[ \t]*$")
  441. "Matches an entire property drawer.")
  442. (defconst org-clock-drawer-re
  443. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  444. org-clock-drawer-end-re "\\)\n?")
  445. "Matches an entire clock drawer.")
  446. ;;;; Headline
  447. (defconst org-heading-keyword-regexp-format
  448. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  449. "Printf format for a regexp matching a headline with some keyword.
  450. This regexp will match the headline of any node which has the
  451. exact keyword that is put into the format. The keyword isn't in
  452. any group by default, but the stars and the body are.")
  453. (defconst org-heading-keyword-maybe-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline, possibly with some keyword.
  456. This regexp can match any headline with the specified keyword, or
  457. without a keyword. The keyword isn't in any group by default,
  458. but the stars and the body are.")
  459. (defconst org-archive-tag "ARCHIVE"
  460. "The tag that marks a subtree as archived.
  461. An archived subtree does not open during visibility cycling, and does
  462. not contribute to the agenda listings.")
  463. (defconst org-comment-string "COMMENT"
  464. "Entries starting with this keyword will never be exported.
  465. \\<org-mode-map>
  466. An entry can be toggled between COMMENT and normal with
  467. `\\[org-toggle-comment]'.")
  468. ;;;; LaTeX Environments and Fragments
  469. (defconst org-latex-regexps
  470. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  471. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  472. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  473. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  474. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  475. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  476. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  477. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  478. "Regular expressions for matching embedded LaTeX.")
  479. ;;;; Node Property
  480. (defconst org-effort-property "Effort"
  481. "The property that is being used to keep track of effort estimates.
  482. Effort estimates given in this property need to have the format H:MM.")
  483. ;;;; Table
  484. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  485. "Detect an org-type or table-type table.")
  486. (defconst org-table-line-regexp "^[ \t]*|"
  487. "Detect an org-type table line.")
  488. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  489. "Detect an org-type table line.")
  490. (defconst org-table-hline-regexp "^[ \t]*|-"
  491. "Detect an org-type table hline.")
  492. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  493. "Detect a table-type table hline.")
  494. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  495. "Detect the first line outside a table when searching from within it.
  496. This works for both table types.")
  497. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  498. "Detect a #+TBLFM line.")
  499. ;;;; Timestamp
  500. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  501. "Regular expression for fast time stamp matching.")
  502. (defconst org-ts-regexp-inactive
  503. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  504. "Regular expression for fast inactive time stamp matching.")
  505. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  506. "Regular expression for fast time stamp matching.")
  507. (defconst org-ts-regexp0
  508. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  509. "Regular expression matching time strings for analysis.
  510. This one does not require the space after the date, so it can be used
  511. on a string that terminates immediately after the date.")
  512. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  513. "Regular expression matching time strings for analysis.")
  514. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  515. "Regular expression matching time stamps, with groups.")
  516. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  517. "Regular expression matching time stamps (also [..]), with groups.")
  518. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  519. "Regular expression matching a time stamp range.")
  520. (defconst org-tr-regexp-both
  521. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  522. "Regular expression matching a time stamp range.")
  523. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  524. org-ts-regexp "\\)?")
  525. "Regular expression matching a time stamp or time stamp range.")
  526. (defconst org-tsr-regexp-both
  527. (concat org-ts-regexp-both "\\(--?-?"
  528. org-ts-regexp-both "\\)?")
  529. "Regular expression matching a time stamp or time stamp range.
  530. The time stamps may be either active or inactive.")
  531. (defconst org-repeat-re
  532. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  533. "Regular expression for specifying repeated events.
  534. After a match, group 1 contains the repeat expression.")
  535. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  536. "Formats for `format-time-string' which are used for time stamps.")
  537. ;;; The custom variables
  538. (defgroup org nil
  539. "Outline-based notes management and organizer."
  540. :tag "Org"
  541. :group 'outlines
  542. :group 'calendar)
  543. (defcustom org-mode-hook nil
  544. "Mode hook for Org mode, run after the mode was turned on."
  545. :group 'org
  546. :type 'hook)
  547. (defcustom org-load-hook nil
  548. "Hook that is run after org.el has been loaded."
  549. :group 'org
  550. :type 'hook)
  551. (defcustom org-log-buffer-setup-hook nil
  552. "Hook that is run after an Org log buffer is created."
  553. :group 'org
  554. :version "24.1"
  555. :type 'hook)
  556. (defvar org-modules) ; defined below
  557. (defvar org-modules-loaded nil
  558. "Have the modules been loaded already?")
  559. (defun org-load-modules-maybe (&optional force)
  560. "Load all extensions listed in `org-modules'."
  561. (when (or force (not org-modules-loaded))
  562. (dolist (ext org-modules)
  563. (condition-case nil (require ext)
  564. (error (message "Problems while trying to load feature `%s'" ext))))
  565. (setq org-modules-loaded t)))
  566. (defun org-set-modules (var value)
  567. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  568. (set var value)
  569. (when (featurep 'org)
  570. (org-load-modules-maybe 'force)
  571. (org-element-cache-reset 'all)))
  572. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  573. "Modules that should always be loaded together with org.el.
  574. If a description starts with <C>, the file is not part of Emacs
  575. and loading it will require that you have downloaded and properly
  576. installed the Org mode distribution.
  577. You can also use this system to load external packages (i.e. neither Org
  578. core modules, nor modules from the CONTRIB directory). Just add symbols
  579. to the end of the list. If the package is called org-xyz.el, then you need
  580. to add the symbol `xyz', and the package must have a call to:
  581. (provide \\='org-xyz)
  582. For export specific modules, see also `org-export-backends'."
  583. :group 'org
  584. :set 'org-set-modules
  585. :version "24.4"
  586. :package-version '(Org . "8.0")
  587. :type
  588. '(set :greedy t
  589. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  590. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  591. (const :tag " crypt: Encryption of subtrees" org-crypt)
  592. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  593. (const :tag " docview: Links to doc-view buffers" org-docview)
  594. (const :tag " eww: Store link to url of eww" org-eww)
  595. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  596. (const :tag " habit: Track your consistency with habits" org-habit)
  597. (const :tag " id: Global IDs for identifying entries" org-id)
  598. (const :tag " info: Links to Info nodes" org-info)
  599. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  600. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  601. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  602. (const :tag " mouse: Additional mouse support" org-mouse)
  603. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  604. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  605. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  606. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  607. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  608. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  609. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  610. (const :tag "C collector: Collect properties into tables" org-collector)
  611. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  612. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  613. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  614. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  615. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  616. (const :tag "C eval: Include command output as text" org-eval)
  617. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  618. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  619. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  620. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  621. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  622. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  623. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  624. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  625. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  626. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  627. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  628. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  629. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  630. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  631. (const :tag "C registry: A registry for Org links" org-registry)
  632. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  633. (const :tag "C secretary: Team management with org-mode" org-secretary)
  634. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  635. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  636. (const :tag "C track: Keep up with Org mode development" org-track)
  637. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  638. (const :tag "C vm: Links to VM folders/messages" org-vm)
  639. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  640. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  641. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  642. (defvar org-export-registered-backends) ; From ox.el.
  643. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  644. (declare-function org-export-backend-name "ox" (backend) t)
  645. (defcustom org-export-backends '(ascii html icalendar latex odt)
  646. "List of export back-ends that should be always available.
  647. If a description starts with <C>, the file is not part of Emacs
  648. and loading it will require that you have downloaded and properly
  649. installed the Org mode distribution.
  650. Unlike to `org-modules', libraries in this list will not be
  651. loaded along with Org, but only once the export framework is
  652. needed.
  653. This variable needs to be set before org.el is loaded. If you
  654. need to make a change while Emacs is running, use the customize
  655. interface or run the following code, where VAL stands for the new
  656. value of the variable, after updating it:
  657. (progn
  658. (setq org-export-registered-backends
  659. (cl-remove-if-not
  660. (lambda (backend)
  661. (let ((name (org-export-backend-name backend)))
  662. (or (memq name val)
  663. (catch \\='parentp
  664. (dolist (b val)
  665. (and (org-export-derived-backend-p b name)
  666. (throw \\='parentp t)))))))
  667. org-export-registered-backends))
  668. (let ((new-list (mapcar #\\='org-export-backend-name
  669. org-export-registered-backends)))
  670. (dolist (backend val)
  671. (cond
  672. ((not (load (format \"ox-%s\" backend) t t))
  673. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  674. backend))
  675. ((not (memq backend new-list)) (push backend new-list))))
  676. (set-default \\='org-export-backends new-list)))
  677. Adding a back-end to this list will also pull the back-end it
  678. depends on, if any."
  679. :group 'org
  680. :group 'org-export
  681. :version "26.1"
  682. :package-version '(Org . "9.0")
  683. :initialize 'custom-initialize-set
  684. :set (lambda (var val)
  685. (if (not (featurep 'ox)) (set-default var val)
  686. ;; Any back-end not required anymore (not present in VAL and not
  687. ;; a parent of any back-end in the new value) is removed from the
  688. ;; list of registered back-ends.
  689. (setq org-export-registered-backends
  690. (cl-remove-if-not
  691. (lambda (backend)
  692. (let ((name (org-export-backend-name backend)))
  693. (or (memq name val)
  694. (catch 'parentp
  695. (dolist (b val)
  696. (and (org-export-derived-backend-p b name)
  697. (throw 'parentp t)))))))
  698. org-export-registered-backends))
  699. ;; Now build NEW-LIST of both new back-ends and required
  700. ;; parents.
  701. (let ((new-list (mapcar #'org-export-backend-name
  702. org-export-registered-backends)))
  703. (dolist (backend val)
  704. (cond
  705. ((not (load (format "ox-%s" backend) t t))
  706. (message "Problems while trying to load export back-end `%s'"
  707. backend))
  708. ((not (memq backend new-list)) (push backend new-list))))
  709. ;; Set VAR to that list with fixed dependencies.
  710. (set-default var new-list))))
  711. :type '(set :greedy t
  712. (const :tag " ascii Export buffer to ASCII format" ascii)
  713. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  714. (const :tag " html Export buffer to HTML format" html)
  715. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  716. (const :tag " latex Export buffer to LaTeX format" latex)
  717. (const :tag " man Export buffer to MAN format" man)
  718. (const :tag " md Export buffer to Markdown format" md)
  719. (const :tag " odt Export buffer to ODT format" odt)
  720. (const :tag " org Export buffer to Org format" org)
  721. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  722. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  723. (const :tag "C deck Export buffer to deck.js presentations" deck)
  724. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  725. (const :tag "C groff Export buffer to Groff format" groff)
  726. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  727. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  728. (const :tag "C s5 Export buffer to s5 presentations" s5)
  729. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  730. (eval-after-load 'ox
  731. '(dolist (backend org-export-backends)
  732. (condition-case nil (require (intern (format "ox-%s" backend)))
  733. (error (message "Problems while trying to load export back-end `%s'"
  734. backend)))))
  735. (defcustom org-support-shift-select nil
  736. "Non-nil means make shift-cursor commands select text when possible.
  737. \\<org-mode-map>\
  738. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  739. start selecting a region, or enlarge regions started in this way.
  740. In Org mode, in special contexts, these same keys are used for
  741. other purposes, important enough to compete with shift selection.
  742. Org tries to balance these needs by supporting `shift-select-mode'
  743. outside these special contexts, under control of this variable.
  744. The default of this variable is nil, to avoid confusing behavior. Shifted
  745. cursor keys will then execute Org commands in the following contexts:
  746. - on a headline, changing TODO state (left/right) and priority (up/down)
  747. - on a time stamp, changing the time
  748. - in a plain list item, changing the bullet type
  749. - in a property definition line, switching between allowed values
  750. - in the BEGIN line of a clock table (changing the time block).
  751. Outside these contexts, the commands will throw an error.
  752. When this variable is t and the cursor is not in a special
  753. context, Org mode will support shift-selection for making and
  754. enlarging regions. To make this more effective, the bullet
  755. cycling will no longer happen anywhere in an item line, but only
  756. if the cursor is exactly on the bullet.
  757. If you set this variable to the symbol `always', then the keys
  758. will not be special in headlines, property lines, and item lines,
  759. to make shift selection work there as well. If this is what you
  760. want, you can use the following alternative commands:
  761. `\\[org-todo]' and `\\[org-priority]' \
  762. to change TODO state and priority,
  763. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  764. can be used to switch TODO sets,
  765. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  766. and properties can be edited by hand or in column view.
  767. However, when the cursor is on a timestamp, shift-cursor commands
  768. will still edit the time stamp - this is just too good to give up."
  769. :group 'org
  770. :type '(choice
  771. (const :tag "Never" nil)
  772. (const :tag "When outside special context" t)
  773. (const :tag "Everywhere except timestamps" always)))
  774. (defcustom org-loop-over-headlines-in-active-region nil
  775. "Shall some commands act upon headlines in the active region?
  776. When set to t, some commands will be performed in all headlines
  777. within the active region.
  778. When set to `start-level', some commands will be performed in all
  779. headlines within the active region, provided that these headlines
  780. are of the same level than the first one.
  781. When set to a string, those commands will be performed on the
  782. matching headlines within the active region. Such string must be
  783. a tags/property/todo match as it is used in the agenda tags view.
  784. The list of commands is: `org-schedule', `org-deadline',
  785. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  786. `org-archive-to-archive-sibling'. The archiving commands skip
  787. already archived entries."
  788. :type '(choice (const :tag "Don't loop" nil)
  789. (const :tag "All headlines in active region" t)
  790. (const :tag "In active region, headlines at the same level than the first one" start-level)
  791. (string :tag "Tags/Property/Todo matcher"))
  792. :version "24.1"
  793. :group 'org-todo
  794. :group 'org-archive)
  795. (defgroup org-startup nil
  796. "Options concerning startup of Org mode."
  797. :tag "Org Startup"
  798. :group 'org)
  799. (defcustom org-startup-folded t
  800. "Non-nil means entering Org mode will switch to OVERVIEW.
  801. This can also be configured on a per-file basis by adding one of
  802. the following lines anywhere in the buffer:
  803. #+STARTUP: fold (or `overview', this is equivalent)
  804. #+STARTUP: nofold (or `showall', this is equivalent)
  805. #+STARTUP: content
  806. #+STARTUP: showeverything
  807. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  808. to ignore this option when Org opens agenda files for the first
  809. time."
  810. :group 'org-startup
  811. :type '(choice
  812. (const :tag "nofold: show all" nil)
  813. (const :tag "fold: overview" t)
  814. (const :tag "content: all headlines" content)
  815. (const :tag "show everything, even drawers" showeverything)))
  816. (defcustom org-startup-truncated t
  817. "Non-nil means entering Org mode will set `truncate-lines'.
  818. This is useful since some lines containing links can be very long and
  819. uninteresting. Also tables look terrible when wrapped.
  820. The variable `org-startup-truncated' allows to configure
  821. truncation for Org mode different to the other modes that use the
  822. variable `truncate-lines' and as a shortcut instead of putting
  823. the variable `truncate-lines' into the `org-mode-hook'. If one
  824. wants to configure truncation for Org mode not statically but
  825. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  826. the variable `truncate-lines' has to be used because in such a
  827. case it is too late to set the variable `org-startup-truncated'."
  828. :group 'org-startup
  829. :type 'boolean)
  830. (defcustom org-startup-indented nil
  831. "Non-nil means turn on `org-indent-mode' on startup.
  832. This can also be configured on a per-file basis by adding one of
  833. the following lines anywhere in the buffer:
  834. #+STARTUP: indent
  835. #+STARTUP: noindent"
  836. :group 'org-structure
  837. :type '(choice
  838. (const :tag "Not" nil)
  839. (const :tag "Globally (slow on startup in large files)" t)))
  840. (defcustom org-use-sub-superscripts t
  841. "Non-nil means interpret \"_\" and \"^\" for display.
  842. If you want to control how Org exports those characters, see
  843. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  844. used to be an alias for `org-export-with-sub-superscripts' in
  845. Org <8.0, it is not anymore.
  846. When this option is turned on, you can use TeX-like syntax for
  847. sub- and superscripts within the buffer. Several characters after
  848. \"_\" or \"^\" will be considered as a single item - so grouping
  849. with {} is normally not needed. For example, the following things
  850. will be parsed as single sub- or superscripts:
  851. 10^24 or 10^tau several digits will be considered 1 item.
  852. 10^-12 or 10^-tau a leading sign with digits or a word
  853. x^2-y^3 will be read as x^2 - y^3, because items are
  854. terminated by almost any nonword/nondigit char.
  855. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  856. Still, ambiguity is possible. So when in doubt, use {} to enclose
  857. the sub/superscript. If you set this variable to the symbol `{}',
  858. the braces are *required* in order to trigger interpretations as
  859. sub/superscript. This can be helpful in documents that need \"_\"
  860. frequently in plain text."
  861. :group 'org-startup
  862. :version "24.4"
  863. :package-version '(Org . "8.0")
  864. :type '(choice
  865. (const :tag "Always interpret" t)
  866. (const :tag "Only with braces" {})
  867. (const :tag "Never interpret" nil)))
  868. (defcustom org-startup-with-beamer-mode nil
  869. "Non-nil means turn on `org-beamer-mode' on startup.
  870. This can also be configured on a per-file basis by adding one of
  871. the following lines anywhere in the buffer:
  872. #+STARTUP: beamer"
  873. :group 'org-startup
  874. :version "24.1"
  875. :type 'boolean)
  876. (defcustom org-startup-align-all-tables nil
  877. "Non-nil means align all tables when visiting a file.
  878. This is useful when the column width in tables is forced with <N> cookies
  879. in table fields. Such tables will look correct only after the first re-align.
  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: align
  883. #+STARTUP: noalign"
  884. :group 'org-startup
  885. :type 'boolean)
  886. (defcustom org-startup-with-inline-images nil
  887. "Non-nil means show inline images when loading a new Org file.
  888. This can also be configured on a per-file basis by adding one of
  889. the following lines anywhere in the buffer:
  890. #+STARTUP: inlineimages
  891. #+STARTUP: noinlineimages"
  892. :group 'org-startup
  893. :version "24.1"
  894. :type 'boolean)
  895. (defcustom org-startup-with-latex-preview nil
  896. "Non-nil means preview LaTeX fragments when loading a new Org file.
  897. This can also be configured on a per-file basis by adding one of
  898. the following lines anywhere in the buffer:
  899. #+STARTUP: latexpreview
  900. #+STARTUP: nolatexpreview"
  901. :group 'org-startup
  902. :version "24.4"
  903. :package-version '(Org . "8.0")
  904. :type 'boolean)
  905. (defcustom org-insert-mode-line-in-empty-file nil
  906. "Non-nil means insert the first line setting Org mode in empty files.
  907. When the function `org-mode' is called interactively in an empty file, this
  908. normally means that the file name does not automatically trigger Org mode.
  909. To ensure that the file will always be in Org mode in the future, a
  910. line enforcing Org mode will be inserted into the buffer, if this option
  911. has been set."
  912. :group 'org-startup
  913. :type 'boolean)
  914. (defcustom org-replace-disputed-keys nil
  915. "Non-nil means use alternative key bindings for some keys.
  916. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  917. These keys are also used by other packages like shift-selection-mode'
  918. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  919. If you want to use Org mode together with one of these other modes,
  920. or more generally if you would like to move some Org mode commands to
  921. other keys, set this variable and configure the keys with the variable
  922. `org-disputed-keys'.
  923. This option is only relevant at load-time of Org mode, and must be set
  924. *before* org.el is loaded. Changing it requires a restart of Emacs to
  925. become effective."
  926. :group 'org-startup
  927. :type 'boolean)
  928. (defcustom org-use-extra-keys nil
  929. "Non-nil means use extra key sequence definitions for certain commands.
  930. This happens automatically if `window-system' is nil. This
  931. variable lets you do the same manually. You must set it before
  932. loading Org."
  933. :group 'org-startup
  934. :type 'boolean)
  935. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  936. (defcustom org-disputed-keys
  937. '(([(shift up)] . [(meta p)])
  938. ([(shift down)] . [(meta n)])
  939. ([(shift left)] . [(meta -)])
  940. ([(shift right)] . [(meta +)])
  941. ([(control shift right)] . [(meta shift +)])
  942. ([(control shift left)] . [(meta shift -)]))
  943. "Keys for which Org mode and other modes compete.
  944. This is an alist, cars are the default keys, second element specifies
  945. the alternative to use when `org-replace-disputed-keys' is t.
  946. Keys can be specified in any syntax supported by `define-key'.
  947. The value of this option takes effect only at Org mode startup,
  948. therefore you'll have to restart Emacs to apply it after changing."
  949. :group 'org-startup
  950. :type 'alist)
  951. (defun org-key (key)
  952. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  953. Or return the original if not disputed."
  954. (when org-replace-disputed-keys
  955. (let* ((nkey (key-description key))
  956. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  957. org-disputed-keys)))
  958. (setq key (if x (cdr x) key))))
  959. key)
  960. (defun org-defkey (keymap key def)
  961. "Define a key, possibly translated, as returned by `org-key'."
  962. (define-key keymap (org-key key) def))
  963. (defcustom org-ellipsis nil
  964. "The ellipsis to use in the Org mode outline.
  965. When nil, just use the standard three dots.
  966. When a string, use that string instead.
  967. The change affects only Org mode (which will then use its own display table).
  968. Changing this requires executing `\\[org-mode]' in a buffer to become
  969. effective."
  970. :group 'org-startup
  971. :type '(choice (const :tag "Default" nil)
  972. (string :tag "String" :value "...#"))
  973. :safe #'string-or-null-p)
  974. (defvar org-display-table nil
  975. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  976. (defgroup org-keywords nil
  977. "Keywords in Org mode."
  978. :tag "Org Keywords"
  979. :group 'org)
  980. (defcustom org-closed-keep-when-no-todo nil
  981. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  982. :group 'org-todo
  983. :group 'org-keywords
  984. :version "24.4"
  985. :package-version '(Org . "8.0")
  986. :type 'boolean)
  987. (defgroup org-structure nil
  988. "Options concerning the general structure of Org files."
  989. :tag "Org Structure"
  990. :group 'org)
  991. (defgroup org-reveal-location nil
  992. "Options about how to make context of a location visible."
  993. :tag "Org Reveal Location"
  994. :group 'org-structure)
  995. (defcustom org-show-context-detail '((agenda . local)
  996. (bookmark-jump . lineage)
  997. (isearch . lineage)
  998. (default . ancestors))
  999. "Alist between context and visibility span when revealing a location.
  1000. \\<org-mode-map>Some actions may move point into invisible
  1001. locations. As a consequence, Org always expose a neighborhood
  1002. around point. How much is shown depends on the initial action,
  1003. or context. Valid contexts are
  1004. agenda when exposing an entry from the agenda
  1005. org-goto when using the command `org-goto' (`\\[org-goto]')
  1006. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1007. tags-tree when constructing a sparse tree based on tags matches
  1008. link-search when exposing search matches associated with a link
  1009. mark-goto when exposing the jump goal of a mark
  1010. bookmark-jump when exposing a bookmark location
  1011. isearch when exiting from an incremental search
  1012. default default for all contexts not set explicitly
  1013. Allowed visibility spans are
  1014. minimal show current headline; if point is not on headline,
  1015. also show entry
  1016. local show current headline, entry and next headline
  1017. ancestors show current headline and its direct ancestors; if
  1018. point is not on headline, also show entry
  1019. lineage show current headline, its direct ancestors and all
  1020. their children; if point is not on headline, also show
  1021. entry and first child
  1022. tree show current headline, its direct ancestors and all
  1023. their children; if point is not on headline, also show
  1024. entry and all children
  1025. canonical show current headline, its direct ancestors along with
  1026. their entries and children; if point is not located on
  1027. the headline, also show current entry and all children
  1028. As special cases, a nil or t value means show all contexts in
  1029. `minimal' or `canonical' view, respectively.
  1030. Some views can make displayed information very compact, but also
  1031. make it harder to edit the location of the match. In such
  1032. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1033. more context."
  1034. :group 'org-reveal-location
  1035. :version "26.1"
  1036. :package-version '(Org . "9.0")
  1037. :type '(choice
  1038. (const :tag "Canonical" t)
  1039. (const :tag "Minimal" nil)
  1040. (repeat :greedy t :tag "Individual contexts"
  1041. (cons
  1042. (choice :tag "Context"
  1043. (const agenda)
  1044. (const org-goto)
  1045. (const occur-tree)
  1046. (const tags-tree)
  1047. (const link-search)
  1048. (const mark-goto)
  1049. (const bookmark-jump)
  1050. (const isearch)
  1051. (const default))
  1052. (choice :tag "Detail level"
  1053. (const minimal)
  1054. (const local)
  1055. (const ancestors)
  1056. (const lineage)
  1057. (const tree)
  1058. (const canonical))))))
  1059. (defcustom org-indirect-buffer-display 'other-window
  1060. "How should indirect tree buffers be displayed?
  1061. This applies to indirect buffers created with the commands
  1062. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1063. Valid values are:
  1064. current-window Display in the current window
  1065. other-window Just display in another window.
  1066. dedicated-frame Create one new frame, and re-use it each time.
  1067. new-frame Make a new frame each time. Note that in this case
  1068. previously-made indirect buffers are kept, and you need to
  1069. kill these buffers yourself."
  1070. :group 'org-structure
  1071. :group 'org-agenda-windows
  1072. :type '(choice
  1073. (const :tag "In current window" current-window)
  1074. (const :tag "In current frame, other window" other-window)
  1075. (const :tag "Each time a new frame" new-frame)
  1076. (const :tag "One dedicated frame" dedicated-frame)))
  1077. (defcustom org-use-speed-commands nil
  1078. "Non-nil means activate single letter commands at beginning of a headline.
  1079. This may also be a function to test for appropriate locations where speed
  1080. commands should be active.
  1081. For example, to activate speed commands when the point is on any
  1082. star at the beginning of the headline, you can do this:
  1083. (setq org-use-speed-commands
  1084. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1085. :group 'org-structure
  1086. :type '(choice
  1087. (const :tag "Never" nil)
  1088. (const :tag "At beginning of headline stars" t)
  1089. (function)))
  1090. (defcustom org-speed-commands-user nil
  1091. "Alist of additional speed commands.
  1092. This list will be checked before `org-speed-commands-default'
  1093. when the variable `org-use-speed-commands' is non-nil
  1094. and when the cursor is at the beginning of a headline.
  1095. The car if each entry is a string with a single letter, which must
  1096. be assigned to `self-insert-command' in the global map.
  1097. The cdr is either a command to be called interactively, a function
  1098. to be called, or a form to be evaluated.
  1099. An entry that is just a list with a single string will be interpreted
  1100. as a descriptive headline that will be added when listing the speed
  1101. commands in the Help buffer using the `?' speed command."
  1102. :group 'org-structure
  1103. :type '(repeat :value ("k" . ignore)
  1104. (choice :value ("k" . ignore)
  1105. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1106. (cons :tag "Letter and Command"
  1107. (string :tag "Command letter")
  1108. (choice
  1109. (function)
  1110. (sexp))))))
  1111. (defcustom org-bookmark-names-plist
  1112. '(:last-capture "org-capture-last-stored"
  1113. :last-refile "org-refile-last-stored"
  1114. :last-capture-marker "org-capture-last-stored-marker")
  1115. "Names for bookmarks automatically set by some Org commands.
  1116. This can provide strings as names for a number of bookmarks Org sets
  1117. automatically. The following keys are currently implemented:
  1118. :last-capture
  1119. :last-capture-marker
  1120. :last-refile
  1121. When a key does not show up in the property list, the corresponding bookmark
  1122. is not set."
  1123. :group 'org-structure
  1124. :type 'plist)
  1125. (defgroup org-cycle nil
  1126. "Options concerning visibility cycling in Org mode."
  1127. :tag "Org Cycle"
  1128. :group 'org-structure)
  1129. (defcustom org-cycle-skip-children-state-if-no-children t
  1130. "Non-nil means skip CHILDREN state in entries that don't have any."
  1131. :group 'org-cycle
  1132. :type 'boolean)
  1133. (defcustom org-cycle-max-level nil
  1134. "Maximum level which should still be subject to visibility cycling.
  1135. Levels higher than this will, for cycling, be treated as text, not a headline.
  1136. When `org-odd-levels-only' is set, a value of N in this variable actually
  1137. means 2N-1 stars as the limiting headline.
  1138. When nil, cycle all levels.
  1139. Note that the limiting level of cycling is also influenced by
  1140. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1141. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1142. than its value."
  1143. :group 'org-cycle
  1144. :type '(choice
  1145. (const :tag "No limit" nil)
  1146. (integer :tag "Maximum level")))
  1147. (defcustom org-hide-block-startup nil
  1148. "Non-nil means entering Org mode will fold all blocks.
  1149. This can also be set in on a per-file basis with
  1150. #+STARTUP: hideblocks
  1151. #+STARTUP: showblocks"
  1152. :group 'org-startup
  1153. :group 'org-cycle
  1154. :type 'boolean)
  1155. (defcustom org-cycle-global-at-bob nil
  1156. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1157. This makes it possible to do global cycling without having to use `S-TAB'
  1158. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1159. line of the buffer
  1160. must not be a headline -- it may be empty or some other text.
  1161. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1162. sure the cursor stays at the beginning of the buffer.
  1163. When this option is nil, don't do anything special at the beginning of
  1164. the buffer."
  1165. :group 'org-cycle
  1166. :type 'boolean)
  1167. (defcustom org-cycle-level-after-item/entry-creation t
  1168. "Non-nil means cycle entry level or item indentation in new empty entries.
  1169. When the cursor is at the end of an empty headline, i.e., with only stars
  1170. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1171. and then all possible ancestor states, before returning to the original state.
  1172. This makes data entry extremely fast: M-RET to create a new headline,
  1173. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1174. When the cursor is at the end of an empty plain list item, one TAB will
  1175. make it a subitem, two or more tabs will back up to make this an item
  1176. higher up in the item hierarchy."
  1177. :group 'org-cycle
  1178. :type 'boolean)
  1179. (defcustom org-cycle-emulate-tab t
  1180. "Where should `org-cycle' emulate TAB.
  1181. nil Never
  1182. white Only in completely white lines
  1183. whitestart Only at the beginning of lines, before the first non-white char
  1184. t Everywhere except in headlines
  1185. exc-hl-bol Everywhere except at the start of a headline
  1186. If TAB is used in a place where it does not emulate TAB, the current subtree
  1187. visibility is cycled."
  1188. :group 'org-cycle
  1189. :type '(choice (const :tag "Never" nil)
  1190. (const :tag "Only in completely white lines" white)
  1191. (const :tag "Before first char in a line" whitestart)
  1192. (const :tag "Everywhere except in headlines" t)
  1193. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1194. (defcustom org-cycle-separator-lines 2
  1195. "Number of empty lines needed to keep an empty line between collapsed trees.
  1196. If you leave an empty line between the end of a subtree and the following
  1197. headline, this empty line is hidden when the subtree is folded.
  1198. Org mode will leave (exactly) one empty line visible if the number of
  1199. empty lines is equal or larger to the number given in this variable.
  1200. So the default 2 means at least 2 empty lines after the end of a subtree
  1201. are needed to produce free space between a collapsed subtree and the
  1202. following headline.
  1203. If the number is negative, and the number of empty lines is at least -N,
  1204. all empty lines are shown.
  1205. Special case: when 0, never leave empty lines in collapsed view."
  1206. :group 'org-cycle
  1207. :type 'integer)
  1208. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1209. (defcustom org-pre-cycle-hook nil
  1210. "Hook that is run before visibility cycling is happening.
  1211. The function(s) in this hook must accept a single argument which indicates
  1212. the new state that will be set right after running this hook. The
  1213. argument is a symbol. Before a global state change, it can have the values
  1214. `overview', `content', or `all'. Before a local state change, it can have
  1215. the values `folded', `children', or `subtree'."
  1216. :group 'org-cycle
  1217. :type 'hook)
  1218. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1219. org-cycle-hide-drawers
  1220. org-cycle-show-empty-lines
  1221. org-optimize-window-after-visibility-change)
  1222. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1223. The function(s) in this hook must accept a single argument which indicates
  1224. the new state that was set by the most recent `org-cycle' command. The
  1225. argument is a symbol. After a global state change, it can have the values
  1226. `overview', `contents', or `all'. After a local state change, it can have
  1227. the values `folded', `children', or `subtree'."
  1228. :group 'org-cycle
  1229. :type 'hook
  1230. :version "26.1"
  1231. :package-version '(Org . "8.3"))
  1232. (defgroup org-edit-structure nil
  1233. "Options concerning structure editing in Org mode."
  1234. :tag "Org Edit Structure"
  1235. :group 'org-structure)
  1236. (defcustom org-odd-levels-only nil
  1237. "Non-nil means skip even levels and only use odd levels for the outline.
  1238. This has the effect that two stars are being added/taken away in
  1239. promotion/demotion commands. It also influences how levels are
  1240. handled by the exporters.
  1241. Changing it requires restart of `font-lock-mode' to become effective
  1242. for fontification also in regions already fontified.
  1243. You may also set this on a per-file basis by adding one of the following
  1244. lines to the buffer:
  1245. #+STARTUP: odd
  1246. #+STARTUP: oddeven"
  1247. :group 'org-edit-structure
  1248. :group 'org-appearance
  1249. :type 'boolean)
  1250. (defcustom org-adapt-indentation t
  1251. "Non-nil means adapt indentation to outline node level.
  1252. When this variable is set, Org assumes that you write outlines by
  1253. indenting text in each node to align with the headline (after the
  1254. stars). The following issues are influenced by this variable:
  1255. - The indentation is increased by one space in a demotion
  1256. command, and decreased by one in a promotion command. However,
  1257. in the latter case, if shifting some line in the entry body
  1258. would alter document structure (e.g., insert a new headline),
  1259. indentation is not changed at all.
  1260. - Property drawers and planning information is inserted indented
  1261. when this variable is set. When nil, they will not be indented.
  1262. - TAB indents a line relative to current level. The lines below
  1263. a headline will be indented when this variable is set.
  1264. Note that this is all about true indentation, by adding and
  1265. removing space characters. See also `org-indent.el' which does
  1266. level-dependent indentation in a virtual way, i.e. at display
  1267. time in Emacs."
  1268. :group 'org-edit-structure
  1269. :type 'boolean)
  1270. (defcustom org-special-ctrl-a/e nil
  1271. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1272. When t, `C-a' will bring back the cursor to the beginning of the
  1273. headline text, i.e. after the stars and after a possible TODO
  1274. keyword. In an item, this will be the position after bullet and
  1275. check-box, if any. When the cursor is already at that position,
  1276. another `C-a' will bring it to the beginning of the line.
  1277. `C-e' will jump to the end of the headline, ignoring the presence
  1278. of tags in the headline. A second `C-e' will then jump to the
  1279. true end of the line, after any tags. This also means that, when
  1280. this variable is non-nil, `C-e' also will never jump beyond the
  1281. end of the heading of a folded section, i.e. not after the
  1282. ellipses.
  1283. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1284. normally, going to the true line boundary first. Only a directly
  1285. following, identical keypress will bring the cursor to the
  1286. special positions.
  1287. This may also be a cons cell where the behavior for `C-a' and
  1288. `C-e' is set separately."
  1289. :group 'org-edit-structure
  1290. :type '(choice
  1291. (const :tag "off" nil)
  1292. (const :tag "on: after stars/bullet and before tags first" t)
  1293. (const :tag "reversed: true line boundary first" reversed)
  1294. (cons :tag "Set C-a and C-e separately"
  1295. (choice :tag "Special C-a"
  1296. (const :tag "off" nil)
  1297. (const :tag "on: after stars/bullet first" t)
  1298. (const :tag "reversed: before stars/bullet first" reversed))
  1299. (choice :tag "Special C-e"
  1300. (const :tag "off" nil)
  1301. (const :tag "on: before tags first" t)
  1302. (const :tag "reversed: after tags first" reversed)))))
  1303. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1304. (defcustom org-special-ctrl-k nil
  1305. "Non-nil means `C-k' will behave specially in headlines.
  1306. When nil, `C-k' will call the default `kill-line' command.
  1307. When t, the following will happen while the cursor is in the headline:
  1308. - When the cursor is at the beginning of a headline, kill the entire
  1309. line and possible the folded subtree below the line.
  1310. - When in the middle of the headline text, kill the headline up to the tags.
  1311. - When after the headline text, kill the tags."
  1312. :group 'org-edit-structure
  1313. :type 'boolean)
  1314. (defcustom org-ctrl-k-protect-subtree nil
  1315. "Non-nil means, do not delete a hidden subtree with C-k.
  1316. When set to the symbol `error', simply throw an error when C-k is
  1317. used to kill (part-of) a headline that has hidden text behind it.
  1318. Any other non-nil value will result in a query to the user, if it is
  1319. OK to kill that hidden subtree. When nil, kill without remorse."
  1320. :group 'org-edit-structure
  1321. :version "24.1"
  1322. :type '(choice
  1323. (const :tag "Do not protect hidden subtrees" nil)
  1324. (const :tag "Protect hidden subtrees with a security query" t)
  1325. (const :tag "Never kill a hidden subtree with C-k" error)))
  1326. (defcustom org-special-ctrl-o t
  1327. "Non-nil means, make `C-o' insert a row in tables."
  1328. :group 'org-edit-structure
  1329. :type 'boolean)
  1330. (defcustom org-catch-invisible-edits nil
  1331. "Check if in invisible region before inserting or deleting a character.
  1332. Valid values are:
  1333. nil Do not check, so just do invisible edits.
  1334. error Throw an error and do nothing.
  1335. show Make point visible, and do the requested edit.
  1336. show-and-error Make point visible, then throw an error and abort the edit.
  1337. smart Make point visible, and do insertion/deletion if it is
  1338. adjacent to visible text and the change feels predictable.
  1339. Never delete a previously invisible character or add in the
  1340. middle or right after an invisible region. Basically, this
  1341. allows insertion and backward-delete right before ellipses.
  1342. FIXME: maybe in this case we should not even show?"
  1343. :group 'org-edit-structure
  1344. :version "24.1"
  1345. :type '(choice
  1346. (const :tag "Do not check" nil)
  1347. (const :tag "Throw error when trying to edit" error)
  1348. (const :tag "Unhide, but do not do the edit" show-and-error)
  1349. (const :tag "Show invisible part and do the edit" show)
  1350. (const :tag "Be smart and do the right thing" smart)))
  1351. (defcustom org-yank-folded-subtrees t
  1352. "Non-nil means when yanking subtrees, fold them.
  1353. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1354. it starts with a heading and all other headings in it are either children
  1355. or siblings, then fold all the subtrees. However, do this only if no
  1356. text after the yank would be swallowed into a folded tree by this action."
  1357. :group 'org-edit-structure
  1358. :type 'boolean)
  1359. (defcustom org-yank-adjusted-subtrees nil
  1360. "Non-nil means when yanking subtrees, adjust the level.
  1361. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1362. this function for details."
  1363. :group 'org-edit-structure
  1364. :type 'boolean)
  1365. (defcustom org-M-RET-may-split-line '((default . t))
  1366. "Non-nil means M-RET will split the line at the cursor position.
  1367. When nil, it will go to the end of the line before making a
  1368. new line.
  1369. You may also set this option in a different way for different
  1370. contexts. Valid contexts are:
  1371. headline when creating a new headline
  1372. item when creating a new item
  1373. table in a table field
  1374. default the value to be used for all contexts not explicitly
  1375. customized"
  1376. :group 'org-structure
  1377. :group 'org-table
  1378. :type '(choice
  1379. (const :tag "Always" t)
  1380. (const :tag "Never" nil)
  1381. (repeat :greedy t :tag "Individual contexts"
  1382. (cons
  1383. (choice :tag "Context"
  1384. (const headline)
  1385. (const item)
  1386. (const table)
  1387. (const default))
  1388. (boolean)))))
  1389. (defcustom org-insert-heading-respect-content nil
  1390. "Non-nil means insert new headings after the current subtree.
  1391. \\<org-mode-map>
  1392. When nil, the new heading is created directly after the current line.
  1393. The commands `\\[org-insert-heading-respect-content]' and \
  1394. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1395. for the duration of the command."
  1396. :group 'org-structure
  1397. :type 'boolean)
  1398. (defcustom org-blank-before-new-entry '((heading . auto)
  1399. (plain-list-item . auto))
  1400. "Should `org-insert-heading' leave a blank line before new heading/item?
  1401. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1402. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1403. which case Org will look at the surrounding headings/items and try to
  1404. make an intelligent decision whether to insert a blank line or not."
  1405. :group 'org-edit-structure
  1406. :type '(list
  1407. (cons (const heading)
  1408. (choice (const :tag "Never" nil)
  1409. (const :tag "Always" t)
  1410. (const :tag "Auto" auto)))
  1411. (cons (const plain-list-item)
  1412. (choice (const :tag "Never" nil)
  1413. (const :tag "Always" t)
  1414. (const :tag "Auto" auto)))))
  1415. (defcustom org-insert-heading-hook nil
  1416. "Hook being run after inserting a new heading."
  1417. :group 'org-edit-structure
  1418. :type 'hook)
  1419. (defcustom org-enable-fixed-width-editor t
  1420. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1421. This currently only means they are never auto-wrapped.
  1422. When nil, such lines will be treated like ordinary lines."
  1423. :group 'org-edit-structure
  1424. :type 'boolean)
  1425. (defcustom org-goto-auto-isearch t
  1426. "Non-nil means typing characters in `org-goto' starts incremental search.
  1427. When nil, you can use these keybindings to navigate the buffer:
  1428. q Quit the org-goto interface
  1429. n Go to the next visible heading
  1430. p Go to the previous visible heading
  1431. f Go one heading forward on same level
  1432. b Go one heading backward on same level
  1433. u Go one heading up"
  1434. :group 'org-edit-structure
  1435. :type 'boolean)
  1436. (defgroup org-sparse-trees nil
  1437. "Options concerning sparse trees in Org mode."
  1438. :tag "Org Sparse Trees"
  1439. :group 'org-structure)
  1440. (defcustom org-highlight-sparse-tree-matches t
  1441. "Non-nil means highlight all matches that define a sparse tree.
  1442. The highlights will automatically disappear the next time the buffer is
  1443. changed by an edit command."
  1444. :group 'org-sparse-trees
  1445. :type 'boolean)
  1446. (defcustom org-remove-highlights-with-change t
  1447. "Non-nil means any change to the buffer will remove temporary highlights.
  1448. \\<org-mode-map>\
  1449. Such highlights are created by `org-occur' and `org-clock-display'.
  1450. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1451. to get rid of the highlights.
  1452. The highlights created by `org-toggle-latex-fragment' always need
  1453. `\\[org-toggle-latex-fragment]' to be removed."
  1454. :group 'org-sparse-trees
  1455. :group 'org-time
  1456. :type 'boolean)
  1457. (defcustom org-occur-case-fold-search t
  1458. "Non-nil means `org-occur' should be case-insensitive.
  1459. If set to `smart' the search will be case-insensitive only if it
  1460. doesn't specify any upper case character."
  1461. :group 'org-sparse-trees
  1462. :version "26.1"
  1463. :type '(choice
  1464. (const :tag "Case-sensitive" nil)
  1465. (const :tag "Case-insensitive" t)
  1466. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1467. (defcustom org-occur-hook '(org-first-headline-recenter)
  1468. "Hook that is run after `org-occur' has constructed a sparse tree.
  1469. This can be used to recenter the window to show as much of the structure
  1470. as possible."
  1471. :group 'org-sparse-trees
  1472. :type 'hook)
  1473. (defgroup org-imenu-and-speedbar nil
  1474. "Options concerning imenu and speedbar in Org mode."
  1475. :tag "Org Imenu and Speedbar"
  1476. :group 'org-structure)
  1477. (defcustom org-imenu-depth 2
  1478. "The maximum level for Imenu access to Org headlines.
  1479. This also applied for speedbar access."
  1480. :group 'org-imenu-and-speedbar
  1481. :type 'integer)
  1482. (defgroup org-table nil
  1483. "Options concerning tables in Org mode."
  1484. :tag "Org Table"
  1485. :group 'org)
  1486. (defcustom org-enable-table-editor 'optimized
  1487. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1488. When nil, such lines will be treated like ordinary lines.
  1489. When equal to the symbol `optimized', the table editor will be optimized to
  1490. do the following:
  1491. - Automatic overwrite mode in front of whitespace in table fields.
  1492. This makes the structure of the table stay in tact as long as the edited
  1493. field does not exceed the column width.
  1494. - Minimize the number of realigns. Normally, the table is aligned each time
  1495. TAB or RET are pressed to move to another field. With optimization this
  1496. happens only if changes to a field might have changed the column width.
  1497. Optimization requires replacing the functions `self-insert-command',
  1498. `delete-char', and `backward-delete-char' in Org buffers, with a
  1499. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1500. good at guessing when a re-align will be necessary, but you can always
  1501. force one with `\\[org-ctrl-c-ctrl-c]'.
  1502. If you would like to use the optimized version in Org mode, but the
  1503. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1504. This variable can be used to turn on and off the table editor during a session,
  1505. but in order to toggle optimization, a restart is required.
  1506. See also the variable `org-table-auto-blank-field'."
  1507. :group 'org-table
  1508. :type '(choice
  1509. (const :tag "off" nil)
  1510. (const :tag "on" t)
  1511. (const :tag "on, optimized" optimized)))
  1512. (defcustom org-self-insert-cluster-for-undo nil
  1513. "Non-nil means cluster self-insert commands for undo when possible.
  1514. If this is set, then, like in the Emacs command loop, 20 consecutive
  1515. characters will be undone together.
  1516. This is configurable, because there is some impact on typing performance."
  1517. :group 'org-table
  1518. :type 'boolean)
  1519. (defcustom org-table-tab-recognizes-table.el t
  1520. "Non-nil means TAB will automatically notice a table.el table.
  1521. When it sees such a table, it moves point into it and - if necessary -
  1522. calls `table-recognize-table'."
  1523. :group 'org-table-editing
  1524. :type 'boolean)
  1525. (defgroup org-link nil
  1526. "Options concerning links in Org mode."
  1527. :tag "Org Link"
  1528. :group 'org)
  1529. (defvar-local org-link-abbrev-alist-local nil
  1530. "Buffer-local version of `org-link-abbrev-alist', which see.
  1531. The value of this is taken from the #+LINK lines.")
  1532. (defcustom org-link-parameters
  1533. '(("doi" :follow org--open-doi-link)
  1534. ("elisp" :follow org--open-elisp-link)
  1535. ("file" :complete org-file-complete-link)
  1536. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1537. ("help" :follow org--open-help-link)
  1538. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1539. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1540. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1541. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1542. ("shell" :follow org--open-shell-link))
  1543. "An alist of properties that defines all the links in Org mode.
  1544. The key in each association is a string of the link type.
  1545. Subsequent optional elements make up a p-list of link properties.
  1546. :follow - A function that takes the link path as an argument.
  1547. :export - A function that takes the link path, description and
  1548. export-backend as arguments.
  1549. :store - A function responsible for storing the link. See the
  1550. function `org-store-link-functions'.
  1551. :complete - A function that inserts a link with completion. The
  1552. function takes one optional prefix arg.
  1553. :face - A face for the link, or a function that returns a face.
  1554. The function takes one argument which is the link path. The
  1555. default face is `org-link'.
  1556. :mouse-face - The mouse-face. The default is `highlight'.
  1557. :display - `full' will not fold the link in descriptive
  1558. display. Default is `org-link'.
  1559. :help-echo - A string or function that takes (window object position)
  1560. as arguments and returns a string.
  1561. :keymap - A keymap that is active on the link. The default is
  1562. `org-mouse-map'.
  1563. :htmlize-link - A function for the htmlize-link. Defaults
  1564. to (list :uri \"type:path\")
  1565. :activate-func - A function to run at the end of font-lock
  1566. activation. The function must accept (link-start link-end path bracketp)
  1567. as arguments."
  1568. :group 'org-link
  1569. :type '(alist :tag "Link display parameters"
  1570. :value-type plist)
  1571. :version "26.1"
  1572. :package-version '(Org . "9.1"))
  1573. (defun org-link-get-parameter (type key)
  1574. "Get TYPE link property for KEY.
  1575. TYPE is a string and KEY is a plist keyword."
  1576. (plist-get
  1577. (cdr (assoc type org-link-parameters))
  1578. key))
  1579. (defun org-link-set-parameters (type &rest parameters)
  1580. "Set link TYPE properties to PARAMETERS.
  1581. PARAMETERS should be :key val pairs."
  1582. (let ((data (assoc type org-link-parameters)))
  1583. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1584. (push (cons type parameters) org-link-parameters)
  1585. (org-make-link-regexps)
  1586. (org-element-update-syntax))))
  1587. (defun org-link-types ()
  1588. "Return a list of known link types."
  1589. (mapcar #'car org-link-parameters))
  1590. (defcustom org-link-abbrev-alist nil
  1591. "Alist of link abbreviations.
  1592. The car of each element is a string, to be replaced at the start of a link.
  1593. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1594. links in Org buffers can have an optional tag after a double colon, e.g.,
  1595. [[linkkey:tag][description]]
  1596. The `linkkey' must be a single word, starting with a letter, followed
  1597. by letters, numbers, `-' or `_'.
  1598. If REPLACE is a string, the tag will simply be appended to create the link.
  1599. If the string contains \"%s\", the tag will be inserted there. If the string
  1600. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1601. at that point (see the function `url-hexify-string'). If the string contains
  1602. the specifier \"%(my-function)\", then the custom function `my-function' will
  1603. be invoked: this function takes the tag as its only argument and must return
  1604. a string.
  1605. REPLACE may also be a function that will be called with the tag as the
  1606. only argument to create the link, which should be returned as a string.
  1607. See the manual for examples."
  1608. :group 'org-link
  1609. :type '(repeat
  1610. (cons
  1611. (string :tag "Protocol")
  1612. (choice
  1613. (string :tag "Format")
  1614. (function)))))
  1615. (defcustom org-descriptive-links t
  1616. "Non-nil means Org will display descriptive links.
  1617. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1618. \"Org Website\", hiding the link itself and just displaying its
  1619. description. When set to nil, Org will display the full links
  1620. literally.
  1621. You can interactively set the value of this variable by calling
  1622. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1623. :group 'org-link
  1624. :type 'boolean)
  1625. (defcustom org-link-file-path-type 'adaptive
  1626. "How the path name in file links should be stored.
  1627. Valid values are:
  1628. relative Relative to the current directory, i.e. the directory of the file
  1629. into which the link is being inserted.
  1630. absolute Absolute path, if possible with ~ for home directory.
  1631. noabbrev Absolute path, no abbreviation of home directory.
  1632. adaptive Use relative path for files in the current directory and sub-
  1633. directories of it. For other files, use an absolute path."
  1634. :group 'org-link
  1635. :type '(choice
  1636. (const relative)
  1637. (const absolute)
  1638. (const noabbrev)
  1639. (const adaptive)))
  1640. (defvaralias 'org-activate-links 'org-highlight-links)
  1641. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1642. "Types of links that should be highlighted in Org files.
  1643. This is a list of symbols, each one of them leading to the
  1644. highlighting of a certain link type.
  1645. You can still open links that are not highlighted.
  1646. In principle, it does not hurt to turn on highlighting for all
  1647. link types. There may be a small gain when turning off unused
  1648. link types. The types are:
  1649. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1650. angle Links in angular brackets that may contain whitespace like
  1651. <bbdb:Carsten Dominik>.
  1652. plain Plain links in normal text, no whitespace, like http://google.com.
  1653. radio Text that is matched by a radio target, see manual for details.
  1654. tag Tag settings in a headline (link to tag search).
  1655. date Time stamps (link to calendar).
  1656. footnote Footnote labels.
  1657. If you set this variable during an Emacs session, use `org-mode-restart'
  1658. in the Org buffer so that the change takes effect."
  1659. :group 'org-link
  1660. :group 'org-appearance
  1661. :type '(set :greedy t
  1662. (const :tag "Double bracket links" bracket)
  1663. (const :tag "Angular bracket links" angle)
  1664. (const :tag "Plain text links" plain)
  1665. (const :tag "Radio target matches" radio)
  1666. (const :tag "Tags" tag)
  1667. (const :tag "Timestamps" date)
  1668. (const :tag "Footnotes" footnote)))
  1669. (defcustom org-make-link-description-function nil
  1670. "Function to use for generating link descriptions from links.
  1671. When nil, the link location will be used. This function must take
  1672. two parameters: the first one is the link, the second one is the
  1673. description generated by `org-insert-link'. The function should
  1674. return the description to use."
  1675. :group 'org-link
  1676. :type '(choice (const nil) (function)))
  1677. (defgroup org-link-store nil
  1678. "Options concerning storing links in Org mode."
  1679. :tag "Org Store Link"
  1680. :group 'org-link)
  1681. (defcustom org-url-hexify-p t
  1682. "When non-nil, hexify URL when creating a link."
  1683. :type 'boolean
  1684. :version "24.3"
  1685. :group 'org-link-store)
  1686. (defcustom org-email-link-description-format "Email %c: %.30s"
  1687. "Format of the description part of a link to an email or usenet message.
  1688. The following %-escapes will be replaced by corresponding information:
  1689. %F full \"From\" field
  1690. %f name, taken from \"From\" field, address if no name
  1691. %T full \"To\" field
  1692. %t first name in \"To\" field, address if no name
  1693. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1694. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1695. %s subject
  1696. %d date
  1697. %m message-id.
  1698. You may use normal field width specification between the % and the letter.
  1699. This is for example useful to limit the length of the subject.
  1700. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1701. :group 'org-link-store
  1702. :type 'string)
  1703. (defcustom org-from-is-user-regexp
  1704. (let (r1 r2)
  1705. (when (and user-mail-address (not (string= user-mail-address "")))
  1706. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1707. (when (and user-full-name (not (string= user-full-name "")))
  1708. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1709. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1710. "Regexp matched against the \"From:\" header of an email or usenet message.
  1711. It should match if the message is from the user him/herself."
  1712. :group 'org-link-store
  1713. :type 'regexp)
  1714. (defcustom org-context-in-file-links t
  1715. "Non-nil means file links from `org-store-link' contain context.
  1716. \\<org-mode-map>
  1717. A search string will be added to the file name with :: as separator
  1718. and used to find the context when the link is activated by the command
  1719. `org-open-at-point'. When this option is t, the entire active region
  1720. will be placed in the search string of the file link. If set to a
  1721. positive integer, only the first n lines of context will be stored.
  1722. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1723. \\[org-store-link]')
  1724. negates this setting for the duration of the command."
  1725. :group 'org-link-store
  1726. :type '(choice boolean integer))
  1727. (defcustom org-keep-stored-link-after-insertion nil
  1728. "Non-nil means keep link in list for entire session.
  1729. \\<org-mode-map>
  1730. The command `org-store-link' adds a link pointing to the current
  1731. location to an internal list. These links accumulate during a session.
  1732. The command `org-insert-link' can be used to insert links into any
  1733. Org file (offering completion for all stored links).
  1734. When this option is nil, every link which has been inserted once using
  1735. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1736. unused
  1737. links more efficient."
  1738. :group 'org-link-store
  1739. :type 'boolean)
  1740. (defgroup org-link-follow nil
  1741. "Options concerning following links in Org mode."
  1742. :tag "Org Follow Link"
  1743. :group 'org-link)
  1744. (defcustom org-link-translation-function nil
  1745. "Function to translate links with different syntax to Org syntax.
  1746. This can be used to translate links created for example by the Planner
  1747. or emacs-wiki packages to Org syntax.
  1748. The function must accept two parameters, a TYPE containing the link
  1749. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1750. which is everything after the link protocol. It should return a cons
  1751. with possibly modified values of type and path.
  1752. Org contains a function for this, so if you set this variable to
  1753. `org-translate-link-from-planner', you should be able follow many
  1754. links created by planner."
  1755. :group 'org-link-follow
  1756. :type '(choice (const nil) (function)))
  1757. (defcustom org-follow-link-hook nil
  1758. "Hook that is run after a link has been followed."
  1759. :group 'org-link-follow
  1760. :type 'hook)
  1761. (defcustom org-tab-follows-link nil
  1762. "Non-nil means on links TAB will follow the link.
  1763. Needs to be set before org.el is loaded.
  1764. This really should not be used, it does not make sense, and the
  1765. implementation is bad."
  1766. :group 'org-link-follow
  1767. :type 'boolean)
  1768. (defcustom org-return-follows-link nil
  1769. "Non-nil means on links RET will follow the link.
  1770. In tables, the special behavior of RET has precedence."
  1771. :group 'org-link-follow
  1772. :type 'boolean)
  1773. (defcustom org-mouse-1-follows-link
  1774. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1775. "Non-nil means mouse-1 on a link will follow the link.
  1776. A longer mouse click will still set point. Needs to be set
  1777. before org.el is loaded."
  1778. :group 'org-link-follow
  1779. :version "24.4"
  1780. :package-version '(Org . "8.3")
  1781. :type '(choice
  1782. (const :tag "A double click follows the link" double)
  1783. (const :tag "Unconditionally follow the link with mouse-1" t)
  1784. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1785. (defcustom org-mark-ring-length 4
  1786. "Number of different positions to be recorded in the ring.
  1787. Changing this requires a restart of Emacs to work correctly."
  1788. :group 'org-link-follow
  1789. :type 'integer)
  1790. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1791. "Non-nil means internal fuzzy links can only match headlines.
  1792. When nil, the a fuzzy link may point to a target or a named
  1793. construct in the document. When set to the special value
  1794. `query-to-create', offer to create a new headline when none
  1795. matched.
  1796. Spaces and statistics cookies are ignored during heading searches."
  1797. :group 'org-link-follow
  1798. :version "24.1"
  1799. :type '(choice
  1800. (const :tag "Use fuzzy text search" nil)
  1801. (const :tag "Match only exact headline" t)
  1802. (const :tag "Match exact headline or query to create it"
  1803. query-to-create))
  1804. :safe #'symbolp)
  1805. (defcustom org-link-frame-setup
  1806. '((vm . vm-visit-folder-other-frame)
  1807. (vm-imap . vm-visit-imap-folder-other-frame)
  1808. (gnus . org-gnus-no-new-news)
  1809. (file . find-file-other-window)
  1810. (wl . wl-other-frame))
  1811. "Setup the frame configuration for following links.
  1812. When following a link with Emacs, it may often be useful to display
  1813. this link in another window or frame. This variable can be used to
  1814. set this up for the different types of links.
  1815. For VM, use any of
  1816. `vm-visit-folder'
  1817. `vm-visit-folder-other-window'
  1818. `vm-visit-folder-other-frame'
  1819. For Gnus, use any of
  1820. `gnus'
  1821. `gnus-other-frame'
  1822. `org-gnus-no-new-news'
  1823. For FILE, use any of
  1824. `find-file'
  1825. `find-file-other-window'
  1826. `find-file-other-frame'
  1827. For Wanderlust use any of
  1828. `wl'
  1829. `wl-other-frame'
  1830. For the calendar, use the variable `calendar-setup'.
  1831. For BBDB, it is currently only possible to display the matches in
  1832. another window."
  1833. :group 'org-link-follow
  1834. :type '(list
  1835. (cons (const vm)
  1836. (choice
  1837. (const vm-visit-folder)
  1838. (const vm-visit-folder-other-window)
  1839. (const vm-visit-folder-other-frame)))
  1840. (cons (const vm-imap)
  1841. (choice
  1842. (const vm-visit-imap-folder)
  1843. (const vm-visit-imap-folder-other-window)
  1844. (const vm-visit-imap-folder-other-frame)))
  1845. (cons (const gnus)
  1846. (choice
  1847. (const gnus)
  1848. (const gnus-other-frame)
  1849. (const org-gnus-no-new-news)))
  1850. (cons (const file)
  1851. (choice
  1852. (const find-file)
  1853. (const find-file-other-window)
  1854. (const find-file-other-frame)))
  1855. (cons (const wl)
  1856. (choice
  1857. (const wl)
  1858. (const wl-other-frame)))))
  1859. (defcustom org-display-internal-link-with-indirect-buffer nil
  1860. "Non-nil means use indirect buffer to display infile links.
  1861. Activating internal links (from one location in a file to another location
  1862. in the same file) normally just jumps to the location. When the link is
  1863. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1864. is displayed in
  1865. another window. When this option is set, the other window actually displays
  1866. an indirect buffer clone of the current buffer, to avoid any visibility
  1867. changes to the current buffer."
  1868. :group 'org-link-follow
  1869. :type 'boolean)
  1870. (defcustom org-open-non-existing-files nil
  1871. "Non-nil means `org-open-file' will open non-existing files.
  1872. When nil, an error will be generated.
  1873. This variable applies only to external applications because they
  1874. might choke on non-existing files. If the link is to a file that
  1875. will be opened in Emacs, the variable is ignored."
  1876. :group 'org-link-follow
  1877. :type 'boolean)
  1878. (defcustom org-open-directory-means-index-dot-org nil
  1879. "Non-nil means a link to a directory really means to index.org.
  1880. When nil, following a directory link will run dired or open a finder/explorer
  1881. window on that directory."
  1882. :group 'org-link-follow
  1883. :type 'boolean)
  1884. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1885. "Non-nil means ask for confirmation before executing shell links.
  1886. Shell links can be dangerous: just think about a link
  1887. [[shell:rm -rf ~/*][Google Search]]
  1888. This link would show up in your Org document as \"Google Search\",
  1889. but really it would remove your entire home directory.
  1890. Therefore we advise against setting this variable to nil.
  1891. Just change it to `y-or-n-p' if you want to confirm with a
  1892. single keystroke rather than having to type \"yes\"."
  1893. :group 'org-link-follow
  1894. :type '(choice
  1895. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1896. (const :tag "with y-or-n (faster)" y-or-n-p)
  1897. (const :tag "no confirmation (dangerous)" nil)))
  1898. (put 'org-confirm-shell-link-function
  1899. 'safe-local-variable
  1900. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1901. (defcustom org-confirm-shell-link-not-regexp ""
  1902. "A regexp to skip confirmation for shell links."
  1903. :group 'org-link-follow
  1904. :version "24.1"
  1905. :type 'regexp)
  1906. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1907. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1908. Elisp links can be dangerous: just think about a link
  1909. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1910. This link would show up in your Org document as \"Google Search\",
  1911. but really it would remove your entire home directory.
  1912. Therefore we advise against setting this variable to nil.
  1913. Just change it to `y-or-n-p' if you want to confirm with a
  1914. single keystroke rather than having to type \"yes\"."
  1915. :group 'org-link-follow
  1916. :type '(choice
  1917. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1918. (const :tag "with y-or-n (faster)" y-or-n-p)
  1919. (const :tag "no confirmation (dangerous)" nil)))
  1920. (put 'org-confirm-shell-link-function
  1921. 'safe-local-variable
  1922. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1923. (defcustom org-confirm-elisp-link-not-regexp ""
  1924. "A regexp to skip confirmation for Elisp links."
  1925. :group 'org-link-follow
  1926. :version "24.1"
  1927. :type 'regexp)
  1928. (defconst org-file-apps-defaults-gnu
  1929. '((remote . emacs)
  1930. (system . mailcap)
  1931. (t . mailcap))
  1932. "Default file applications on a UNIX or GNU/Linux system.
  1933. See `org-file-apps'.")
  1934. (defconst org-file-apps-defaults-macosx
  1935. '((remote . emacs)
  1936. (system . "open %s")
  1937. ("ps.gz" . "gv %s")
  1938. ("eps.gz" . "gv %s")
  1939. ("dvi" . "xdvi %s")
  1940. ("fig" . "xfig %s")
  1941. (t . "open %s"))
  1942. "Default file applications on a macOS system.
  1943. The system \"open\" is known as a default, but we use X11 applications
  1944. for some files for which the OS does not have a good default.
  1945. See `org-file-apps'.")
  1946. (defconst org-file-apps-defaults-windowsnt
  1947. (list '(remote . emacs)
  1948. (cons 'system (lambda (file _path)
  1949. (with-no-warnings (w32-shell-execute "open" file))))
  1950. (cons t (lambda (file _path)
  1951. (with-no-warnings (w32-shell-execute "open" file)))))
  1952. "Default file applications on a Windows NT system.
  1953. The system \"open\" is used for most files.
  1954. See `org-file-apps'.")
  1955. (defcustom org-file-apps
  1956. '((auto-mode . emacs)
  1957. ("\\.mm\\'" . default)
  1958. ("\\.x?html?\\'" . default)
  1959. ("\\.pdf\\'" . default))
  1960. "External applications for opening `file:path' items in a document.
  1961. \\<org-mode-map>\
  1962. Org mode uses system defaults for different file types, but
  1963. you can use this variable to set the application for a given file
  1964. extension. The entries in this list are cons cells where the car identifies
  1965. files and the cdr the corresponding command.
  1966. Possible values for the file identifier are:
  1967. \"string\" A string as a file identifier can be interpreted in different
  1968. ways, depending on its contents:
  1969. - Alphanumeric characters only:
  1970. Match links with this file extension.
  1971. Example: (\"pdf\" . \"evince %s\")
  1972. to open PDFs with evince.
  1973. - Regular expression: Match links where the
  1974. filename matches the regexp. If you want to
  1975. use groups here, use shy groups.
  1976. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1977. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1978. to open *.html and *.xhtml with firefox.
  1979. - Regular expression which contains (non-shy) groups:
  1980. Match links where the whole link, including \"::\", and
  1981. anything after that, matches the regexp.
  1982. In a custom command string, %1, %2, etc. are replaced with
  1983. the parts of the link that were matched by the groups.
  1984. For backwards compatibility, if a command string is given
  1985. that does not use any of the group matches, this case is
  1986. handled identically to the second one (i.e. match against
  1987. file name only).
  1988. In a custom function, you can access the group matches with
  1989. (match-string n link).
  1990. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1991. \"evince -p %1 %s\")
  1992. to open [[file:document.pdf::5]] with evince at page 5.
  1993. `directory' Matches a directory
  1994. `remote' Matches a remote file, accessible through tramp or efs.
  1995. Remote files most likely should be visited through Emacs
  1996. because external applications cannot handle such paths.
  1997. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1998. so all files Emacs knows how to handle. Using this with
  1999. command `emacs' will open most files in Emacs. Beware that this
  2000. will also open html files inside Emacs, unless you add
  2001. (\"html\" . default) to the list as well.
  2002. `system' The system command to open files, like `open' on Windows
  2003. and macOS, and mailcap under GNU/Linux. This is the command
  2004. that will be selected if you call `org-open-at-point' with a
  2005. double prefix argument (`\\[universal-argument] \
  2006. \\[universal-argument] \\[org-open-at-point]').
  2007. t Default for files not matched by any of the other options.
  2008. Possible values for the command are:
  2009. `emacs' The file will be visited by the current Emacs process.
  2010. `default' Use the default application for this file type, which is the
  2011. association for t in the list, most likely in the system-specific
  2012. part. This can be used to overrule an unwanted setting in the
  2013. system-specific variable.
  2014. `system' Use the system command for opening files, like \"open\".
  2015. This command is specified by the entry whose car is `system'.
  2016. Most likely, the system-specific version of this variable
  2017. does define this command, but you can overrule/replace it
  2018. here.
  2019. `mailcap' Use command specified in the mailcaps.
  2020. string A command to be executed by a shell; %s will be replaced
  2021. by the path to the file.
  2022. function A Lisp function, which will be called with two arguments:
  2023. the file path and the original link string, without the
  2024. \"file:\" prefix.
  2025. For more examples, see the system specific constants
  2026. `org-file-apps-defaults-macosx'
  2027. `org-file-apps-defaults-windowsnt'
  2028. `org-file-apps-defaults-gnu'."
  2029. :group 'org-link-follow
  2030. :type '(repeat
  2031. (cons (choice :value ""
  2032. (string :tag "Extension")
  2033. (const :tag "System command to open files" system)
  2034. (const :tag "Default for unrecognized files" t)
  2035. (const :tag "Remote file" remote)
  2036. (const :tag "Links to a directory" directory)
  2037. (const :tag "Any files that have Emacs modes"
  2038. auto-mode))
  2039. (choice :value ""
  2040. (const :tag "Visit with Emacs" emacs)
  2041. (const :tag "Use default" default)
  2042. (const :tag "Use the system command" system)
  2043. (string :tag "Command")
  2044. (function :tag "Function")))))
  2045. (defcustom org-doi-server-url "http://dx.doi.org/"
  2046. "The URL of the DOI server."
  2047. :type 'string
  2048. :version "24.3"
  2049. :group 'org-link-follow)
  2050. (defgroup org-refile nil
  2051. "Options concerning refiling entries in Org mode."
  2052. :tag "Org Refile"
  2053. :group 'org)
  2054. (defcustom org-directory "~/org"
  2055. "Directory with Org files.
  2056. This is just a default location to look for Org files. There is no need
  2057. at all to put your files into this directory. It is used in the
  2058. following situations:
  2059. 1. When a capture template specifies a target file that is not an
  2060. absolute path. The path will then be interpreted relative to
  2061. `org-directory'
  2062. 2. When the value of variable `org-agenda-files' is a single file, any
  2063. relative paths in this file will be taken as relative to
  2064. `org-directory'."
  2065. :group 'org-refile
  2066. :group 'org-capture
  2067. :type 'directory)
  2068. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2069. "Default target for storing notes.
  2070. Used as a fall back file for org-capture.el, for templates that
  2071. do not specify a target file."
  2072. :group 'org-refile
  2073. :group 'org-capture
  2074. :type 'file)
  2075. (defcustom org-goto-interface 'outline
  2076. "The default interface to be used for `org-goto'.
  2077. Allowed values are:
  2078. outline The interface shows an outline of the relevant file
  2079. and the correct heading is found by moving through
  2080. the outline or by searching with incremental search.
  2081. outline-path-completion Headlines in the current buffer are offered via
  2082. completion. This is the interface also used by
  2083. the refile command."
  2084. :group 'org-refile
  2085. :type '(choice
  2086. (const :tag "Outline" outline)
  2087. (const :tag "Outline-path-completion" outline-path-completion)))
  2088. (defcustom org-goto-max-level 5
  2089. "Maximum target level when running `org-goto' with refile interface."
  2090. :group 'org-refile
  2091. :type 'integer)
  2092. (defcustom org-reverse-note-order nil
  2093. "Non-nil means store new notes at the beginning of a file or entry.
  2094. When nil, new notes will be filed to the end of a file or entry.
  2095. This can also be a list with cons cells of regular expressions that
  2096. are matched against file names, and values."
  2097. :group 'org-capture
  2098. :group 'org-refile
  2099. :type '(choice
  2100. (const :tag "Reverse always" t)
  2101. (const :tag "Reverse never" nil)
  2102. (repeat :tag "By file name regexp"
  2103. (cons regexp boolean))))
  2104. (defcustom org-log-refile nil
  2105. "Information to record when a task is refiled.
  2106. Possible values are:
  2107. nil Don't add anything
  2108. time Add a time stamp to the task
  2109. note Prompt for a note and add it with template `org-log-note-headings'
  2110. This option can also be set with on a per-file-basis with
  2111. #+STARTUP: nologrefile
  2112. #+STARTUP: logrefile
  2113. #+STARTUP: lognoterefile
  2114. You can have local logging settings for a subtree by setting the LOGGING
  2115. property to one or more of these keywords.
  2116. When bulk-refiling from the agenda, the value `note' is forbidden and
  2117. will temporarily be changed to `time'."
  2118. :group 'org-refile
  2119. :group 'org-progress
  2120. :version "24.1"
  2121. :type '(choice
  2122. (const :tag "No logging" nil)
  2123. (const :tag "Record timestamp" time)
  2124. (const :tag "Record timestamp with note." note)))
  2125. (defcustom org-refile-targets nil
  2126. "Targets for refiling entries with `\\[org-refile]'.
  2127. This is a list of cons cells. Each cell contains:
  2128. - a specification of the files to be considered, either a list of files,
  2129. or a symbol whose function or variable value will be used to retrieve
  2130. a file name or a list of file names. If you use `org-agenda-files' for
  2131. that, all agenda files will be scanned for targets. Nil means consider
  2132. headings in the current buffer.
  2133. - A specification of how to find candidate refile targets. This may be
  2134. any of:
  2135. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2136. This tag has to be present in all target headlines, inheritance will
  2137. not be considered.
  2138. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2139. todo keyword.
  2140. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2141. headlines that are refiling targets.
  2142. - a cons cell (:level . N). Any headline of level N is considered a target.
  2143. Note that, when `org-odd-levels-only' is set, level corresponds to
  2144. order in hierarchy, not to the number of stars.
  2145. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2146. Note that, when `org-odd-levels-only' is set, level corresponds to
  2147. order in hierarchy, not to the number of stars.
  2148. Each element of this list generates a set of possible targets.
  2149. The union of these sets is presented (with completion) to
  2150. the user by `org-refile'.
  2151. You can set the variable `org-refile-target-verify-function' to a function
  2152. to verify each headline found by the simple criteria above.
  2153. When this variable is nil, all top-level headlines in the current buffer
  2154. are used, equivalent to the value `((nil . (:level . 1))'."
  2155. :group 'org-refile
  2156. :type '(repeat
  2157. (cons
  2158. (choice :value org-agenda-files
  2159. (const :tag "All agenda files" org-agenda-files)
  2160. (const :tag "Current buffer" nil)
  2161. (function) (variable) (file))
  2162. (choice :tag "Identify target headline by"
  2163. (cons :tag "Specific tag" (const :value :tag) (string))
  2164. (cons :tag "TODO keyword" (const :value :todo) (string))
  2165. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2166. (cons :tag "Level number" (const :value :level) (integer))
  2167. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2168. (defcustom org-refile-target-verify-function nil
  2169. "Function to verify if the headline at point should be a refile target.
  2170. The function will be called without arguments, with point at the
  2171. beginning of the headline. It should return t and leave point
  2172. where it is if the headline is a valid target for refiling.
  2173. If the target should not be selected, the function must return nil.
  2174. In addition to this, it may move point to a place from where the search
  2175. should be continued. For example, the function may decide that the entire
  2176. subtree of the current entry should be excluded and move point to the end
  2177. of the subtree."
  2178. :group 'org-refile
  2179. :type '(choice
  2180. (const nil)
  2181. (function)))
  2182. (defcustom org-refile-use-cache nil
  2183. "Non-nil means cache refile targets to speed up the process.
  2184. \\<org-mode-map>\
  2185. The cache for a particular file will be updated automatically when
  2186. the buffer has been killed, or when any of the marker used for flagging
  2187. refile targets no longer points at a live buffer.
  2188. If you have added new entries to a buffer that might themselves be targets,
  2189. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2190. if you find that easier, \
  2191. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2192. \\[org-refile]'."
  2193. :group 'org-refile
  2194. :version "24.1"
  2195. :type 'boolean)
  2196. (defcustom org-refile-use-outline-path nil
  2197. "Non-nil means provide refile targets as paths.
  2198. So a level 3 headline will be available as level1/level2/level3.
  2199. When the value is `file', also include the file name (without directory)
  2200. into the path. In this case, you can also stop the completion after
  2201. the file name, to get entries inserted as top level in the file.
  2202. When `full-file-path', include the full file path."
  2203. :group 'org-refile
  2204. :type '(choice
  2205. (const :tag "Not" nil)
  2206. (const :tag "Yes" t)
  2207. (const :tag "Start with file name" file)
  2208. (const :tag "Start with full file path" full-file-path)))
  2209. (defcustom org-outline-path-complete-in-steps t
  2210. "Non-nil means complete the outline path in hierarchical steps.
  2211. When Org uses the refile interface to select an outline path (see
  2212. `org-refile-use-outline-path'), the completion of the path can be
  2213. done in a single go, or it can be done in steps down the headline
  2214. hierarchy. Going in steps is probably the best if you do not use
  2215. a special completion package like `ido' or `icicles'. However,
  2216. when using these packages, going in one step can be very fast,
  2217. while still showing the whole path to the entry."
  2218. :group 'org-refile
  2219. :type 'boolean)
  2220. (defcustom org-refile-allow-creating-parent-nodes nil
  2221. "Non-nil means allow the creation of new nodes as refile targets.
  2222. New nodes are then created by adding \"/new node name\" to the completion
  2223. of an existing node. When the value of this variable is `confirm',
  2224. new node creation must be confirmed by the user (recommended).
  2225. When nil, the completion must match an existing entry.
  2226. Note that, if the new heading is not seen by the criteria
  2227. listed in `org-refile-targets', multiple instances of the same
  2228. heading would be created by trying again to file under the new
  2229. heading."
  2230. :group 'org-refile
  2231. :type '(choice
  2232. (const :tag "Never" nil)
  2233. (const :tag "Always" t)
  2234. (const :tag "Prompt for confirmation" confirm)))
  2235. (defcustom org-refile-active-region-within-subtree nil
  2236. "Non-nil means also refile active region within a subtree.
  2237. By default `org-refile' doesn't allow refiling regions if they
  2238. don't contain a set of subtrees, but it might be convenient to
  2239. do so sometimes: in that case, the first line of the region is
  2240. converted to a headline before refiling."
  2241. :group 'org-refile
  2242. :version "24.1"
  2243. :type 'boolean)
  2244. (defgroup org-todo nil
  2245. "Options concerning TODO items in Org mode."
  2246. :tag "Org TODO"
  2247. :group 'org)
  2248. (defgroup org-progress nil
  2249. "Options concerning Progress logging in Org mode."
  2250. :tag "Org Progress"
  2251. :group 'org-time)
  2252. (defvar org-todo-interpretation-widgets
  2253. '((:tag "Sequence (cycling hits every state)" sequence)
  2254. (:tag "Type (cycling directly to DONE)" type))
  2255. "The available interpretation symbols for customizing `org-todo-keywords'.
  2256. Interested libraries should add to this list.")
  2257. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2258. "List of TODO entry keyword sequences and their interpretation.
  2259. \\<org-mode-map>This is a list of sequences.
  2260. Each sequence starts with a symbol, either `sequence' or `type',
  2261. indicating if the keywords should be interpreted as a sequence of
  2262. action steps, or as different types of TODO items. The first
  2263. keywords are states requiring action - these states will select a headline
  2264. for inclusion into the global TODO list Org produces. If one of the
  2265. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2266. signify that no further action is necessary. If \"|\" is not found,
  2267. the last keyword is treated as the only DONE state of the sequence.
  2268. The command `\\[org-todo]' cycles an entry through these states, and one
  2269. additional state where no keyword is present. For details about this
  2270. cycling, see the manual.
  2271. TODO keywords and interpretation can also be set on a per-file basis with
  2272. the special #+SEQ_TODO and #+TYP_TODO lines.
  2273. Each keyword can optionally specify a character for fast state selection
  2274. \(in combination with the variable `org-use-fast-todo-selection')
  2275. and specifiers for state change logging, using the same syntax that
  2276. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2277. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2278. indicates to record a time stamp each time this state is selected.
  2279. Each keyword may also specify if a timestamp or a note should be
  2280. recorded when entering or leaving the state, by adding additional
  2281. characters in the parenthesis after the keyword. This looks like this:
  2282. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2283. record only the time of the state change. With X and Y being either
  2284. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2285. Y when leaving the state if and only if the *target* state does not
  2286. define X. You may omit any of the fast-selection key or X or /Y,
  2287. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2288. For backward compatibility, this variable may also be just a list
  2289. of keywords. In this case the interpretation (sequence or type) will be
  2290. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2291. :group 'org-todo
  2292. :group 'org-keywords
  2293. :type '(choice
  2294. (repeat :tag "Old syntax, just keywords"
  2295. (string :tag "Keyword"))
  2296. (repeat :tag "New syntax"
  2297. (cons
  2298. (choice
  2299. :tag "Interpretation"
  2300. ;;Quick and dirty way to see
  2301. ;;`org-todo-interpretations'. This takes the
  2302. ;;place of item arguments
  2303. :convert-widget
  2304. (lambda (widget)
  2305. (widget-put widget
  2306. :args (mapcar
  2307. (lambda (x)
  2308. (widget-convert
  2309. (cons 'const x)))
  2310. org-todo-interpretation-widgets))
  2311. widget))
  2312. (repeat
  2313. (string :tag "Keyword"))))))
  2314. (defvar-local org-todo-keywords-1 nil
  2315. "All TODO and DONE keywords active in a buffer.")
  2316. (defvar org-todo-keywords-for-agenda nil)
  2317. (defvar org-done-keywords-for-agenda nil)
  2318. (defvar org-todo-keyword-alist-for-agenda nil)
  2319. (defvar org-tag-alist-for-agenda nil
  2320. "Alist of all tags from all agenda files.")
  2321. (defvar org-tag-groups-alist-for-agenda nil
  2322. "Alist of all groups tags from all current agenda files.")
  2323. (defvar-local org-tag-groups-alist nil)
  2324. (defvar org-agenda-contributing-files nil)
  2325. (defvar-local org-current-tag-alist nil
  2326. "Alist of all tag groups in current buffer.
  2327. This variable takes into consideration `org-tag-alist',
  2328. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2329. (defvar-local org-not-done-keywords nil)
  2330. (defvar-local org-done-keywords nil)
  2331. (defvar-local org-todo-heads nil)
  2332. (defvar-local org-todo-sets nil)
  2333. (defvar-local org-todo-log-states nil)
  2334. (defvar-local org-todo-kwd-alist nil)
  2335. (defvar-local org-todo-key-alist nil)
  2336. (defvar-local org-todo-key-trigger nil)
  2337. (defcustom org-todo-interpretation 'sequence
  2338. "Controls how TODO keywords are interpreted.
  2339. This variable is in principle obsolete and is only used for
  2340. backward compatibility, if the interpretation of todo keywords is
  2341. not given already in `org-todo-keywords'. See that variable for
  2342. more information."
  2343. :group 'org-todo
  2344. :group 'org-keywords
  2345. :type '(choice (const sequence)
  2346. (const type)))
  2347. (defcustom org-use-fast-todo-selection t
  2348. "\\<org-mode-map>\
  2349. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2350. This variable describes if and under what circumstances the cycling
  2351. mechanism for TODO keywords will be replaced by a single-key, direct
  2352. selection scheme.
  2353. When nil, fast selection is never used.
  2354. When the symbol `prefix', it will be used when `org-todo' is called
  2355. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2356. in an Org buffer, and
  2357. `\\[universal-argument] t' in an agenda buffer.
  2358. When t, fast selection is used by default. In this case, the prefix
  2359. argument forces cycling instead.
  2360. In all cases, the special interface is only used if access keys have
  2361. actually been assigned by the user, i.e. if keywords in the configuration
  2362. are followed by a letter in parenthesis, like TODO(t)."
  2363. :group 'org-todo
  2364. :type '(choice
  2365. (const :tag "Never" nil)
  2366. (const :tag "By default" t)
  2367. (const :tag "Only with C-u C-c C-t" prefix)))
  2368. (defcustom org-provide-todo-statistics t
  2369. "Non-nil means update todo statistics after insert and toggle.
  2370. ALL-HEADLINES means update todo statistics by including headlines
  2371. with no TODO keyword as well, counting them as not done.
  2372. A list of TODO keywords means the same, but skip keywords that are
  2373. not in this list.
  2374. When set to a list of two lists, the first list contains keywords
  2375. to consider as TODO keywords, the second list contains keywords
  2376. to consider as DONE keywords.
  2377. When this is set, todo statistics is updated in the parent of the
  2378. current entry each time a todo state is changed."
  2379. :group 'org-todo
  2380. :type '(choice
  2381. (const :tag "Yes, only for TODO entries" t)
  2382. (const :tag "Yes, including all entries" all-headlines)
  2383. (repeat :tag "Yes, for TODOs in this list"
  2384. (string :tag "TODO keyword"))
  2385. (list :tag "Yes, for TODOs and DONEs in these lists"
  2386. (repeat (string :tag "TODO keyword"))
  2387. (repeat (string :tag "DONE keyword")))
  2388. (other :tag "No TODO statistics" nil)))
  2389. (defcustom org-hierarchical-todo-statistics t
  2390. "Non-nil means TODO statistics covers just direct children.
  2391. When nil, all entries in the subtree are considered.
  2392. This has only an effect if `org-provide-todo-statistics' is set.
  2393. To set this to nil for only a single subtree, use a COOKIE_DATA
  2394. property and include the word \"recursive\" into the value."
  2395. :group 'org-todo
  2396. :type 'boolean)
  2397. (defcustom org-after-todo-state-change-hook nil
  2398. "Hook which is run after the state of a TODO item was changed.
  2399. The new state (a string with a TODO keyword, or nil) is available in the
  2400. Lisp variable `org-state'."
  2401. :group 'org-todo
  2402. :type 'hook)
  2403. (defvar org-blocker-hook nil
  2404. "Hook for functions that are allowed to block a state change.
  2405. Functions in this hook should not modify the buffer.
  2406. Each function gets as its single argument a property list,
  2407. see `org-trigger-hook' for more information about this list.
  2408. If any of the functions in this hook returns nil, the state change
  2409. is blocked.")
  2410. (defvar org-trigger-hook nil
  2411. "Hook for functions that are triggered by a state change.
  2412. Each function gets as its single argument a property list with at
  2413. least the following elements:
  2414. (:type type-of-change :position pos-at-entry-start
  2415. :from old-state :to new-state)
  2416. Depending on the type, more properties may be present.
  2417. This mechanism is currently implemented for:
  2418. TODO state changes
  2419. ------------------
  2420. :type todo-state-change
  2421. :from previous state (keyword as a string), or nil, or a symbol
  2422. `todo' or `done', to indicate the general type of state.
  2423. :to new state, like in :from")
  2424. (defcustom org-enforce-todo-dependencies nil
  2425. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2426. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2427. be blocked if any prior sibling is not yet done.
  2428. Finally, if the parent is blocked because of ordered siblings of its own,
  2429. the child will also be blocked."
  2430. :set (lambda (var val)
  2431. (set var val)
  2432. (if val
  2433. (add-hook 'org-blocker-hook
  2434. 'org-block-todo-from-children-or-siblings-or-parent)
  2435. (remove-hook 'org-blocker-hook
  2436. 'org-block-todo-from-children-or-siblings-or-parent)))
  2437. :group 'org-todo
  2438. :type 'boolean)
  2439. (defcustom org-enforce-todo-checkbox-dependencies nil
  2440. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2441. When this is nil, checkboxes have no influence on switching TODO states.
  2442. When non-nil, you first need to check off all check boxes before the TODO
  2443. entry can be switched to DONE.
  2444. This variable needs to be set before org.el is loaded, and you need to
  2445. restart Emacs after a change to make the change effective. The only way
  2446. to change is while Emacs is running is through the customize interface."
  2447. :set (lambda (var val)
  2448. (set var val)
  2449. (if val
  2450. (add-hook 'org-blocker-hook
  2451. 'org-block-todo-from-checkboxes)
  2452. (remove-hook 'org-blocker-hook
  2453. 'org-block-todo-from-checkboxes)))
  2454. :group 'org-todo
  2455. :type 'boolean)
  2456. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2457. "Non-nil means inserting a TODO heading is treated as state change.
  2458. So when the command `\\[org-insert-todo-heading]' is used, state change
  2459. logging will apply if appropriate. When nil, the new TODO item will
  2460. be inserted directly, and no logging will take place."
  2461. :group 'org-todo
  2462. :type 'boolean)
  2463. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2464. "Non-nil means switching TODO states with S-cursor counts as state change.
  2465. This is the default behavior. However, setting this to nil allows a
  2466. convenient way to select a TODO state and bypass any logging associated
  2467. with that."
  2468. :group 'org-todo
  2469. :type 'boolean)
  2470. (defcustom org-todo-state-tags-triggers nil
  2471. "Tag changes that should be triggered by TODO state changes.
  2472. This is a list. Each entry is
  2473. (state-change (tag . flag) .......)
  2474. State-change can be a string with a state, and empty string to indicate the
  2475. state that has no TODO keyword, or it can be one of the symbols `todo'
  2476. or `done', meaning any not-done or done state, respectively."
  2477. :group 'org-todo
  2478. :group 'org-tags
  2479. :type '(repeat
  2480. (cons (choice :tag "When changing to"
  2481. (const :tag "Not-done state" todo)
  2482. (const :tag "Done state" done)
  2483. (string :tag "State"))
  2484. (repeat
  2485. (cons :tag "Tag action"
  2486. (string :tag "Tag")
  2487. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2488. (defcustom org-log-done nil
  2489. "Information to record when a task moves to the DONE state.
  2490. Possible values are:
  2491. nil Don't add anything, just change the keyword
  2492. time Add a time stamp to the task
  2493. note Prompt for a note and add it with template `org-log-note-headings'
  2494. This option can also be set with on a per-file-basis with
  2495. #+STARTUP: nologdone
  2496. #+STARTUP: logdone
  2497. #+STARTUP: lognotedone
  2498. You can have local logging settings for a subtree by setting the LOGGING
  2499. property to one or more of these keywords."
  2500. :group 'org-todo
  2501. :group 'org-progress
  2502. :type '(choice
  2503. (const :tag "No logging" nil)
  2504. (const :tag "Record CLOSED timestamp" time)
  2505. (const :tag "Record CLOSED timestamp with note." note)))
  2506. ;; Normalize old uses of org-log-done.
  2507. (cond
  2508. ((eq org-log-done t) (setq org-log-done 'time))
  2509. ((and (listp org-log-done) (memq 'done org-log-done))
  2510. (setq org-log-done 'note)))
  2511. (defcustom org-log-reschedule nil
  2512. "Information to record when the scheduling date of a tasks is modified.
  2513. Possible values are:
  2514. nil Don't add anything, just change the date
  2515. time Add a time stamp to the task
  2516. note Prompt for a note and add it with template `org-log-note-headings'
  2517. This option can also be set with on a per-file-basis with
  2518. #+STARTUP: nologreschedule
  2519. #+STARTUP: logreschedule
  2520. #+STARTUP: lognotereschedule"
  2521. :group 'org-todo
  2522. :group 'org-progress
  2523. :type '(choice
  2524. (const :tag "No logging" nil)
  2525. (const :tag "Record timestamp" time)
  2526. (const :tag "Record timestamp with note." note)))
  2527. (defcustom org-log-redeadline nil
  2528. "Information to record when the deadline date of a tasks is modified.
  2529. Possible values are:
  2530. nil Don't add anything, just change the date
  2531. time Add a time stamp to the task
  2532. note Prompt for a note and add it with template `org-log-note-headings'
  2533. This option can also be set with on a per-file-basis with
  2534. #+STARTUP: nologredeadline
  2535. #+STARTUP: logredeadline
  2536. #+STARTUP: lognoteredeadline
  2537. You can have local logging settings for a subtree by setting the LOGGING
  2538. property to one or more of these keywords."
  2539. :group 'org-todo
  2540. :group 'org-progress
  2541. :type '(choice
  2542. (const :tag "No logging" nil)
  2543. (const :tag "Record timestamp" time)
  2544. (const :tag "Record timestamp with note." note)))
  2545. (defcustom org-log-note-clock-out nil
  2546. "Non-nil means record a note when clocking out of an item.
  2547. This can also be configured on a per-file basis by adding one of
  2548. the following lines anywhere in the buffer:
  2549. #+STARTUP: lognoteclock-out
  2550. #+STARTUP: nolognoteclock-out"
  2551. :group 'org-todo
  2552. :group 'org-progress
  2553. :type 'boolean)
  2554. (defcustom org-log-done-with-time t
  2555. "Non-nil means the CLOSED time stamp will contain date and time.
  2556. When nil, only the date will be recorded."
  2557. :group 'org-progress
  2558. :type 'boolean)
  2559. (defcustom org-log-note-headings
  2560. '((done . "CLOSING NOTE %t")
  2561. (state . "State %-12s from %-12S %t")
  2562. (note . "Note taken on %t")
  2563. (reschedule . "Rescheduled from %S on %t")
  2564. (delschedule . "Not scheduled, was %S on %t")
  2565. (redeadline . "New deadline from %S on %t")
  2566. (deldeadline . "Removed deadline, was %S on %t")
  2567. (refile . "Refiled on %t")
  2568. (clock-out . ""))
  2569. "Headings for notes added to entries.
  2570. The value is an alist, with the car being a symbol indicating the
  2571. note context, and the cdr is the heading to be used. The heading
  2572. may also be the empty string. The following placeholders can be
  2573. used:
  2574. %t a time stamp.
  2575. %T an active time stamp instead the default inactive one
  2576. %d a short-format time stamp.
  2577. %D an active short-format time stamp.
  2578. %s the new TODO state or time stamp (inactive), in double quotes.
  2579. %S the old TODO state or time stamp (inactive), in double quotes.
  2580. %u the user name.
  2581. %U full user name.
  2582. In fact, it is not a good idea to change the `state' entry,
  2583. because Agenda Log mode depends on the format of these entries."
  2584. :group 'org-todo
  2585. :group 'org-progress
  2586. :type '(list :greedy t
  2587. (cons (const :tag "Heading when closing an item" done) string)
  2588. (cons (const :tag
  2589. "Heading when changing todo state (todo sequence only)"
  2590. state) string)
  2591. (cons (const :tag "Heading when just taking a note" note) string)
  2592. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2593. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2594. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2595. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2596. (cons (const :tag "Heading when refiling" refile) string)
  2597. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2598. (unless (assq 'note org-log-note-headings)
  2599. (push '(note . "%t") org-log-note-headings))
  2600. (defcustom org-log-into-drawer nil
  2601. "Non-nil means insert state change notes and time stamps into a drawer.
  2602. When nil, state changes notes will be inserted after the headline and
  2603. any scheduling and clock lines, but not inside a drawer.
  2604. The value of this variable should be the name of the drawer to use.
  2605. LOGBOOK is proposed as the default drawer for this purpose, you can
  2606. also set this to a string to define the drawer of your choice.
  2607. A value of t is also allowed, representing \"LOGBOOK\".
  2608. A value of t or nil can also be set with on a per-file-basis with
  2609. #+STARTUP: logdrawer
  2610. #+STARTUP: nologdrawer
  2611. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2612. will be ignored.
  2613. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2614. a subtree.
  2615. Do not check directly this variable in a Lisp program. Call
  2616. function `org-log-into-drawer' instead."
  2617. :group 'org-todo
  2618. :group 'org-progress
  2619. :type '(choice
  2620. (const :tag "Not into a drawer" nil)
  2621. (const :tag "LOGBOOK" t)
  2622. (string :tag "Other")))
  2623. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2624. (defun org-log-into-drawer ()
  2625. "Name of the log drawer, as a string, or nil.
  2626. This is the value of `org-log-into-drawer'. However, if the
  2627. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2628. be used instead of the default value."
  2629. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2630. (cond ((equal p "nil") nil)
  2631. ((equal p "t") "LOGBOOK")
  2632. ((stringp p) p)
  2633. (p "LOGBOOK")
  2634. ((stringp org-log-into-drawer) org-log-into-drawer)
  2635. (org-log-into-drawer "LOGBOOK"))))
  2636. (defcustom org-log-state-notes-insert-after-drawers nil
  2637. "Non-nil means insert state change notes after any drawers in entry.
  2638. Only the drawers that *immediately* follow the headline and the
  2639. deadline/scheduled line are skipped.
  2640. When nil, insert notes right after the heading and perhaps the line
  2641. with deadline/scheduling if present.
  2642. This variable will have no effect if `org-log-into-drawer' is
  2643. set."
  2644. :group 'org-todo
  2645. :group 'org-progress
  2646. :type 'boolean)
  2647. (defcustom org-log-states-order-reversed t
  2648. "Non-nil means the latest state note will be directly after heading.
  2649. When nil, the state change notes will be ordered according to time.
  2650. This option can also be set with on a per-file-basis with
  2651. #+STARTUP: logstatesreversed
  2652. #+STARTUP: nologstatesreversed"
  2653. :group 'org-todo
  2654. :group 'org-progress
  2655. :type 'boolean)
  2656. (defcustom org-todo-repeat-to-state nil
  2657. "The TODO state to which a repeater should return the repeating task.
  2658. By default this is the first task in a TODO sequence, or the previous state
  2659. in a TODO_TYP set. But you can specify another task here.
  2660. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2661. :group 'org-todo
  2662. :version "24.1"
  2663. :type '(choice (const :tag "Head of sequence" nil)
  2664. (string :tag "Specific state")))
  2665. (defcustom org-log-repeat 'time
  2666. "Non-nil means record moving through the DONE state when triggering repeat.
  2667. An auto-repeating task is immediately switched back to TODO when
  2668. marked DONE. If you are not logging state changes (by adding \"@\"
  2669. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2670. record a closing note, there will be no record of the task moving
  2671. through DONE. This variable forces taking a note anyway.
  2672. nil Don't force a record
  2673. time Record a time stamp
  2674. note Prompt for a note and add it with template `org-log-note-headings'
  2675. This option can also be set with on a per-file-basis with
  2676. #+STARTUP: nologrepeat
  2677. #+STARTUP: logrepeat
  2678. #+STARTUP: lognoterepeat
  2679. You can have local logging settings for a subtree by setting the LOGGING
  2680. property to one or more of these keywords."
  2681. :group 'org-todo
  2682. :group 'org-progress
  2683. :type '(choice
  2684. (const :tag "Don't force a record" nil)
  2685. (const :tag "Force recording the DONE state" time)
  2686. (const :tag "Force recording a note with the DONE state" note)))
  2687. (defgroup org-priorities nil
  2688. "Priorities in Org mode."
  2689. :tag "Org Priorities"
  2690. :group 'org-todo)
  2691. (defcustom org-enable-priority-commands t
  2692. "Non-nil means priority commands are active.
  2693. When nil, these commands will be disabled, so that you never accidentally
  2694. set a priority."
  2695. :group 'org-priorities
  2696. :type 'boolean)
  2697. (defcustom org-highest-priority ?A
  2698. "The highest priority of TODO items. A character like ?A, ?B etc.
  2699. Must have a smaller ASCII number than `org-lowest-priority'."
  2700. :group 'org-priorities
  2701. :type 'character)
  2702. (defcustom org-lowest-priority ?C
  2703. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2704. Must have a larger ASCII number than `org-highest-priority'."
  2705. :group 'org-priorities
  2706. :type 'character)
  2707. (defcustom org-default-priority ?B
  2708. "The default priority of TODO items.
  2709. This is the priority an item gets if no explicit priority is given.
  2710. When starting to cycle on an empty priority the first step in the cycle
  2711. depends on `org-priority-start-cycle-with-default'. The resulting first
  2712. step priority must not exceed the range from `org-highest-priority' to
  2713. `org-lowest-priority' which means that `org-default-priority' has to be
  2714. in this range exclusive or inclusive the range boundaries. Else the
  2715. first step refuses to set the default and the second will fall back
  2716. to (depending on the command used) the highest or lowest priority."
  2717. :group 'org-priorities
  2718. :type 'character)
  2719. (defcustom org-priority-start-cycle-with-default t
  2720. "Non-nil means start with default priority when starting to cycle.
  2721. When this is nil, the first step in the cycle will be (depending on the
  2722. command used) one higher or lower than the default priority.
  2723. See also `org-default-priority'."
  2724. :group 'org-priorities
  2725. :type 'boolean)
  2726. (defcustom org-get-priority-function nil
  2727. "Function to extract the priority from a string.
  2728. The string is normally the headline. If this is nil Org computes the
  2729. priority from the priority cookie like [#A] in the headline. It returns
  2730. an integer, increasing by 1000 for each priority level.
  2731. The user can set a different function here, which should take a string
  2732. as an argument and return the numeric priority."
  2733. :group 'org-priorities
  2734. :version "24.1"
  2735. :type '(choice
  2736. (const nil)
  2737. (function)))
  2738. (defgroup org-time nil
  2739. "Options concerning time stamps and deadlines in Org mode."
  2740. :tag "Org Time"
  2741. :group 'org)
  2742. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2743. "Number of minutes to round time stamps to.
  2744. \\<org-mode-map>\
  2745. These are two values, the first applies when first creating a time stamp.
  2746. The second applies when changing it with the commands `S-up' and `S-down'.
  2747. When changing the time stamp, this means that it will change in steps
  2748. of N minutes, as given by the second value.
  2749. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2750. numbers should be factors of 60, so for example 5, 10, 15.
  2751. When this is larger than 1, you can still force an exact time stamp by using
  2752. a double prefix argument to a time stamp command like \
  2753. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2754. and by using a prefix arg to `S-up/down' to specify the exact number
  2755. of minutes to shift."
  2756. :group 'org-time
  2757. :get (lambda (var) ; Make sure both elements are there
  2758. (if (integerp (default-value var))
  2759. (list (default-value var) 5)
  2760. (default-value var)))
  2761. :type '(list
  2762. (integer :tag "when inserting times")
  2763. (integer :tag "when modifying times")))
  2764. ;; Normalize old customizations of this variable.
  2765. (when (integerp org-time-stamp-rounding-minutes)
  2766. (setq org-time-stamp-rounding-minutes
  2767. (list org-time-stamp-rounding-minutes
  2768. org-time-stamp-rounding-minutes)))
  2769. (defcustom org-display-custom-times nil
  2770. "Non-nil means overlay custom formats over all time stamps.
  2771. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2772. To turn this on on a per-file basis, insert anywhere in the file:
  2773. #+STARTUP: customtime"
  2774. :group 'org-time
  2775. :set 'set-default
  2776. :type 'sexp)
  2777. (make-variable-buffer-local 'org-display-custom-times)
  2778. (defcustom org-time-stamp-custom-formats
  2779. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2780. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2781. These are overlaid over the default ISO format if the variable
  2782. `org-display-custom-times' is set. Time like %H:%M should be at the
  2783. end of the second format. The custom formats are also honored by export
  2784. commands, if custom time display is turned on at the time of export."
  2785. :group 'org-time
  2786. :type 'sexp)
  2787. (defun org-time-stamp-format (&optional long inactive)
  2788. "Get the right format for a time string."
  2789. (let ((f (if long (cdr org-time-stamp-formats)
  2790. (car org-time-stamp-formats))))
  2791. (if inactive
  2792. (concat "[" (substring f 1 -1) "]")
  2793. f)))
  2794. (defcustom org-deadline-warning-days 14
  2795. "Number of days before expiration during which a deadline becomes active.
  2796. This variable governs the display in sparse trees and in the agenda.
  2797. When 0 or negative, it means use this number (the absolute value of it)
  2798. even if a deadline has a different individual lead time specified.
  2799. Custom commands can set this variable in the options section."
  2800. :group 'org-time
  2801. :group 'org-agenda-daily/weekly
  2802. :type 'integer)
  2803. (defcustom org-scheduled-delay-days 0
  2804. "Number of days before a scheduled item becomes active.
  2805. This variable governs the display in sparse trees and in the agenda.
  2806. The default value (i.e. 0) means: don't delay scheduled item.
  2807. When negative, it means use this number (the absolute value of it)
  2808. even if a scheduled item has a different individual delay time
  2809. specified.
  2810. Custom commands can set this variable in the options section."
  2811. :group 'org-time
  2812. :group 'org-agenda-daily/weekly
  2813. :version "24.4"
  2814. :package-version '(Org . "8.0")
  2815. :type 'integer)
  2816. (defcustom org-read-date-prefer-future t
  2817. "Non-nil means assume future for incomplete date input from user.
  2818. This affects the following situations:
  2819. 1. The user gives a month but not a year.
  2820. For example, if it is April and you enter \"feb 2\", this will be read
  2821. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2822. 2. The user gives a day, but no month.
  2823. For example, if today is the 15th, and you enter \"3\", Org will read
  2824. this as the third of *next* month. However, if you enter \"17\",
  2825. it will be considered as *this* month.
  2826. If you set this variable to the symbol `time', then also the following
  2827. will work:
  2828. 3. If the user gives a time.
  2829. If the time is before now, it will be interpreted as tomorrow.
  2830. Currently none of this works for ISO week specifications.
  2831. When this option is nil, the current day, month and year will always be
  2832. used as defaults.
  2833. See also `org-agenda-jump-prefer-future'."
  2834. :group 'org-time
  2835. :type '(choice
  2836. (const :tag "Never" nil)
  2837. (const :tag "Check month and day" t)
  2838. (const :tag "Check month, day, and time" time)))
  2839. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2840. "Should the agenda jump command prefer the future for incomplete dates?
  2841. The default is to do the same as configured in `org-read-date-prefer-future'.
  2842. But you can also set a deviating value here.
  2843. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2844. :group 'org-agenda
  2845. :group 'org-time
  2846. :version "24.1"
  2847. :type '(choice
  2848. (const :tag "Use org-read-date-prefer-future"
  2849. org-read-date-prefer-future)
  2850. (const :tag "Never" nil)
  2851. (const :tag "Always" t)))
  2852. (defcustom org-read-date-force-compatible-dates t
  2853. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2854. Depending on the system Emacs is running on, certain dates cannot
  2855. be represented with the type used internally to represent time.
  2856. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2857. correctly. Some systems allow for earlier dates, some for later,
  2858. some for both. One way to find out it to insert any date into an
  2859. Org buffer, putting the cursor on the year and hitting S-up and
  2860. S-down to test the range.
  2861. When this variable is set to t, the date/time prompt will not let
  2862. you specify dates outside the 1970-2037 range, so it is certain that
  2863. these dates will work in whatever version of Emacs you are
  2864. running, and also that you can move a file from one Emacs implementation
  2865. to another. WHenever Org is forcing the year for you, it will display
  2866. a message and beep.
  2867. When this variable is nil, Org will check if the date is
  2868. representable in the specific Emacs implementation you are using.
  2869. If not, it will force a year, usually the current year, and beep
  2870. to remind you. Currently this setting is not recommended because
  2871. the likelihood that you will open your Org files in an Emacs that
  2872. has limited date range is not negligible.
  2873. A workaround for this problem is to use diary sexp dates for time
  2874. stamps outside of this range."
  2875. :group 'org-time
  2876. :version "24.1"
  2877. :type 'boolean)
  2878. (defcustom org-read-date-display-live t
  2879. "Non-nil means display current interpretation of date prompt live.
  2880. This display will be in an overlay, in the minibuffer."
  2881. :group 'org-time
  2882. :type 'boolean)
  2883. (defcustom org-read-date-popup-calendar t
  2884. "Non-nil means pop up a calendar when prompting for a date.
  2885. In the calendar, the date can be selected with mouse-1. However, the
  2886. minibuffer will also be active, and you can simply enter the date as well.
  2887. When nil, only the minibuffer will be available."
  2888. :group 'org-time
  2889. :type 'boolean)
  2890. (defvaralias 'org-popup-calendar-for-date-prompt
  2891. 'org-read-date-popup-calendar)
  2892. (defcustom org-extend-today-until 0
  2893. "The hour when your day really ends. Must be an integer.
  2894. This has influence for the following applications:
  2895. - When switching the agenda to \"today\". It it is still earlier than
  2896. the time given here, the day recognized as TODAY is actually yesterday.
  2897. - When a date is read from the user and it is still before the time given
  2898. here, the current date and time will be assumed to be yesterday, 23:59.
  2899. Also, timestamps inserted in capture templates follow this rule.
  2900. IMPORTANT: This is a feature whose implementation is and likely will
  2901. remain incomplete. Really, it is only here because past midnight seems to
  2902. be the favorite working time of John Wiegley :-)"
  2903. :group 'org-time
  2904. :type 'integer)
  2905. (defcustom org-use-effective-time nil
  2906. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2907. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2908. \"effective time\" of any timestamps between midnight and 8am will be
  2909. 23:59 of the previous day."
  2910. :group 'org-time
  2911. :version "24.1"
  2912. :type 'boolean)
  2913. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2914. "When non-nil, use the last clock out time for `org-todo'.
  2915. Note that this option has precedence over the combined use of
  2916. `org-use-effective-time' and `org-extend-today-until'."
  2917. :group 'org-time
  2918. :version "24.4"
  2919. :package-version '(Org . "8.0")
  2920. :type 'boolean)
  2921. (defcustom org-edit-timestamp-down-means-later nil
  2922. "Non-nil means S-down will increase the time in a time stamp.
  2923. When nil, S-up will increase."
  2924. :group 'org-time
  2925. :type 'boolean)
  2926. (defcustom org-calendar-follow-timestamp-change t
  2927. "Non-nil means make the calendar window follow timestamp changes.
  2928. When a timestamp is modified and the calendar window is visible, it will be
  2929. moved to the new date."
  2930. :group 'org-time
  2931. :type 'boolean)
  2932. (defgroup org-tags nil
  2933. "Options concerning tags in Org mode."
  2934. :tag "Org Tags"
  2935. :group 'org)
  2936. (defcustom org-tag-alist nil
  2937. "Default tags available in Org files.
  2938. The value of this variable is an alist. Associations either:
  2939. (TAG)
  2940. (TAG . SELECT)
  2941. (SPECIAL)
  2942. where TAG is a tag as a string, SELECT is character, used to
  2943. select that tag through the fast tag selection interface, and
  2944. SPECIAL is one of the following keywords: `:startgroup',
  2945. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2946. `:newline'. These keywords are used to define a hierarchy of
  2947. tags. See manual for details.
  2948. When this variable is nil, Org mode bases tag input on what is
  2949. already in the buffer. The value can be overridden locally by
  2950. using a TAGS keyword, e.g.,
  2951. #+TAGS: tag1 tag2
  2952. See also `org-tag-persistent-alist' to sidestep this behavior."
  2953. :group 'org-tags
  2954. :type '(repeat
  2955. (choice
  2956. (cons (string :tag "Tag name")
  2957. (character :tag "Access char"))
  2958. (const :tag "Start radio group" (:startgroup))
  2959. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2960. (const :tag "Group tags delimiter" (:grouptags))
  2961. (const :tag "End radio group" (:endgroup))
  2962. (const :tag "End tag group, non distinct" (:endgrouptag))
  2963. (const :tag "New line" (:newline)))))
  2964. (defcustom org-tag-persistent-alist nil
  2965. "Tags always available in Org files.
  2966. The value of this variable is an alist. Associations either:
  2967. (TAG)
  2968. (TAG . SELECT)
  2969. (SPECIAL)
  2970. where TAG is a tag as a string, SELECT is a character, used to
  2971. select that tag through the fast tag selection interface, and
  2972. SPECIAL is one of the following keywords: `:startgroup',
  2973. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2974. `:newline'. These keywords are used to define a hierarchy of
  2975. tags. See manual for details.
  2976. Unlike to `org-tag-alist', tags defined in this variable do not
  2977. depend on a local TAGS keyword. Instead, to disable these tags
  2978. on a per-file basis, insert anywhere in the file:
  2979. #+STARTUP: noptag"
  2980. :group 'org-tags
  2981. :type '(repeat
  2982. (choice
  2983. (cons (string :tag "Tag name")
  2984. (character :tag "Access char"))
  2985. (const :tag "Start radio group" (:startgroup))
  2986. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2987. (const :tag "Group tags delimiter" (:grouptags))
  2988. (const :tag "End radio group" (:endgroup))
  2989. (const :tag "End tag group, non distinct" (:endgrouptag))
  2990. (const :tag "New line" (:newline)))))
  2991. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2992. "If non-nil, always offer completion for all tags of all agenda files.
  2993. Instead of customizing this variable directly, you might want to
  2994. set it locally for capture buffers, because there no list of
  2995. tags in that file can be created dynamically (there are none).
  2996. (add-hook \\='org-capture-mode-hook
  2997. (lambda ()
  2998. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2999. :group 'org-tags
  3000. :version "24.1"
  3001. :type 'boolean)
  3002. (defvar org-file-tags nil
  3003. "List of tags that can be inherited by all entries in the file.
  3004. The tags will be inherited if the variable `org-use-tag-inheritance'
  3005. says they should be.
  3006. This variable is populated from #+FILETAGS lines.")
  3007. (defcustom org-use-fast-tag-selection 'auto
  3008. "Non-nil means use fast tag selection scheme.
  3009. This is a special interface to select and deselect tags with single keys.
  3010. When nil, fast selection is never used.
  3011. When the symbol `auto', fast selection is used if and only if selection
  3012. characters for tags have been configured, either through the variable
  3013. `org-tag-alist' or through a #+TAGS line in the buffer.
  3014. When t, fast selection is always used and selection keys are assigned
  3015. automatically if necessary."
  3016. :group 'org-tags
  3017. :type '(choice
  3018. (const :tag "Always" t)
  3019. (const :tag "Never" nil)
  3020. (const :tag "When selection characters are configured" auto)))
  3021. (defcustom org-fast-tag-selection-single-key nil
  3022. "Non-nil means fast tag selection exits after first change.
  3023. When nil, you have to press RET to exit it.
  3024. During fast tag selection, you can toggle this flag with `C-c'.
  3025. This variable can also have the value `expert'. In this case, the window
  3026. displaying the tags menu is not even shown, until you press C-c again."
  3027. :group 'org-tags
  3028. :type '(choice
  3029. (const :tag "No" nil)
  3030. (const :tag "Yes" t)
  3031. (const :tag "Expert" expert)))
  3032. (defvar org-fast-tag-selection-include-todo nil
  3033. "Non-nil means fast tags selection interface will also offer TODO states.
  3034. This is an undocumented feature, you should not rely on it.")
  3035. (defcustom org-tags-column -77
  3036. "The column to which tags should be indented in a headline.
  3037. If this number is positive, it specifies the column. If it is negative,
  3038. it means that the tags should be flushright to that column. For example,
  3039. -80 works well for a normal 80 character screen.
  3040. When 0, place tags directly after headline text, with only one space in
  3041. between."
  3042. :group 'org-tags
  3043. :type 'integer)
  3044. (defcustom org-auto-align-tags t
  3045. "Non-nil keeps tags aligned when modifying headlines.
  3046. Some operations (i.e. demoting) change the length of a headline and
  3047. therefore shift the tags around. With this option turned on, after
  3048. each such operation the tags are again aligned to `org-tags-column'."
  3049. :group 'org-tags
  3050. :type 'boolean)
  3051. (defcustom org-use-tag-inheritance t
  3052. "Non-nil means tags in levels apply also for sublevels.
  3053. When nil, only the tags directly given in a specific line apply there.
  3054. This may also be a list of tags that should be inherited, or a regexp that
  3055. matches tags that should be inherited. Additional control is possible
  3056. with the variable `org-tags-exclude-from-inheritance' which gives an
  3057. explicit list of tags to be excluded from inheritance, even if the value of
  3058. `org-use-tag-inheritance' would select it for inheritance.
  3059. If this option is t, a match early-on in a tree can lead to a large
  3060. number of matches in the subtree when constructing the agenda or creating
  3061. a sparse tree. If you only want to see the first match in a tree during
  3062. a search, check out the variable `org-tags-match-list-sublevels'."
  3063. :group 'org-tags
  3064. :type '(choice
  3065. (const :tag "Not" nil)
  3066. (const :tag "Always" t)
  3067. (repeat :tag "Specific tags" (string :tag "Tag"))
  3068. (regexp :tag "Tags matched by regexp")))
  3069. (defcustom org-tags-exclude-from-inheritance nil
  3070. "List of tags that should never be inherited.
  3071. This is a way to exclude a few tags from inheritance. For way to do
  3072. the opposite, to actively allow inheritance for selected tags,
  3073. see the variable `org-use-tag-inheritance'."
  3074. :group 'org-tags
  3075. :type '(repeat (string :tag "Tag")))
  3076. (defun org-tag-inherit-p (tag)
  3077. "Check if TAG is one that should be inherited."
  3078. (cond
  3079. ((member tag org-tags-exclude-from-inheritance) nil)
  3080. ((eq org-use-tag-inheritance t) t)
  3081. ((not org-use-tag-inheritance) nil)
  3082. ((stringp org-use-tag-inheritance)
  3083. (string-match org-use-tag-inheritance tag))
  3084. ((listp org-use-tag-inheritance)
  3085. (member tag org-use-tag-inheritance))
  3086. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3087. (defcustom org-tags-match-list-sublevels t
  3088. "Non-nil means list also sublevels of headlines matching a search.
  3089. This variable applies to tags/property searches, and also to stuck
  3090. projects because this search is based on a tags match as well.
  3091. When set to the symbol `indented', sublevels are indented with
  3092. leading dots.
  3093. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3094. the sublevels of a headline matching a tag search often also match
  3095. the same search. Listing all of them can create very long lists.
  3096. Setting this variable to nil causes subtrees of a match to be skipped.
  3097. This variable is semi-obsolete and probably should always be true. It
  3098. is better to limit inheritance to certain tags using the variables
  3099. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3100. :group 'org-tags
  3101. :type '(choice
  3102. (const :tag "No, don't list them" nil)
  3103. (const :tag "Yes, do list them" t)
  3104. (const :tag "List them, indented with leading dots" indented)))
  3105. (defcustom org-tags-sort-function nil
  3106. "When set, tags are sorted using this function as a comparator."
  3107. :group 'org-tags
  3108. :type '(choice
  3109. (const :tag "No sorting" nil)
  3110. (const :tag "Alphabetical" string<)
  3111. (const :tag "Reverse alphabetical" string>)
  3112. (function :tag "Custom function" nil)))
  3113. (defvar org-tags-history nil
  3114. "History of minibuffer reads for tags.")
  3115. (defvar org-last-tags-completion-table nil
  3116. "The last used completion table for tags.")
  3117. (defvar org-after-tags-change-hook nil
  3118. "Hook that is run after the tags in a line have changed.")
  3119. (defgroup org-properties nil
  3120. "Options concerning properties in Org mode."
  3121. :tag "Org Properties"
  3122. :group 'org)
  3123. (defcustom org-property-format "%-10s %s"
  3124. "How property key/value pairs should be formatted by `indent-line'.
  3125. When `indent-line' hits a property definition, it will format the line
  3126. according to this format, mainly to make sure that the values are
  3127. lined-up with respect to each other."
  3128. :group 'org-properties
  3129. :type 'string)
  3130. (defcustom org-properties-postprocess-alist nil
  3131. "Alist of properties and functions to adjust inserted values.
  3132. Elements of this alist must be of the form
  3133. ([string] [function])
  3134. where [string] must be a property name and [function] must be a
  3135. lambda expression: this lambda expression must take one argument,
  3136. the value to adjust, and return the new value as a string.
  3137. For example, this element will allow the property \"Remaining\"
  3138. to be updated wrt the relation between the \"Effort\" property
  3139. and the clock summary:
  3140. ((\"Remaining\" (lambda(value)
  3141. (let ((clocksum (org-clock-sum-current-item))
  3142. (effort (org-duration-to-minutes
  3143. (org-entry-get (point) \"Effort\"))))
  3144. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3145. :group 'org-properties
  3146. :version "24.1"
  3147. :type '(alist :key-type (string :tag "Property")
  3148. :value-type (function :tag "Function")))
  3149. (defcustom org-use-property-inheritance nil
  3150. "Non-nil means properties apply also for sublevels.
  3151. This setting is chiefly used during property searches. Turning it on can
  3152. cause significant overhead when doing a search, which is why it is not
  3153. on by default.
  3154. When nil, only the properties directly given in the current entry count.
  3155. When t, every property is inherited. The value may also be a list of
  3156. properties that should have inheritance, or a regular expression matching
  3157. properties that should be inherited.
  3158. However, note that some special properties use inheritance under special
  3159. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3160. and the properties ending in \"_ALL\" when they are used as descriptor
  3161. for valid values of a property.
  3162. Note for programmers:
  3163. When querying an entry with `org-entry-get', you can control if inheritance
  3164. should be used. By default, `org-entry-get' looks only at the local
  3165. properties. You can request inheritance by setting the inherit argument
  3166. to t (to force inheritance) or to `selective' (to respect the setting
  3167. in this variable)."
  3168. :group 'org-properties
  3169. :type '(choice
  3170. (const :tag "Not" nil)
  3171. (const :tag "Always" t)
  3172. (repeat :tag "Specific properties" (string :tag "Property"))
  3173. (regexp :tag "Properties matched by regexp")))
  3174. (defun org-property-inherit-p (property)
  3175. "Return a non-nil value if PROPERTY should be inherited."
  3176. (cond
  3177. ((eq org-use-property-inheritance t) t)
  3178. ((not org-use-property-inheritance) nil)
  3179. ((stringp org-use-property-inheritance)
  3180. (string-match org-use-property-inheritance property))
  3181. ((listp org-use-property-inheritance)
  3182. (member-ignore-case property org-use-property-inheritance))
  3183. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3184. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3185. "The default column format, if no other format has been defined.
  3186. This variable can be set on the per-file basis by inserting a line
  3187. #+COLUMNS: %25ITEM ....."
  3188. :group 'org-properties
  3189. :type 'string)
  3190. (defcustom org-columns-ellipses ".."
  3191. "The ellipses to be used when a field in column view is truncated.
  3192. When this is the empty string, as many characters as possible are shown,
  3193. but then there will be no visual indication that the field has been truncated.
  3194. When this is a string of length N, the last N characters of a truncated
  3195. field are replaced by this string. If the column is narrower than the
  3196. ellipses string, only part of the ellipses string will be shown."
  3197. :group 'org-properties
  3198. :type 'string)
  3199. (defconst org-global-properties-fixed
  3200. '(("VISIBILITY_ALL" . "folded children content all")
  3201. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3202. "List of property/value pairs that can be inherited by any entry.
  3203. These are fixed values, for the preset properties. The user variable
  3204. that can be used to add to this list is `org-global-properties'.
  3205. The entries in this list are cons cells where the car is a property
  3206. name and cdr is a string with the value. If the value represents
  3207. multiple items like an \"_ALL\" property, separate the items by
  3208. spaces.")
  3209. (defcustom org-global-properties nil
  3210. "List of property/value pairs that can be inherited by any entry.
  3211. This list will be combined with the constant `org-global-properties-fixed'.
  3212. The entries in this list are cons cells where the car is a property
  3213. name and cdr is a string with the value.
  3214. You can set buffer-local values for the same purpose in the variable
  3215. `org-file-properties' this by adding lines like
  3216. #+PROPERTY: NAME VALUE"
  3217. :group 'org-properties
  3218. :type '(repeat
  3219. (cons (string :tag "Property")
  3220. (string :tag "Value"))))
  3221. (defvar-local org-file-properties nil
  3222. "List of property/value pairs that can be inherited by any entry.
  3223. Valid for the current buffer.
  3224. This variable is populated from #+PROPERTY lines.")
  3225. (defgroup org-agenda nil
  3226. "Options concerning agenda views in Org mode."
  3227. :tag "Org Agenda"
  3228. :group 'org)
  3229. (defvar-local org-category nil
  3230. "Variable used by org files to set a category for agenda display.
  3231. Such files should use a file variable to set it, for example
  3232. # -*- mode: org; org-category: \"ELisp\"
  3233. or contain a special line
  3234. #+CATEGORY: ELisp
  3235. If the file does not specify a category, then file's base name
  3236. is used instead.")
  3237. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3238. (defcustom org-agenda-files nil
  3239. "The files to be used for agenda display.
  3240. If an entry is a directory, all files in that directory that are matched
  3241. by `org-agenda-file-regexp' will be part of the file list.
  3242. If the value of the variable is not a list but a single file name, then
  3243. the list of agenda files is actually stored and maintained in that file,
  3244. one agenda file per line. In this file paths can be given relative to
  3245. `org-directory'. Tilde expansion and environment variable substitution
  3246. are also made.
  3247. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3248. and removed with `\\[org-remove-file]'."
  3249. :group 'org-agenda
  3250. :type '(choice
  3251. (repeat :tag "List of files and directories" file)
  3252. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3253. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3254. "Regular expression to match files for `org-agenda-files'.
  3255. If any element in the list in that variable contains a directory instead
  3256. of a normal file, all files in that directory that are matched by this
  3257. regular expression will be included."
  3258. :group 'org-agenda
  3259. :type 'regexp)
  3260. (defcustom org-agenda-text-search-extra-files nil
  3261. "List of extra files to be searched by text search commands.
  3262. These files will be searched in addition to the agenda files by the
  3263. commands `org-search-view' (`\\[org-agenda] s') \
  3264. and `org-occur-in-agenda-files'.
  3265. Note that these files will only be searched for text search commands,
  3266. not for the other agenda views like todo lists, tag searches or the weekly
  3267. agenda. This variable is intended to list notes and possibly archive files
  3268. that should also be searched by these two commands.
  3269. In fact, if the first element in the list is the symbol `agenda-archives',
  3270. then all archive files of all agenda files will be added to the search
  3271. scope."
  3272. :group 'org-agenda
  3273. :type '(set :greedy t
  3274. (const :tag "Agenda Archives" agenda-archives)
  3275. (repeat :inline t (file))))
  3276. (defvaralias 'org-agenda-multi-occur-extra-files
  3277. 'org-agenda-text-search-extra-files)
  3278. (defcustom org-agenda-skip-unavailable-files nil
  3279. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3280. A nil value means to remove them, after a query, from the list."
  3281. :group 'org-agenda
  3282. :type 'boolean)
  3283. (defcustom org-calendar-to-agenda-key [?c]
  3284. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3285. The command `org-calendar-goto-agenda' will be bound to this key. The
  3286. default is the character `c' because then `c' can be used to switch back and
  3287. forth between agenda and calendar."
  3288. :group 'org-agenda
  3289. :type 'sexp)
  3290. (defcustom org-calendar-insert-diary-entry-key [?i]
  3291. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3292. This option is irrelevant until `org-agenda-diary-file' has been configured
  3293. to point to an Org file. When that is the case, the command
  3294. `org-agenda-diary-entry' will be bound to the key given here, by default
  3295. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3296. if you want to continue doing this, you need to change this to a different
  3297. key."
  3298. :group 'org-agenda
  3299. :type 'sexp)
  3300. (defcustom org-agenda-diary-file 'diary-file
  3301. "File to which to add new entries with the `i' key in agenda and calendar.
  3302. When this is the symbol `diary-file', the functionality in the Emacs
  3303. calendar will be used to add entries to the `diary-file'. But when this
  3304. points to a file, `org-agenda-diary-entry' will be used instead."
  3305. :group 'org-agenda
  3306. :type '(choice
  3307. (const :tag "The standard Emacs diary file" diary-file)
  3308. (file :tag "Special Org file diary entries")))
  3309. (eval-after-load "calendar"
  3310. '(progn
  3311. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3312. 'org-calendar-goto-agenda)
  3313. (add-hook 'calendar-mode-hook
  3314. (lambda ()
  3315. (unless (eq org-agenda-diary-file 'diary-file)
  3316. (define-key calendar-mode-map
  3317. org-calendar-insert-diary-entry-key
  3318. 'org-agenda-diary-entry))))))
  3319. (defgroup org-latex nil
  3320. "Options for embedding LaTeX code into Org mode."
  3321. :tag "Org LaTeX"
  3322. :group 'org)
  3323. (defcustom org-format-latex-options
  3324. '(:foreground default :background default :scale 1.0
  3325. :html-foreground "Black" :html-background "Transparent"
  3326. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3327. "Options for creating images from LaTeX fragments.
  3328. This is a property list with the following properties:
  3329. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3330. `default' means use the foreground of the default face.
  3331. `auto' means use the foreground from the text face.
  3332. :background the background color, or \"Transparent\".
  3333. `default' means use the background of the default face.
  3334. `auto' means use the background from the text face.
  3335. :scale a scaling factor for the size of the images, to get more pixels
  3336. :html-foreground, :html-background, :html-scale
  3337. the same numbers for HTML export.
  3338. :matchers a list indicating which matchers should be used to
  3339. find LaTeX fragments. Valid members of this list are:
  3340. \"begin\" find environments
  3341. \"$1\" find single characters surrounded by $.$
  3342. \"$\" find math expressions surrounded by $...$
  3343. \"$$\" find math expressions surrounded by $$....$$
  3344. \"\\(\" find math expressions surrounded by \\(...\\)
  3345. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3346. :group 'org-latex
  3347. :type 'plist)
  3348. (defcustom org-format-latex-signal-error t
  3349. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3350. When nil, just push out a message."
  3351. :group 'org-latex
  3352. :version "24.1"
  3353. :type 'boolean)
  3354. (defcustom org-latex-to-mathml-jar-file nil
  3355. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3356. Use this to specify additional executable file say a jar file.
  3357. When using MathToWeb as the converter, specify the full-path to
  3358. your mathtoweb.jar file."
  3359. :group 'org-latex
  3360. :version "24.1"
  3361. :type '(choice
  3362. (const :tag "None" nil)
  3363. (file :tag "JAR file" :must-match t)))
  3364. (defcustom org-latex-to-mathml-convert-command nil
  3365. "Command to convert LaTeX fragments to MathML.
  3366. Replace format-specifiers in the command as noted below and use
  3367. `shell-command' to convert LaTeX to MathML.
  3368. %j: Executable file in fully expanded form as specified by
  3369. `org-latex-to-mathml-jar-file'.
  3370. %I: Input LaTeX file in fully expanded form.
  3371. %i: The latex fragment to be converted.
  3372. %o: Output MathML file.
  3373. This command is used by `org-create-math-formula'.
  3374. When using MathToWeb as the converter, set this option to
  3375. \"java -jar %j -unicode -force -df %o %I\".
  3376. When using LaTeXML set this option to
  3377. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3378. :group 'org-latex
  3379. :version "24.1"
  3380. :type '(choice
  3381. (const :tag "None" nil)
  3382. (string :tag "\nShell command")))
  3383. (defcustom org-preview-latex-default-process 'dvipng
  3384. "The default process to convert LaTeX fragments to image files.
  3385. All available processes and theirs documents can be found in
  3386. `org-preview-latex-process-alist', which see."
  3387. :group 'org-latex
  3388. :version "26.1"
  3389. :package-version '(Org . "9.0")
  3390. :type 'symbol)
  3391. (defcustom org-preview-latex-process-alist
  3392. '((dvipng
  3393. :programs ("latex" "dvipng")
  3394. :description "dvi > png"
  3395. :message "you need to install the programs: latex and dvipng."
  3396. :image-input-type "dvi"
  3397. :image-output-type "png"
  3398. :image-size-adjust (1.0 . 1.0)
  3399. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3400. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3401. (dvisvgm
  3402. :programs ("latex" "dvisvgm")
  3403. :description "dvi > svg"
  3404. :message "you need to install the programs: latex and dvisvgm."
  3405. :use-xcolor t
  3406. :image-input-type "dvi"
  3407. :image-output-type "svg"
  3408. :image-size-adjust (1.7 . 1.5)
  3409. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3410. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3411. (imagemagick
  3412. :programs ("latex" "convert")
  3413. :description "pdf > png"
  3414. :message "you need to install the programs: latex and imagemagick."
  3415. :use-xcolor t
  3416. :image-input-type "pdf"
  3417. :image-output-type "png"
  3418. :image-size-adjust (1.0 . 1.0)
  3419. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3420. :image-converter
  3421. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3422. "Definitions of external processes for LaTeX previewing.
  3423. Org mode can use some external commands to generate TeX snippet's images for
  3424. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3425. `org-create-formula-image' how to call them.
  3426. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3427. PROPERTIES accepts the following attributes:
  3428. :programs list of strings, required programs.
  3429. :description string, describe the process.
  3430. :message string, message it when required programs cannot be found.
  3431. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3432. :image-output-type string, output file type of image converter (e.g., \"png\").
  3433. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3434. deal with background and foreground color of image.
  3435. Otherwise, dvipng style background and foregroud color
  3436. format are generated. You may then refer to them in
  3437. command options with \"%F\" and \"%B\".
  3438. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3439. image size showed in buffer and the cdr element is for
  3440. HTML file. This option is only useful for process
  3441. developers, users should use variable
  3442. `org-format-latex-options' instead.
  3443. :post-clean list of strings, files matched are to be cleaned up once
  3444. the image is generated. When nil, the files with \".dvi\",
  3445. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3446. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3447. be cleaned up.
  3448. :latex-header list of strings, the LaTeX header of the snippet file.
  3449. When nil, the fallback value is used instead, which is
  3450. controlled by `org-format-latex-header',
  3451. `org-latex-default-packages-alist' and
  3452. `org-latex-packages-alist', which see.
  3453. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3454. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3455. replaced with values defined below.
  3456. :image-converter list of image converter commands strings. Each of them is
  3457. given to the shell and supports any of the following
  3458. place-holders defined below.
  3459. Place-holders used by `:image-converter' and `:latex-compiler':
  3460. %f input file name
  3461. %b base name of input file
  3462. %o base directory of input file
  3463. %O absolute output file name
  3464. Place-holders only used by `:image-converter':
  3465. %F foreground of image
  3466. %B background of image
  3467. %D dpi, which is used to adjust image size by some processing commands.
  3468. %S the image size scale ratio, which is used to adjust image size by some
  3469. processing commands."
  3470. :group 'org-latex
  3471. :version "26.1"
  3472. :package-version '(Org . "9.0")
  3473. :type '(alist :tag "LaTeX to image backends"
  3474. :value-type (plist)))
  3475. (defcustom org-preview-latex-image-directory "ltximg/"
  3476. "Path to store latex preview images.
  3477. A relative path here creates many directories relative to the
  3478. processed org files paths. An absolute path puts all preview
  3479. images at the same place."
  3480. :group 'org-latex
  3481. :version "26.1"
  3482. :package-version '(Org . "9.0")
  3483. :type 'string)
  3484. (defun org-format-latex-mathml-available-p ()
  3485. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3486. (save-match-data
  3487. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3488. org-latex-to-mathml-convert-command)
  3489. (let ((executable (car (split-string
  3490. org-latex-to-mathml-convert-command))))
  3491. (when (executable-find executable)
  3492. (if (string-match
  3493. "%j" org-latex-to-mathml-convert-command)
  3494. (file-readable-p org-latex-to-mathml-jar-file)
  3495. t))))))
  3496. (defcustom org-format-latex-header "\\documentclass{article}
  3497. \\usepackage[usenames]{color}
  3498. \[PACKAGES]
  3499. \[DEFAULT-PACKAGES]
  3500. \\pagestyle{empty} % do not remove
  3501. % The settings below are copied from fullpage.sty
  3502. \\setlength{\\textwidth}{\\paperwidth}
  3503. \\addtolength{\\textwidth}{-3cm}
  3504. \\setlength{\\oddsidemargin}{1.5cm}
  3505. \\addtolength{\\oddsidemargin}{-2.54cm}
  3506. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3507. \\setlength{\\textheight}{\\paperheight}
  3508. \\addtolength{\\textheight}{-\\headheight}
  3509. \\addtolength{\\textheight}{-\\headsep}
  3510. \\addtolength{\\textheight}{-\\footskip}
  3511. \\addtolength{\\textheight}{-3cm}
  3512. \\setlength{\\topmargin}{1.5cm}
  3513. \\addtolength{\\topmargin}{-2.54cm}"
  3514. "The document header used for processing LaTeX fragments.
  3515. It is imperative that this header make sure that no page number
  3516. appears on the page. The package defined in the variables
  3517. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3518. will either replace the placeholder \"[PACKAGES]\" in this
  3519. header, or they will be appended."
  3520. :group 'org-latex
  3521. :type 'string)
  3522. (defun org-set-packages-alist (var val)
  3523. "Set the packages alist and make sure it has 3 elements per entry."
  3524. (set var (mapcar (lambda (x)
  3525. (if (and (consp x) (= (length x) 2))
  3526. (list (car x) (nth 1 x) t)
  3527. x))
  3528. val)))
  3529. (defun org-get-packages-alist (var)
  3530. "Get the packages alist and make sure it has 3 elements per entry."
  3531. (mapcar (lambda (x)
  3532. (if (and (consp x) (= (length x) 2))
  3533. (list (car x) (nth 1 x) t)
  3534. x))
  3535. (default-value var)))
  3536. (defcustom org-latex-default-packages-alist
  3537. '(("AUTO" "inputenc" t ("pdflatex"))
  3538. ("T1" "fontenc" t ("pdflatex"))
  3539. ("" "graphicx" t)
  3540. ("" "grffile" t)
  3541. ("" "longtable" nil)
  3542. ("" "wrapfig" nil)
  3543. ("" "rotating" nil)
  3544. ("normalem" "ulem" t)
  3545. ("" "amsmath" t)
  3546. ("" "textcomp" t)
  3547. ("" "amssymb" t)
  3548. ("" "capt-of" nil)
  3549. ("" "hyperref" nil))
  3550. "Alist of default packages to be inserted in the header.
  3551. Change this only if one of the packages here causes an
  3552. incompatibility with another package you are using.
  3553. The packages in this list are needed by one part or another of
  3554. Org mode to function properly:
  3555. - inputenc, fontenc: for basic font and character selection
  3556. - graphicx: for including images
  3557. - grffile: allow periods and spaces in graphics file names
  3558. - longtable: For multipage tables
  3559. - wrapfig: for figure placement
  3560. - rotating: for sideways figures and tables
  3561. - ulem: for underline and strike-through
  3562. - amsmath: for subscript and superscript and math environments
  3563. - textcomp, amssymb: for various symbols used
  3564. for interpreting the entities in `org-entities'. You can skip
  3565. some of these packages if you don't use any of their symbols.
  3566. - capt-of: for captions outside of floats
  3567. - hyperref: for cross references
  3568. Therefore you should not modify this variable unless you know
  3569. what you are doing. The one reason to change it anyway is that
  3570. you might be loading some other package that conflicts with one
  3571. of the default packages. Each element is either a cell or
  3572. a string.
  3573. A cell is of the format
  3574. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3575. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3576. when compiling LaTeX snippets into images for inclusion into
  3577. non-LaTeX output. COMPILERS is a list of compilers that should
  3578. include the package, see `org-latex-compiler'. If the document
  3579. compiler is not in the list, and the list is non-nil, the package
  3580. will not be inserted in the final document.
  3581. A string will be inserted as-is in the header of the document."
  3582. :group 'org-latex
  3583. :group 'org-export-latex
  3584. :set 'org-set-packages-alist
  3585. :get 'org-get-packages-alist
  3586. :version "26.1"
  3587. :package-version '(Org . "8.3")
  3588. :type '(repeat
  3589. (choice
  3590. (list :tag "options/package pair"
  3591. (string :tag "options")
  3592. (string :tag "package")
  3593. (boolean :tag "Snippet"))
  3594. (string :tag "A line of LaTeX"))))
  3595. (defcustom org-latex-packages-alist nil
  3596. "Alist of packages to be inserted in every LaTeX header.
  3597. These will be inserted after `org-latex-default-packages-alist'.
  3598. Each element is either a cell or a string.
  3599. A cell is of the format:
  3600. (\"options\" \"package\" SNIPPET-FLAG)
  3601. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3602. needed when turning LaTeX snippets into images for inclusion into
  3603. non-LaTeX output.
  3604. A string will be inserted as-is in the header of the document.
  3605. Make sure that you only list packages here which:
  3606. - you want in every file;
  3607. - do not conflict with the setup in `org-format-latex-header';
  3608. - do not conflict with the default packages in
  3609. `org-latex-default-packages-alist'."
  3610. :group 'org-latex
  3611. :group 'org-export-latex
  3612. :set 'org-set-packages-alist
  3613. :get 'org-get-packages-alist
  3614. :type '(repeat
  3615. (choice
  3616. (list :tag "options/package pair"
  3617. (string :tag "options")
  3618. (string :tag "package")
  3619. (boolean :tag "Snippet"))
  3620. (string :tag "A line of LaTeX"))))
  3621. (defgroup org-appearance nil
  3622. "Settings for Org mode appearance."
  3623. :tag "Org Appearance"
  3624. :group 'org)
  3625. (defcustom org-level-color-stars-only nil
  3626. "Non-nil means fontify only the stars in each headline.
  3627. When nil, the entire headline is fontified.
  3628. Changing it requires restart of `font-lock-mode' to become effective
  3629. also in regions already fontified."
  3630. :group 'org-appearance
  3631. :type 'boolean)
  3632. (defcustom org-hide-leading-stars nil
  3633. "Non-nil means hide the first N-1 stars in a headline.
  3634. This works by using the face `org-hide' for these stars. This
  3635. face is white for a light background, and black for a dark
  3636. background. You may have to customize the face `org-hide' to
  3637. make this work.
  3638. Changing it requires restart of `font-lock-mode' to become effective
  3639. also in regions already fontified.
  3640. You may also set this on a per-file basis by adding one of the following
  3641. lines to the buffer:
  3642. #+STARTUP: hidestars
  3643. #+STARTUP: showstars"
  3644. :group 'org-appearance
  3645. :type 'boolean)
  3646. (defcustom org-hidden-keywords nil
  3647. "List of symbols corresponding to keywords to be hidden the org buffer.
  3648. For example, a value \\='(title) for this list will make the document's title
  3649. appear in the buffer without the initial #+TITLE: keyword."
  3650. :group 'org-appearance
  3651. :version "24.1"
  3652. :type '(set (const :tag "#+AUTHOR" author)
  3653. (const :tag "#+DATE" date)
  3654. (const :tag "#+EMAIL" email)
  3655. (const :tag "#+TITLE" title)))
  3656. (defcustom org-custom-properties nil
  3657. "List of properties (as strings) with a special meaning.
  3658. The default use of these custom properties is to let the user
  3659. hide them with `org-toggle-custom-properties-visibility'."
  3660. :group 'org-properties
  3661. :group 'org-appearance
  3662. :version "24.3"
  3663. :type '(repeat (string :tag "Property Name")))
  3664. (defcustom org-fontify-done-headline nil
  3665. "Non-nil means change the face of a headline if it is marked DONE.
  3666. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3667. When this is non-nil, the headline after the keyword is set to the
  3668. `org-headline-done' as an additional indication."
  3669. :group 'org-appearance
  3670. :type 'boolean)
  3671. (defcustom org-fontify-emphasized-text t
  3672. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3673. Changing this variable requires a restart of Emacs to take effect."
  3674. :group 'org-appearance
  3675. :type 'boolean)
  3676. (defcustom org-fontify-whole-heading-line nil
  3677. "Non-nil means fontify the whole line for headings.
  3678. This is useful when setting a background color for the
  3679. org-level-* faces."
  3680. :group 'org-appearance
  3681. :type 'boolean)
  3682. (defcustom org-highlight-latex-and-related nil
  3683. "Non-nil means highlight LaTeX related syntax in the buffer.
  3684. When non nil, the value should be a list containing any of the
  3685. following symbols:
  3686. `latex' Highlight LaTeX snippets and environments.
  3687. `script' Highlight subscript and superscript.
  3688. `entities' Highlight entities."
  3689. :group 'org-appearance
  3690. :version "24.4"
  3691. :package-version '(Org . "8.0")
  3692. :type '(choice
  3693. (const :tag "No highlighting" nil)
  3694. (set :greedy t :tag "Highlight"
  3695. (const :tag "LaTeX snippets and environments" latex)
  3696. (const :tag "Subscript and superscript" script)
  3697. (const :tag "Entities" entities))))
  3698. (defcustom org-hide-emphasis-markers nil
  3699. "Non-nil mean font-lock should hide the emphasis marker characters."
  3700. :group 'org-appearance
  3701. :type 'boolean)
  3702. (defcustom org-hide-macro-markers nil
  3703. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3704. :group 'org-appearance
  3705. :type 'boolean)
  3706. (defcustom org-pretty-entities nil
  3707. "Non-nil means show entities as UTF8 characters.
  3708. When nil, the \\name form remains in the buffer."
  3709. :group 'org-appearance
  3710. :version "24.1"
  3711. :type 'boolean)
  3712. (defcustom org-pretty-entities-include-sub-superscripts t
  3713. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3714. :group 'org-appearance
  3715. :version "24.1"
  3716. :type 'boolean)
  3717. (defvar org-emph-re nil
  3718. "Regular expression for matching emphasis.
  3719. After a match, the match groups contain these elements:
  3720. 0 The match of the full regular expression, including the characters
  3721. before and after the proper match
  3722. 1 The character before the proper match, or empty at beginning of line
  3723. 2 The proper match, including the leading and trailing markers
  3724. 3 The leading marker like * or /, indicating the type of highlighting
  3725. 4 The text between the emphasis markers, not including the markers
  3726. 5 The character after the match, empty at the end of a line")
  3727. (defvar org-verbatim-re nil
  3728. "Regular expression for matching verbatim text.")
  3729. (defvar org-emphasis-regexp-components) ; defined just below
  3730. (defvar org-emphasis-alist) ; defined just below
  3731. (defun org-set-emph-re (var val)
  3732. "Set variable and compute the emphasis regular expression."
  3733. (set var val)
  3734. (when (and (boundp 'org-emphasis-alist)
  3735. (boundp 'org-emphasis-regexp-components)
  3736. org-emphasis-alist org-emphasis-regexp-components)
  3737. (pcase-let*
  3738. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3739. (body (if (<= nl 0) body
  3740. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3741. (template
  3742. (format (concat "\\([%s]\\|^\\)" ;before markers
  3743. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3744. "\\([%s]\\|$\\)") ;after markers
  3745. pre border border body border post)))
  3746. (setq org-emph-re (format template "*/_+"))
  3747. (setq org-verbatim-re (format template "=~")))))
  3748. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3749. ;; set this option proved cumbersome. See this message/thread:
  3750. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3751. (defvar org-emphasis-regexp-components
  3752. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3753. "Components used to build the regular expression for emphasis.
  3754. This is a list with five entries. Terminology: In an emphasis string
  3755. like \" *strong word* \", we call the initial space PREMATCH, the final
  3756. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3757. and \"trong wor\" is the body. The different components in this variable
  3758. specify what is allowed/forbidden in each part:
  3759. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3760. post Chars allowed as postmatch. End of line will be allowed too.
  3761. border The chars *forbidden* as border characters.
  3762. body-regexp A regexp like \".\" to match a body character. Don't use
  3763. non-shy groups here, and don't allow newline here.
  3764. newline The maximum number of newlines allowed in an emphasis exp.
  3765. You need to reload Org or to restart Emacs after customizing this.")
  3766. (defcustom org-emphasis-alist
  3767. '(("*" bold)
  3768. ("/" italic)
  3769. ("_" underline)
  3770. ("=" org-verbatim verbatim)
  3771. ("~" org-code verbatim)
  3772. ("+" (:strike-through t)))
  3773. "Alist of characters and faces to emphasize text.
  3774. Text starting and ending with a special character will be emphasized,
  3775. for example *bold*, _underlined_ and /italic/. This variable sets the
  3776. marker characters and the face to be used by font-lock for highlighting
  3777. in Org buffers.
  3778. You need to reload Org or to restart Emacs after customizing this."
  3779. :group 'org-appearance
  3780. :set 'org-set-emph-re
  3781. :version "24.4"
  3782. :package-version '(Org . "8.0")
  3783. :type '(repeat
  3784. (list
  3785. (string :tag "Marker character")
  3786. (choice
  3787. (face :tag "Font-lock-face")
  3788. (plist :tag "Face property list"))
  3789. (option (const verbatim)))))
  3790. (defvar org-protecting-blocks '("src" "example" "export")
  3791. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3792. This is needed for font-lock setup.")
  3793. ;;; Functions and variables from their packages
  3794. ;; Declared here to avoid compiler warnings
  3795. (defvar mark-active)
  3796. ;; Various packages
  3797. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3798. (declare-function calendar-forward-day "cal-move" (arg))
  3799. (declare-function calendar-goto-date "cal-move" (date))
  3800. (declare-function calendar-goto-today "cal-move" ())
  3801. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3802. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3803. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3804. (declare-function cdlatex-tab "ext:cdlatex" ())
  3805. (declare-function dired-get-filename
  3806. "dired"
  3807. (&optional localp no-error-if-not-filep))
  3808. (declare-function iswitchb-read-buffer
  3809. "iswitchb"
  3810. (prompt &optional
  3811. default require-match _predicate start matches-set))
  3812. (declare-function org-agenda-change-all-lines
  3813. "org-agenda"
  3814. (newhead hdmarker &optional fixface just-this))
  3815. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3816. "org-agenda"
  3817. (&optional end))
  3818. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3819. (declare-function org-agenda-format-item
  3820. "org-agenda"
  3821. (extra txt &optional level category tags dotime
  3822. remove-re habitp))
  3823. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3824. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3825. (declare-function org-agenda-save-markers-for-cut-and-paste
  3826. "org-agenda"
  3827. (beg end))
  3828. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3829. (declare-function org-agenda-skip "org-agenda" ())
  3830. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3831. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3832. (declare-function org-indent-mode "org-indent" (&optional arg))
  3833. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3834. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3835. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3836. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3837. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3838. (declare-function parse-time-string "parse-time" (string))
  3839. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3840. (defvar align-mode-rules-list)
  3841. (defvar calc-embedded-close-formula)
  3842. (defvar calc-embedded-open-formula)
  3843. (defvar calc-embedded-open-mode)
  3844. (defvar font-lock-unfontify-region-function)
  3845. (defvar iswitchb-temp-buflist)
  3846. (defvar org-agenda-tags-todo-honor-ignore-options)
  3847. (defvar remember-data-file)
  3848. (defvar texmathp-why)
  3849. ;;;###autoload
  3850. (defun turn-on-orgtbl ()
  3851. "Unconditionally turn on `orgtbl-mode'."
  3852. (require 'org-table)
  3853. (orgtbl-mode 1))
  3854. (defun org-at-table-p (&optional table-type)
  3855. "Non-nil if the cursor is inside an Org table.
  3856. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3857. If `org-enable-table-editor' is nil, return nil unconditionally."
  3858. (and
  3859. org-enable-table-editor
  3860. (save-excursion
  3861. (beginning-of-line)
  3862. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3863. (or (not (derived-mode-p 'org-mode))
  3864. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3865. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3866. (defun org-at-table.el-p ()
  3867. "Non-nil when point is at a table.el table."
  3868. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3869. (let ((element (org-element-at-point)))
  3870. (and (eq (org-element-type element) 'table)
  3871. (eq (org-element-property :type element) 'table.el)))))
  3872. (defun org-at-table-hline-p ()
  3873. "Non-nil when point is inside a hline in a table.
  3874. Assume point is already in a table. If `org-enable-table-editor'
  3875. is nil, return nil unconditionally."
  3876. (and org-enable-table-editor
  3877. (save-excursion
  3878. (beginning-of-line)
  3879. (looking-at org-table-hline-regexp))))
  3880. (defun org-table-map-tables (function &optional quietly)
  3881. "Apply FUNCTION to the start of all tables in the buffer."
  3882. (org-with-wide-buffer
  3883. (goto-char (point-min))
  3884. (while (re-search-forward org-table-any-line-regexp nil t)
  3885. (unless quietly
  3886. (message "Mapping tables: %d%%"
  3887. (floor (* 100.0 (point)) (buffer-size))))
  3888. (beginning-of-line 1)
  3889. (when (and (looking-at org-table-line-regexp)
  3890. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3891. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3892. (save-excursion (funcall function))
  3893. (or (looking-at org-table-line-regexp)
  3894. (forward-char 1)))
  3895. (re-search-forward org-table-any-border-regexp nil 1)))
  3896. (unless quietly (message "Mapping tables: done")))
  3897. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3898. (declare-function org-clock-update-mode-line "org-clock" ())
  3899. (declare-function org-resolve-clocks "org-clock"
  3900. (&optional also-non-dangling-p prompt last-valid))
  3901. (defun org-at-TBLFM-p (&optional pos)
  3902. "Non-nil when point (or POS) is in #+TBLFM line."
  3903. (save-excursion
  3904. (goto-char (or pos (point)))
  3905. (beginning-of-line)
  3906. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3907. (eq (org-element-type (org-element-at-point)) 'table))))
  3908. (defvar org-clock-start-time)
  3909. (defvar org-clock-marker (make-marker)
  3910. "Marker recording the last clock-in.")
  3911. (defvar org-clock-hd-marker (make-marker)
  3912. "Marker recording the last clock-in, but the headline position.")
  3913. (defvar org-clock-heading ""
  3914. "The heading of the current clock entry.")
  3915. (defun org-clock-is-active ()
  3916. "Return the buffer where the clock is currently running.
  3917. Return nil if no clock is running."
  3918. (marker-buffer org-clock-marker))
  3919. (defun org-check-running-clock ()
  3920. "Check if the current buffer contains the running clock.
  3921. If yes, offer to stop it and to save the buffer with the changes."
  3922. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3923. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3924. (buffer-name))))
  3925. (org-clock-out)
  3926. (when (y-or-n-p "Save changed buffer?")
  3927. (save-buffer))))
  3928. (defun org-clocktable-try-shift (dir n)
  3929. "Check if this line starts a clock table, if yes, shift the time block."
  3930. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3931. (org-clocktable-shift dir n)))
  3932. ;;;###autoload
  3933. (defun org-clock-persistence-insinuate ()
  3934. "Set up hooks for clock persistence."
  3935. (require 'org-clock)
  3936. (add-hook 'org-mode-hook 'org-clock-load)
  3937. (add-hook 'kill-emacs-hook 'org-clock-save))
  3938. (defgroup org-archive nil
  3939. "Options concerning archiving in Org mode."
  3940. :tag "Org Archive"
  3941. :group 'org-structure)
  3942. (defcustom org-archive-location "%s_archive::"
  3943. "The location where subtrees should be archived.
  3944. The value of this variable is a string, consisting of two parts,
  3945. separated by a double-colon. The first part is a filename and
  3946. the second part is a headline.
  3947. When the filename is omitted, archiving happens in the same file.
  3948. %s in the filename will be replaced by the current file
  3949. name (without the directory part). Archiving to a different file
  3950. is useful to keep archived entries from contributing to the
  3951. Org Agenda.
  3952. The archived entries will be filed as subtrees of the specified
  3953. headline. When the headline is omitted, the subtrees are simply
  3954. filed away at the end of the file, as top-level entries. Also in
  3955. the heading you can use %s to represent the file name, this can be
  3956. useful when using the same archive for a number of different files.
  3957. Here are a few examples:
  3958. \"%s_archive::\"
  3959. If the current file is Projects.org, archive in file
  3960. Projects.org_archive, as top-level trees. This is the default.
  3961. \"::* Archived Tasks\"
  3962. Archive in the current file, under the top-level headline
  3963. \"* Archived Tasks\".
  3964. \"~/org/archive.org::\"
  3965. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3966. \"~/org/archive.org::* From %s\"
  3967. Archive in file ~/org/archive.org (absolute path), under headlines
  3968. \"From FILENAME\" where file name is the current file name.
  3969. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3970. The \"datetree/\" string is special, signifying to archive
  3971. items to the datetree. Items are placed in either the CLOSED
  3972. date of the item, or the current date if there is no CLOSED date.
  3973. The heading will be a subentry to the current date. There doesn't
  3974. need to be a heading, but there always needs to be a slash after
  3975. datetree. For example, to store archived items directly in the
  3976. datetree, use \"~/org/datetree.org::datetree/\".
  3977. \"basement::** Finished Tasks\"
  3978. Archive in file ./basement (relative path), as level 3 trees
  3979. below the level 2 heading \"** Finished Tasks\".
  3980. You may set this option on a per-file basis by adding to the buffer a
  3981. line like
  3982. #+ARCHIVE: basement::** Finished Tasks
  3983. You may also define it locally for a subtree by setting an ARCHIVE property
  3984. in the entry. If such a property is found in an entry, or anywhere up
  3985. the hierarchy, it will be used."
  3986. :group 'org-archive
  3987. :type 'string)
  3988. (defcustom org-agenda-skip-archived-trees t
  3989. "Non-nil means the agenda will skip any items located in archived trees.
  3990. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3991. variable is no longer recommended, you should leave it at the value t.
  3992. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3993. :group 'org-archive
  3994. :group 'org-agenda-skip
  3995. :type 'boolean)
  3996. (defcustom org-columns-skip-archived-trees t
  3997. "Non-nil means ignore archived trees when creating column view."
  3998. :group 'org-archive
  3999. :group 'org-properties
  4000. :type 'boolean)
  4001. (defcustom org-cycle-open-archived-trees nil
  4002. "Non-nil means `org-cycle' will open archived trees.
  4003. An archived tree is a tree marked with the tag ARCHIVE.
  4004. When nil, archived trees will stay folded. You can still open them with
  4005. normal outline commands like `show-all', but not with the cycling commands."
  4006. :group 'org-archive
  4007. :group 'org-cycle
  4008. :type 'boolean)
  4009. (defcustom org-sparse-tree-open-archived-trees nil
  4010. "Non-nil means sparse tree construction shows matches in archived trees.
  4011. When nil, matches in these trees are highlighted, but the trees are kept in
  4012. collapsed state."
  4013. :group 'org-archive
  4014. :group 'org-sparse-trees
  4015. :type 'boolean)
  4016. (defcustom org-sparse-tree-default-date-type nil
  4017. "The default date type when building a sparse tree.
  4018. When this is nil, a date is a scheduled or a deadline timestamp.
  4019. Otherwise, these types are allowed:
  4020. all: all timestamps
  4021. active: only active timestamps (<...>)
  4022. inactive: only inactive timestamps ([...])
  4023. scheduled: only scheduled timestamps
  4024. deadline: only deadline timestamps"
  4025. :type '(choice (const :tag "Scheduled or deadline" nil)
  4026. (const :tag "All timestamps" all)
  4027. (const :tag "Only active timestamps" active)
  4028. (const :tag "Only inactive timestamps" inactive)
  4029. (const :tag "Only scheduled timestamps" scheduled)
  4030. (const :tag "Only deadline timestamps" deadline)
  4031. (const :tag "Only closed timestamps" closed))
  4032. :version "26.1"
  4033. :package-version '(Org . "8.3")
  4034. :group 'org-sparse-trees)
  4035. (defun org-cycle-hide-archived-subtrees (state)
  4036. "Re-hide all archived subtrees after a visibility state change."
  4037. (when (and (not org-cycle-open-archived-trees)
  4038. (not (memq state '(overview folded))))
  4039. (save-excursion
  4040. (let* ((globalp (memq state '(contents all)))
  4041. (beg (if globalp (point-min) (point)))
  4042. (end (if globalp (point-max) (org-end-of-subtree t))))
  4043. (org-hide-archived-subtrees beg end)
  4044. (goto-char beg)
  4045. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4046. (message "%s" (substitute-command-keys
  4047. "Subtree is archived and stays closed. Use \
  4048. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4049. (defun org-force-cycle-archived ()
  4050. "Cycle subtree even if it is archived."
  4051. (interactive)
  4052. (setq this-command 'org-cycle)
  4053. (let ((org-cycle-open-archived-trees t))
  4054. (call-interactively 'org-cycle)))
  4055. (defun org-hide-archived-subtrees (beg end)
  4056. "Re-hide all archived subtrees after a visibility state change."
  4057. (org-with-wide-buffer
  4058. (let ((case-fold-search nil)
  4059. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4060. (goto-char beg)
  4061. ;; Include headline point is currently on.
  4062. (beginning-of-line)
  4063. (while (and (< (point) end) (re-search-forward re end t))
  4064. (when (member org-archive-tag (org-get-tags))
  4065. (org-flag-subtree t)
  4066. (org-end-of-subtree t))))))
  4067. (declare-function outline-end-of-heading "outline" ())
  4068. (declare-function outline-flag-region "outline" (from to flag))
  4069. (defun org-flag-subtree (flag)
  4070. (save-excursion
  4071. (org-back-to-heading t)
  4072. (outline-end-of-heading)
  4073. (outline-flag-region (point)
  4074. (progn (org-end-of-subtree t) (point))
  4075. flag)))
  4076. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4077. ;; Declare Column View Code
  4078. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4079. (declare-function org-columns-compute "org-colview" (property))
  4080. ;; Declare ID code
  4081. (declare-function org-id-store-link "org-id")
  4082. (declare-function org-id-locations-load "org-id")
  4083. (declare-function org-id-locations-save "org-id")
  4084. (defvar org-id-track-globally)
  4085. ;;; Variables for pre-computed regular expressions, all buffer local
  4086. (defvar-local org-todo-regexp nil
  4087. "Matches any of the TODO state keywords.
  4088. Since TODO keywords are case-sensitive, `case-fold-search' is
  4089. expected to be bound to nil when matching against this regexp.")
  4090. (defvar-local org-not-done-regexp nil
  4091. "Matches any of the TODO state keywords except the last one.
  4092. Since TODO keywords are case-sensitive, `case-fold-search' is
  4093. expected to be bound to nil when matching against this regexp.")
  4094. (defvar-local org-not-done-heading-regexp nil
  4095. "Matches a TODO headline that is not done.
  4096. Since TODO keywords are case-sensitive, `case-fold-search' is
  4097. expected to be bound to nil when matching against this regexp.")
  4098. (defvar-local org-todo-line-regexp nil
  4099. "Matches a headline and puts TODO state into group 2 if present.
  4100. Since TODO keywords are case-sensitive, `case-fold-search' is
  4101. expected to be bound to nil when matching against this regexp.")
  4102. (defvar-local org-complex-heading-regexp nil
  4103. "Matches a headline and puts everything into groups:
  4104. group 1: Stars
  4105. group 2: The TODO keyword, maybe
  4106. group 3: Priority cookie
  4107. group 4: True headline
  4108. group 5: Tags
  4109. Since TODO keywords are case-sensitive, `case-fold-search' is
  4110. expected to be bound to nil when matching against this regexp.")
  4111. (defvar-local org-complex-heading-regexp-format nil
  4112. "Printf format to make regexp to match an exact headline.
  4113. This regexp will match the headline of any node which has the
  4114. exact headline text that is put into the format, but may have any
  4115. TODO state, priority and tags.")
  4116. (defvar-local org-todo-line-tags-regexp nil
  4117. "Matches a headline and puts TODO state into group 2 if present.
  4118. Also put tags into group 4 if tags are present.")
  4119. (defconst org-plain-time-of-day-regexp
  4120. (concat
  4121. "\\(\\<[012]?[0-9]"
  4122. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4123. "\\(--?"
  4124. "\\(\\<[012]?[0-9]"
  4125. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4126. "\\)?")
  4127. "Regular expression to match a plain time or time range.
  4128. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4129. groups carry important information:
  4130. 0 the full match
  4131. 1 the first time, range or not
  4132. 8 the second time, if it is a range.")
  4133. (defconst org-plain-time-extension-regexp
  4134. (concat
  4135. "\\(\\<[012]?[0-9]"
  4136. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4137. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4138. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4139. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4140. groups carry important information:
  4141. 0 the full match
  4142. 7 hours of duration
  4143. 9 minutes of duration")
  4144. (defconst org-stamp-time-of-day-regexp
  4145. (concat
  4146. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4147. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4148. "\\(--?"
  4149. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4150. "Regular expression to match a timestamp time or time range.
  4151. After a match, the following groups carry important information:
  4152. 0 the full match
  4153. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4154. 2 the first time, range or not
  4155. 4 the second time, if it is a range.")
  4156. (defconst org-startup-options
  4157. '(("fold" org-startup-folded t)
  4158. ("overview" org-startup-folded t)
  4159. ("nofold" org-startup-folded nil)
  4160. ("showall" org-startup-folded nil)
  4161. ("showeverything" org-startup-folded showeverything)
  4162. ("content" org-startup-folded content)
  4163. ("indent" org-startup-indented t)
  4164. ("noindent" org-startup-indented nil)
  4165. ("hidestars" org-hide-leading-stars t)
  4166. ("showstars" org-hide-leading-stars nil)
  4167. ("odd" org-odd-levels-only t)
  4168. ("oddeven" org-odd-levels-only nil)
  4169. ("align" org-startup-align-all-tables t)
  4170. ("noalign" org-startup-align-all-tables nil)
  4171. ("inlineimages" org-startup-with-inline-images t)
  4172. ("noinlineimages" org-startup-with-inline-images nil)
  4173. ("latexpreview" org-startup-with-latex-preview t)
  4174. ("nolatexpreview" org-startup-with-latex-preview nil)
  4175. ("customtime" org-display-custom-times t)
  4176. ("logdone" org-log-done time)
  4177. ("lognotedone" org-log-done note)
  4178. ("nologdone" org-log-done nil)
  4179. ("lognoteclock-out" org-log-note-clock-out t)
  4180. ("nolognoteclock-out" org-log-note-clock-out nil)
  4181. ("logrepeat" org-log-repeat state)
  4182. ("lognoterepeat" org-log-repeat note)
  4183. ("logdrawer" org-log-into-drawer t)
  4184. ("nologdrawer" org-log-into-drawer nil)
  4185. ("logstatesreversed" org-log-states-order-reversed t)
  4186. ("nologstatesreversed" org-log-states-order-reversed nil)
  4187. ("nologrepeat" org-log-repeat nil)
  4188. ("logreschedule" org-log-reschedule time)
  4189. ("lognotereschedule" org-log-reschedule note)
  4190. ("nologreschedule" org-log-reschedule nil)
  4191. ("logredeadline" org-log-redeadline time)
  4192. ("lognoteredeadline" org-log-redeadline note)
  4193. ("nologredeadline" org-log-redeadline nil)
  4194. ("logrefile" org-log-refile time)
  4195. ("lognoterefile" org-log-refile note)
  4196. ("nologrefile" org-log-refile nil)
  4197. ("fninline" org-footnote-define-inline t)
  4198. ("nofninline" org-footnote-define-inline nil)
  4199. ("fnlocal" org-footnote-section nil)
  4200. ("fnauto" org-footnote-auto-label t)
  4201. ("fnprompt" org-footnote-auto-label nil)
  4202. ("fnconfirm" org-footnote-auto-label confirm)
  4203. ("fnplain" org-footnote-auto-label plain)
  4204. ("fnadjust" org-footnote-auto-adjust t)
  4205. ("nofnadjust" org-footnote-auto-adjust nil)
  4206. ("constcgs" constants-unit-system cgs)
  4207. ("constSI" constants-unit-system SI)
  4208. ("noptag" org-tag-persistent-alist nil)
  4209. ("hideblocks" org-hide-block-startup t)
  4210. ("nohideblocks" org-hide-block-startup nil)
  4211. ("beamer" org-startup-with-beamer-mode t)
  4212. ("entitiespretty" org-pretty-entities t)
  4213. ("entitiesplain" org-pretty-entities nil))
  4214. "Variable associated with STARTUP options for org-mode.
  4215. Each element is a list of three items: the startup options (as written
  4216. in the #+STARTUP line), the corresponding variable, and the value to set
  4217. this variable to if the option is found. An optional forth element PUSH
  4218. means to push this value onto the list in the variable.")
  4219. (defcustom org-group-tags t
  4220. "When non-nil (the default), use group tags.
  4221. This can be turned on/off through `org-toggle-tags-groups'."
  4222. :group 'org-tags
  4223. :group 'org-startup
  4224. :type 'boolean)
  4225. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4226. (defun org-toggle-tags-groups ()
  4227. "Toggle support for group tags.
  4228. Support for group tags is controlled by the option
  4229. `org-group-tags', which is non-nil by default."
  4230. (interactive)
  4231. (setq org-group-tags (not org-group-tags))
  4232. (cond ((and (derived-mode-p 'org-agenda-mode)
  4233. org-group-tags)
  4234. (org-agenda-redo))
  4235. ((derived-mode-p 'org-mode)
  4236. (let ((org-inhibit-startup t)) (org-mode))))
  4237. (message "Groups tags support has been turned %s"
  4238. (if org-group-tags "on" "off")))
  4239. (defun org-set-regexps-and-options (&optional tags-only)
  4240. "Precompute regular expressions used in the current buffer.
  4241. When optional argument TAGS-ONLY is non-nil, only compute tags
  4242. related expressions."
  4243. (when (derived-mode-p 'org-mode)
  4244. (let ((alist (org--setup-collect-keywords
  4245. (org-make-options-regexp
  4246. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4247. (and (not tags-only)
  4248. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4249. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4250. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4251. ;; Startup options. Get this early since it does change
  4252. ;; behavior for other options (e.g., tags).
  4253. (let ((startup (cdr (assq 'startup alist))))
  4254. (dolist (option startup)
  4255. (let ((entry (assoc-string option org-startup-options t)))
  4256. (when entry
  4257. (let ((var (nth 1 entry))
  4258. (val (nth 2 entry)))
  4259. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4260. (unless (listp (symbol-value var))
  4261. (set (make-local-variable var) nil))
  4262. (add-to-list var val)))))))
  4263. (setq-local org-file-tags
  4264. (mapcar #'org-add-prop-inherited
  4265. (cdr (assq 'filetags alist))))
  4266. (setq org-current-tag-alist
  4267. (append org-tag-persistent-alist
  4268. (let ((tags (cdr (assq 'tags alist))))
  4269. (if tags (org-tag-string-to-alist tags)
  4270. org-tag-alist))))
  4271. (setq org-tag-groups-alist
  4272. (org-tag-alist-to-groups org-current-tag-alist))
  4273. (unless tags-only
  4274. ;; File properties.
  4275. (setq-local org-file-properties (cdr (assq 'property alist)))
  4276. ;; Archive location.
  4277. (let ((archive (cdr (assq 'archive alist))))
  4278. (when archive (setq-local org-archive-location archive)))
  4279. ;; Category.
  4280. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4281. (when cat
  4282. (setq-local org-category (intern cat))
  4283. (setq-local org-file-properties
  4284. (org--update-property-plist
  4285. "CATEGORY" cat org-file-properties))))
  4286. ;; Columns.
  4287. (let ((column (cdr (assq 'columns alist))))
  4288. (when column (setq-local org-columns-default-format column)))
  4289. ;; Constants.
  4290. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4291. ;; Link abbreviations.
  4292. (let ((links (cdr (assq 'link alist))))
  4293. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4294. ;; Priorities.
  4295. (let ((priorities (cdr (assq 'priorities alist))))
  4296. (when priorities
  4297. (setq-local org-highest-priority (nth 0 priorities))
  4298. (setq-local org-lowest-priority (nth 1 priorities))
  4299. (setq-local org-default-priority (nth 2 priorities))))
  4300. ;; Scripts.
  4301. (let ((scripts (assq 'scripts alist)))
  4302. (when scripts
  4303. (setq-local org-use-sub-superscripts (cdr scripts))))
  4304. ;; TODO keywords.
  4305. (setq-local org-todo-kwd-alist nil)
  4306. (setq-local org-todo-key-alist nil)
  4307. (setq-local org-todo-key-trigger nil)
  4308. (setq-local org-todo-keywords-1 nil)
  4309. (setq-local org-done-keywords nil)
  4310. (setq-local org-todo-heads nil)
  4311. (setq-local org-todo-sets nil)
  4312. (setq-local org-todo-log-states nil)
  4313. (let ((todo-sequences
  4314. (or (nreverse (cdr (assq 'todo alist)))
  4315. (let ((d (default-value 'org-todo-keywords)))
  4316. (if (not (stringp (car d))) d
  4317. ;; XXX: Backward compatibility code.
  4318. (list (cons org-todo-interpretation d)))))))
  4319. (dolist (sequence todo-sequences)
  4320. (let* ((sequence (or (run-hook-with-args-until-success
  4321. 'org-todo-setup-filter-hook sequence)
  4322. sequence))
  4323. (sequence-type (car sequence))
  4324. (keywords (cdr sequence))
  4325. (sep (member "|" keywords))
  4326. names alist)
  4327. (dolist (k (remove "|" keywords))
  4328. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4329. k)
  4330. (error "Invalid TODO keyword %s" k))
  4331. (let ((name (match-string 1 k))
  4332. (key (match-string 2 k))
  4333. (log (org-extract-log-state-settings k)))
  4334. (push name names)
  4335. (push (cons name (and key (string-to-char key))) alist)
  4336. (when log (push log org-todo-log-states))))
  4337. (let* ((names (nreverse names))
  4338. (done (if sep (org-remove-keyword-keys (cdr sep))
  4339. (last names)))
  4340. (head (car names))
  4341. (tail (list sequence-type head (car done) (org-last done))))
  4342. (add-to-list 'org-todo-heads head 'append)
  4343. (push names org-todo-sets)
  4344. (setq org-done-keywords (append org-done-keywords done nil))
  4345. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4346. (setq org-todo-key-alist
  4347. (append org-todo-key-alist
  4348. (and alist
  4349. (append '((:startgroup))
  4350. (nreverse alist)
  4351. '((:endgroup))))))
  4352. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4353. (setq org-todo-sets (nreverse org-todo-sets)
  4354. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4355. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4356. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4357. ;; Compute the regular expressions and other local variables.
  4358. ;; Using `org-outline-regexp-bol' would complicate them much,
  4359. ;; because of the fixed white space at the end of that string.
  4360. (unless org-done-keywords
  4361. (setq org-done-keywords
  4362. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4363. (setq org-not-done-keywords
  4364. (org-delete-all org-done-keywords
  4365. (copy-sequence org-todo-keywords-1))
  4366. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4367. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4368. org-not-done-heading-regexp
  4369. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4370. org-todo-line-regexp
  4371. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4372. org-complex-heading-regexp
  4373. (concat "^\\(\\*+\\)"
  4374. "\\(?: +" org-todo-regexp "\\)?"
  4375. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4376. "\\(?: +\\(.*?\\)\\)??"
  4377. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4378. "[ \t]*$")
  4379. org-complex-heading-regexp-format
  4380. (concat "^\\(\\*+\\)"
  4381. "\\(?: +" org-todo-regexp "\\)?"
  4382. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4383. "\\(?: +"
  4384. ;; Stats cookies can be stuck to body.
  4385. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4386. "\\(%s\\)"
  4387. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4388. "\\)"
  4389. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4390. "[ \t]*$")
  4391. org-todo-line-tags-regexp
  4392. (concat "^\\(\\*+\\)"
  4393. "\\(?: +" org-todo-regexp "\\)?"
  4394. "\\(?: +\\(.*?\\)\\)??"
  4395. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4396. "[ \t]*$"))
  4397. (org-compute-latex-and-related-regexp)))))
  4398. (defun org--setup-collect-keywords (regexp &optional files alist)
  4399. "Return setup keywords values as an alist.
  4400. REGEXP matches a subset of setup keywords. FILES is a list of
  4401. file names already visited. It is used to avoid circular setup
  4402. files. ALIST, when non-nil, is the alist computed so far.
  4403. Return value contains the following keys: `archive', `category',
  4404. `columns', `constants', `filetags', `link', `priorities',
  4405. `property', `scripts', `startup', `tags' and `todo'."
  4406. (org-with-wide-buffer
  4407. (goto-char (point-min))
  4408. (let ((case-fold-search t))
  4409. (while (re-search-forward regexp nil t)
  4410. (let ((element (org-element-at-point)))
  4411. (when (eq (org-element-type element) 'keyword)
  4412. (let ((key (org-element-property :key element))
  4413. (value (org-element-property :value element)))
  4414. (cond
  4415. ((equal key "ARCHIVE")
  4416. (when (org-string-nw-p value)
  4417. (push (cons 'archive value) alist)))
  4418. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4419. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4420. ((equal key "CONSTANTS")
  4421. (let* ((constants (assq 'constants alist))
  4422. (store (cdr constants)))
  4423. (dolist (pair (org-split-string value))
  4424. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4425. pair)
  4426. (let* ((name (match-string 1 pair))
  4427. (value (match-string 2 pair))
  4428. (old (assoc name store)))
  4429. (if old (setcdr old value)
  4430. (push (cons name value) store)))))
  4431. (if constants (setcdr constants store)
  4432. (push (cons 'constants store) alist))))
  4433. ((equal key "FILETAGS")
  4434. (when (org-string-nw-p value)
  4435. (let ((old (assq 'filetags alist))
  4436. (new (apply #'nconc
  4437. (mapcar (lambda (x) (org-split-string x ":"))
  4438. (org-split-string value)))))
  4439. (if old (setcdr old (append new (cdr old)))
  4440. (push (cons 'filetags new) alist)))))
  4441. ((equal key "LINK")
  4442. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4443. (let ((links (assq 'link alist))
  4444. (pair (cons (match-string-no-properties 1 value)
  4445. (match-string-no-properties 2 value))))
  4446. (if links (push pair (cdr links))
  4447. (push (list 'link pair) alist)))))
  4448. ((equal key "OPTIONS")
  4449. (when (and (org-string-nw-p value)
  4450. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4451. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4452. ((equal key "PRIORITIES")
  4453. (push (cons 'priorities
  4454. (let ((prio (org-split-string value)))
  4455. (if (< (length prio) 3) '(?A ?C ?B)
  4456. (mapcar #'string-to-char prio))))
  4457. alist))
  4458. ((equal key "PROPERTY")
  4459. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4460. (let* ((property (assq 'property alist))
  4461. (value (org--update-property-plist
  4462. (match-string-no-properties 1 value)
  4463. (match-string-no-properties 2 value)
  4464. (cdr property))))
  4465. (if property (setcdr property value)
  4466. (push (cons 'property value) alist)))))
  4467. ((equal key "STARTUP")
  4468. (let ((startup (assq 'startup alist)))
  4469. (if startup
  4470. (setcdr startup
  4471. (append (cdr startup) (org-split-string value)))
  4472. (push (cons 'startup (org-split-string value)) alist))))
  4473. ((equal key "TAGS")
  4474. (let ((tag-cell (assq 'tags alist)))
  4475. (if tag-cell
  4476. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4477. (push (cons 'tags value) alist))))
  4478. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4479. (let ((todo (assq 'todo alist))
  4480. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4481. (org-split-string value))))
  4482. (if todo (push value (cdr todo))
  4483. (push (list 'todo value) alist))))
  4484. ((equal key "SETUPFILE")
  4485. (unless buffer-read-only ; Do not check in Gnus messages.
  4486. (let ((f (and (org-string-nw-p value)
  4487. (expand-file-name
  4488. (org-unbracket-string "\"" "\"" value)))))
  4489. (when (and f (file-readable-p f) (not (member f files)))
  4490. (with-temp-buffer
  4491. (setq default-directory (file-name-directory f))
  4492. (insert-file-contents f)
  4493. (setq alist
  4494. ;; Fake Org mode to benefit from cache
  4495. ;; without recurring needlessly.
  4496. (let ((major-mode 'org-mode))
  4497. (org--setup-collect-keywords
  4498. regexp (cons f files) alist)))))))))))))))
  4499. alist)
  4500. (defun org-tag-string-to-alist (s)
  4501. "Return tag alist associated to string S.
  4502. S is a value for TAGS keyword or produced with
  4503. `org-tag-alist-to-string'. Return value is an alist suitable for
  4504. `org-tag-alist' or `org-tag-persistent-alist'."
  4505. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4506. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4507. "\\|{.+?}\\)" ; regular expression
  4508. "\\(?:(\\(.\\))\\)?\\'"))
  4509. alist group-flag)
  4510. (dolist (tokens lines (cdr (nreverse alist)))
  4511. (push '(:newline) alist)
  4512. (while tokens
  4513. (let ((token (pop tokens)))
  4514. (pcase token
  4515. ("{"
  4516. (push '(:startgroup) alist)
  4517. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4518. ("}"
  4519. (push '(:endgroup) alist)
  4520. (setq group-flag nil))
  4521. ("["
  4522. (push '(:startgrouptag) alist)
  4523. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4524. ("]"
  4525. (push '(:endgrouptag) alist)
  4526. (setq group-flag nil))
  4527. (":"
  4528. (push '(:grouptags) alist))
  4529. ((guard (string-match tag-re token))
  4530. (let ((tag (match-string 1 token))
  4531. (key (and (match-beginning 2)
  4532. (string-to-char (match-string 2 token)))))
  4533. ;; Push all tags in groups, no matter if they already
  4534. ;; appear somewhere else in the list.
  4535. (when (or group-flag (not (assoc tag alist)))
  4536. (push (cons tag key) alist))))))))))
  4537. (defun org-tag-alist-to-string (alist &optional skip-key)
  4538. "Return tag string associated to ALIST.
  4539. ALIST is an alist, as defined in `org-tag-alist' or
  4540. `org-tag-persistent-alist', or produced with
  4541. `org-tag-string-to-alist'.
  4542. Return value is a string suitable as a value for \"TAGS\"
  4543. keyword.
  4544. When optional argument SKIP-KEY is non-nil, skip selection keys
  4545. next to tags."
  4546. (mapconcat (lambda (token)
  4547. (pcase token
  4548. (`(:startgroup) "{")
  4549. (`(:endgroup) "}")
  4550. (`(:startgrouptag) "[")
  4551. (`(:endgrouptag) "]")
  4552. (`(:grouptags) ":")
  4553. (`(:newline) "\\n")
  4554. ((and
  4555. (guard (not skip-key))
  4556. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4557. (format "%s(%c)" tag key))
  4558. (`(,(and tag (pred stringp)) . ,_) tag)
  4559. (_ (user-error "Invalid tag token: %S" token))))
  4560. alist
  4561. " "))
  4562. (defun org-tag-alist-to-groups (alist)
  4563. "Return group alist from tag ALIST.
  4564. ALIST is an alist, as defined in `org-tag-alist' or
  4565. `org-tag-persistent-alist', or produced with
  4566. `org-tag-string-to-alist'. Return value is an alist following
  4567. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4568. a string, summarizing TAGS, as a list of strings."
  4569. (let (groups group-status current-group)
  4570. (dolist (token alist (nreverse groups))
  4571. (pcase token
  4572. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4573. (`(,(or :endgroup :endgrouptag))
  4574. (when (eq group-status 'append)
  4575. (push (nreverse current-group) groups))
  4576. (setq group-status nil))
  4577. (`(:grouptags) (setq group-status 'append))
  4578. ((and `(,tag . ,_) (guard group-status))
  4579. (if (eq group-status 'append) (push tag current-group)
  4580. (setq current-group (list tag))))
  4581. (_ nil)))))
  4582. (defun org-file-contents (file &optional noerror)
  4583. "Return the contents of FILE, as a string."
  4584. (if (and file (file-readable-p file))
  4585. (with-temp-buffer
  4586. (insert-file-contents file)
  4587. (buffer-string))
  4588. (funcall (if noerror 'message 'error)
  4589. "Cannot read file \"%s\"%s"
  4590. file
  4591. (let ((from (buffer-file-name (buffer-base-buffer))))
  4592. (if from (concat " (referenced in file \"" from "\")") "")))))
  4593. (defun org-extract-log-state-settings (x)
  4594. "Extract the log state setting from a TODO keyword string.
  4595. This will extract info from a string like \"WAIT(w@/!)\"."
  4596. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4597. (let ((kw (match-string 1 x))
  4598. (log1 (and (match-end 3) (match-string 3 x)))
  4599. (log2 (and (match-end 4) (match-string 4 x))))
  4600. (and (or log1 log2)
  4601. (list kw
  4602. (and log1 (if (equal log1 "!") 'time 'note))
  4603. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4604. (defun org-remove-keyword-keys (list)
  4605. "Remove a pair of parenthesis at the end of each string in LIST."
  4606. (mapcar (lambda (x)
  4607. (if (string-match "(.*)$" x)
  4608. (substring x 0 (match-beginning 0))
  4609. x))
  4610. list))
  4611. (defun org-assign-fast-keys (alist)
  4612. "Assign fast keys to a keyword-key alist.
  4613. Respect keys that are already there."
  4614. (let (new e (alt ?0))
  4615. (while (setq e (pop alist))
  4616. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4617. (cdr e)) ;; Key already assigned.
  4618. (push e new)
  4619. (let ((clist (string-to-list (downcase (car e))))
  4620. (used (append new alist)))
  4621. (when (= (car clist) ?@)
  4622. (pop clist))
  4623. (while (and clist (rassoc (car clist) used))
  4624. (pop clist))
  4625. (unless clist
  4626. (while (rassoc alt used)
  4627. (cl-incf alt)))
  4628. (push (cons (car e) (or (car clist) alt)) new))))
  4629. (nreverse new)))
  4630. ;;; Some variables used in various places
  4631. (defvar org-window-configuration nil
  4632. "Used in various places to store a window configuration.")
  4633. (defvar org-selected-window nil
  4634. "Used in various places to store a window configuration.")
  4635. (defvar org-finish-function nil
  4636. "Function to be called when `C-c C-c' is used.
  4637. This is for getting out of special buffers like capture.")
  4638. (defvar org-last-state)
  4639. ;; Defined somewhere in this file, but used before definition.
  4640. (defvar org-entities) ;; defined in org-entities.el
  4641. (defvar org-struct-menu)
  4642. (defvar org-org-menu)
  4643. (defvar org-tbl-menu)
  4644. ;;;; Define the Org mode
  4645. ;; We use a before-change function to check if a table might need
  4646. ;; an update.
  4647. (defvar org-table-may-need-update t
  4648. "Indicates that a table might need an update.
  4649. This variable is set by `org-before-change-function'.
  4650. `org-table-align' sets it back to nil.")
  4651. (defun org-before-change-function (_beg _end)
  4652. "Every change indicates that a table might need an update."
  4653. (setq org-table-may-need-update t))
  4654. (defvar org-mode-map)
  4655. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4656. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4657. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4658. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4659. (defvar org-table-buffer-is-an nil)
  4660. (defvar bidi-paragraph-direction)
  4661. (defvar buffer-face-mode-face)
  4662. (require 'outline)
  4663. ;; Other stuff we need.
  4664. (require 'time-date)
  4665. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4666. (require 'easymenu)
  4667. (autoload 'easy-menu-add "easymenu")
  4668. (require 'overlay)
  4669. ;; (require 'org-macs) moved higher up in the file before it is first used
  4670. (require 'org-entities)
  4671. ;; (require 'org-compat) moved higher up in the file before it is first used
  4672. (require 'org-faces)
  4673. (require 'org-list)
  4674. (require 'org-pcomplete)
  4675. (require 'org-src)
  4676. (require 'org-footnote)
  4677. (require 'org-macro)
  4678. ;; babel
  4679. (require 'ob)
  4680. ;;;###autoload
  4681. (define-derived-mode org-mode outline-mode "Org"
  4682. "Outline-based notes management and organizer, alias
  4683. \"Carsten's outline-mode for keeping track of everything.\"
  4684. Org mode develops organizational tasks around a NOTES file which
  4685. contains information about projects as plain text. Org mode is
  4686. implemented on top of Outline mode, which is ideal to keep the content
  4687. of large files well structured. It supports ToDo items, deadlines and
  4688. time stamps, which magically appear in the diary listing of the Emacs
  4689. calendar. Tables are easily created with a built-in table editor.
  4690. Plain text URL-like links connect to websites, emails (VM), Usenet
  4691. messages (Gnus), BBDB entries, and any files related to the project.
  4692. For printing and sharing of notes, an Org file (or a part of it)
  4693. can be exported as a structured ASCII or HTML file.
  4694. The following commands are available:
  4695. \\{org-mode-map}"
  4696. ;; Get rid of Outline menus, they are not needed
  4697. ;; Need to do this here because define-derived-mode sets up
  4698. ;; the keymap so late. Still, it is a waste to call this each time
  4699. ;; we switch another buffer into Org mode.
  4700. (define-key org-mode-map [menu-bar headings] 'undefined)
  4701. (define-key org-mode-map [menu-bar hide] 'undefined)
  4702. (define-key org-mode-map [menu-bar show] 'undefined)
  4703. (org-load-modules-maybe)
  4704. (org-install-agenda-files-menu)
  4705. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4706. (add-to-invisibility-spec '(org-cwidth))
  4707. (add-to-invisibility-spec '(org-hide-block . t))
  4708. (setq-local outline-regexp org-outline-regexp)
  4709. (setq-local outline-level 'org-outline-level)
  4710. (setq bidi-paragraph-direction 'left-to-right)
  4711. (when (and org-ellipsis
  4712. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4713. (fboundp 'make-glyph-code))
  4714. (unless org-display-table
  4715. (setq org-display-table (make-display-table)))
  4716. (set-display-table-slot
  4717. org-display-table 4
  4718. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4719. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4720. (setq buffer-display-table org-display-table))
  4721. (org-set-regexps-and-options)
  4722. (org-set-font-lock-defaults)
  4723. (when (and org-tag-faces (not org-tags-special-faces-re))
  4724. ;; tag faces set outside customize.... force initialization.
  4725. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4726. ;; Calc embedded
  4727. (setq-local calc-embedded-open-mode "# ")
  4728. ;; Modify a few syntax entries
  4729. (modify-syntax-entry ?@ "w")
  4730. (modify-syntax-entry ?\" "\"")
  4731. (modify-syntax-entry ?\\ "_")
  4732. (modify-syntax-entry ?~ "_")
  4733. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4734. ;; Activate before-change-function
  4735. (setq-local org-table-may-need-update t)
  4736. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4737. ;; Check for running clock before killing a buffer
  4738. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4739. ;; Initialize macros templates.
  4740. (org-macro-initialize-templates)
  4741. ;; Initialize radio targets.
  4742. (org-update-radio-target-regexp)
  4743. ;; Indentation.
  4744. (setq-local indent-line-function 'org-indent-line)
  4745. (setq-local indent-region-function 'org-indent-region)
  4746. ;; Filling and auto-filling.
  4747. (org-setup-filling)
  4748. ;; Comments.
  4749. (org-setup-comments-handling)
  4750. ;; Initialize cache.
  4751. (org-element-cache-reset)
  4752. ;; Beginning/end of defun
  4753. (setq-local beginning-of-defun-function 'org-backward-element)
  4754. (setq-local end-of-defun-function
  4755. (lambda ()
  4756. (if (not (org-at-heading-p))
  4757. (org-forward-element)
  4758. (org-forward-element)
  4759. (forward-char -1))))
  4760. ;; Next error for sparse trees
  4761. (setq-local next-error-function 'org-occur-next-match)
  4762. ;; Make sure dependence stuff works reliably, even for users who set it
  4763. ;; too late :-(
  4764. (if org-enforce-todo-dependencies
  4765. (add-hook 'org-blocker-hook
  4766. 'org-block-todo-from-children-or-siblings-or-parent)
  4767. (remove-hook 'org-blocker-hook
  4768. 'org-block-todo-from-children-or-siblings-or-parent))
  4769. (if org-enforce-todo-checkbox-dependencies
  4770. (add-hook 'org-blocker-hook
  4771. 'org-block-todo-from-checkboxes)
  4772. (remove-hook 'org-blocker-hook
  4773. 'org-block-todo-from-checkboxes))
  4774. ;; Align options lines
  4775. (setq-local
  4776. align-mode-rules-list
  4777. '((org-in-buffer-settings
  4778. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4779. (modes . '(org-mode)))))
  4780. ;; Imenu
  4781. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4782. ;; Make isearch reveal context
  4783. (setq-local outline-isearch-open-invisible-function
  4784. (lambda (&rest _) (org-show-context 'isearch)))
  4785. ;; Setup the pcomplete hooks
  4786. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4787. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4788. (setq-local pcomplete-default-completion-function 'ignore)
  4789. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4790. (setq-local pcomplete-termination-string "")
  4791. (setq-local buffer-face-mode-face 'org-default)
  4792. ;; If empty file that did not turn on Org mode automatically, make
  4793. ;; it to.
  4794. (when (and org-insert-mode-line-in-empty-file
  4795. (called-interactively-p 'any)
  4796. (= (point-min) (point-max)))
  4797. (insert "# -*- mode: org -*-\n\n"))
  4798. (unless org-inhibit-startup
  4799. (org-unmodified
  4800. (when org-startup-with-beamer-mode (org-beamer-mode))
  4801. (when org-startup-align-all-tables
  4802. (org-table-map-tables #'org-table-align t))
  4803. (when org-startup-with-inline-images (org-display-inline-images))
  4804. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4805. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4806. (when org-startup-truncated (setq truncate-lines t))
  4807. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4808. (org-refresh-effort-properties)))
  4809. ;; Try to set `org-hide' face correctly.
  4810. (let ((foreground (org-find-invisible-foreground)))
  4811. (when foreground
  4812. (set-face-foreground 'org-hide foreground))))
  4813. ;; Update `customize-package-emacs-version-alist'
  4814. (add-to-list 'customize-package-emacs-version-alist
  4815. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4816. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4817. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4818. ("9.0" . "26.1")))
  4819. (defvar org-mode-transpose-word-syntax-table
  4820. (let ((st (make-syntax-table text-mode-syntax-table)))
  4821. (dolist (c org-emphasis-alist st)
  4822. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4823. (when (fboundp 'abbrev-table-put)
  4824. (abbrev-table-put org-mode-abbrev-table
  4825. :parents (list text-mode-abbrev-table)))
  4826. (defun org-find-invisible-foreground ()
  4827. (let ((candidates (remove
  4828. "unspecified-bg"
  4829. (nconc
  4830. (list (face-background 'default)
  4831. (face-background 'org-default))
  4832. (mapcar
  4833. (lambda (alist)
  4834. (when (boundp alist)
  4835. (cdr (assq 'background-color (symbol-value alist)))))
  4836. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4837. (list (face-foreground 'org-hide))))))
  4838. (car (remove nil candidates))))
  4839. (defun org-current-time (&optional rounding-minutes past)
  4840. "Current time, possibly rounded to ROUNDING-MINUTES.
  4841. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4842. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4843. the rounding returns a past time."
  4844. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4845. (car org-time-stamp-rounding-minutes)))
  4846. (time (decode-time)) res)
  4847. (if (< r 1)
  4848. (current-time)
  4849. (setq res
  4850. (apply 'encode-time
  4851. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4852. (nthcdr 2 time))))
  4853. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4854. (seconds-to-time (- (float-time res) (* r 60)))
  4855. res))))
  4856. (defun org-today ()
  4857. "Return today date, considering `org-extend-today-until'."
  4858. (time-to-days
  4859. (time-subtract (current-time)
  4860. (list 0 (* 3600 org-extend-today-until) 0))))
  4861. ;;;; Font-Lock stuff, including the activators
  4862. (defvar org-mouse-map (make-sparse-keymap))
  4863. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4864. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4865. (when org-mouse-1-follows-link
  4866. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4867. (when org-tab-follows-link
  4868. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4869. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4870. (require 'font-lock)
  4871. (defconst org-non-link-chars "]\t\n\r<>")
  4872. (defvar org-link-types-re nil
  4873. "Matches a link that has a url-like prefix like \"http:\"")
  4874. (defvar org-link-re-with-space nil
  4875. "Matches a link with spaces, optional angular brackets around it.")
  4876. (defvar org-link-re-with-space2 nil
  4877. "Matches a link with spaces, optional angular brackets around it.")
  4878. (defvar org-link-re-with-space3 nil
  4879. "Matches a link with spaces, only for internal part in bracket links.")
  4880. (defvar org-angle-link-re nil
  4881. "Matches link with angular brackets, spaces are allowed.")
  4882. (defvar org-plain-link-re nil
  4883. "Matches plain link, without spaces.")
  4884. (defvar org-bracket-link-regexp nil
  4885. "Matches a link in double brackets.")
  4886. (defvar org-bracket-link-analytic-regexp nil
  4887. "Regular expression used to analyze links.
  4888. Here is what the match groups contain after a match:
  4889. 1: http:
  4890. 2: http
  4891. 3: path
  4892. 4: [desc]
  4893. 5: desc")
  4894. (defvar org-bracket-link-analytic-regexp++ nil
  4895. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4896. (defvar org-any-link-re nil
  4897. "Regular expression matching any link.")
  4898. (defconst org-match-sexp-depth 3
  4899. "Number of stacked braces for sub/superscript matching.")
  4900. (defun org-create-multibrace-regexp (left right n)
  4901. "Create a regular expression which will match a balanced sexp.
  4902. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4903. as single character strings.
  4904. The regexp returned will match the entire expression including the
  4905. delimiters. It will also define a single group which contains the
  4906. match except for the outermost delimiters. The maximum depth of
  4907. stacked delimiters is N. Escaping delimiters is not possible."
  4908. (let* ((nothing (concat "[^" left right "]*?"))
  4909. (or "\\|")
  4910. (re nothing)
  4911. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4912. (while (> n 1)
  4913. (setq n (1- n)
  4914. re (concat re or next)
  4915. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4916. (concat left "\\(" re "\\)" right)))
  4917. (defconst org-match-substring-regexp
  4918. (concat
  4919. "\\(\\S-\\)\\([_^]\\)\\("
  4920. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4921. "\\|"
  4922. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4923. "\\|"
  4924. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4925. "The regular expression matching a sub- or superscript.")
  4926. (defconst org-match-substring-with-braces-regexp
  4927. (concat
  4928. "\\(\\S-\\)\\([_^]\\)"
  4929. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4930. "The regular expression matching a sub- or superscript, forcing braces.")
  4931. (defun org-make-link-regexps ()
  4932. "Update the link regular expressions.
  4933. This should be called after the variable `org-link-parameters' has changed."
  4934. (let ((types-re (regexp-opt (org-link-types) t)))
  4935. (setq org-link-types-re
  4936. (concat "\\`" types-re ":")
  4937. org-link-re-with-space
  4938. (concat "<?" types-re ":"
  4939. "\\([^" org-non-link-chars " ]"
  4940. "[^" org-non-link-chars "]*"
  4941. "[^" org-non-link-chars " ]\\)>?")
  4942. org-link-re-with-space2
  4943. (concat "<?" types-re ":"
  4944. "\\([^" org-non-link-chars " ]"
  4945. "[^\t\n\r]*"
  4946. "[^" org-non-link-chars " ]\\)>?")
  4947. org-link-re-with-space3
  4948. (concat "<?" types-re ":"
  4949. "\\([^" org-non-link-chars " ]"
  4950. "[^\t\n\r]*\\)")
  4951. org-angle-link-re
  4952. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4953. types-re)
  4954. org-plain-link-re
  4955. (concat
  4956. "\\<" types-re ":"
  4957. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4958. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4959. org-bracket-link-regexp
  4960. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4961. org-bracket-link-analytic-regexp
  4962. (concat
  4963. "\\[\\["
  4964. "\\(" types-re ":\\)?"
  4965. "\\([^]]+\\)"
  4966. "\\]"
  4967. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4968. "\\]")
  4969. org-bracket-link-analytic-regexp++
  4970. (concat
  4971. "\\[\\["
  4972. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4973. "\\([^]]+\\)"
  4974. "\\]"
  4975. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4976. "\\]")
  4977. org-any-link-re
  4978. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4979. org-angle-link-re "\\)\\|\\("
  4980. org-plain-link-re "\\)"))))
  4981. (org-make-link-regexps)
  4982. (defvar org-emph-face nil)
  4983. (defun org-do-emphasis-faces (limit)
  4984. "Run through the buffer and emphasize strings."
  4985. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4986. (car org-emphasis-regexp-components))))
  4987. (catch :exit
  4988. (while (re-search-forward quick-re limit t)
  4989. (let* ((marker (match-string 2))
  4990. (verbatim? (member marker '("~" "="))))
  4991. (when (save-excursion
  4992. (goto-char (match-beginning 0))
  4993. ;; Do not match headline stars. Do not consider
  4994. ;; stars of a headline as closing marker for bold
  4995. ;; markup either.
  4996. (and (not (looking-at-p org-outline-regexp-bol))
  4997. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4998. (not (string-match-p
  4999. (concat org-outline-regexp-bol "\\'")
  5000. (match-string 0)))))
  5001. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5002. (font-lock-prepend-text-property
  5003. (match-beginning 2) (match-end 2) 'face face)
  5004. (when verbatim?
  5005. (org-remove-flyspell-overlays-in
  5006. (match-beginning 0) (match-end 0)))
  5007. (add-text-properties (match-beginning 2) (match-end 2)
  5008. '(font-lock-multiline t org-emphasis t))
  5009. (when org-hide-emphasis-markers
  5010. (add-text-properties (match-end 4) (match-beginning 5)
  5011. '(invisible org-link))
  5012. (add-text-properties (match-beginning 3) (match-end 3)
  5013. '(invisible org-link)))
  5014. (throw :exit t))))))))
  5015. (defun org-emphasize (&optional char)
  5016. "Insert or change an emphasis, i.e. a font like bold or italic.
  5017. If there is an active region, change that region to a new emphasis.
  5018. If there is no region, just insert the marker characters and position
  5019. the cursor between them.
  5020. CHAR should be the marker character. If it is a space, it means to
  5021. remove the emphasis of the selected region.
  5022. If CHAR is not given (for example in an interactive call) it will be
  5023. prompted for."
  5024. (interactive)
  5025. (let ((erc org-emphasis-regexp-components)
  5026. (string "") beg end move s)
  5027. (if (org-region-active-p)
  5028. (setq beg (region-beginning)
  5029. end (region-end)
  5030. string (buffer-substring beg end))
  5031. (setq move t))
  5032. (unless char
  5033. (message "Emphasis marker or tag: [%s]"
  5034. (mapconcat #'car org-emphasis-alist ""))
  5035. (setq char (read-char-exclusive)))
  5036. (if (equal char ?\s)
  5037. (setq s ""
  5038. move nil)
  5039. (unless (assoc (char-to-string char) org-emphasis-alist)
  5040. (user-error "No such emphasis marker: \"%c\"" char))
  5041. (setq s (char-to-string char)))
  5042. (while (and (> (length string) 1)
  5043. (equal (substring string 0 1) (substring string -1))
  5044. (assoc (substring string 0 1) org-emphasis-alist))
  5045. (setq string (substring string 1 -1)))
  5046. (setq string (concat s string s))
  5047. (when beg (delete-region beg end))
  5048. (unless (or (bolp)
  5049. (string-match (concat "[" (nth 0 erc) "\n]")
  5050. (char-to-string (char-before (point)))))
  5051. (insert " "))
  5052. (unless (or (eobp)
  5053. (string-match (concat "[" (nth 1 erc) "\n]")
  5054. (char-to-string (char-after (point)))))
  5055. (insert " ") (backward-char 1))
  5056. (insert string)
  5057. (and move (backward-char 1))))
  5058. (defconst org-nonsticky-props
  5059. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5060. (defsubst org-rear-nonsticky-at (pos)
  5061. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5062. (defun org-activate-plain-links (limit)
  5063. "Add link properties for plain links."
  5064. (when (and (re-search-forward org-plain-link-re limit t)
  5065. (not (org-in-src-block-p)))
  5066. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5067. 'face))
  5068. (link (match-string-no-properties 0))
  5069. (type (match-string-no-properties 1))
  5070. (path (match-string-no-properties 2))
  5071. (link-start (match-beginning 0))
  5072. (link-end (match-end 0))
  5073. (link-face (org-link-get-parameter type :face))
  5074. (help-echo (org-link-get-parameter type :help-echo))
  5075. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5076. (activate-func (org-link-get-parameter type :activate-func)))
  5077. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5078. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5079. (add-text-properties (match-beginning 0) (match-end 0)
  5080. (list
  5081. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5082. 'highlight)
  5083. 'face (cond
  5084. ;; A function that returns a face
  5085. ((functionp link-face)
  5086. (funcall link-face path))
  5087. ;; a face
  5088. ((facep link-face)
  5089. link-face)
  5090. ;; An anonymous face
  5091. ((consp link-face)
  5092. link-face)
  5093. ;; default
  5094. (t
  5095. 'org-link))
  5096. 'help-echo (cond
  5097. ((stringp help-echo)
  5098. help-echo)
  5099. ((functionp help-echo)
  5100. help-echo)
  5101. (t
  5102. (concat "LINK: "
  5103. (save-match-data
  5104. (org-link-unescape link)))))
  5105. 'htmlize-link (cond
  5106. ((functionp htmlize-link)
  5107. (funcall htmlize-link path))
  5108. (t
  5109. `(:uri ,link)))
  5110. 'keymap (or (org-link-get-parameter type :keymap)
  5111. org-mouse-map)
  5112. 'org-link-start (match-beginning 0)))
  5113. (org-rear-nonsticky-at (match-end 0))
  5114. (when activate-func
  5115. (funcall activate-func link-start link-end path nil))
  5116. t))))
  5117. (defun org-activate-code (limit)
  5118. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5119. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5120. (remove-text-properties (match-beginning 0) (match-end 0)
  5121. '(display t invisible t intangible t))
  5122. t))
  5123. (defcustom org-src-fontify-natively t
  5124. "When non-nil, fontify code in code blocks.
  5125. See also the `org-block' face."
  5126. :type 'boolean
  5127. :version "24.4"
  5128. :package-version '(Org . "8.3")
  5129. :group 'org-appearance
  5130. :group 'org-babel)
  5131. (defcustom org-allow-promoting-top-level-subtree nil
  5132. "When non-nil, allow promoting a top level subtree.
  5133. The leading star of the top level headline will be replaced
  5134. by a #."
  5135. :type 'boolean
  5136. :version "24.1"
  5137. :group 'org-appearance)
  5138. (defun org-fontify-meta-lines-and-blocks (limit)
  5139. (condition-case nil
  5140. (org-fontify-meta-lines-and-blocks-1 limit)
  5141. (error (message "org-mode fontification error in %S at %d"
  5142. (current-buffer)
  5143. (line-number-at-pos)))))
  5144. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5145. "Fontify #+ lines and blocks."
  5146. (let ((case-fold-search t))
  5147. (when (re-search-forward
  5148. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5149. limit t)
  5150. (let ((beg (match-beginning 0))
  5151. (block-start (match-end 0))
  5152. (block-end nil)
  5153. (lang (match-string 7))
  5154. (beg1 (line-beginning-position 2))
  5155. (dc1 (downcase (match-string 2)))
  5156. (dc3 (downcase (match-string 3)))
  5157. end end1 quoting block-type)
  5158. (cond
  5159. ((and (match-end 4) (equal dc3 "+begin"))
  5160. ;; Truly a block
  5161. (setq block-type (downcase (match-string 5))
  5162. quoting (member block-type org-protecting-blocks))
  5163. (when (re-search-forward
  5164. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5165. nil t) ;; on purpose, we look further than LIMIT
  5166. (setq end (min (point-max) (match-end 0))
  5167. end1 (min (point-max) (1- (match-beginning 0))))
  5168. (setq block-end (match-beginning 0))
  5169. (when quoting
  5170. (org-remove-flyspell-overlays-in beg1 end1)
  5171. (remove-text-properties beg end
  5172. '(display t invisible t intangible t)))
  5173. (add-text-properties
  5174. beg end '(font-lock-fontified t font-lock-multiline t))
  5175. (add-text-properties beg beg1 '(face org-meta-line))
  5176. (org-remove-flyspell-overlays-in beg beg1)
  5177. (add-text-properties ; For end_src
  5178. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5179. (org-remove-flyspell-overlays-in end1 end)
  5180. (cond
  5181. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5182. (org-src-font-lock-fontify-block lang block-start block-end)
  5183. (add-text-properties beg1 block-end '(src-block t)))
  5184. (quoting
  5185. (add-text-properties beg1 (min (point-max) (1+ end1))
  5186. (list 'face
  5187. (list :inherit
  5188. (let ((face-name
  5189. (intern (format "org-block-%s" lang))))
  5190. (append (and (facep face-name) (list face-name))
  5191. '(org-block))))))) ; end of source block
  5192. ((not org-fontify-quote-and-verse-blocks))
  5193. ((string= block-type "quote")
  5194. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5195. ((string= block-type "verse")
  5196. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5197. (add-text-properties beg beg1 '(face org-block-begin-line))
  5198. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5199. '(face org-block-end-line))
  5200. t))
  5201. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5202. (org-remove-flyspell-overlays-in
  5203. (match-beginning 0)
  5204. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5205. (add-text-properties
  5206. beg (match-end 3)
  5207. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5208. '(font-lock-fontified t invisible t)
  5209. '(font-lock-fontified t face org-document-info-keyword)))
  5210. (add-text-properties
  5211. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5212. (if (string-equal dc1 "+title:")
  5213. '(font-lock-fontified t face org-document-title)
  5214. '(font-lock-fontified t face org-document-info))))
  5215. ((string-prefix-p "+caption" dc1)
  5216. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5217. (remove-text-properties (match-beginning 0) (match-end 0)
  5218. '(display t invisible t intangible t))
  5219. ;; Handle short captions.
  5220. (save-excursion
  5221. (beginning-of-line)
  5222. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5223. (add-text-properties (line-beginning-position) (match-end 1)
  5224. '(font-lock-fontified t face org-meta-line))
  5225. (add-text-properties (match-end 0) (line-end-position)
  5226. '(font-lock-fontified t face org-block))
  5227. t)
  5228. ((member dc3 '(" " ""))
  5229. (org-remove-flyspell-overlays-in beg (match-end 0))
  5230. (add-text-properties
  5231. beg (match-end 0)
  5232. '(font-lock-fontified t face font-lock-comment-face)))
  5233. (t ;; just any other in-buffer setting, but not indented
  5234. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5235. (remove-text-properties (match-beginning 0) (match-end 0)
  5236. '(display t invisible t intangible t))
  5237. (add-text-properties beg (match-end 0)
  5238. '(font-lock-fontified t face org-meta-line))
  5239. t))))))
  5240. (defun org-fontify-drawers (limit)
  5241. "Fontify drawers."
  5242. (when (re-search-forward org-drawer-regexp limit t)
  5243. (add-text-properties
  5244. (match-beginning 0) (match-end 0)
  5245. '(font-lock-fontified t face org-special-keyword))
  5246. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5247. t))
  5248. (defun org-fontify-macros (limit)
  5249. "Fontify macros."
  5250. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5251. (add-text-properties
  5252. (match-beginning 0) (match-end 0)
  5253. '(font-lock-fontified t face org-macro))
  5254. (when org-hide-macro-markers
  5255. (add-text-properties (match-end 2) (match-beginning 2)
  5256. '(invisible t))
  5257. (add-text-properties (match-beginning 1) (match-end 1)
  5258. '(invisible t)))
  5259. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5260. t))
  5261. (defun org-activate-angle-links (limit)
  5262. "Add text properties for angle links."
  5263. (when (and (re-search-forward org-angle-link-re limit t)
  5264. (not (org-in-src-block-p)))
  5265. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5266. (add-text-properties (match-beginning 0) (match-end 0)
  5267. (list 'mouse-face 'highlight
  5268. 'keymap org-mouse-map
  5269. 'font-lock-multiline t))
  5270. (org-rear-nonsticky-at (match-end 0))
  5271. t))
  5272. (defun org-activate-footnote-links (limit)
  5273. "Add text properties for footnotes."
  5274. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5275. (when fn
  5276. (let* ((beg (nth 1 fn))
  5277. (end (nth 2 fn))
  5278. (label (car fn))
  5279. (referencep (/= (line-beginning-position) beg)))
  5280. (when (and referencep (nth 3 fn))
  5281. (save-excursion
  5282. (goto-char beg)
  5283. (search-forward (or label "fn:"))
  5284. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5285. (add-text-properties beg end
  5286. (list 'mouse-face 'highlight
  5287. 'keymap org-mouse-map
  5288. 'help-echo
  5289. (if referencep "Footnote reference"
  5290. "Footnote definition")
  5291. 'font-lock-fontified t
  5292. 'font-lock-multiline t
  5293. 'face 'org-footnote))))))
  5294. (defun org-activate-bracket-links (limit)
  5295. "Add text properties for bracketed links."
  5296. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5297. (not (org-in-src-block-p)))
  5298. (let* ((hl (save-match-data
  5299. (org-link-expand-abbrev (match-string-no-properties 1))))
  5300. (type (save-match-data
  5301. (and (string-match org-plain-link-re hl)
  5302. (match-string-no-properties 1 hl))))
  5303. (path (save-match-data
  5304. (and (string-match org-plain-link-re hl)
  5305. (match-string-no-properties 2 hl))))
  5306. (link-start (match-beginning 0))
  5307. (link-end (match-end 0))
  5308. (bracketp t)
  5309. (help-echo (org-link-get-parameter type :help-echo))
  5310. (help (cond
  5311. ((stringp help-echo)
  5312. help-echo)
  5313. ((functionp help-echo)
  5314. help-echo)
  5315. (t
  5316. (concat "LINK: "
  5317. (save-match-data
  5318. (org-link-unescape hl))))))
  5319. (link-face (org-link-get-parameter type :face))
  5320. (face (cond
  5321. ;; A function that returns a face
  5322. ((functionp link-face)
  5323. (funcall link-face path))
  5324. ;; a face
  5325. ((facep link-face)
  5326. link-face)
  5327. ;; An anonymous face
  5328. ((consp link-face)
  5329. link-face)
  5330. ;; default
  5331. (t
  5332. 'org-link)))
  5333. (keymap (or (org-link-get-parameter type :keymap)
  5334. org-mouse-map))
  5335. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5336. 'highlight))
  5337. (htmlize (org-link-get-parameter type :htmlize-link))
  5338. (htmlize-link (cond
  5339. ((functionp htmlize)
  5340. (funcall htmlize))
  5341. (t
  5342. `(:uri ,(format "%s:%s" type path)))))
  5343. (activate-func (org-link-get-parameter type :activate-func))
  5344. ;; invisible part
  5345. (ip (list 'invisible (or
  5346. (org-link-get-parameter type :display)
  5347. 'org-link)
  5348. 'face face
  5349. 'keymap keymap
  5350. 'mouse-face mouse-face
  5351. 'font-lock-multiline t
  5352. 'help-echo help
  5353. 'htmlize-link htmlize-link))
  5354. ;; visible part
  5355. (vp (list 'keymap keymap
  5356. 'face face
  5357. 'mouse-face mouse-face
  5358. 'font-lock-multiline t
  5359. 'help-echo help
  5360. 'htmlize-link htmlize-link)))
  5361. ;; We need to remove the invisible property here. Table narrowing
  5362. ;; may have made some of this invisible.
  5363. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5364. (remove-text-properties (match-beginning 0) (match-end 0)
  5365. '(invisible nil))
  5366. (if (match-end 3)
  5367. (progn
  5368. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5369. (org-rear-nonsticky-at (match-beginning 3))
  5370. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5371. (org-rear-nonsticky-at (match-end 3))
  5372. (add-text-properties (match-end 3) (match-end 0) ip)
  5373. (org-rear-nonsticky-at (match-end 0)))
  5374. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5375. (org-rear-nonsticky-at (match-beginning 1))
  5376. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5377. (org-rear-nonsticky-at (match-end 1))
  5378. (add-text-properties (match-end 1) (match-end 0) ip)
  5379. (org-rear-nonsticky-at (match-end 0)))
  5380. (when activate-func
  5381. (funcall activate-func link-start link-end path bracketp))
  5382. t)))
  5383. (defun org-activate-dates (limit)
  5384. "Add text properties for dates."
  5385. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5386. (not (equal (char-before (match-beginning 0)) 91)))
  5387. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5388. (add-text-properties (match-beginning 0) (match-end 0)
  5389. (list 'mouse-face 'highlight
  5390. 'keymap org-mouse-map))
  5391. (org-rear-nonsticky-at (match-end 0))
  5392. (when org-display-custom-times
  5393. (if (match-end 3)
  5394. (org-display-custom-time (match-beginning 3) (match-end 3))
  5395. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5396. t))
  5397. (defvar-local org-target-link-regexp nil
  5398. "Regular expression matching radio targets in plain text.")
  5399. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5400. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5401. border border border))
  5402. "Regular expression matching a link target.")
  5403. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5404. "Regular expression matching a radio target.")
  5405. (defconst org-any-target-regexp
  5406. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5407. "Regular expression matching any target.")
  5408. (defun org-activate-target-links (limit)
  5409. "Add text properties for target matches."
  5410. (when org-target-link-regexp
  5411. (let ((case-fold-search t))
  5412. (when (re-search-forward org-target-link-regexp limit t)
  5413. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5414. (add-text-properties (match-beginning 1) (match-end 1)
  5415. (list 'mouse-face 'highlight
  5416. 'keymap org-mouse-map
  5417. 'help-echo "Radio target link"
  5418. 'org-linked-text t))
  5419. (org-rear-nonsticky-at (match-end 1))
  5420. t))))
  5421. (defun org-update-radio-target-regexp ()
  5422. "Find all radio targets in this file and update the regular expression.
  5423. Also refresh fontification if needed."
  5424. (interactive)
  5425. (let ((old-regexp org-target-link-regexp)
  5426. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5427. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5428. (targets
  5429. (org-with-wide-buffer
  5430. (goto-char (point-min))
  5431. (let (rtn)
  5432. (while (re-search-forward org-radio-target-regexp nil t)
  5433. ;; Make sure point is really within the object.
  5434. (backward-char)
  5435. (let ((obj (org-element-context)))
  5436. (when (eq (org-element-type obj) 'radio-target)
  5437. (cl-pushnew (org-element-property :value obj) rtn
  5438. :test #'equal))))
  5439. rtn))))
  5440. (setq org-target-link-regexp
  5441. (and targets
  5442. (concat before-re
  5443. (mapconcat
  5444. (lambda (x)
  5445. (replace-regexp-in-string
  5446. " +" "\\s-+" (regexp-quote x) t t))
  5447. targets
  5448. "\\|")
  5449. after-re)))
  5450. (unless (equal old-regexp org-target-link-regexp)
  5451. ;; Clean-up cache.
  5452. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5453. ((not org-target-link-regexp) old-regexp)
  5454. (t
  5455. (concat before-re
  5456. (mapconcat
  5457. (lambda (re)
  5458. (substring re (length before-re)
  5459. (- (length after-re))))
  5460. (list old-regexp org-target-link-regexp)
  5461. "\\|")
  5462. after-re)))))
  5463. (org-with-wide-buffer
  5464. (goto-char (point-min))
  5465. (while (re-search-forward regexp nil t)
  5466. (org-element-cache-refresh (match-beginning 1)))))
  5467. ;; Re fontify buffer.
  5468. (when (memq 'radio org-highlight-links)
  5469. (org-restart-font-lock)))))
  5470. (defun org-hide-wide-columns (limit)
  5471. (let (s e)
  5472. (setq s (text-property-any (point) (or limit (point-max))
  5473. 'org-cwidth t))
  5474. (when s
  5475. (setq e (next-single-property-change s 'org-cwidth))
  5476. (add-text-properties s e '(invisible org-cwidth))
  5477. (goto-char e)
  5478. t)))
  5479. (defvar org-latex-and-related-regexp nil
  5480. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5481. (defun org-compute-latex-and-related-regexp ()
  5482. "Compute regular expression for LaTeX, entities and sub/superscript.
  5483. Result depends on variable `org-highlight-latex-and-related'."
  5484. (setq-local
  5485. org-latex-and-related-regexp
  5486. (let* ((re-sub
  5487. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5488. ((eq org-use-sub-superscripts '{})
  5489. (list org-match-substring-with-braces-regexp))
  5490. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5491. (re-latex
  5492. (when (memq 'latex org-highlight-latex-and-related)
  5493. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5494. (delq nil
  5495. (mapcar (lambda (x)
  5496. (and (member (car x) matchers) (nth 1 x)))
  5497. org-latex-regexps)))))
  5498. (re-entities
  5499. (when (memq 'entities org-highlight-latex-and-related)
  5500. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5501. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5502. (defun org-do-latex-and-related (limit)
  5503. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5504. LIMIT bounds the search for syntax to highlight. Stop at first
  5505. highlighted object, if any. Return t if some highlighting was
  5506. done, nil otherwise."
  5507. (when (org-string-nw-p org-latex-and-related-regexp)
  5508. (catch 'found
  5509. (while (re-search-forward org-latex-and-related-regexp limit t)
  5510. (unless
  5511. (cl-some
  5512. (lambda (f)
  5513. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5514. (save-excursion
  5515. (goto-char (1+ (match-beginning 0)))
  5516. (face-at-point nil t)))
  5517. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5518. '(?_ ?^))
  5519. 1
  5520. 0)))
  5521. (font-lock-prepend-text-property
  5522. (+ offset (match-beginning 0)) (match-end 0)
  5523. 'face 'org-latex-and-related)
  5524. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5525. '(font-lock-multiline t)))
  5526. (throw 'found t)))
  5527. nil)))
  5528. (defun org-restart-font-lock ()
  5529. "Restart `font-lock-mode', to force refontification."
  5530. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5531. (font-lock-mode -1)
  5532. (font-lock-mode 1)))
  5533. (defun org-activate-tags (limit)
  5534. (when (re-search-forward
  5535. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5536. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5537. (add-text-properties (match-beginning 1) (match-end 1)
  5538. (list 'mouse-face 'highlight
  5539. 'keymap org-mouse-map))
  5540. (org-rear-nonsticky-at (match-end 1))
  5541. t))
  5542. (defun org-outline-level ()
  5543. "Compute the outline level of the heading at point.
  5544. If this is called at a normal headline, the level is the number
  5545. of stars. Use `org-reduced-level' to remove the effect of
  5546. `org-odd-levels'. Unlike to `org-current-level', this function
  5547. takes into consideration inlinetasks."
  5548. (org-with-wide-buffer
  5549. (end-of-line)
  5550. (if (re-search-backward org-outline-regexp-bol nil t)
  5551. (1- (- (match-end 0) (match-beginning 0)))
  5552. 0)))
  5553. (defvar org-font-lock-keywords nil)
  5554. (defsubst org-re-property (property &optional literal allow-null value)
  5555. "Return a regexp matching a PROPERTY line.
  5556. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5557. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5558. non-nil, match properties even without a value.
  5559. Match group 3 is set to the value when it exists. If there is no
  5560. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5561. With optional argument VALUE, match only property lines with
  5562. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5563. unless LITERAL is non-nil."
  5564. (concat
  5565. "^\\(?4:[ \t]*\\)"
  5566. (format "\\(?1::\\(?2:%s\\):\\)"
  5567. (if literal property (regexp-quote property)))
  5568. (cond (value
  5569. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5570. (if literal value (regexp-quote value))))
  5571. (allow-null
  5572. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5573. (t
  5574. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5575. (defconst org-property-re
  5576. (org-re-property "\\S-+" 'literal t)
  5577. "Regular expression matching a property line.
  5578. There are four matching groups:
  5579. 1: :PROPKEY: including the leading and trailing colon,
  5580. 2: PROPKEY without the leading and trailing colon,
  5581. 3: PROPVAL without leading or trailing spaces,
  5582. 4: the indentation of the current line,
  5583. 5: trailing whitespace.")
  5584. (defvar org-font-lock-hook nil
  5585. "Functions to be called for special font lock stuff.")
  5586. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5587. (defvar org-font-lock-set-keywords-hook nil
  5588. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5589. This is called after `org-font-lock-extra-keywords' is defined, but before
  5590. it is installed to be used by font lock. This can be useful if something
  5591. needs to be inserted at a specific position in the font-lock sequence.")
  5592. (defun org-font-lock-hook (limit)
  5593. "Run `org-font-lock-hook' within LIMIT."
  5594. (run-hook-with-args 'org-font-lock-hook limit))
  5595. (defun org-set-font-lock-defaults ()
  5596. "Set font lock defaults for the current buffer."
  5597. (let* ((em org-fontify-emphasized-text)
  5598. (lk org-highlight-links)
  5599. (org-font-lock-extra-keywords
  5600. (list
  5601. ;; Call the hook
  5602. '(org-font-lock-hook)
  5603. ;; Headlines
  5604. `(,(if org-fontify-whole-heading-line
  5605. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5606. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5607. (1 (org-get-level-face 1))
  5608. (2 (org-get-level-face 2))
  5609. (3 (org-get-level-face 3)))
  5610. ;; Table lines
  5611. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5612. (1 'org-table t))
  5613. ;; Table internals
  5614. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5615. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5616. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5617. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5618. ;; Drawers
  5619. '(org-fontify-drawers)
  5620. ;; Properties
  5621. (list org-property-re
  5622. '(1 'org-special-keyword t)
  5623. '(3 'org-property-value t))
  5624. ;; Links
  5625. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5626. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5627. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5628. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5629. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5630. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5631. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5632. ;; Targets.
  5633. (list org-any-target-regexp '(0 'org-target t))
  5634. ;; Diary sexps.
  5635. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5636. ;; Macro
  5637. '(org-fontify-macros)
  5638. '(org-hide-wide-columns (0 nil append))
  5639. ;; TODO keyword
  5640. (list (format org-heading-keyword-regexp-format
  5641. org-todo-regexp)
  5642. '(2 (org-get-todo-face 2) t))
  5643. ;; DONE
  5644. (if org-fontify-done-headline
  5645. (list (format org-heading-keyword-regexp-format
  5646. (concat
  5647. "\\(?:"
  5648. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5649. "\\)"))
  5650. '(2 'org-headline-done t))
  5651. nil)
  5652. ;; Priorities
  5653. '(org-font-lock-add-priority-faces)
  5654. ;; Tags
  5655. '(org-font-lock-add-tag-faces)
  5656. ;; Tags groups
  5657. (when (and org-group-tags org-tag-groups-alist)
  5658. (list (concat org-outline-regexp-bol ".+\\(:"
  5659. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5660. ":\\).*$")
  5661. '(1 'org-tag-group prepend)))
  5662. ;; Special keywords
  5663. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5664. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5665. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5666. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5667. ;; Emphasis
  5668. (when em '(org-do-emphasis-faces))
  5669. ;; Checkboxes
  5670. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5671. 1 'org-checkbox prepend)
  5672. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5673. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5674. (0 (org-get-checkbox-statistics-face) t)))
  5675. ;; Description list items
  5676. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5677. 1 'org-list-dt prepend)
  5678. ;; ARCHIVEd headings
  5679. (list (concat
  5680. org-outline-regexp-bol
  5681. "\\(.*:" org-archive-tag ":.*\\)")
  5682. '(1 'org-archived prepend))
  5683. ;; Specials
  5684. '(org-do-latex-and-related)
  5685. '(org-fontify-entities)
  5686. '(org-raise-scripts)
  5687. ;; Code
  5688. '(org-activate-code (1 'org-code t))
  5689. ;; COMMENT
  5690. (list (format
  5691. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5692. org-todo-regexp
  5693. org-comment-string)
  5694. '(9 'org-special-keyword t))
  5695. ;; Blocks and meta lines
  5696. '(org-fontify-meta-lines-and-blocks))))
  5697. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5698. (run-hooks 'org-font-lock-set-keywords-hook)
  5699. ;; Now set the full font-lock-keywords
  5700. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5701. (setq-local font-lock-defaults
  5702. '(org-font-lock-keywords t nil nil backward-paragraph))
  5703. (kill-local-variable 'font-lock-keywords)
  5704. nil))
  5705. (defun org-toggle-pretty-entities ()
  5706. "Toggle the composition display of entities as UTF8 characters."
  5707. (interactive)
  5708. (setq-local org-pretty-entities (not org-pretty-entities))
  5709. (org-restart-font-lock)
  5710. (if org-pretty-entities
  5711. (message "Entities are now displayed as UTF8 characters")
  5712. (save-restriction
  5713. (widen)
  5714. (decompose-region (point-min) (point-max))
  5715. (message "Entities are now displayed as plain text"))))
  5716. (defvar-local org-custom-properties-overlays nil
  5717. "List of overlays used for custom properties.")
  5718. (defun org-toggle-custom-properties-visibility ()
  5719. "Display or hide properties in `org-custom-properties'."
  5720. (interactive)
  5721. (if org-custom-properties-overlays
  5722. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5723. (setq org-custom-properties-overlays nil))
  5724. (when org-custom-properties
  5725. (org-with-wide-buffer
  5726. (goto-char (point-min))
  5727. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5728. (while (re-search-forward regexp nil t)
  5729. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5730. (when (and end (< (point) end))
  5731. ;; Hide first custom property in current drawer.
  5732. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5733. (overlay-put o 'invisible t)
  5734. (overlay-put o 'org-custom-property t)
  5735. (push o org-custom-properties-overlays))
  5736. ;; Hide additional custom properties in the same drawer.
  5737. (while (re-search-forward regexp end t)
  5738. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5739. (overlay-put o 'invisible t)
  5740. (overlay-put o 'org-custom-property t)
  5741. (push o org-custom-properties-overlays)))))
  5742. ;; Each entry is limited to a single property drawer.
  5743. (outline-next-heading)))))))
  5744. (defun org-fontify-entities (limit)
  5745. "Find an entity to fontify."
  5746. (let (ee)
  5747. (when org-pretty-entities
  5748. (catch 'match
  5749. ;; "\_ "-family is left out on purpose. Only the first one,
  5750. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5751. ;; confusing when adding a second white space character.
  5752. (while (re-search-forward
  5753. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5754. limit t)
  5755. (when (and (not (org-at-comment-p))
  5756. (setq ee (org-entity-get (match-string 1)))
  5757. (= (length (nth 6 ee)) 1))
  5758. (let* ((end (if (equal (match-string 2) "{}")
  5759. (match-end 2)
  5760. (match-end 1))))
  5761. (add-text-properties
  5762. (match-beginning 0) end
  5763. (list 'font-lock-fontified t))
  5764. (compose-region (match-beginning 0) end
  5765. (nth 6 ee) nil)
  5766. (backward-char 1)
  5767. (throw 'match t))))
  5768. nil))))
  5769. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5770. "Fontify string S like in Org mode."
  5771. (with-temp-buffer
  5772. (insert s)
  5773. (let ((org-odd-levels-only odd-levels))
  5774. (org-mode)
  5775. (org-font-lock-ensure)
  5776. (buffer-string))))
  5777. (defvar org-m nil)
  5778. (defvar org-l nil)
  5779. (defvar org-f nil)
  5780. (defun org-get-level-face (n)
  5781. "Get the right face for match N in font-lock matching of headlines."
  5782. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5783. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5784. (if org-cycle-level-faces
  5785. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5786. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5787. (cond
  5788. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5789. ((eq n 2) org-f)
  5790. (t (unless org-level-color-stars-only org-f))))
  5791. (defun org-face-from-face-or-color (context inherit face-or-color)
  5792. "Create a face list that inherits INHERIT, but sets the foreground color.
  5793. When FACE-OR-COLOR is not a string, just return it."
  5794. (if (stringp face-or-color)
  5795. (list :inherit inherit
  5796. (cdr (assoc context org-faces-easy-properties))
  5797. face-or-color)
  5798. face-or-color))
  5799. (defun org-get-todo-face (kwd)
  5800. "Get the right face for a TODO keyword KWD.
  5801. If KWD is a number, get the corresponding match group."
  5802. (when (numberp kwd) (setq kwd (match-string kwd)))
  5803. (or (org-face-from-face-or-color
  5804. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5805. (and (member kwd org-done-keywords) 'org-done)
  5806. 'org-todo))
  5807. (defun org-get-priority-face (priority)
  5808. "Get the right face for PRIORITY.
  5809. PRIORITY is a character."
  5810. (or (org-face-from-face-or-color
  5811. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5812. 'org-priority))
  5813. (defun org-get-tag-face (tag)
  5814. "Get the right face for TAG.
  5815. If TAG is a number, get the corresponding match group."
  5816. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5817. (or (org-face-from-face-or-color
  5818. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5819. 'org-tag)))
  5820. (defun org-font-lock-add-priority-faces (limit)
  5821. "Add the special priority faces."
  5822. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5823. (add-text-properties
  5824. (match-beginning 1) (match-end 1)
  5825. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5826. 'font-lock-fontified t))))
  5827. (defun org-font-lock-add-tag-faces (limit)
  5828. "Add the special tag faces."
  5829. (when (and org-tag-faces org-tags-special-faces-re)
  5830. (while (re-search-forward org-tags-special-faces-re limit t)
  5831. (add-text-properties (match-beginning 1) (match-end 1)
  5832. (list 'face (org-get-tag-face 1)
  5833. 'font-lock-fontified t))
  5834. (backward-char 1))))
  5835. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5836. "Remove fontification and activation overlays from links."
  5837. (font-lock-default-unfontify-region beg end)
  5838. (let* ((buffer-undo-list t)
  5839. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5840. (inhibit-modification-hooks t)
  5841. deactivate-mark buffer-file-name buffer-file-truename)
  5842. (decompose-region beg end)
  5843. (remove-text-properties beg end
  5844. '(mouse-face t keymap t org-linked-text t
  5845. invisible t intangible t
  5846. org-emphasis t))
  5847. (org-remove-font-lock-display-properties beg end)))
  5848. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5849. ((raise 0.3) (height 0.7))
  5850. ((raise -0.5))
  5851. ((raise 0.5)))
  5852. "Display properties for showing superscripts and subscripts.")
  5853. (defun org-remove-font-lock-display-properties (beg end)
  5854. "Remove specific display properties that have been added by font lock.
  5855. The will remove the raise properties that are used to show superscripts
  5856. and subscripts."
  5857. (let (next prop)
  5858. (while (< beg end)
  5859. (setq next (next-single-property-change beg 'display nil end)
  5860. prop (get-text-property beg 'display))
  5861. (when (member prop org-script-display)
  5862. (put-text-property beg next 'display nil))
  5863. (setq beg next))))
  5864. (defun org-raise-scripts (limit)
  5865. "Add raise properties to sub/superscripts."
  5866. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5867. (re-search-forward
  5868. (if (eq org-use-sub-superscripts t)
  5869. org-match-substring-regexp
  5870. org-match-substring-with-braces-regexp)
  5871. limit t))
  5872. (let* ((pos (point)) table-p comment-p
  5873. (mpos (match-beginning 3))
  5874. (emph-p (get-text-property mpos 'org-emphasis))
  5875. (link-p (get-text-property mpos 'mouse-face))
  5876. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5877. (goto-char (point-at-bol))
  5878. (setq table-p (looking-at-p org-table-dataline-regexp)
  5879. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5880. (goto-char pos)
  5881. ;; Handle a_b^c
  5882. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5883. (unless (or comment-p emph-p link-p keyw-p)
  5884. (put-text-property (match-beginning 3) (match-end 0)
  5885. 'display
  5886. (if (equal (char-after (match-beginning 2)) ?^)
  5887. (nth (if table-p 3 1) org-script-display)
  5888. (nth (if table-p 2 0) org-script-display)))
  5889. (add-text-properties (match-beginning 2) (match-end 2)
  5890. (list 'invisible t
  5891. 'org-dwidth t 'org-dwidth-n 1))
  5892. (if (and (eq (char-after (match-beginning 3)) ?{)
  5893. (eq (char-before (match-end 3)) ?}))
  5894. (progn
  5895. (add-text-properties
  5896. (match-beginning 3) (1+ (match-beginning 3))
  5897. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5898. (add-text-properties
  5899. (1- (match-end 3)) (match-end 3)
  5900. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5901. t)))
  5902. ;;;; Visibility cycling, including org-goto and indirect buffer
  5903. ;;; Cycling
  5904. (defvar-local org-cycle-global-status nil)
  5905. (put 'org-cycle-global-status 'org-state t)
  5906. (defvar-local org-cycle-subtree-status nil)
  5907. (put 'org-cycle-subtree-status 'org-state t)
  5908. (defvar org-inlinetask-min-level)
  5909. (defun org-unlogged-message (&rest args)
  5910. "Display a message, but avoid logging it in the *Messages* buffer."
  5911. (let ((message-log-max nil))
  5912. (apply 'message args)))
  5913. ;;;###autoload
  5914. (defun org-cycle (&optional arg)
  5915. "TAB-action and visibility cycling for Org mode.
  5916. This is the command invoked in Org mode by the `TAB' key. Its main
  5917. purpose is outline visibility cycling, but it also invokes other actions
  5918. in special contexts.
  5919. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5920. the entire
  5921. buffer through 3 states (global cycling)
  5922. 1. OVERVIEW: Show only top-level headlines.
  5923. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5924. 3. SHOW ALL: Show everything.
  5925. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5926. switch to the startup visibility,
  5927. determined by the variable `org-startup-folded', and by any VISIBILITY
  5928. properties in the buffer.
  5929. With a `\\[universal-argument] \\[universal-argument] \
  5930. \\[universal-argument]' prefix argument, show the entire buffer, including
  5931. any drawers.
  5932. When inside a table, re-align the table and move to the next field.
  5933. When point is at the beginning of a headline, rotate the subtree started
  5934. by this line through 3 different states (local cycling)
  5935. 1. FOLDED: Only the main headline is shown.
  5936. 2. CHILDREN: The main headline and the direct children are shown.
  5937. From this state, you can move to one of the children
  5938. and zoom in further.
  5939. 3. SUBTREE: Show the entire subtree, including body text.
  5940. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5941. When point is at the beginning of an empty headline and the variable
  5942. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5943. of the headline by demoting and promoting it to likely levels. This
  5944. speeds up creation document structure by pressing `TAB' once or several
  5945. times right after creating a new headline.
  5946. When there is a numeric prefix, go up to a heading with level ARG, do
  5947. a `show-subtree' and return to the previous cursor position. If ARG
  5948. is negative, go up that many levels.
  5949. When point is not at the beginning of a headline, execute the global
  5950. binding for `TAB', which is re-indenting the line. See the option
  5951. `org-cycle-emulate-tab' for details.
  5952. As a special case, if point is at the beginning of the buffer and there is
  5953. no headline in line 1, this function will act as if called with prefix arg
  5954. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5955. prefix arg, but only
  5956. if the variable `org-cycle-global-at-bob' is t."
  5957. (interactive "P")
  5958. (org-load-modules-maybe)
  5959. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5960. (and org-cycle-level-after-item/entry-creation
  5961. (or (org-cycle-level)
  5962. (org-cycle-item-indentation))))
  5963. (let* ((limit-level
  5964. (or org-cycle-max-level
  5965. (and (boundp 'org-inlinetask-min-level)
  5966. org-inlinetask-min-level
  5967. (1- org-inlinetask-min-level))))
  5968. (nstars (and limit-level
  5969. (if org-odd-levels-only
  5970. (and limit-level (1- (* limit-level 2)))
  5971. limit-level)))
  5972. (org-outline-regexp
  5973. (if (not (derived-mode-p 'org-mode))
  5974. outline-regexp
  5975. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5976. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5977. (not (looking-at org-outline-regexp))))
  5978. (org-cycle-hook
  5979. (if bob-special
  5980. (delq 'org-optimize-window-after-visibility-change
  5981. (copy-sequence org-cycle-hook))
  5982. org-cycle-hook))
  5983. (pos (point)))
  5984. (cond
  5985. ((equal arg '(16))
  5986. (setq last-command 'dummy)
  5987. (org-set-startup-visibility)
  5988. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5989. ((equal arg '(64))
  5990. (outline-show-all)
  5991. (org-unlogged-message "Entire buffer visible, including drawers"))
  5992. ((equal arg '(4)) (org-cycle-internal-global))
  5993. ;; Try hiding block at point.
  5994. ((org-hide-block-toggle-maybe))
  5995. ;; Try cdlatex TAB completion
  5996. ((org-try-cdlatex-tab))
  5997. ;; Table: enter it or move to the next field.
  5998. ((org-at-table-p 'any)
  5999. (if (org-at-table.el-p)
  6000. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6001. Use `\\[org-edit-special]' to edit table.el tables"))
  6002. (if arg (org-table-edit-field t)
  6003. (org-table-justify-field-maybe)
  6004. (call-interactively 'org-table-next-field))))
  6005. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6006. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6007. (bob-special (org-cycle-internal-global))
  6008. ;; Drawers: delegate to `org-flag-drawer'.
  6009. ((save-excursion
  6010. (beginning-of-line 1)
  6011. (looking-at org-drawer-regexp))
  6012. (org-flag-drawer ; toggle block visibility
  6013. (not (get-char-property (match-end 0) 'invisible))))
  6014. ;; Show-subtree, ARG levels up from here.
  6015. ((integerp arg)
  6016. (save-excursion
  6017. (org-back-to-heading)
  6018. (outline-up-heading (if (< arg 0) (- arg)
  6019. (- (funcall outline-level) arg)))
  6020. (org-show-subtree)))
  6021. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6022. ((and (featurep 'org-inlinetask)
  6023. (org-inlinetask-at-task-p)
  6024. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6025. (org-inlinetask-toggle-visibility))
  6026. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6027. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6028. (save-excursion (move-beginning-of-line 1)
  6029. (looking-at org-outline-regexp)))
  6030. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6031. (org-cycle-internal-local))
  6032. ;; From there: TAB emulation and template completion.
  6033. (buffer-read-only (org-back-to-heading))
  6034. ((run-hook-with-args-until-success
  6035. 'org-tab-after-check-for-cycling-hook))
  6036. ((org-try-structure-completion))
  6037. ((run-hook-with-args-until-success
  6038. 'org-tab-before-tab-emulation-hook))
  6039. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6040. (or (not (bolp))
  6041. (not (looking-at org-outline-regexp))))
  6042. (call-interactively (global-key-binding "\t")))
  6043. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6044. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6045. (or (and (eq org-cycle-emulate-tab 'white)
  6046. (= (match-end 0) (point-at-eol)))
  6047. (and (eq org-cycle-emulate-tab 'whitestart)
  6048. (>= (match-end 0) pos))))
  6049. t
  6050. (eq org-cycle-emulate-tab t))
  6051. (call-interactively (global-key-binding "\t")))
  6052. (t (save-excursion
  6053. (org-back-to-heading)
  6054. (org-cycle)))))))
  6055. (defun org-cycle-internal-global ()
  6056. "Do the global cycling action."
  6057. ;; Hack to avoid display of messages for .org attachments in Gnus
  6058. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6059. (cond
  6060. ((and (eq last-command this-command)
  6061. (eq org-cycle-global-status 'overview))
  6062. ;; We just created the overview - now do table of contents
  6063. ;; This can be slow in very large buffers, so indicate action
  6064. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6065. (unless ga (org-unlogged-message "CONTENTS..."))
  6066. (org-content)
  6067. (unless ga (org-unlogged-message "CONTENTS...done"))
  6068. (setq org-cycle-global-status 'contents)
  6069. (run-hook-with-args 'org-cycle-hook 'contents))
  6070. ((and (eq last-command this-command)
  6071. (eq org-cycle-global-status 'contents))
  6072. ;; We just showed the table of contents - now show everything
  6073. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6074. (outline-show-all)
  6075. (unless ga (org-unlogged-message "SHOW ALL"))
  6076. (setq org-cycle-global-status 'all)
  6077. (run-hook-with-args 'org-cycle-hook 'all))
  6078. (t
  6079. ;; Default action: go to overview
  6080. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6081. (org-overview)
  6082. (unless ga (org-unlogged-message "OVERVIEW"))
  6083. (setq org-cycle-global-status 'overview)
  6084. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6085. (defvar org-called-with-limited-levels nil
  6086. "Non-nil when `org-with-limited-levels' is currently active.")
  6087. (defun org-cycle-internal-local ()
  6088. "Do the local cycling action."
  6089. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6090. ;; First, determine end of headline (EOH), end of subtree or item
  6091. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6092. (save-excursion
  6093. (if (org-at-item-p)
  6094. (progn
  6095. (beginning-of-line)
  6096. (setq struct (org-list-struct))
  6097. (setq eoh (point-at-eol))
  6098. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6099. (setq has-children (org-list-has-child-p (point) struct)))
  6100. (org-back-to-heading)
  6101. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6102. (setq eos (save-excursion (org-end-of-subtree t t)
  6103. (when (bolp) (backward-char)) (point)))
  6104. (setq has-children
  6105. (or (save-excursion
  6106. (let ((level (funcall outline-level)))
  6107. (outline-next-heading)
  6108. (and (org-at-heading-p t)
  6109. (> (funcall outline-level) level))))
  6110. (save-excursion
  6111. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6112. ;; Determine end invisible part of buffer (EOL)
  6113. (beginning-of-line 2)
  6114. (while (and (not (eobp)) ;This is like `next-line'.
  6115. (get-char-property (1- (point)) 'invisible))
  6116. (goto-char (next-single-char-property-change (point) 'invisible))
  6117. (and (eolp) (beginning-of-line 2)))
  6118. (setq eol (point)))
  6119. ;; Find out what to do next and set `this-command'
  6120. (cond
  6121. ((= eos eoh)
  6122. ;; Nothing is hidden behind this heading
  6123. (unless (org-before-first-heading-p)
  6124. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6125. (org-unlogged-message "EMPTY ENTRY")
  6126. (setq org-cycle-subtree-status nil)
  6127. (save-excursion
  6128. (goto-char eos)
  6129. (outline-next-heading)
  6130. (when (outline-invisible-p) (org-flag-heading nil))))
  6131. ((and (or (>= eol eos)
  6132. (not (string-match "\\S-" (buffer-substring eol eos))))
  6133. (or has-children
  6134. (not (setq children-skipped
  6135. org-cycle-skip-children-state-if-no-children))))
  6136. ;; Entire subtree is hidden in one line: children view
  6137. (unless (org-before-first-heading-p)
  6138. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6139. (if (org-at-item-p)
  6140. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6141. (org-show-entry)
  6142. (org-with-limited-levels (org-show-children))
  6143. ;; FIXME: This slows down the func way too much.
  6144. ;; How keep drawers hidden in subtree anyway?
  6145. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6146. ;; (org-cycle-hide-drawers 'subtree))
  6147. ;; Fold every list in subtree to top-level items.
  6148. (when (eq org-cycle-include-plain-lists 'integrate)
  6149. (save-excursion
  6150. (org-back-to-heading)
  6151. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6152. (beginning-of-line 1)
  6153. (let* ((struct (org-list-struct))
  6154. (prevs (org-list-prevs-alist struct))
  6155. (end (org-list-get-bottom-point struct)))
  6156. (dolist (e (org-list-get-all-items (point) struct prevs))
  6157. (org-list-set-item-visibility e struct 'folded))
  6158. (goto-char (if (< end eos) end eos)))))))
  6159. (org-unlogged-message "CHILDREN")
  6160. (save-excursion
  6161. (goto-char eos)
  6162. (outline-next-heading)
  6163. (when (outline-invisible-p) (org-flag-heading nil)))
  6164. (setq org-cycle-subtree-status 'children)
  6165. (unless (org-before-first-heading-p)
  6166. (run-hook-with-args 'org-cycle-hook 'children)))
  6167. ((or children-skipped
  6168. (and (eq last-command this-command)
  6169. (eq org-cycle-subtree-status 'children)))
  6170. ;; We just showed the children, or no children are there,
  6171. ;; now show everything.
  6172. (unless (org-before-first-heading-p)
  6173. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6174. (outline-flag-region eoh eos nil)
  6175. (org-unlogged-message
  6176. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6177. (setq org-cycle-subtree-status 'subtree)
  6178. (unless (org-before-first-heading-p)
  6179. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6180. (t
  6181. ;; Default action: hide the subtree.
  6182. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6183. (outline-flag-region eoh eos t)
  6184. (org-unlogged-message "FOLDED")
  6185. (setq org-cycle-subtree-status 'folded)
  6186. (unless (org-before-first-heading-p)
  6187. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6188. ;;;###autoload
  6189. (defun org-global-cycle (&optional arg)
  6190. "Cycle the global visibility. For details see `org-cycle'.
  6191. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6192. With a numeric prefix, show all headlines up to that level."
  6193. (interactive "P")
  6194. (let ((org-cycle-include-plain-lists
  6195. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6196. (cond
  6197. ((integerp arg)
  6198. (outline-show-all)
  6199. (outline-hide-sublevels arg)
  6200. (setq org-cycle-global-status 'contents))
  6201. ((equal arg '(4))
  6202. (org-set-startup-visibility)
  6203. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6204. (t
  6205. (org-cycle '(4))))))
  6206. (defun org-set-startup-visibility ()
  6207. "Set the visibility required by startup options and properties."
  6208. (cond
  6209. ((eq org-startup-folded t)
  6210. (org-overview))
  6211. ((eq org-startup-folded 'content)
  6212. (org-content))
  6213. ((or (eq org-startup-folded 'showeverything)
  6214. (eq org-startup-folded nil))
  6215. (outline-show-all)))
  6216. (unless (eq org-startup-folded 'showeverything)
  6217. (when org-hide-block-startup (org-hide-block-all))
  6218. (org-set-visibility-according-to-property 'no-cleanup)
  6219. (org-cycle-hide-archived-subtrees 'all)
  6220. (org-cycle-hide-drawers 'all)
  6221. (org-cycle-show-empty-lines t)))
  6222. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6223. "Switch subtree visibilities according to :VISIBILITY: property."
  6224. (interactive)
  6225. (org-with-wide-buffer
  6226. (goto-char (point-min))
  6227. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6228. (if (not (org-at-property-p)) (outline-next-heading)
  6229. (let ((state (match-string 3)))
  6230. (save-excursion
  6231. (org-back-to-heading t)
  6232. (outline-hide-subtree)
  6233. (org-reveal)
  6234. (cond
  6235. ((equal state "folded")
  6236. (outline-hide-subtree))
  6237. ((equal state "children")
  6238. (org-show-hidden-entry)
  6239. (org-show-children))
  6240. ((equal state "content")
  6241. (save-excursion
  6242. (save-restriction
  6243. (org-narrow-to-subtree)
  6244. (org-content))))
  6245. ((member state '("all" "showall"))
  6246. (outline-show-subtree)))))))
  6247. (unless no-cleanup
  6248. (org-cycle-hide-archived-subtrees 'all)
  6249. (org-cycle-hide-drawers 'all)
  6250. (org-cycle-show-empty-lines 'all))))
  6251. ;; This function uses outline-regexp instead of the more fundamental
  6252. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6253. ;; buffers, where outline-regexp is needed.
  6254. (defun org-overview ()
  6255. "Switch to overview mode, showing only top-level headlines.
  6256. This shows all headlines with a level equal or greater than the level
  6257. of the first headline in the buffer. This is important, because if the
  6258. first headline is not level one, then (hide-sublevels 1) gives confusing
  6259. results."
  6260. (interactive)
  6261. (save-excursion
  6262. (let ((level
  6263. (save-excursion
  6264. (goto-char (point-min))
  6265. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6266. (goto-char (match-beginning 0))
  6267. (funcall outline-level)))))
  6268. (and level (outline-hide-sublevels level)))))
  6269. (defun org-content (&optional arg)
  6270. "Show all headlines in the buffer, like a table of contents.
  6271. With numerical argument N, show content up to level N."
  6272. (interactive "P")
  6273. (org-overview)
  6274. (save-excursion
  6275. ;; Visit all headings and show their offspring
  6276. (and (integerp arg) (org-overview))
  6277. (goto-char (point-max))
  6278. (catch 'exit
  6279. (while (and (progn (condition-case nil
  6280. (outline-previous-visible-heading 1)
  6281. (error (goto-char (point-min))))
  6282. t)
  6283. (looking-at org-outline-regexp))
  6284. (if (integerp arg)
  6285. (org-show-children (1- arg))
  6286. (outline-show-branches))
  6287. (when (bobp) (throw 'exit nil))))))
  6288. (defun org-optimize-window-after-visibility-change (state)
  6289. "Adjust the window after a change in outline visibility.
  6290. This function is the default value of the hook `org-cycle-hook'."
  6291. (when (get-buffer-window (current-buffer))
  6292. (cond
  6293. ((eq state 'content) nil)
  6294. ((eq state 'all) nil)
  6295. ((eq state 'folded) nil)
  6296. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6297. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6298. (defun org-remove-empty-overlays-at (pos)
  6299. "Remove outline overlays that do not contain non-white stuff."
  6300. (dolist (o (overlays-at pos))
  6301. (and (eq 'outline (overlay-get o 'invisible))
  6302. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6303. (overlay-end o))))
  6304. (delete-overlay o))))
  6305. (defun org-clean-visibility-after-subtree-move ()
  6306. "Fix visibility issues after moving a subtree."
  6307. ;; First, find a reasonable region to look at:
  6308. ;; Start two siblings above, end three below
  6309. (let* ((beg (save-excursion
  6310. (and (org-get-last-sibling)
  6311. (org-get-last-sibling))
  6312. (point)))
  6313. (end (save-excursion
  6314. (and (org-get-next-sibling)
  6315. (org-get-next-sibling)
  6316. (org-get-next-sibling))
  6317. (if (org-at-heading-p)
  6318. (point-at-eol)
  6319. (point))))
  6320. (level (looking-at "\\*+"))
  6321. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6322. (save-excursion
  6323. (save-restriction
  6324. (narrow-to-region beg end)
  6325. (when re
  6326. ;; Properly fold already folded siblings
  6327. (goto-char (point-min))
  6328. (while (re-search-forward re nil t)
  6329. (when (and (not (outline-invisible-p))
  6330. (save-excursion
  6331. (goto-char (point-at-eol)) (outline-invisible-p)))
  6332. (outline-hide-entry))))
  6333. (org-cycle-show-empty-lines 'overview)
  6334. (org-cycle-hide-drawers 'overview)))))
  6335. (defun org-cycle-show-empty-lines (state)
  6336. "Show empty lines above all visible headlines.
  6337. The region to be covered depends on STATE when called through
  6338. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6339. entire buffer covered. Note that an empty line is only shown if there
  6340. are at least `org-cycle-separator-lines' empty lines before the headline."
  6341. (when (/= org-cycle-separator-lines 0)
  6342. (save-excursion
  6343. (let* ((n (abs org-cycle-separator-lines))
  6344. (re (cond
  6345. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6346. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6347. (t (let ((ns (number-to-string (- n 2))))
  6348. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6349. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6350. beg end)
  6351. (cond
  6352. ((memq state '(overview contents t))
  6353. (setq beg (point-min) end (point-max)))
  6354. ((memq state '(children folded))
  6355. (setq beg (point)
  6356. end (progn (org-end-of-subtree t t)
  6357. (line-beginning-position 2)))))
  6358. (when beg
  6359. (goto-char beg)
  6360. (while (re-search-forward re end t)
  6361. (unless (get-char-property (match-end 1) 'invisible)
  6362. (let ((e (match-end 1))
  6363. (b (if (>= org-cycle-separator-lines 0)
  6364. (match-beginning 1)
  6365. (save-excursion
  6366. (goto-char (match-beginning 0))
  6367. (skip-chars-backward " \t\n")
  6368. (line-end-position)))))
  6369. (outline-flag-region b e nil))))))))
  6370. ;; Never hide empty lines at the end of the file.
  6371. (save-excursion
  6372. (goto-char (point-max))
  6373. (outline-previous-heading)
  6374. (outline-end-of-heading)
  6375. (when (and (looking-at "[ \t\n]+")
  6376. (= (match-end 0) (point-max)))
  6377. (outline-flag-region (point) (match-end 0) nil))))
  6378. (defun org-show-empty-lines-in-parent ()
  6379. "Move to the parent and re-show empty lines before visible headlines."
  6380. (save-excursion
  6381. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6382. (org-cycle-show-empty-lines context))))
  6383. (defun org-files-list ()
  6384. "Return `org-agenda-files' list, plus all open Org files.
  6385. This is useful for operations that need to scan all of a user's
  6386. open and agenda-wise Org files."
  6387. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6388. (dolist (buf (buffer-list))
  6389. (with-current-buffer buf
  6390. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6391. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6392. files))
  6393. (defsubst org-entry-beginning-position ()
  6394. "Return the beginning position of the current entry."
  6395. (save-excursion (org-back-to-heading t) (point)))
  6396. (defsubst org-entry-end-position ()
  6397. "Return the end position of the current entry."
  6398. (save-excursion (outline-next-heading) (point)))
  6399. (defun org-cycle-hide-drawers (state &optional exceptions)
  6400. "Re-hide all drawers after a visibility state change.
  6401. When non-nil, optional argument EXCEPTIONS is a list of strings
  6402. specifying which drawers should not be hidden."
  6403. (when (and (derived-mode-p 'org-mode)
  6404. (not (memq state '(overview folded contents))))
  6405. (save-excursion
  6406. (let* ((globalp (memq state '(contents all)))
  6407. (beg (if globalp (point-min) (point)))
  6408. (end (if globalp (point-max)
  6409. (if (eq state 'children)
  6410. (save-excursion (outline-next-heading) (point))
  6411. (org-end-of-subtree t)))))
  6412. (goto-char beg)
  6413. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6414. (unless (member-ignore-case (match-string 1) exceptions)
  6415. (let ((drawer (org-element-at-point)))
  6416. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6417. (org-flag-drawer t drawer)
  6418. ;; Make sure to skip drawer entirely or we might flag
  6419. ;; it another time when matching its ending line with
  6420. ;; `org-drawer-regexp'.
  6421. (goto-char (org-element-property :end drawer))))))))))
  6422. (defun org-flag-drawer (flag &optional element)
  6423. "When FLAG is non-nil, hide the drawer we are at.
  6424. Otherwise make it visible. When optional argument ELEMENT is
  6425. a parsed drawer, as returned by `org-element-at-point', hide or
  6426. show that drawer instead."
  6427. (let ((drawer (or element
  6428. (and (save-excursion
  6429. (beginning-of-line)
  6430. (looking-at-p org-drawer-regexp))
  6431. (org-element-at-point)))))
  6432. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6433. (let ((post (org-element-property :post-affiliated drawer)))
  6434. (save-excursion
  6435. (outline-flag-region
  6436. (progn (goto-char post) (line-end-position))
  6437. (progn (goto-char (org-element-property :end drawer))
  6438. (skip-chars-backward " \r\t\n")
  6439. (line-end-position))
  6440. flag))
  6441. ;; When the drawer is hidden away, make sure point lies in
  6442. ;; a visible part of the buffer.
  6443. (when (and flag (> (line-beginning-position) post))
  6444. (goto-char post))))))
  6445. (defun org-subtree-end-visible-p ()
  6446. "Is the end of the current subtree visible?"
  6447. (pos-visible-in-window-p
  6448. (save-excursion (org-end-of-subtree t) (point))))
  6449. (defun org-first-headline-recenter ()
  6450. "Move cursor to the first headline and recenter the headline."
  6451. (let ((window (get-buffer-window)))
  6452. (when window
  6453. (goto-char (point-min))
  6454. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6455. (set-window-start window (line-beginning-position))))))
  6456. ;;; Saving and restoring visibility
  6457. (defun org-outline-overlay-data (&optional use-markers)
  6458. "Return a list of the locations of all outline overlays.
  6459. These are overlays with the `invisible' property value `outline'.
  6460. The return value is a list of cons cells, with start and stop
  6461. positions for each overlay.
  6462. If USE-MARKERS is set, return the positions as markers."
  6463. (let (beg end)
  6464. (org-with-wide-buffer
  6465. (delq nil
  6466. (mapcar (lambda (o)
  6467. (when (eq (overlay-get o 'invisible) 'outline)
  6468. (setq beg (overlay-start o)
  6469. end (overlay-end o))
  6470. (and beg end (> end beg)
  6471. (if use-markers
  6472. (cons (copy-marker beg)
  6473. (copy-marker end t))
  6474. (cons beg end)))))
  6475. (overlays-in (point-min) (point-max)))))))
  6476. (defun org-set-outline-overlay-data (data)
  6477. "Create visibility overlays for all positions in DATA.
  6478. DATA should have been made by `org-outline-overlay-data'."
  6479. (org-with-wide-buffer
  6480. (outline-show-all)
  6481. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6482. ;;; Folding of blocks
  6483. (defvar-local org-hide-block-overlays nil
  6484. "Overlays hiding blocks.")
  6485. (defun org-block-map (function &optional start end)
  6486. "Call FUNCTION at the head of all source blocks in the current buffer.
  6487. Optional arguments START and END can be used to limit the range."
  6488. (let ((start (or start (point-min)))
  6489. (end (or end (point-max))))
  6490. (save-excursion
  6491. (goto-char start)
  6492. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6493. (save-excursion
  6494. (save-match-data
  6495. (goto-char (match-beginning 0))
  6496. (funcall function)))))))
  6497. (defun org-hide-block-toggle-all ()
  6498. "Toggle the visibility of all blocks in the current buffer."
  6499. (org-block-map 'org-hide-block-toggle))
  6500. (defun org-hide-block-all ()
  6501. "Fold all blocks in the current buffer."
  6502. (interactive)
  6503. (org-show-block-all)
  6504. (org-block-map 'org-hide-block-toggle-maybe))
  6505. (defun org-show-block-all ()
  6506. "Unfold all blocks in the current buffer."
  6507. (interactive)
  6508. (mapc #'delete-overlay org-hide-block-overlays)
  6509. (setq org-hide-block-overlays nil))
  6510. (defun org-hide-block-toggle-maybe ()
  6511. "Toggle visibility of block at point.
  6512. Unlike to `org-hide-block-toggle', this function does not throw
  6513. an error. Return a non-nil value when toggling is successful."
  6514. (interactive)
  6515. (ignore-errors (org-hide-block-toggle)))
  6516. (defun org-hide-block-toggle (&optional force)
  6517. "Toggle the visibility of the current block.
  6518. When optional argument FORCE is `off', make block visible. If it
  6519. is non-nil, hide it unconditionally. Throw an error when not at
  6520. a block. Return a non-nil value when toggling is successful."
  6521. (interactive)
  6522. (let ((element (org-element-at-point)))
  6523. (unless (memq (org-element-type element)
  6524. '(center-block comment-block dynamic-block example-block
  6525. export-block quote-block special-block
  6526. src-block verse-block))
  6527. (user-error "Not at a block"))
  6528. (let* ((start (save-excursion
  6529. (goto-char (org-element-property :post-affiliated element))
  6530. (line-end-position)))
  6531. (end (save-excursion
  6532. (goto-char (org-element-property :end element))
  6533. (skip-chars-backward " \r\t\n")
  6534. (line-end-position)))
  6535. (overlays (overlays-at start)))
  6536. (cond
  6537. ;; Do nothing when not before or at the block opening line or
  6538. ;; at the block closing line.
  6539. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6540. ((and (not (eq force 'off))
  6541. (not (memq t (mapcar
  6542. (lambda (o)
  6543. (eq (overlay-get o 'invisible) 'org-hide-block))
  6544. overlays))))
  6545. (let ((ov (make-overlay start end)))
  6546. (overlay-put ov 'invisible 'org-hide-block)
  6547. ;; Make the block accessible to `isearch'.
  6548. (overlay-put
  6549. ov 'isearch-open-invisible
  6550. (lambda (ov)
  6551. (when (memq ov org-hide-block-overlays)
  6552. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6553. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6554. (delete-overlay ov))))
  6555. (push ov org-hide-block-overlays)
  6556. ;; When the block is hidden away, make sure point is left in
  6557. ;; a visible part of the buffer.
  6558. (when (> (line-beginning-position) start)
  6559. (goto-char start)
  6560. (beginning-of-line))
  6561. ;; Signal successful toggling.
  6562. t))
  6563. ((or (not force) (eq force 'off))
  6564. (dolist (ov overlays t)
  6565. (when (memq ov org-hide-block-overlays)
  6566. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6567. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6568. (delete-overlay ov))))))))
  6569. ;; Remove overlays when changing major mode
  6570. (add-hook 'org-mode-hook
  6571. (lambda () (add-hook 'change-major-mode-hook
  6572. 'org-show-block-all 'append 'local)))
  6573. ;;; Org-goto
  6574. (defvar org-goto-window-configuration nil)
  6575. (defvar org-goto-marker nil)
  6576. (defvar org-goto-map)
  6577. (defun org-goto-map ()
  6578. "Set the keymap `org-goto'."
  6579. (setq org-goto-map
  6580. (let ((map (make-sparse-keymap)))
  6581. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6582. mouse-drag-region universal-argument org-occur)))
  6583. (dolist (cmd cmds)
  6584. (substitute-key-definition cmd cmd map global-map)))
  6585. (suppress-keymap map)
  6586. (org-defkey map "\C-m" 'org-goto-ret)
  6587. (org-defkey map [(return)] 'org-goto-ret)
  6588. (org-defkey map [(left)] 'org-goto-left)
  6589. (org-defkey map [(right)] 'org-goto-right)
  6590. (org-defkey map [(control ?g)] 'org-goto-quit)
  6591. (org-defkey map "\C-i" 'org-cycle)
  6592. (org-defkey map [(tab)] 'org-cycle)
  6593. (org-defkey map [(down)] 'outline-next-visible-heading)
  6594. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6595. (if org-goto-auto-isearch
  6596. (if (fboundp 'define-key-after)
  6597. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6598. nil)
  6599. (org-defkey map "q" 'org-goto-quit)
  6600. (org-defkey map "n" 'outline-next-visible-heading)
  6601. (org-defkey map "p" 'outline-previous-visible-heading)
  6602. (org-defkey map "f" 'outline-forward-same-level)
  6603. (org-defkey map "b" 'outline-backward-same-level)
  6604. (org-defkey map "u" 'outline-up-heading))
  6605. (org-defkey map "/" 'org-occur)
  6606. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6607. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6608. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6609. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6610. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6611. map)))
  6612. (defconst org-goto-help
  6613. "Browse buffer copy, to find location or copy text.%s
  6614. RET=jump to location C-g=quit and return to previous location
  6615. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6616. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6617. (defun org-goto (&optional alternative-interface)
  6618. "Look up a different location in the current file, keeping current visibility.
  6619. When you want look-up or go to a different location in a
  6620. document, the fastest way is often to fold the entire buffer and
  6621. then dive into the tree. This method has the disadvantage, that
  6622. the previous location will be folded, which may not be what you
  6623. want.
  6624. This command works around this by showing a copy of the current
  6625. buffer in an indirect buffer, in overview mode. You can dive
  6626. into the tree in that copy, use org-occur and incremental search
  6627. to find a location. When pressing RET or `Q', the command
  6628. returns to the original buffer in which the visibility is still
  6629. unchanged. After RET it will also jump to the location selected
  6630. in the indirect buffer and expose the headline hierarchy above.
  6631. With a prefix argument, use the alternative interface: e.g., if
  6632. `org-goto-interface' is `outline' use `outline-path-completion'."
  6633. (interactive "P")
  6634. (org-goto-map)
  6635. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6636. (org-refile-use-outline-path t)
  6637. (org-refile-target-verify-function nil)
  6638. (interface
  6639. (if (not alternative-interface)
  6640. org-goto-interface
  6641. (if (eq org-goto-interface 'outline)
  6642. 'outline-path-completion
  6643. 'outline)))
  6644. (org-goto-start-pos (point))
  6645. (selected-point
  6646. (if (eq interface 'outline)
  6647. (car (org-get-location (current-buffer) org-goto-help))
  6648. (let ((pa (org-refile-get-location "Goto")))
  6649. (org-refile-check-position pa)
  6650. (nth 3 pa)))))
  6651. (if selected-point
  6652. (progn
  6653. (org-mark-ring-push org-goto-start-pos)
  6654. (goto-char selected-point)
  6655. (when (or (outline-invisible-p) (org-invisible-p2))
  6656. (org-show-context 'org-goto)))
  6657. (message "Quit"))))
  6658. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6659. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6660. (defvar org-goto-local-auto-isearch-map) ; defined below
  6661. (defun org-get-location (_buf help)
  6662. "Let the user select a location in current buffer.
  6663. This function uses a recursive edit. It returns the selected position
  6664. or nil."
  6665. (org-no-popups
  6666. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6667. (isearch-hide-immediately nil)
  6668. (isearch-search-fun-function
  6669. (lambda () 'org-goto-local-search-headings))
  6670. (org-goto-selected-point org-goto-exit-command))
  6671. (save-excursion
  6672. (save-window-excursion
  6673. (delete-other-windows)
  6674. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6675. (pop-to-buffer-same-window
  6676. (condition-case nil
  6677. (make-indirect-buffer (current-buffer) "*org-goto*")
  6678. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6679. (with-output-to-temp-buffer "*Org Help*"
  6680. (princ (format help (if org-goto-auto-isearch
  6681. " Just type for auto-isearch."
  6682. " n/p/f/b/u to navigate, q to quit."))))
  6683. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6684. (setq buffer-read-only nil)
  6685. (let ((org-startup-truncated t)
  6686. (org-startup-folded nil)
  6687. (org-startup-align-all-tables nil))
  6688. (org-mode)
  6689. (org-overview))
  6690. (setq buffer-read-only t)
  6691. (if (and (boundp 'org-goto-start-pos)
  6692. (integer-or-marker-p org-goto-start-pos))
  6693. (progn (goto-char org-goto-start-pos)
  6694. (when (outline-invisible-p)
  6695. (org-show-set-visibility 'lineage)))
  6696. (goto-char (point-min)))
  6697. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6698. (message "Select location and press RET")
  6699. (use-local-map org-goto-map)
  6700. (recursive-edit)))
  6701. (kill-buffer "*org-goto*")
  6702. (cons org-goto-selected-point org-goto-exit-command))))
  6703. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6704. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6705. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6706. (if (fboundp 'isearch-other-control-char)
  6707. (progn
  6708. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6709. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6710. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6711. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6712. (define-key org-goto-local-auto-isearch-map [return] nil))
  6713. (defun org-goto-local-search-headings (string bound noerror)
  6714. "Search and make sure that any matches are in headlines."
  6715. (catch 'return
  6716. (while (if isearch-forward
  6717. (search-forward string bound noerror)
  6718. (search-backward string bound noerror))
  6719. (when (save-match-data
  6720. (and (save-excursion
  6721. (beginning-of-line)
  6722. (looking-at org-complex-heading-regexp))
  6723. (or (not (match-beginning 5))
  6724. (< (point) (match-beginning 5)))))
  6725. (throw 'return (point))))))
  6726. (defun org-goto-local-auto-isearch ()
  6727. "Start isearch."
  6728. (interactive)
  6729. (goto-char (point-min))
  6730. (let ((keys (this-command-keys)))
  6731. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6732. (isearch-mode t)
  6733. (isearch-process-search-char (string-to-char keys)))))
  6734. (defun org-goto-ret (&optional _arg)
  6735. "Finish `org-goto' by going to the new location."
  6736. (interactive "P")
  6737. (setq org-goto-selected-point (point))
  6738. (setq org-goto-exit-command 'return)
  6739. (throw 'exit nil))
  6740. (defun org-goto-left ()
  6741. "Finish `org-goto' by going to the new location."
  6742. (interactive)
  6743. (if (org-at-heading-p)
  6744. (progn
  6745. (beginning-of-line 1)
  6746. (setq org-goto-selected-point (point)
  6747. org-goto-exit-command 'left)
  6748. (throw 'exit nil))
  6749. (user-error "Not on a heading")))
  6750. (defun org-goto-right ()
  6751. "Finish `org-goto' by going to the new location."
  6752. (interactive)
  6753. (if (org-at-heading-p)
  6754. (progn
  6755. (setq org-goto-selected-point (point)
  6756. org-goto-exit-command 'right)
  6757. (throw 'exit nil))
  6758. (user-error "Not on a heading")))
  6759. (defun org-goto-quit ()
  6760. "Finish `org-goto' without cursor motion."
  6761. (interactive)
  6762. (setq org-goto-selected-point nil)
  6763. (setq org-goto-exit-command 'quit)
  6764. (throw 'exit nil))
  6765. ;;; Indirect buffer display of subtrees
  6766. (defvar org-indirect-dedicated-frame nil
  6767. "This is the frame being used for indirect tree display.")
  6768. (defvar org-last-indirect-buffer nil)
  6769. (defun org-tree-to-indirect-buffer (&optional arg)
  6770. "Create indirect buffer and narrow it to current subtree.
  6771. With a numerical prefix ARG, go up to this level and then take that tree.
  6772. If ARG is negative, go up that many levels.
  6773. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6774. indirect buffer previously made with this command, to avoid proliferation of
  6775. indirect buffers. However, when you call the command with a \
  6776. `\\[universal-argument]' prefix, or
  6777. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6778. so that you can work with several indirect buffers at the same time. If
  6779. `org-indirect-buffer-display' is `dedicated-frame', the \
  6780. `\\[universal-argument]' prefix also
  6781. requests that a new frame be made for the new buffer, so that the dedicated
  6782. frame is not changed."
  6783. (interactive "P")
  6784. (let ((cbuf (current-buffer))
  6785. (cwin (selected-window))
  6786. (pos (point))
  6787. beg end level heading ibuf)
  6788. (save-excursion
  6789. (org-back-to-heading t)
  6790. (when (numberp arg)
  6791. (setq level (org-outline-level))
  6792. (when (< arg 0) (setq arg (+ level arg)))
  6793. (while (> (setq level (org-outline-level)) arg)
  6794. (org-up-heading-safe)))
  6795. (setq beg (point)
  6796. heading (org-get-heading 'no-tags))
  6797. (org-end-of-subtree t t)
  6798. (when (org-at-heading-p) (backward-char 1))
  6799. (setq end (point)))
  6800. (when (and (buffer-live-p org-last-indirect-buffer)
  6801. (not (eq org-indirect-buffer-display 'new-frame))
  6802. (not arg))
  6803. (kill-buffer org-last-indirect-buffer))
  6804. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6805. org-last-indirect-buffer ibuf)
  6806. (cond
  6807. ((or (eq org-indirect-buffer-display 'new-frame)
  6808. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6809. (select-frame (make-frame))
  6810. (delete-other-windows)
  6811. (pop-to-buffer-same-window ibuf)
  6812. (org-set-frame-title heading))
  6813. ((eq org-indirect-buffer-display 'dedicated-frame)
  6814. (raise-frame
  6815. (select-frame (or (and org-indirect-dedicated-frame
  6816. (frame-live-p org-indirect-dedicated-frame)
  6817. org-indirect-dedicated-frame)
  6818. (setq org-indirect-dedicated-frame (make-frame)))))
  6819. (delete-other-windows)
  6820. (pop-to-buffer-same-window ibuf)
  6821. (org-set-frame-title (concat "Indirect: " heading)))
  6822. ((eq org-indirect-buffer-display 'current-window)
  6823. (pop-to-buffer-same-window ibuf))
  6824. ((eq org-indirect-buffer-display 'other-window)
  6825. (pop-to-buffer ibuf))
  6826. (t (error "Invalid value")))
  6827. (narrow-to-region beg end)
  6828. (outline-show-all)
  6829. (goto-char pos)
  6830. (run-hook-with-args 'org-cycle-hook 'all)
  6831. (and (window-live-p cwin) (select-window cwin))))
  6832. (defun org-get-indirect-buffer (&optional buffer heading)
  6833. (setq buffer (or buffer (current-buffer)))
  6834. (let ((n 1) (base (buffer-name buffer)) bname)
  6835. (while (buffer-live-p
  6836. (get-buffer
  6837. (setq bname
  6838. (concat base "-"
  6839. (if heading (concat heading "-" (number-to-string n))
  6840. (number-to-string n))))))
  6841. (setq n (1+ n)))
  6842. (condition-case nil
  6843. (make-indirect-buffer buffer bname 'clone)
  6844. (error (make-indirect-buffer buffer bname)))))
  6845. (defun org-set-frame-title (title)
  6846. "Set the title of the current frame to the string TITLE."
  6847. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6848. ;;;; Structure editing
  6849. ;;; Inserting headlines
  6850. (defun org--line-empty-p (n)
  6851. "Is the Nth next line empty?
  6852. Counts the current line as N = 1 and the previous line as N = 0;
  6853. see `beginning-of-line'."
  6854. (save-excursion
  6855. (and (not (bobp))
  6856. (or (beginning-of-line n) t)
  6857. (save-match-data
  6858. (looking-at "[ \t]*$")))))
  6859. (defun org-previous-line-empty-p ()
  6860. "Is the previous line a blank line?
  6861. When NEXT is non-nil, check the next line instead."
  6862. (org--line-empty-p 0))
  6863. (defun org-next-line-empty-p ()
  6864. "Is the previous line a blank line?
  6865. When NEXT is non-nil, check the next line instead."
  6866. (org--line-empty-p 2))
  6867. (defun org--blank-before-heading-p (&optional parent)
  6868. "Non-nil when an empty line should precede a new heading here.
  6869. When optional argument PARENT is non-nil, consider parent
  6870. headline instead of current one."
  6871. (pcase (assq 'heading org-blank-before-new-entry)
  6872. (`(heading . auto)
  6873. (save-excursion
  6874. (org-with-limited-levels
  6875. (unless (and (org-before-first-heading-p)
  6876. (not (outline-next-heading)))
  6877. (org-back-to-heading t)
  6878. (when parent (org-up-heading-safe))
  6879. (cond ((not (bobp))
  6880. (org-previous-line-empty-p))
  6881. ((outline-next-heading)
  6882. (org-previous-line-empty-p))
  6883. ;; Ignore trailing spaces on last buffer line.
  6884. ((progn (skip-chars-backward " \t") (bolp))
  6885. (org-previous-line-empty-p))
  6886. (t nil))))))
  6887. (`(heading . ,value) value)
  6888. (_ nil)))
  6889. (defun org-insert-heading (&optional arg invisible-ok top)
  6890. "Insert a new heading or an item with the same depth at point.
  6891. If point is at the beginning of a heading, insert a new heading
  6892. or a new headline above the current one. When at the beginning
  6893. of a regular line of text, turn it into a heading.
  6894. If point is in the middle of a line, split it and create a new
  6895. headline with the text in the current line after point (see
  6896. `org-M-RET-may-split-line' on how to modify this behavior). As
  6897. a special case, on a headline, splitting can only happen on the
  6898. title itself. E.g., this excludes breaking stars or tags.
  6899. With a `\\[universal-argument]' prefix, set \
  6900. `org-insert-heading-respect-content' to
  6901. a non-nil value for the duration of the command. This forces the
  6902. insertion of a heading after the current subtree, independently
  6903. on the location of point.
  6904. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6905. insert the heading at the end of the tree
  6906. above the current heading. For example, if point is within a
  6907. 2nd-level heading, then it will insert a 2nd-level heading at
  6908. the end of the 1st-level parent subtree.
  6909. When INVISIBLE-OK is set, stop at invisible headlines when going
  6910. back. This is important for non-interactive uses of the
  6911. command.
  6912. When optional argument TOP is non-nil, insert a level 1 heading,
  6913. unconditionally."
  6914. (interactive "P")
  6915. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6916. (level (org-current-level))
  6917. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6918. (cond
  6919. ((or org-insert-heading-respect-content
  6920. (member arg '((4) (16)))
  6921. (and (not invisible-ok)
  6922. (invisible-p (max (1- (point)) (point-min)))))
  6923. ;; Position point at the location of insertion.
  6924. (if (not level) ;before first headline
  6925. (org-with-limited-levels (outline-next-heading))
  6926. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6927. ;; is nil.
  6928. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6929. (cond ((equal arg '(16))
  6930. (org-up-heading-safe)
  6931. (org-end-of-subtree t t))
  6932. (t
  6933. (org-end-of-subtree t t))))
  6934. (unless (bolp) (insert "\n")) ;ensure final newline
  6935. (unless (and blank? (org-previous-line-empty-p))
  6936. (org-N-empty-lines-before-current (if blank? 1 0)))
  6937. (insert stars " \n")
  6938. (forward-char -1))
  6939. ;; At a headline...
  6940. ((org-at-heading-p)
  6941. (cond ((bolp)
  6942. (when blank? (save-excursion (insert "\n")))
  6943. (save-excursion (insert stars " \n"))
  6944. (unless (and blank? (org-previous-line-empty-p))
  6945. (org-N-empty-lines-before-current (if blank? 1 0)))
  6946. (end-of-line))
  6947. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6948. (org-match-line org-complex-heading-regexp)
  6949. (org-pos-in-match-range (point) 4))
  6950. ;; Grab the text that should moved to the new headline.
  6951. ;; Preserve tags.
  6952. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6953. (if (looking-at "[ \t]*$") (replace-match "")
  6954. (org-set-tags nil t))
  6955. (end-of-line)
  6956. (when blank? (insert "\n"))
  6957. (insert "\n" stars " ")
  6958. (when (org-string-nw-p split) (insert split))
  6959. (when (eobp) (save-excursion (insert "\n")))))
  6960. (t
  6961. (end-of-line)
  6962. (when blank? (insert "\n"))
  6963. (insert "\n" stars " ")
  6964. (when (eobp) (save-excursion (insert "\n"))))))
  6965. ;; On regular text, turn line into a headline or split, if
  6966. ;; appropriate.
  6967. ((bolp)
  6968. (insert stars " ")
  6969. (unless (and blank? (org-previous-line-empty-p))
  6970. (org-N-empty-lines-before-current (if blank? 1 0))))
  6971. (t
  6972. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6973. (end-of-line))
  6974. (insert "\n" stars " ")
  6975. (unless (and blank? (org-previous-line-empty-p))
  6976. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6977. (run-hooks 'org-insert-heading-hook))
  6978. (defun org-N-empty-lines-before-current (n)
  6979. "Make the number of empty lines before current exactly N.
  6980. So this will delete or add empty lines."
  6981. (let ((column (current-column))
  6982. (empty-lines (make-string n ?\n)))
  6983. (beginning-of-line)
  6984. (let ((p (point)))
  6985. (skip-chars-backward " \r\t\n")
  6986. (unless (bolp) (forward-line))
  6987. (delete-region (point) p))
  6988. (insert empty-lines)
  6989. (move-to-column column)))
  6990. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6991. "Return the heading of the current entry, without the stars.
  6992. When NO-TAGS is non-nil, don't include tags.
  6993. When NO-TODO is non-nil, don't include TODO keywords.
  6994. When NO-PRIORITY is non-nil, don't include priority cookie.
  6995. When NO-COMMENT is non-nil, don't include COMMENT string."
  6996. (save-excursion
  6997. (org-back-to-heading t)
  6998. (let ((case-fold-search nil))
  6999. (looking-at org-complex-heading-regexp)
  7000. (let ((todo (and (not no-todo) (match-string 2)))
  7001. (priority (and (not no-priority) (match-string 3)))
  7002. (headline (pcase (match-string 4)
  7003. (`nil "")
  7004. ((and (guard no-comment) h)
  7005. (replace-regexp-in-string
  7006. (eval-when-compile
  7007. (format "\\`%s[ \t]+" org-comment-string))
  7008. "" h))
  7009. (h h)))
  7010. (tags (and (not no-tags) (match-string 5))))
  7011. (mapconcat #'identity
  7012. (delq nil (list todo priority headline tags))
  7013. " ")))))
  7014. (defvar orgstruct-mode) ; defined below
  7015. (defun org-heading-components ()
  7016. "Return the components of the current heading.
  7017. This is a list with the following elements:
  7018. - the level as an integer
  7019. - the reduced level, different if `org-odd-levels-only' is set.
  7020. - the TODO keyword, or nil
  7021. - the priority character, like ?A, or nil if no priority is given
  7022. - the headline text itself, or the tags string if no headline text
  7023. - the tags string, or nil."
  7024. (save-excursion
  7025. (org-back-to-heading t)
  7026. (when (let (case-fold-search)
  7027. (looking-at
  7028. (if orgstruct-mode
  7029. org-heading-regexp
  7030. org-complex-heading-regexp)))
  7031. (if orgstruct-mode
  7032. (list (length (match-string 1))
  7033. (org-reduced-level (length (match-string 1)))
  7034. nil
  7035. nil
  7036. (match-string 2)
  7037. nil)
  7038. (list (length (match-string 1))
  7039. (org-reduced-level (length (match-string 1)))
  7040. (match-string-no-properties 2)
  7041. (and (match-end 3) (aref (match-string 3) 2))
  7042. (match-string-no-properties 4)
  7043. (match-string-no-properties 5))))))
  7044. (defun org-get-entry ()
  7045. "Get the entry text, after heading, entire subtree."
  7046. (save-excursion
  7047. (org-back-to-heading t)
  7048. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7049. (defun org-edit-headline (&optional heading)
  7050. "Edit the current headline.
  7051. Set it to HEADING when provided."
  7052. (interactive)
  7053. (org-with-wide-buffer
  7054. (org-back-to-heading t)
  7055. (let ((case-fold-search nil))
  7056. (when (looking-at org-complex-heading-regexp)
  7057. (let* ((old (match-string-no-properties 4))
  7058. (new (save-match-data
  7059. (org-trim (or heading (read-string "Edit: " old))))))
  7060. (unless (equal old new)
  7061. (if old (replace-match new t t nil 4)
  7062. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7063. (insert " " new))
  7064. (org-set-tags nil t)
  7065. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7066. (defun org-insert-heading-after-current ()
  7067. "Insert a new heading with same level as current, after current subtree."
  7068. (interactive)
  7069. (org-back-to-heading)
  7070. (org-insert-heading)
  7071. (org-move-subtree-down)
  7072. (end-of-line 1))
  7073. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7074. "Insert heading with `org-insert-heading-respect-content' set to t."
  7075. (interactive)
  7076. (org-insert-heading '(4) invisible-ok))
  7077. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7078. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7079. (interactive)
  7080. (org-insert-todo-heading force-state '(4)))
  7081. (defun org-insert-todo-heading (arg &optional force-heading)
  7082. "Insert a new heading with the same level and TODO state as current heading.
  7083. If the heading has no TODO state, or if the state is DONE, use
  7084. the first state (TODO by default). Also with one prefix arg,
  7085. force first state. With two prefix args, force inserting at the
  7086. end of the parent subtree.
  7087. When called at a plain list item, insert a new item with an
  7088. unchecked check box."
  7089. (interactive "P")
  7090. (when (or force-heading (not (org-insert-item 'checkbox)))
  7091. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7092. force-heading))
  7093. (save-excursion
  7094. (org-back-to-heading)
  7095. (outline-previous-heading)
  7096. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7097. (let* ((new-mark-x
  7098. (if (or (equal arg '(4))
  7099. (not (match-beginning 2))
  7100. (member (match-string 2) org-done-keywords))
  7101. (car org-todo-keywords-1)
  7102. (match-string 2)))
  7103. (new-mark
  7104. (or
  7105. (run-hook-with-args-until-success
  7106. 'org-todo-get-default-hook new-mark-x nil)
  7107. new-mark-x)))
  7108. (beginning-of-line 1)
  7109. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7110. (if org-treat-insert-todo-heading-as-state-change
  7111. (org-todo new-mark)
  7112. (insert new-mark " "))))
  7113. (when org-provide-todo-statistics
  7114. (org-update-parent-todo-statistics))))
  7115. (defun org-insert-subheading (arg)
  7116. "Insert a new subheading and demote it.
  7117. Works for outline headings and for plain lists alike."
  7118. (interactive "P")
  7119. (org-insert-heading arg)
  7120. (cond
  7121. ((org-at-heading-p) (org-do-demote))
  7122. ((org-at-item-p) (org-indent-item))))
  7123. (defun org-insert-todo-subheading (arg)
  7124. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7125. Works for outline headings and for plain lists alike."
  7126. (interactive "P")
  7127. (org-insert-todo-heading arg)
  7128. (cond
  7129. ((org-at-heading-p) (org-do-demote))
  7130. ((org-at-item-p) (org-indent-item))))
  7131. ;;; Promotion and Demotion
  7132. (defvar org-after-demote-entry-hook nil
  7133. "Hook run after an entry has been demoted.
  7134. The cursor will be at the beginning of the entry.
  7135. When a subtree is being demoted, the hook will be called for each node.")
  7136. (defvar org-after-promote-entry-hook nil
  7137. "Hook run after an entry has been promoted.
  7138. The cursor will be at the beginning of the entry.
  7139. When a subtree is being promoted, the hook will be called for each node.")
  7140. (defun org-promote-subtree ()
  7141. "Promote the entire subtree.
  7142. See also `org-promote'."
  7143. (interactive)
  7144. (save-excursion
  7145. (org-with-limited-levels (org-map-tree 'org-promote)))
  7146. (org-fix-position-after-promote))
  7147. (defun org-demote-subtree ()
  7148. "Demote the entire subtree.
  7149. See `org-demote' and `org-promote'."
  7150. (interactive)
  7151. (save-excursion
  7152. (org-with-limited-levels (org-map-tree 'org-demote)))
  7153. (org-fix-position-after-promote))
  7154. (defun org-do-promote ()
  7155. "Promote the current heading higher up the tree.
  7156. If the region is active in `transient-mark-mode', promote all
  7157. headings in the region."
  7158. (interactive)
  7159. (save-excursion
  7160. (if (org-region-active-p)
  7161. (org-map-region 'org-promote (region-beginning) (region-end))
  7162. (org-promote)))
  7163. (org-fix-position-after-promote))
  7164. (defun org-do-demote ()
  7165. "Demote the current heading lower down the tree.
  7166. If the region is active in `transient-mark-mode', demote all
  7167. headings in the region."
  7168. (interactive)
  7169. (save-excursion
  7170. (if (org-region-active-p)
  7171. (org-map-region 'org-demote (region-beginning) (region-end))
  7172. (org-demote)))
  7173. (org-fix-position-after-promote))
  7174. (defun org-fix-position-after-promote ()
  7175. "Fix cursor position and indentation after demoting/promoting."
  7176. (let ((pos (point)))
  7177. (when (save-excursion
  7178. (beginning-of-line)
  7179. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7180. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7181. (cond ((eobp) (insert " "))
  7182. ((eolp) (insert " "))
  7183. ((equal (char-after) ?\s) (forward-char 1))))))
  7184. (defun org-current-level ()
  7185. "Return the level of the current entry, or nil if before the first headline.
  7186. The level is the number of stars at the beginning of the
  7187. headline. Use `org-reduced-level' to remove the effect of
  7188. `org-odd-levels'. Unlike to `org-outline-level', this function
  7189. ignores inlinetasks."
  7190. (let ((level (org-with-limited-levels (org-outline-level))))
  7191. (and (> level 0) level)))
  7192. (defun org-get-previous-line-level ()
  7193. "Return the outline depth of the last headline before the current line.
  7194. Returns 0 for the first headline in the buffer, and nil if before the
  7195. first headline."
  7196. (and (org-current-level)
  7197. (or (and (/= (line-beginning-position) (point-min))
  7198. (save-excursion (beginning-of-line 0) (org-current-level)))
  7199. 0)))
  7200. (defun org-reduced-level (l)
  7201. "Compute the effective level of a heading.
  7202. This takes into account the setting of `org-odd-levels-only'."
  7203. (cond
  7204. ((zerop l) 0)
  7205. (org-odd-levels-only (1+ (floor (/ l 2))))
  7206. (t l)))
  7207. (defun org-level-increment ()
  7208. "Return the number of stars that will be added or removed at a
  7209. time to headlines when structure editing, based on the value of
  7210. `org-odd-levels-only'."
  7211. (if org-odd-levels-only 2 1))
  7212. (defun org-get-valid-level (level &optional change)
  7213. "Rectify a level change under the influence of `org-odd-levels-only'.
  7214. LEVEL is a current level, CHANGE is by how much the level should
  7215. be modified. Even if CHANGE is nil, LEVEL may be returned
  7216. modified because even level numbers will become the next higher
  7217. odd number. Returns values greater than 0."
  7218. (if org-odd-levels-only
  7219. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7220. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7221. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7222. (max 1 (+ level (or change 0)))))
  7223. (defun org-promote ()
  7224. "Promote the current heading higher up the tree."
  7225. (org-with-wide-buffer
  7226. (org-back-to-heading t)
  7227. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7228. after-change-functions))
  7229. (level (save-match-data (funcall outline-level)))
  7230. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7231. (diff (abs (- level (length up-head) -1))))
  7232. (cond
  7233. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7234. (replace-match "# " nil t))
  7235. ((= level 1)
  7236. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7237. (t (replace-match up-head nil t)))
  7238. (unless (= level 1)
  7239. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7240. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7241. (run-hooks 'org-after-promote-entry-hook))))
  7242. (defun org-demote ()
  7243. "Demote the current heading lower down the tree."
  7244. (org-with-wide-buffer
  7245. (org-back-to-heading t)
  7246. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7247. after-change-functions))
  7248. (level (save-match-data (funcall outline-level)))
  7249. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7250. (diff (abs (- level (length down-head) -1))))
  7251. (replace-match down-head nil t)
  7252. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7253. (when org-adapt-indentation (org-fixup-indentation diff))
  7254. (run-hooks 'org-after-demote-entry-hook))))
  7255. (defun org-cycle-level ()
  7256. "Cycle the level of an empty headline through possible states.
  7257. This goes first to child, then to parent, level, then up the hierarchy.
  7258. After top level, it switches back to sibling level."
  7259. (interactive)
  7260. (let ((org-adapt-indentation nil))
  7261. (when (org-point-at-end-of-empty-headline)
  7262. (setq this-command 'org-cycle-level) ; Only needed for caching
  7263. (let ((cur-level (org-current-level))
  7264. (prev-level (org-get-previous-line-level)))
  7265. (cond
  7266. ;; If first headline in file, promote to top-level.
  7267. ((= prev-level 0)
  7268. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7269. do (org-do-promote)))
  7270. ;; If same level as prev, demote one.
  7271. ((= prev-level cur-level)
  7272. (org-do-demote))
  7273. ;; If parent is top-level, promote to top level if not already.
  7274. ((= prev-level 1)
  7275. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7276. do (org-do-promote)))
  7277. ;; If top-level, return to prev-level.
  7278. ((= cur-level 1)
  7279. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7280. do (org-do-demote)))
  7281. ;; If less than prev-level, promote one.
  7282. ((< cur-level prev-level)
  7283. (org-do-promote))
  7284. ;; If deeper than prev-level, promote until higher than
  7285. ;; prev-level.
  7286. ((> cur-level prev-level)
  7287. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7288. do (org-do-promote))))
  7289. t))))
  7290. (defun org-map-tree (fun)
  7291. "Call FUN for every heading underneath the current one."
  7292. (org-back-to-heading t)
  7293. (let ((level (funcall outline-level)))
  7294. (save-excursion
  7295. (funcall fun)
  7296. (while (and (progn
  7297. (outline-next-heading)
  7298. (> (funcall outline-level) level))
  7299. (not (eobp)))
  7300. (funcall fun)))))
  7301. (defun org-map-region (fun beg end)
  7302. "Call FUN for every heading between BEG and END."
  7303. (let ((org-ignore-region t))
  7304. (save-excursion
  7305. (setq end (copy-marker end))
  7306. (goto-char beg)
  7307. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7308. (< (point) end))
  7309. (funcall fun))
  7310. (while (and (progn
  7311. (outline-next-heading)
  7312. (< (point) end))
  7313. (not (eobp)))
  7314. (funcall fun)))))
  7315. (defun org-fixup-indentation (diff)
  7316. "Change the indentation in the current entry by DIFF.
  7317. DIFF is an integer. Indentation is done according to the
  7318. following rules:
  7319. - Planning information and property drawers are always indented
  7320. according to the new level of the headline;
  7321. - Footnote definitions and their contents are ignored;
  7322. - Inlinetasks' boundaries are not shifted;
  7323. - Empty lines are ignored;
  7324. - Other lines' indentation are shifted by DIFF columns, unless
  7325. it would introduce a structural change in the document, in
  7326. which case no shifting is done at all.
  7327. Assume point is at a heading or an inlinetask beginning."
  7328. (org-with-wide-buffer
  7329. (narrow-to-region (line-beginning-position)
  7330. (save-excursion
  7331. (if (org-with-limited-levels (org-at-heading-p))
  7332. (org-with-limited-levels (outline-next-heading))
  7333. (org-inlinetask-goto-end))
  7334. (point)))
  7335. (forward-line)
  7336. ;; Indent properly planning info and property drawer.
  7337. (when (looking-at-p org-planning-line-re)
  7338. (org-indent-line)
  7339. (forward-line))
  7340. (when (looking-at org-property-drawer-re)
  7341. (goto-char (match-end 0))
  7342. (forward-line)
  7343. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7344. (catch 'no-shift
  7345. (when (zerop diff) (throw 'no-shift nil))
  7346. ;; If DIFF is negative, first check if a shift is possible at all
  7347. ;; (e.g., it doesn't break structure). This can only happen if
  7348. ;; some contents are not properly indented.
  7349. (let ((case-fold-search t))
  7350. (when (< diff 0)
  7351. (let ((diff (- diff))
  7352. (forbidden-re (concat org-outline-regexp
  7353. "\\|"
  7354. (substring org-footnote-definition-re 1))))
  7355. (save-excursion
  7356. (while (not (eobp))
  7357. (cond
  7358. ((looking-at-p "[ \t]*$") (forward-line))
  7359. ((and (looking-at-p org-footnote-definition-re)
  7360. (let ((e (org-element-at-point)))
  7361. (and (eq (org-element-type e) 'footnote-definition)
  7362. (goto-char (org-element-property :end e))))))
  7363. ((looking-at-p org-outline-regexp) (forward-line))
  7364. ;; Give up if shifting would move before column 0 or
  7365. ;; if it would introduce a headline or a footnote
  7366. ;; definition.
  7367. (t
  7368. (skip-chars-forward " \t")
  7369. (let ((ind (current-column)))
  7370. (when (or (< ind diff)
  7371. (and (= ind diff) (looking-at-p forbidden-re)))
  7372. (throw 'no-shift nil)))
  7373. ;; Ignore contents of example blocks and source
  7374. ;; blocks if their indentation is meant to be
  7375. ;; preserved. Jump to block's closing line.
  7376. (beginning-of-line)
  7377. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7378. (let ((e (org-element-at-point)))
  7379. (and (memq (org-element-type e)
  7380. '(example-block src-block))
  7381. (or org-src-preserve-indentation
  7382. (org-element-property :preserve-indent e))
  7383. (goto-char (org-element-property :end e))
  7384. (progn (skip-chars-backward " \r\t\n")
  7385. (beginning-of-line)
  7386. t))))
  7387. (forward-line))))))))
  7388. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7389. ;; by DIFF. Also skip contents of source or example blocks
  7390. ;; when indentation is meant to be preserved.
  7391. (while (not (eobp))
  7392. (cond
  7393. ((and (looking-at-p org-footnote-definition-re)
  7394. (let ((e (org-element-at-point)))
  7395. (and (eq (org-element-type e) 'footnote-definition)
  7396. (goto-char (org-element-property :end e))))))
  7397. ((looking-at-p org-outline-regexp) (forward-line))
  7398. ((looking-at-p "[ \t]*$") (forward-line))
  7399. (t
  7400. (indent-line-to (+ (org-get-indentation) diff))
  7401. (beginning-of-line)
  7402. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7403. (let ((e (org-element-at-point)))
  7404. (and (memq (org-element-type e)
  7405. '(example-block src-block))
  7406. (or org-src-preserve-indentation
  7407. (org-element-property :preserve-indent e))
  7408. (goto-char (org-element-property :end e))
  7409. (progn (skip-chars-backward " \r\t\n")
  7410. (beginning-of-line)
  7411. t))))
  7412. (forward-line)))))))))
  7413. (defun org-convert-to-odd-levels ()
  7414. "Convert an Org file with all levels allowed to one with odd levels.
  7415. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7416. level 5 etc."
  7417. (interactive)
  7418. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7419. (let ((outline-level 'org-outline-level)
  7420. (org-odd-levels-only nil) n)
  7421. (save-excursion
  7422. (goto-char (point-min))
  7423. (while (re-search-forward "^\\*\\*+ " nil t)
  7424. (setq n (- (length (match-string 0)) 2))
  7425. (while (>= (setq n (1- n)) 0)
  7426. (org-demote))
  7427. (end-of-line 1))))))
  7428. (defun org-convert-to-oddeven-levels ()
  7429. "Convert an Org file with only odd levels to one with odd/even levels.
  7430. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7431. file contains a section with an even level, conversion would
  7432. destroy the structure of the file. An error is signaled in this
  7433. case."
  7434. (interactive)
  7435. (goto-char (point-min))
  7436. ;; First check if there are no even levels
  7437. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7438. (org-show-set-visibility 'canonical)
  7439. (error "Not all levels are odd in this file. Conversion not possible"))
  7440. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7441. (let ((outline-regexp org-outline-regexp)
  7442. (outline-level 'org-outline-level)
  7443. (org-odd-levels-only nil) n)
  7444. (save-excursion
  7445. (goto-char (point-min))
  7446. (while (re-search-forward "^\\*\\*+ " nil t)
  7447. (setq n (/ (1- (length (match-string 0))) 2))
  7448. (while (>= (setq n (1- n)) 0)
  7449. (org-promote))
  7450. (end-of-line 1))))))
  7451. (defun org-tr-level (n)
  7452. "Make N odd if required."
  7453. (if org-odd-levels-only (1+ (/ n 2)) n))
  7454. ;;; Vertical tree motion, cutting and pasting of subtrees
  7455. (defun org-move-subtree-up (&optional arg)
  7456. "Move the current subtree up past ARG headlines of the same level."
  7457. (interactive "p")
  7458. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7459. (defun org-move-subtree-down (&optional arg)
  7460. "Move the current subtree down past ARG headlines of the same level."
  7461. (interactive "p")
  7462. (setq arg (prefix-numeric-value arg))
  7463. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7464. 'org-get-last-sibling))
  7465. (ins-point (make-marker))
  7466. (cnt (abs arg))
  7467. (col (current-column))
  7468. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7469. ;; Select the tree
  7470. (org-back-to-heading)
  7471. (setq beg0 (point))
  7472. (save-excursion
  7473. (setq ne-beg (org-back-over-empty-lines))
  7474. (setq beg (point)))
  7475. (save-match-data
  7476. (save-excursion (outline-end-of-heading)
  7477. (setq folded (outline-invisible-p)))
  7478. (progn (org-end-of-subtree nil t)
  7479. (unless (eobp) (backward-char))))
  7480. (outline-next-heading)
  7481. (setq ne-end (org-back-over-empty-lines))
  7482. (setq end (point))
  7483. (goto-char beg0)
  7484. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7485. ;; include less whitespace
  7486. (save-excursion
  7487. (goto-char beg)
  7488. (forward-line (- ne-beg ne-end))
  7489. (setq beg (point))))
  7490. ;; Find insertion point, with error handling
  7491. (while (> cnt 0)
  7492. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7493. (progn (goto-char beg0)
  7494. (user-error "Cannot move past superior level or buffer limit")))
  7495. (setq cnt (1- cnt)))
  7496. (when (> arg 0)
  7497. ;; Moving forward - still need to move over subtree
  7498. (org-end-of-subtree t t)
  7499. (save-excursion
  7500. (org-back-over-empty-lines)
  7501. (or (bolp) (newline))))
  7502. (setq ne-ins (org-back-over-empty-lines))
  7503. (move-marker ins-point (point))
  7504. (setq txt (buffer-substring beg end))
  7505. (org-save-markers-in-region beg end)
  7506. (delete-region beg end)
  7507. (org-remove-empty-overlays-at beg)
  7508. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7509. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7510. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7511. (let ((bbb (point)))
  7512. (insert-before-markers txt)
  7513. (org-reinstall-markers-in-region bbb)
  7514. (move-marker ins-point bbb))
  7515. (or (bolp) (insert "\n"))
  7516. (setq ins-end (point))
  7517. (goto-char ins-point)
  7518. (org-skip-whitespace)
  7519. (when (and (< arg 0)
  7520. (org-first-sibling-p)
  7521. (> ne-ins ne-beg))
  7522. ;; Move whitespace back to beginning
  7523. (save-excursion
  7524. (goto-char ins-end)
  7525. (let ((kill-whole-line t))
  7526. (kill-line (- ne-ins ne-beg)) (point)))
  7527. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7528. (move-marker ins-point nil)
  7529. (if folded
  7530. (outline-hide-subtree)
  7531. (org-show-entry)
  7532. (org-show-children)
  7533. (org-cycle-hide-drawers 'children))
  7534. (org-clean-visibility-after-subtree-move)
  7535. ;; move back to the initial column we were at
  7536. (move-to-column col)))
  7537. (defvar org-subtree-clip ""
  7538. "Clipboard for cut and paste of subtrees.
  7539. This is actually only a copy of the kill, because we use the normal kill
  7540. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7541. (defvar org-subtree-clip-folded nil
  7542. "Was the last copied subtree folded?
  7543. This is used to fold the tree back after pasting.")
  7544. (defun org-cut-subtree (&optional n)
  7545. "Cut the current subtree into the clipboard.
  7546. With prefix arg N, cut this many sequential subtrees.
  7547. This is a short-hand for marking the subtree and then cutting it."
  7548. (interactive "p")
  7549. (org-copy-subtree n 'cut))
  7550. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7551. "Copy the current subtree it in the clipboard.
  7552. With prefix arg N, copy this many sequential subtrees.
  7553. This is a short-hand for marking the subtree and then copying it.
  7554. If CUT is non-nil, actually cut the subtree.
  7555. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7556. of some markers in the region, even if CUT is non-nil. This is
  7557. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7558. (interactive "p")
  7559. (let (beg end folded (beg0 (point)))
  7560. (if (called-interactively-p 'any)
  7561. (org-back-to-heading nil) ; take what looks like a subtree
  7562. (org-back-to-heading t)) ; take what is really there
  7563. (setq beg (point))
  7564. (skip-chars-forward " \t\r\n")
  7565. (save-match-data
  7566. (if nosubtrees
  7567. (outline-next-heading)
  7568. (save-excursion (outline-end-of-heading)
  7569. (setq folded (outline-invisible-p)))
  7570. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7571. (org-end-of-subtree t t)))
  7572. ;; Include the end of an inlinetask
  7573. (when (and (featurep 'org-inlinetask)
  7574. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7575. "END[ \t]*$")))
  7576. (end-of-line))
  7577. (setq end (point))
  7578. (goto-char beg0)
  7579. (when (> end beg)
  7580. (setq org-subtree-clip-folded folded)
  7581. (when (or cut force-store-markers)
  7582. (org-save-markers-in-region beg end))
  7583. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7584. (setq org-subtree-clip (current-kill 0))
  7585. (message "%s: Subtree(s) with %d characters"
  7586. (if cut "Cut" "Copied")
  7587. (length org-subtree-clip)))))
  7588. (defun org-paste-subtree (&optional level tree for-yank remove)
  7589. "Paste the clipboard as a subtree, with modification of headline level.
  7590. The entire subtree is promoted or demoted in order to match a new headline
  7591. level.
  7592. If the cursor is at the beginning of a headline, the same level as
  7593. that headline is used to paste the tree.
  7594. If not, the new level is derived from the *visible* headings
  7595. before and after the insertion point, and taken to be the inferior headline
  7596. level of the two. So if the previous visible heading is level 3 and the
  7597. next is level 4 (or vice versa), level 4 will be used for insertion.
  7598. This makes sure that the subtree remains an independent subtree and does
  7599. not swallow low level entries.
  7600. You can also force a different level, either by using a numeric prefix
  7601. argument, or by inserting the heading marker by hand. For example, if the
  7602. cursor is after \"*****\", then the tree will be shifted to level 5.
  7603. If optional TREE is given, use this text instead of the kill ring.
  7604. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7605. move back over whitespace before inserting, and move point to the end of
  7606. the inserted text when done.
  7607. When REMOVE is non-nil, remove the subtree from the clipboard."
  7608. (interactive "P")
  7609. (setq tree (or tree (and kill-ring (current-kill 0))))
  7610. (unless (org-kill-is-subtree-p tree)
  7611. (user-error "%s"
  7612. (substitute-command-keys
  7613. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7614. (org-with-limited-levels
  7615. (let* ((visp (not (outline-invisible-p)))
  7616. (txt tree)
  7617. (^re_ "\\(\\*+\\)[ \t]*")
  7618. (old-level (if (string-match org-outline-regexp-bol txt)
  7619. (- (match-end 0) (match-beginning 0) 1)
  7620. -1))
  7621. (force-level (cond (level (prefix-numeric-value level))
  7622. ((and (looking-at "[ \t]*$")
  7623. (string-match
  7624. "^\\*+$" (buffer-substring
  7625. (point-at-bol) (point))))
  7626. (- (match-end 0) (match-beginning 0)))
  7627. ((and (bolp)
  7628. (looking-at org-outline-regexp))
  7629. (- (match-end 0) (point) 1))))
  7630. (previous-level (save-excursion
  7631. (condition-case nil
  7632. (progn
  7633. (outline-previous-visible-heading 1)
  7634. (if (looking-at ^re_)
  7635. (- (match-end 0) (match-beginning 0) 1)
  7636. 1))
  7637. (error 1))))
  7638. (next-level (save-excursion
  7639. (condition-case nil
  7640. (progn
  7641. (or (looking-at org-outline-regexp)
  7642. (outline-next-visible-heading 1))
  7643. (if (looking-at ^re_)
  7644. (- (match-end 0) (match-beginning 0) 1)
  7645. 1))
  7646. (error 1))))
  7647. (new-level (or force-level (max previous-level next-level)))
  7648. (shift (if (or (= old-level -1)
  7649. (= new-level -1)
  7650. (= old-level new-level))
  7651. 0
  7652. (- new-level old-level)))
  7653. (delta (if (> shift 0) -1 1))
  7654. (func (if (> shift 0) 'org-demote 'org-promote))
  7655. (org-odd-levels-only nil)
  7656. beg end newend)
  7657. ;; Remove the forced level indicator
  7658. (when force-level
  7659. (delete-region (point-at-bol) (point)))
  7660. ;; Paste
  7661. (beginning-of-line (if (bolp) 1 2))
  7662. (setq beg (point))
  7663. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7664. (insert-before-markers txt)
  7665. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7666. (setq newend (point))
  7667. (org-reinstall-markers-in-region beg)
  7668. (setq end (point))
  7669. (goto-char beg)
  7670. (skip-chars-forward " \t\n\r")
  7671. (setq beg (point))
  7672. (when (and (outline-invisible-p) visp)
  7673. (save-excursion (outline-show-heading)))
  7674. ;; Shift if necessary
  7675. (unless (= shift 0)
  7676. (save-restriction
  7677. (narrow-to-region beg end)
  7678. (while (not (= shift 0))
  7679. (org-map-region func (point-min) (point-max))
  7680. (setq shift (+ delta shift)))
  7681. (goto-char (point-min))
  7682. (setq newend (point-max))))
  7683. (when (or (called-interactively-p 'interactive) for-yank)
  7684. (message "Clipboard pasted as level %d subtree" new-level))
  7685. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7686. kill-ring
  7687. (eq org-subtree-clip (current-kill 0))
  7688. org-subtree-clip-folded)
  7689. ;; The tree was folded before it was killed/copied
  7690. (outline-hide-subtree))
  7691. (and for-yank (goto-char newend))
  7692. (and remove (setq kill-ring (cdr kill-ring))))))
  7693. (defun org-kill-is-subtree-p (&optional txt)
  7694. "Check if the current kill is an outline subtree, or a set of trees.
  7695. Returns nil if kill does not start with a headline, or if the first
  7696. headline level is not the largest headline level in the tree.
  7697. So this will actually accept several entries of equal levels as well,
  7698. which is OK for `org-paste-subtree'.
  7699. If optional TXT is given, check this string instead of the current kill."
  7700. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7701. (re (org-get-limited-outline-regexp))
  7702. (^re (concat "^" re))
  7703. (start-level (and kill
  7704. (string-match
  7705. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7706. kill)
  7707. (- (match-end 2) (match-beginning 2) 1)))
  7708. (start (1+ (or (match-beginning 2) -1))))
  7709. (if (not start-level)
  7710. (progn
  7711. nil) ;; does not even start with a heading
  7712. (catch 'exit
  7713. (while (setq start (string-match ^re kill (1+ start)))
  7714. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7715. (throw 'exit nil)))
  7716. t))))
  7717. (defvar org-markers-to-move nil
  7718. "Markers that should be moved with a cut-and-paste operation.
  7719. Those markers are stored together with their positions relative to
  7720. the start of the region.")
  7721. (defun org-save-markers-in-region (beg end)
  7722. "Check markers in region.
  7723. If these markers are between BEG and END, record their position relative
  7724. to BEG, so that after moving the block of text, we can put the markers back
  7725. into place.
  7726. This function gets called just before an entry or tree gets cut from the
  7727. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7728. called immediately, to move the markers with the entries."
  7729. (setq org-markers-to-move nil)
  7730. (when (featurep 'org-clock)
  7731. (org-clock-save-markers-for-cut-and-paste beg end))
  7732. (when (featurep 'org-agenda)
  7733. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7734. (defun org-check-and-save-marker (marker beg end)
  7735. "Check if MARKER is between BEG and END.
  7736. If yes, remember the marker and the distance to BEG."
  7737. (when (and (marker-buffer marker)
  7738. (equal (marker-buffer marker) (current-buffer))
  7739. (>= marker beg) (< marker end))
  7740. (push (cons marker (- marker beg)) org-markers-to-move)))
  7741. (defun org-reinstall-markers-in-region (beg)
  7742. "Move all remembered markers to their position relative to BEG."
  7743. (dolist (x org-markers-to-move)
  7744. (move-marker (car x) (+ beg (cdr x))))
  7745. (setq org-markers-to-move nil))
  7746. (defun org-narrow-to-subtree ()
  7747. "Narrow buffer to the current subtree."
  7748. (interactive)
  7749. (save-excursion
  7750. (save-match-data
  7751. (org-with-limited-levels
  7752. (narrow-to-region
  7753. (progn (org-back-to-heading t) (point))
  7754. (progn (org-end-of-subtree t t)
  7755. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7756. (point)))))))
  7757. (defun org-narrow-to-block ()
  7758. "Narrow buffer to the current block."
  7759. (interactive)
  7760. (let* ((case-fold-search t)
  7761. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7762. "^[ \t]*#\\+end_.*")))
  7763. (if blockp
  7764. (narrow-to-region (car blockp) (cdr blockp))
  7765. (user-error "Not in a block"))))
  7766. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7767. "Clone the task (subtree) at point N times.
  7768. The clones will be inserted as siblings.
  7769. In interactive use, the user will be prompted for the number of
  7770. clones to be produced. If the entry has a timestamp, the user
  7771. will also be prompted for a time shift, which may be a repeater
  7772. as used in time stamps, for example `+3d'. To disable this,
  7773. you can call the function with a universal prefix argument.
  7774. When a valid repeater is given and the entry contains any time
  7775. stamps, the clones will become a sequence in time, with time
  7776. stamps in the subtree shifted for each clone produced. If SHIFT
  7777. is nil or the empty string, time stamps will be left alone. The
  7778. ID property of the original subtree is removed.
  7779. In each clone, all the CLOCK entries will be removed. This
  7780. prevents Org from considering that the clocked times overlap.
  7781. If the original subtree did contain time stamps with a repeater,
  7782. the following will happen:
  7783. - the repeater will be removed in each clone
  7784. - an additional clone will be produced, with the current, unshifted
  7785. date(s) in the entry.
  7786. - the original entry will be placed *after* all the clones, with
  7787. repeater intact.
  7788. - the start days in the repeater in the original entry will be shifted
  7789. to past the last clone.
  7790. In this way you can spell out a number of instances of a repeating task,
  7791. and still retain the repeater to cover future instances of the task.
  7792. As described above, N+1 clones are produced when the original
  7793. subtree has a repeater. Setting N to 0, then, can be used to
  7794. remove the repeater from a subtree and create a shifted clone
  7795. with the original repeater."
  7796. (interactive "nNumber of clones to produce: ")
  7797. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7798. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7799. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7800. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7801. (shift
  7802. (or shift
  7803. (if (and (not (equal current-prefix-arg '(4)))
  7804. (save-excursion
  7805. (goto-char beg)
  7806. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7807. (read-from-minibuffer
  7808. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7809. ""))) ;No time shift
  7810. (doshift
  7811. (and (org-string-nw-p shift)
  7812. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7813. shift)
  7814. (user-error "Invalid shift specification %s" shift)))))
  7815. (goto-char end-of-tree)
  7816. (unless (bolp) (insert "\n"))
  7817. (let* ((end (point))
  7818. (template (buffer-substring beg end))
  7819. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7820. (shift-what (pcase (and doshift (match-string 2 shift))
  7821. (`nil nil)
  7822. ("d" 'day)
  7823. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7824. ("m" 'month)
  7825. ("y" 'year)
  7826. (_ (error "Unsupported time unit"))))
  7827. (nmin 1)
  7828. (nmax n)
  7829. (n-no-remove -1)
  7830. (idprop (org-entry-get nil "ID")))
  7831. (when (and doshift
  7832. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7833. template))
  7834. (delete-region beg end)
  7835. (setq end beg)
  7836. (setq nmin 0)
  7837. (setq nmax (1+ nmax))
  7838. (setq n-no-remove nmax))
  7839. (goto-char end)
  7840. (cl-loop for n from nmin to nmax do
  7841. (insert
  7842. ;; Prepare clone.
  7843. (with-temp-buffer
  7844. (insert template)
  7845. (org-mode)
  7846. (goto-char (point-min))
  7847. (org-show-subtree)
  7848. (and idprop (if org-clone-delete-id
  7849. (org-entry-delete nil "ID")
  7850. (org-id-get-create t)))
  7851. (unless (= n 0)
  7852. (while (re-search-forward org-clock-line-re nil t)
  7853. (delete-region (line-beginning-position)
  7854. (line-beginning-position 2)))
  7855. (goto-char (point-min))
  7856. (while (re-search-forward org-drawer-regexp nil t)
  7857. (org-remove-empty-drawer-at (point))))
  7858. (goto-char (point-min))
  7859. (when doshift
  7860. (while (re-search-forward org-ts-regexp-both nil t)
  7861. (org-timestamp-change (* n shift-n) shift-what))
  7862. (unless (= n n-no-remove)
  7863. (goto-char (point-min))
  7864. (while (re-search-forward org-ts-regexp nil t)
  7865. (save-excursion
  7866. (goto-char (match-beginning 0))
  7867. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7868. (delete-region (match-beginning 1) (match-end 1)))))))
  7869. (buffer-string)))))
  7870. (goto-char beg)))
  7871. ;;; Outline Sorting
  7872. (defun org-sort (with-case)
  7873. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7874. Optional argument WITH-CASE means sort case-sensitively."
  7875. (interactive "P")
  7876. (cond
  7877. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7878. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7879. (t
  7880. (org-call-with-arg 'org-sort-entries with-case))))
  7881. (defun org-sort-remove-invisible (s)
  7882. "Remove invisible part of links and emphasis markers from string S."
  7883. (remove-text-properties 0 (length s) org-rm-props s)
  7884. (replace-regexp-in-string
  7885. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7886. (replace-regexp-in-string
  7887. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7888. (org-link-display-format s)
  7889. t t) t t))
  7890. (defvar org-priority-regexp) ; defined later in the file
  7891. (defvar org-after-sorting-entries-or-items-hook nil
  7892. "Hook that is run after a bunch of entries or items have been sorted.
  7893. When children are sorted, the cursor is in the parent line when this
  7894. hook gets called. When a region or a plain list is sorted, the cursor
  7895. will be in the first entry of the sorted region/list.")
  7896. (defun org-sort-entries
  7897. (&optional with-case sorting-type getkey-func compare-func property)
  7898. "Sort entries on a certain level of an outline tree.
  7899. If there is an active region, the entries in the region are sorted.
  7900. Else, if the cursor is before the first entry, sort the top-level items.
  7901. Else, the children of the entry at point are sorted.
  7902. Sorting can be alphabetically, numerically, by date/time as given by
  7903. a time stamp, by a property, by priority order, or by a custom function.
  7904. The command prompts for the sorting type unless it has been given to the
  7905. function through the SORTING-TYPE argument, which needs to be a character,
  7906. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7907. the precise meaning of each character:
  7908. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7909. c By creation time, which is assumed to be the first inactive time stamp
  7910. at the beginning of a line.
  7911. d By deadline date/time.
  7912. k By clocking time.
  7913. n Numerically, by converting the beginning of the entry/item to a number.
  7914. o By order of TODO keywords.
  7915. p By priority according to the cookie.
  7916. r By the value of a property.
  7917. s By scheduled date/time.
  7918. t By date/time, either the first active time stamp in the entry, or, if
  7919. none exist, by the first inactive one.
  7920. Capital letters will reverse the sort order.
  7921. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7922. called with point at the beginning of the record. It must return either
  7923. a string or a number that should serve as the sorting key for that record.
  7924. Comparing entries ignores case by default. However, with an optional argument
  7925. WITH-CASE, the sorting considers case as well.
  7926. Sorting is done against the visible part of the headlines, it ignores hidden
  7927. links.
  7928. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  7929. (interactive "P")
  7930. (let ((case-func (if with-case 'identity 'downcase))
  7931. (cmstr
  7932. ;; The clock marker is lost when using `sort-subr', let's
  7933. ;; store the clocking string.
  7934. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7935. (save-excursion
  7936. (goto-char org-clock-marker)
  7937. (buffer-substring-no-properties (line-beginning-position)
  7938. (point)))))
  7939. start beg end stars re re2
  7940. txt what tmp)
  7941. ;; Find beginning and end of region to sort
  7942. (cond
  7943. ((org-region-active-p)
  7944. ;; we will sort the region
  7945. (setq end (region-end)
  7946. what "region")
  7947. (goto-char (region-beginning))
  7948. (unless (org-at-heading-p) (outline-next-heading))
  7949. (setq start (point)))
  7950. ((or (org-at-heading-p)
  7951. (ignore-errors (progn (org-back-to-heading) t)))
  7952. ;; we will sort the children of the current headline
  7953. (org-back-to-heading)
  7954. (setq start (point)
  7955. end (progn (org-end-of-subtree t t)
  7956. (or (bolp) (insert "\n"))
  7957. (when (>= (org-back-over-empty-lines) 1)
  7958. (forward-line 1))
  7959. (point))
  7960. what "children")
  7961. (goto-char start)
  7962. (outline-show-subtree)
  7963. (outline-next-heading))
  7964. (t
  7965. ;; we will sort the top-level entries in this file
  7966. (goto-char (point-min))
  7967. (or (org-at-heading-p) (outline-next-heading))
  7968. (setq start (point))
  7969. (goto-char (point-max))
  7970. (beginning-of-line 1)
  7971. (when (looking-at ".*?\\S-")
  7972. ;; File ends in a non-white line
  7973. (end-of-line 1)
  7974. (insert "\n"))
  7975. (setq end (point-max))
  7976. (setq what "top-level")
  7977. (goto-char start)
  7978. (outline-show-all)))
  7979. (setq beg (point))
  7980. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7981. (looking-at "\\(\\*+\\)")
  7982. (setq stars (match-string 1)
  7983. re (concat "^" (regexp-quote stars) " +")
  7984. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7985. txt (buffer-substring beg end))
  7986. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7987. (when (and (not (equal stars "*")) (string-match re2 txt))
  7988. (user-error "Region to sort contains a level above the first entry"))
  7989. (unless sorting-type
  7990. (message
  7991. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7992. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7993. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7994. what)
  7995. (setq sorting-type (read-char-exclusive))
  7996. (unless getkey-func
  7997. (and (= (downcase sorting-type) ?f)
  7998. (setq getkey-func
  7999. (completing-read "Sort using function: "
  8000. obarray 'fboundp t nil nil))
  8001. (setq getkey-func (intern getkey-func))))
  8002. (and (= (downcase sorting-type) ?r)
  8003. (not property)
  8004. (setq property
  8005. (completing-read "Property: "
  8006. (mapcar #'list (org-buffer-property-keys t))
  8007. nil t))))
  8008. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8009. (message "Sorting entries...")
  8010. (save-restriction
  8011. (narrow-to-region start end)
  8012. (let ((dcst (downcase sorting-type))
  8013. (case-fold-search nil)
  8014. (now (current-time)))
  8015. (sort-subr
  8016. (/= dcst sorting-type)
  8017. ;; This function moves to the beginning character of the "record" to
  8018. ;; be sorted.
  8019. (lambda nil
  8020. (if (re-search-forward re nil t)
  8021. (goto-char (match-beginning 0))
  8022. (goto-char (point-max))))
  8023. ;; This function moves to the last character of the "record" being
  8024. ;; sorted.
  8025. (lambda nil
  8026. (save-match-data
  8027. (condition-case nil
  8028. (outline-forward-same-level 1)
  8029. (error
  8030. (goto-char (point-max))))))
  8031. ;; This function returns the value that gets sorted against.
  8032. (lambda nil
  8033. (cond
  8034. ((= dcst ?n)
  8035. (if (looking-at org-complex-heading-regexp)
  8036. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8037. nil))
  8038. ((= dcst ?a)
  8039. (if (looking-at org-complex-heading-regexp)
  8040. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8041. nil))
  8042. ((= dcst ?k)
  8043. (or (get-text-property (point) :org-clock-minutes) 0))
  8044. ((= dcst ?t)
  8045. (let ((end (save-excursion (outline-next-heading) (point))))
  8046. (if (or (re-search-forward org-ts-regexp end t)
  8047. (re-search-forward org-ts-regexp-both end t))
  8048. (org-time-string-to-seconds (match-string 0))
  8049. (float-time now))))
  8050. ((= dcst ?c)
  8051. (let ((end (save-excursion (outline-next-heading) (point))))
  8052. (if (re-search-forward
  8053. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8054. end t)
  8055. (org-time-string-to-seconds (match-string 0))
  8056. (float-time now))))
  8057. ((= dcst ?s)
  8058. (let ((end (save-excursion (outline-next-heading) (point))))
  8059. (if (re-search-forward org-scheduled-time-regexp end t)
  8060. (org-time-string-to-seconds (match-string 1))
  8061. (float-time now))))
  8062. ((= dcst ?d)
  8063. (let ((end (save-excursion (outline-next-heading) (point))))
  8064. (if (re-search-forward org-deadline-time-regexp end t)
  8065. (org-time-string-to-seconds (match-string 1))
  8066. (float-time now))))
  8067. ((= dcst ?p)
  8068. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8069. (string-to-char (match-string 2))
  8070. org-default-priority))
  8071. ((= dcst ?r)
  8072. (or (org-entry-get nil property) ""))
  8073. ((= dcst ?o)
  8074. (when (looking-at org-complex-heading-regexp)
  8075. (let* ((m (match-string 2))
  8076. (s (if (member m org-done-keywords) '- '+)))
  8077. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8078. ((= dcst ?f)
  8079. (if getkey-func
  8080. (progn
  8081. (setq tmp (funcall getkey-func))
  8082. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8083. tmp)
  8084. (error "Invalid key function `%s'" getkey-func)))
  8085. (t (error "Invalid sorting type `%c'" sorting-type))))
  8086. nil
  8087. (cond
  8088. ((= dcst ?a) 'string<)
  8089. ((= dcst ?f) compare-func)
  8090. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8091. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8092. ;; Reset the clock marker if needed
  8093. (when cmstr
  8094. (save-excursion
  8095. (goto-char start)
  8096. (search-forward cmstr nil t)
  8097. (move-marker org-clock-marker (point))))
  8098. (message "Sorting entries...done")))
  8099. ;;; The orgstruct minor mode
  8100. ;; Define a minor mode which can be used in other modes in order to
  8101. ;; integrate the Org mode structure editing commands.
  8102. ;; This is really a hack, because the Org mode structure commands use
  8103. ;; keys which normally belong to the major mode. Here is how it
  8104. ;; works: The minor mode defines all the keys necessary to operate the
  8105. ;; structure commands, but wraps the commands into a function which
  8106. ;; tests if the cursor is currently at a headline or a plain list
  8107. ;; item. If that is the case, the structure command is used,
  8108. ;; temporarily setting many Org mode variables like regular
  8109. ;; expressions for filling etc. However, when any of those keys is
  8110. ;; used at a different location, function uses `key-binding' to look
  8111. ;; up if the key has an associated command in another currently active
  8112. ;; keymap (minor modes, major mode, global), and executes that
  8113. ;; command. There might be problems if any of the keys is otherwise
  8114. ;; used as a prefix key.
  8115. (defcustom orgstruct-heading-prefix-regexp ""
  8116. "Regexp that matches the custom prefix of Org headlines in
  8117. orgstruct(++)-mode."
  8118. :group 'org
  8119. :version "24.4"
  8120. :package-version '(Org . "8.3")
  8121. :type 'regexp)
  8122. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8123. (defcustom orgstruct-setup-hook nil
  8124. "Hook run after orgstruct-mode-map is filled."
  8125. :group 'org
  8126. :version "24.4"
  8127. :package-version '(Org . "8.0")
  8128. :type 'hook)
  8129. (defvar orgstruct-initialized nil)
  8130. (defvar org-local-vars nil
  8131. "List of local variables, for use by `orgstruct-mode'.")
  8132. ;;;###autoload
  8133. (define-minor-mode orgstruct-mode
  8134. "Toggle the minor mode `orgstruct-mode'.
  8135. This mode is for using Org mode structure commands in other
  8136. modes. The following keys behave as if Org mode were active, if
  8137. the cursor is on a headline, or on a plain list item (both as
  8138. defined by Org mode)."
  8139. nil " OrgStruct" (make-sparse-keymap)
  8140. (funcall (if orgstruct-mode
  8141. 'add-to-invisibility-spec
  8142. 'remove-from-invisibility-spec)
  8143. '(outline . t))
  8144. (when orgstruct-mode
  8145. (org-load-modules-maybe)
  8146. (unless orgstruct-initialized
  8147. (orgstruct-setup)
  8148. (setq orgstruct-initialized t))))
  8149. ;;;###autoload
  8150. (defun turn-on-orgstruct ()
  8151. "Unconditionally turn on `orgstruct-mode'."
  8152. (orgstruct-mode 1))
  8153. (defvar-local orgstruct-is-++ nil
  8154. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8155. (defvar-local org-fb-vars nil)
  8156. (defun orgstruct++-mode (&optional arg)
  8157. "Toggle `orgstruct-mode', the enhanced version of it.
  8158. In addition to setting orgstruct-mode, this also exports all
  8159. indentation and autofilling variables from Org mode into the
  8160. buffer. It will also recognize item context in multiline items."
  8161. (interactive "P")
  8162. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8163. (if (< arg 1)
  8164. (progn (orgstruct-mode -1)
  8165. (dolist (v org-fb-vars)
  8166. (set (make-local-variable (car v))
  8167. (if (eq (car-safe (cadr v)) 'quote)
  8168. (cl-cadadr v)
  8169. (nth 1 v)))))
  8170. (orgstruct-mode 1)
  8171. (setq org-fb-vars nil)
  8172. (unless org-local-vars
  8173. (setq org-local-vars (org-get-local-variables)))
  8174. (let (var val)
  8175. (dolist (x org-local-vars)
  8176. (when (string-match
  8177. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8178. \\|fill-prefix\\|indent-\\)"
  8179. (symbol-name (car x)))
  8180. (setq var (car x) val (nth 1 x))
  8181. (push (list var `(quote ,(eval var))) org-fb-vars)
  8182. (set (make-local-variable var)
  8183. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8184. (setq-local orgstruct-is-++ t))))
  8185. ;;;###autoload
  8186. (defun turn-on-orgstruct++ ()
  8187. "Unconditionally turn on `orgstruct++-mode'."
  8188. (orgstruct++-mode 1))
  8189. (defun orgstruct-error ()
  8190. "Error when there is no default binding for a structure key."
  8191. (interactive)
  8192. (funcall (if (fboundp 'user-error)
  8193. 'user-error
  8194. 'error)
  8195. "This key has no function outside structure elements"))
  8196. (defun orgstruct-setup ()
  8197. "Setup orgstruct keymap."
  8198. (dolist (cell '((org-demote . t)
  8199. (org-metaleft . t)
  8200. (org-metaright . t)
  8201. (org-promote . t)
  8202. (org-shiftmetaleft . t)
  8203. (org-shiftmetaright . t)
  8204. org-backward-element
  8205. org-backward-heading-same-level
  8206. org-ctrl-c-ret
  8207. org-ctrl-c-minus
  8208. org-ctrl-c-star
  8209. org-cycle
  8210. org-force-cycle-archived
  8211. org-forward-heading-same-level
  8212. org-insert-heading
  8213. org-insert-heading-respect-content
  8214. org-kill-note-or-show-branches
  8215. org-mark-subtree
  8216. org-meta-return
  8217. org-metadown
  8218. org-metaup
  8219. org-narrow-to-subtree
  8220. org-promote-subtree
  8221. org-reveal
  8222. org-shiftdown
  8223. org-shiftleft
  8224. org-shiftmetadown
  8225. org-shiftmetaup
  8226. org-shiftright
  8227. org-shifttab
  8228. org-shifttab
  8229. org-shiftup
  8230. org-show-children
  8231. org-show-subtree
  8232. org-sort
  8233. org-up-element
  8234. outline-demote
  8235. outline-next-visible-heading
  8236. outline-previous-visible-heading
  8237. outline-promote
  8238. outline-up-heading))
  8239. (let ((f (or (car-safe cell) cell))
  8240. (disable-when-heading-prefix (cdr-safe cell)))
  8241. (when (fboundp f)
  8242. (let ((new-bindings))
  8243. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8244. (where-is-internal f outline-mode-map)))
  8245. (push binding new-bindings)
  8246. ;; TODO use local-function-key-map
  8247. (dolist (rep '(("<tab>" . "TAB")
  8248. ("<return>" . "RET")
  8249. ("<escape>" . "ESC")
  8250. ("<delete>" . "DEL")))
  8251. (setq binding (read-kbd-macro
  8252. (let ((case-fold-search))
  8253. (replace-regexp-in-string
  8254. (regexp-quote (cdr rep))
  8255. (car rep)
  8256. (key-description binding)))))
  8257. (cl-pushnew binding new-bindings :test 'equal)))
  8258. (dolist (binding new-bindings)
  8259. (let ((key (lookup-key orgstruct-mode-map binding)))
  8260. (when (or (not key) (numberp key))
  8261. (ignore-errors
  8262. (org-defkey orgstruct-mode-map
  8263. binding
  8264. (orgstruct-make-binding
  8265. f binding disable-when-heading-prefix))))))))))
  8266. (run-hooks 'orgstruct-setup-hook))
  8267. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8268. "Create a function for binding in the structure minor mode.
  8269. FUN is the command to call inside a table. KEY is the key that
  8270. should be checked in for a command to execute outside of tables.
  8271. Non-nil `disable-when-heading-prefix' means to disable the command
  8272. if `orgstruct-heading-prefix-regexp' is not empty."
  8273. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8274. (let ((nname name)
  8275. (i 0))
  8276. (while (fboundp (intern nname))
  8277. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8278. (setq name (intern nname)))
  8279. (eval
  8280. (let ((bindings '((org-heading-regexp
  8281. (concat "^"
  8282. orgstruct-heading-prefix-regexp
  8283. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8284. (org-outline-regexp
  8285. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8286. (org-outline-regexp-bol
  8287. (concat "^" org-outline-regexp))
  8288. (outline-regexp org-outline-regexp)
  8289. (outline-heading-end-regexp "\n")
  8290. (outline-level 'org-outline-level)
  8291. (outline-heading-alist))))
  8292. `(defun ,name (arg)
  8293. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8294. "Outside of structure, run the binding of `"
  8295. (key-description key) "'."
  8296. (when disable-when-heading-prefix
  8297. (concat
  8298. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8299. "back to the default binding due to limitations of Org's implementation of\n"
  8300. "`" (symbol-name fun) "'.")))
  8301. (interactive "p")
  8302. (let* ((disable
  8303. ,(and disable-when-heading-prefix
  8304. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8305. (fallback
  8306. (or disable
  8307. (not
  8308. (let* ,bindings
  8309. (org-context-p 'headline 'item
  8310. ,(when (memq fun
  8311. '(org-insert-heading
  8312. org-insert-heading-respect-content
  8313. org-meta-return))
  8314. '(when orgstruct-is-++
  8315. 'item-body))))))))
  8316. (if fallback
  8317. (let* ((orgstruct-mode)
  8318. (binding
  8319. (let ((key ,key))
  8320. (catch 'exit
  8321. (dolist
  8322. (rep
  8323. '(nil
  8324. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8325. ("<\\([^>]*\\)return>" . "\\1RET")
  8326. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8327. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8328. nil)
  8329. (when rep
  8330. (setq key (read-kbd-macro
  8331. (let ((case-fold-search))
  8332. (replace-regexp-in-string
  8333. (car rep)
  8334. (cdr rep)
  8335. (key-description key))))))
  8336. (when (key-binding key)
  8337. (throw 'exit (key-binding key))))))))
  8338. (if (keymapp binding)
  8339. (org-set-transient-map binding)
  8340. (let ((func (or binding
  8341. (unless disable
  8342. 'orgstruct-error))))
  8343. (when func
  8344. (call-interactively func)))))
  8345. (org-run-like-in-org-mode
  8346. (lambda ()
  8347. (interactive)
  8348. (let* ,bindings
  8349. (call-interactively ',fun)))))))))
  8350. name))
  8351. (defun org-contextualize-keys (alist contexts)
  8352. "Return valid elements in ALIST depending on CONTEXTS.
  8353. `org-agenda-custom-commands' or `org-capture-templates' are the
  8354. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8355. or `org-capture-templates-contexts' are the associated contexts
  8356. definitions."
  8357. (let ((contexts
  8358. ;; normalize contexts
  8359. (mapcar
  8360. (lambda(c) (cond ((listp (cadr c))
  8361. (list (car c) (car c) (nth 1 c)))
  8362. ((string= "" (cadr c))
  8363. (list (car c) (car c) (nth 2 c)))
  8364. (t c)))
  8365. contexts))
  8366. (a alist) r s)
  8367. ;; loop over all commands or templates
  8368. (dolist (c a)
  8369. (let (vrules repl)
  8370. (cond
  8371. ((not (assoc (car c) contexts))
  8372. (push c r))
  8373. ((and (assoc (car c) contexts)
  8374. (setq vrules (org-contextualize-validate-key
  8375. (car c) contexts)))
  8376. (mapc (lambda (vr)
  8377. (unless (equal (car vr) (cadr vr))
  8378. (setq repl vr)))
  8379. vrules)
  8380. (if (not repl) (push c r)
  8381. (push (cadr repl) s)
  8382. (push
  8383. (cons (car c)
  8384. (cdr (or (assoc (cadr repl) alist)
  8385. (error "Undefined key `%s' as contextual replacement for `%s'"
  8386. (cadr repl) (car c)))))
  8387. r))))))
  8388. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8389. (delq
  8390. nil
  8391. (delete-dups
  8392. (mapcar (lambda (x)
  8393. (let ((tpl (car x)))
  8394. (unless (delq
  8395. nil
  8396. (mapcar (lambda (y)
  8397. (equal y tpl))
  8398. s))
  8399. x)))
  8400. (reverse r))))))
  8401. (defun org-contextualize-validate-key (key contexts)
  8402. "Check CONTEXTS for agenda or capture KEY."
  8403. (let (res)
  8404. (dolist (r contexts)
  8405. (dolist (rr (car (last r)))
  8406. (when
  8407. (and (equal key (car r))
  8408. (if (functionp rr) (funcall rr)
  8409. (or (and (eq (car rr) 'in-file)
  8410. (buffer-file-name)
  8411. (string-match (cdr rr) (buffer-file-name)))
  8412. (and (eq (car rr) 'in-mode)
  8413. (string-match (cdr rr) (symbol-name major-mode)))
  8414. (and (eq (car rr) 'in-buffer)
  8415. (string-match (cdr rr) (buffer-name)))
  8416. (when (and (eq (car rr) 'not-in-file)
  8417. (buffer-file-name))
  8418. (not (string-match (cdr rr) (buffer-file-name))))
  8419. (when (eq (car rr) 'not-in-mode)
  8420. (not (string-match (cdr rr) (symbol-name major-mode))))
  8421. (when (eq (car rr) 'not-in-buffer)
  8422. (not (string-match (cdr rr) (buffer-name)))))))
  8423. (push r res))))
  8424. (delete-dups (delq nil res))))
  8425. (defun org-context-p (&rest contexts)
  8426. "Check if local context is any of CONTEXTS.
  8427. Possible values in the list of contexts are `table', `headline', and `item'."
  8428. (let ((pos (point)))
  8429. (goto-char (point-at-bol))
  8430. (prog1 (or (and (memq 'table contexts)
  8431. (looking-at "[ \t]*|"))
  8432. (and (memq 'headline contexts)
  8433. (looking-at org-outline-regexp))
  8434. (and (memq 'item contexts)
  8435. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8436. (and (memq 'item-body contexts)
  8437. (org-in-item-p)))
  8438. (goto-char pos))))
  8439. (defconst org-unique-local-variables
  8440. '(org-element--cache
  8441. org-element--cache-objects
  8442. org-element--cache-sync-keys
  8443. org-element--cache-sync-requests
  8444. org-element--cache-sync-timer)
  8445. "List of local variables that cannot be transferred to another buffer.")
  8446. (defun org-get-local-variables ()
  8447. "Return a list of all local variables in an Org mode buffer."
  8448. (delq nil
  8449. (mapcar
  8450. (lambda (x)
  8451. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8452. (name (car binding)))
  8453. (and (not (get name 'org-state))
  8454. (not (memq name org-unique-local-variables))
  8455. (string-match-p
  8456. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8457. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8458. (symbol-name name))
  8459. binding)))
  8460. (with-temp-buffer
  8461. (org-mode)
  8462. (buffer-local-variables)))))
  8463. (defun org-clone-local-variables (from-buffer &optional regexp)
  8464. "Clone local variables from FROM-BUFFER.
  8465. Optional argument REGEXP selects variables to clone."
  8466. (dolist (pair (buffer-local-variables from-buffer))
  8467. (let ((name (car pair)))
  8468. (when (and (symbolp name)
  8469. (not (memq name org-unique-local-variables))
  8470. (or (null regexp) (string-match regexp (symbol-name name))))
  8471. (set (make-local-variable name) (cdr pair))))))
  8472. ;;;###autoload
  8473. (defun org-run-like-in-org-mode (cmd)
  8474. "Run a command, pretending that the current buffer is in Org mode.
  8475. This will temporarily bind local variables that are typically bound in
  8476. Org mode to the values they have in Org mode, and then interactively
  8477. call CMD."
  8478. (org-load-modules-maybe)
  8479. (unless org-local-vars
  8480. (setq org-local-vars (org-get-local-variables)))
  8481. (let (binds)
  8482. (dolist (var org-local-vars)
  8483. (when (or (not (boundp (car var)))
  8484. (eq (symbol-value (car var))
  8485. (default-value (car var))))
  8486. (push (list (car var) `(quote ,(cadr var))) binds)))
  8487. (eval `(let ,binds
  8488. (call-interactively (quote ,cmd))))))
  8489. (defun org-get-category (&optional pos force-refresh)
  8490. "Get the category applying to position POS."
  8491. (save-match-data
  8492. (when force-refresh (org-refresh-category-properties))
  8493. (let ((pos (or pos (point))))
  8494. (or (get-text-property pos 'org-category)
  8495. (progn (org-refresh-category-properties)
  8496. (get-text-property pos 'org-category))))))
  8497. ;;; Refresh properties
  8498. (defun org-refresh-properties (dprop tprop)
  8499. "Refresh buffer text properties.
  8500. DPROP is the drawer property and TPROP is either the
  8501. corresponding text property to set, or an alist with each element
  8502. being a text property (as a symbol) and a function to apply to
  8503. the value of the drawer property."
  8504. (let* ((case-fold-search t)
  8505. (inhibit-read-only t)
  8506. (inherit? (org-property-inherit-p dprop))
  8507. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8508. (global (and inherit? (org--property-global-value dprop nil))))
  8509. (org-with-silent-modifications
  8510. (org-with-point-at 1
  8511. ;; Set global values (e.g., values defined through
  8512. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8513. (when global (put-text-property (point-min) (point-max) tprop global))
  8514. ;; Set local values.
  8515. (while (re-search-forward property-re nil t)
  8516. (when (org-at-property-p)
  8517. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8518. (outline-next-heading))))))
  8519. (defun org-refresh-property (tprop p &optional inherit)
  8520. "Refresh the buffer text property TPROP from the drawer property P.
  8521. The refresh happens only for the current headline, or the whole
  8522. sub-tree if optional argument INHERIT is non-nil."
  8523. (unless (org-before-first-heading-p)
  8524. (save-excursion
  8525. (org-back-to-heading t)
  8526. (let ((start (point))
  8527. (end (save-excursion
  8528. (if inherit (org-end-of-subtree t t)
  8529. (or (outline-next-heading) (point-max))))))
  8530. (if (symbolp tprop)
  8531. ;; TPROP is a text property symbol.
  8532. (put-text-property start end tprop p)
  8533. ;; TPROP is an alist with (property . function) elements.
  8534. (pcase-dolist (`(,prop . ,f) tprop)
  8535. (put-text-property start end prop (funcall f p))))))))
  8536. (defun org-refresh-category-properties ()
  8537. "Refresh category text properties in the buffer."
  8538. (let ((case-fold-search t)
  8539. (inhibit-read-only t)
  8540. (default-category
  8541. (cond ((null org-category)
  8542. (if buffer-file-name
  8543. (file-name-sans-extension
  8544. (file-name-nondirectory buffer-file-name))
  8545. "???"))
  8546. ((symbolp org-category) (symbol-name org-category))
  8547. (t org-category))))
  8548. (org-with-silent-modifications
  8549. (org-with-wide-buffer
  8550. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8551. ;; This is the default category for the buffer. If none is
  8552. ;; found, fall-back to `org-category' or buffer file name.
  8553. (put-text-property
  8554. (point-min) (point-max)
  8555. 'org-category
  8556. (catch 'buffer-category
  8557. (goto-char (point-max))
  8558. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8559. (let ((element (org-element-at-point)))
  8560. (when (eq (org-element-type element) 'keyword)
  8561. (throw 'buffer-category
  8562. (org-element-property :value element)))))
  8563. default-category))
  8564. ;; Set sub-tree specific categories.
  8565. (goto-char (point-min))
  8566. (let ((regexp (org-re-property "CATEGORY")))
  8567. (while (re-search-forward regexp nil t)
  8568. (let ((value (match-string-no-properties 3)))
  8569. (when (org-at-property-p)
  8570. (put-text-property
  8571. (save-excursion (org-back-to-heading t) (point))
  8572. (save-excursion (org-end-of-subtree t t) (point))
  8573. 'org-category
  8574. value)))))))))
  8575. (defun org-refresh-stats-properties ()
  8576. "Refresh stats text properties in the buffer."
  8577. (let (stats)
  8578. (org-with-silent-modifications
  8579. (org-with-wide-buffer
  8580. (goto-char (point-min))
  8581. (while (re-search-forward
  8582. (concat org-outline-regexp-bol ".*"
  8583. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8584. nil t)
  8585. (setq stats (cond ((equal (match-string 3) "0") 0)
  8586. ((match-string 2)
  8587. (/ (* (string-to-number (match-string 2)) 100)
  8588. (string-to-number (match-string 3))))
  8589. (t (string-to-number (match-string 1)))))
  8590. (org-back-to-heading t)
  8591. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8592. 'org-stats stats))))))
  8593. (defun org-refresh-effort-properties ()
  8594. "Refresh effort properties"
  8595. (org-refresh-properties
  8596. org-effort-property
  8597. '((effort . identity)
  8598. (effort-minutes . org-duration-to-minutes))))
  8599. ;;;; Link Stuff
  8600. ;;; Link abbreviations
  8601. (defun org-link-expand-abbrev (link)
  8602. "Apply replacements as defined in `org-link-abbrev-alist'."
  8603. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8604. (let* ((key (match-string 1 link))
  8605. (as (or (assoc key org-link-abbrev-alist-local)
  8606. (assoc key org-link-abbrev-alist)))
  8607. (tag (and (match-end 2) (match-string 3 link)))
  8608. rpl)
  8609. (if (not as)
  8610. link
  8611. (setq rpl (cdr as))
  8612. (cond
  8613. ((symbolp rpl) (funcall rpl tag))
  8614. ((string-match "%(\\([^)]+\\))" rpl)
  8615. (replace-match
  8616. (save-match-data
  8617. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8618. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8619. ((string-match "%h" rpl)
  8620. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8621. (t (concat rpl tag)))))
  8622. link))
  8623. ;;; Storing and inserting links
  8624. (defvar org-insert-link-history nil
  8625. "Minibuffer history for links inserted with `org-insert-link'.")
  8626. (defvar org-stored-links nil
  8627. "Contains the links stored with `org-store-link'.")
  8628. (defvar org-store-link-plist nil
  8629. "Plist with info about the most recently link created with `org-store-link'.")
  8630. (defun org-store-link-functions ()
  8631. "Return a list of functions that are called to create and store a link.
  8632. The functions defined in the :store property of
  8633. `org-link-parameters'.
  8634. Each function will be called in turn until one returns a non-nil
  8635. value. Each function should check if it is responsible for
  8636. creating this link (for example by looking at the major mode).
  8637. If not, it must exit and return nil. If yes, it should return
  8638. a non-nil value after calling `org-store-link-props' with a list
  8639. of properties and values. Special properties are:
  8640. :type The link prefix, like \"http\". This must be given.
  8641. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8642. This is obligatory as well.
  8643. :description Optional default description for the second pair
  8644. of brackets in an Org mode link. The user can still change
  8645. this when inserting this link into an Org mode buffer.
  8646. In addition to these, any additional properties can be specified
  8647. and then used in capture templates."
  8648. (cl-loop for link in org-link-parameters
  8649. with store-func
  8650. do (setq store-func (org-link-get-parameter (car link) :store))
  8651. if store-func
  8652. collect store-func))
  8653. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8654. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8655. ;;;###autoload
  8656. (defun org-store-link (arg)
  8657. "Store an org-link to the current location.
  8658. \\<org-mode-map>
  8659. This link is added to `org-stored-links' and can later be inserted
  8660. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8661. For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
  8662. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8663. For file links, ARG negates `org-context-in-file-links'.
  8664. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8665. skipping storing functions that are not
  8666. part of Org core.
  8667. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8668. prefix ARG forces storing a link for each line in the
  8669. active region."
  8670. (interactive "P")
  8671. (org-load-modules-maybe)
  8672. (if (and (equal arg '(64)) (org-region-active-p))
  8673. (save-excursion
  8674. (let ((end (region-end)))
  8675. (goto-char (region-beginning))
  8676. (set-mark (point))
  8677. (while (< (point-at-eol) end)
  8678. (move-end-of-line 1) (activate-mark)
  8679. (let (current-prefix-arg)
  8680. (call-interactively 'org-store-link))
  8681. (move-beginning-of-line 2)
  8682. (set-mark (point)))))
  8683. (setq org-store-link-plist nil)
  8684. (let (link cpltxt desc description search
  8685. txt custom-id agenda-link sfuns sfunsn)
  8686. (cond
  8687. ;; Store a link using an external link type
  8688. ((and (not (equal arg '(16)))
  8689. (setq sfuns
  8690. (delq
  8691. nil (mapcar (lambda (f)
  8692. (let (fs) (if (funcall f) (push f fs))))
  8693. (org-store-link-functions)))
  8694. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8695. (or (and (cdr sfuns)
  8696. (funcall (intern
  8697. (completing-read
  8698. "Which function for creating the link? "
  8699. sfunsn nil t (car sfunsn)))))
  8700. (funcall (caar sfuns)))
  8701. (setq link (plist-get org-store-link-plist :link)
  8702. desc (or (plist-get org-store-link-plist
  8703. :description)
  8704. link))))
  8705. ;; Store a link from a source code buffer.
  8706. ((org-src-edit-buffer-p)
  8707. (let ((coderef-format (org-src-coderef-format)))
  8708. (cond ((save-excursion
  8709. (beginning-of-line)
  8710. (looking-at (org-src-coderef-regexp coderef-format)))
  8711. (setq link (format "(%s)" (match-string-no-properties 3))))
  8712. ((called-interactively-p 'any)
  8713. (let ((label (read-string "Code line label: ")))
  8714. (end-of-line)
  8715. (setq link (format coderef-format label))
  8716. (let ((gc (- 79 (length link))))
  8717. (if (< (current-column) gc)
  8718. (org-move-to-column gc t)
  8719. (insert " ")))
  8720. (insert link)
  8721. (setq link (concat "(" label ")"))
  8722. (setq desc nil)))
  8723. (t (setq link nil)))))
  8724. ;; We are in the agenda, link to referenced location
  8725. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8726. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8727. (get-text-property (point) 'org-marker))))
  8728. (when m
  8729. (org-with-point-at m
  8730. (setq agenda-link
  8731. (if (called-interactively-p 'any)
  8732. (call-interactively 'org-store-link)
  8733. (org-store-link nil)))))))
  8734. ((eq major-mode 'calendar-mode)
  8735. (let ((cd (calendar-cursor-to-date)))
  8736. (setq link
  8737. (format-time-string
  8738. (car org-time-stamp-formats)
  8739. (apply 'encode-time
  8740. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8741. nil nil nil))))
  8742. (org-store-link-props :type "calendar" :date cd)))
  8743. ((eq major-mode 'help-mode)
  8744. (setq link (concat "help:" (save-excursion
  8745. (goto-char (point-min))
  8746. (looking-at "^[^ ]+")
  8747. (match-string 0))))
  8748. (org-store-link-props :type "help"))
  8749. ((eq major-mode 'w3-mode)
  8750. (setq cpltxt (if (and (buffer-name)
  8751. (not (string-match "Untitled" (buffer-name))))
  8752. (buffer-name)
  8753. (url-view-url t))
  8754. link (url-view-url t))
  8755. (org-store-link-props :type "w3" :url (url-view-url t)))
  8756. ((eq major-mode 'image-mode)
  8757. (setq cpltxt (concat "file:"
  8758. (abbreviate-file-name buffer-file-name))
  8759. link cpltxt)
  8760. (org-store-link-props :type "image" :file buffer-file-name))
  8761. ;; In dired, store a link to the file of the current line
  8762. ((derived-mode-p 'dired-mode)
  8763. (let ((file (dired-get-filename nil t)))
  8764. (setq file (if file
  8765. (abbreviate-file-name
  8766. (expand-file-name (dired-get-filename nil t)))
  8767. ;; otherwise, no file so use current directory.
  8768. default-directory))
  8769. (setq cpltxt (concat "file:" file)
  8770. link cpltxt)))
  8771. ((setq search (run-hook-with-args-until-success
  8772. 'org-create-file-search-functions))
  8773. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8774. "::" search))
  8775. (setq cpltxt (or description link)))
  8776. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8777. (org-with-limited-levels
  8778. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8779. (cond
  8780. ;; Store a link using the target at point
  8781. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8782. (setq cpltxt
  8783. (concat "file:"
  8784. (abbreviate-file-name
  8785. (buffer-file-name (buffer-base-buffer)))
  8786. "::" (match-string 1))
  8787. link cpltxt))
  8788. ((and (featurep 'org-id)
  8789. (or (eq org-id-link-to-org-use-id t)
  8790. (and (called-interactively-p 'any)
  8791. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8792. (and (eq org-id-link-to-org-use-id
  8793. 'create-if-interactive-and-no-custom-id)
  8794. (not custom-id))))
  8795. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8796. ;; Store a link using the ID at point
  8797. (setq link (condition-case nil
  8798. (prog1 (org-id-store-link)
  8799. (setq desc (or (plist-get org-store-link-plist
  8800. :description)
  8801. "")))
  8802. (error
  8803. ;; Probably before first headline, link only to file
  8804. (concat "file:"
  8805. (abbreviate-file-name
  8806. (buffer-file-name (buffer-base-buffer))))))))
  8807. (t
  8808. ;; Just link to current headline
  8809. (setq cpltxt (concat "file:"
  8810. (abbreviate-file-name
  8811. (buffer-file-name (buffer-base-buffer)))))
  8812. ;; Add a context search string
  8813. (when (org-xor org-context-in-file-links arg)
  8814. (let* ((element (org-element-at-point))
  8815. (name (org-element-property :name element)))
  8816. (setq txt (cond
  8817. ((org-at-heading-p) nil)
  8818. (name)
  8819. ((org-region-active-p)
  8820. (buffer-substring (region-beginning) (region-end)))))
  8821. (when (or (null txt) (string-match "\\S-" txt))
  8822. (setq cpltxt
  8823. (concat cpltxt "::"
  8824. (condition-case nil
  8825. (org-make-org-heading-search-string txt)
  8826. (error "")))
  8827. desc (or name
  8828. (nth 4 (ignore-errors (org-heading-components)))
  8829. "NONE")))))
  8830. (when (string-match "::\\'" cpltxt)
  8831. (setq cpltxt (substring cpltxt 0 -2)))
  8832. (setq link cpltxt)))))
  8833. ((buffer-file-name (buffer-base-buffer))
  8834. ;; Just link to this file here.
  8835. (setq cpltxt (concat "file:"
  8836. (abbreviate-file-name
  8837. (buffer-file-name (buffer-base-buffer)))))
  8838. ;; Add a context string.
  8839. (when (org-xor org-context-in-file-links arg)
  8840. (setq txt (if (org-region-active-p)
  8841. (buffer-substring (region-beginning) (region-end))
  8842. (buffer-substring (point-at-bol) (point-at-eol))))
  8843. ;; Only use search option if there is some text.
  8844. (when (string-match "\\S-" txt)
  8845. (setq cpltxt
  8846. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8847. desc "NONE")))
  8848. (setq link cpltxt))
  8849. ((called-interactively-p 'interactive)
  8850. (user-error "No method for storing a link from this buffer"))
  8851. (t (setq link nil)))
  8852. ;; We're done setting link and desc, clean up
  8853. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8854. (setq link (or link cpltxt)
  8855. desc (or desc cpltxt))
  8856. (cond ((not desc))
  8857. ((equal desc "NONE") (setq desc nil))
  8858. (t (setq desc
  8859. (replace-regexp-in-string
  8860. org-bracket-link-analytic-regexp
  8861. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8862. desc))))
  8863. ;; Return the link
  8864. (if (not (and (or (called-interactively-p 'any)
  8865. executing-kbd-macro)
  8866. link))
  8867. (or agenda-link (and link (org-make-link-string link desc)))
  8868. (push (list link desc) org-stored-links)
  8869. (message "Stored: %s" (or desc link))
  8870. (when custom-id
  8871. (setq link (concat "file:" (abbreviate-file-name
  8872. (buffer-file-name)) "::#" custom-id))
  8873. (push (list link desc) org-stored-links))
  8874. (car org-stored-links)))))
  8875. (defun org-store-link-props (&rest plist)
  8876. "Store link properties, extract names, addresses and dates."
  8877. (let ((x (plist-get plist :from)))
  8878. (when x
  8879. (let ((adr (mail-extract-address-components x)))
  8880. (setq plist (plist-put plist :fromname (car adr)))
  8881. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8882. (let ((x (plist-get plist :to)))
  8883. (when x
  8884. (let ((adr (mail-extract-address-components x)))
  8885. (setq plist (plist-put plist :toname (car adr)))
  8886. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8887. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8888. (when x
  8889. (setq plist (plist-put plist :date-timestamp
  8890. (format-time-string
  8891. (org-time-stamp-format t) x)))
  8892. (setq plist (plist-put plist :date-timestamp-inactive
  8893. (format-time-string
  8894. (org-time-stamp-format t t) x)))))
  8895. (let ((from (plist-get plist :from))
  8896. (to (plist-get plist :to)))
  8897. (when (and from to org-from-is-user-regexp)
  8898. (setq plist
  8899. (plist-put plist :fromto
  8900. (if (string-match org-from-is-user-regexp from)
  8901. (concat "to %t")
  8902. (concat "from %f"))))))
  8903. (setq org-store-link-plist plist))
  8904. (defun org-add-link-props (&rest plist)
  8905. "Add these properties to the link property list."
  8906. (let (key value)
  8907. (while plist
  8908. (setq key (pop plist) value (pop plist))
  8909. (setq org-store-link-plist
  8910. (plist-put org-store-link-plist key value)))))
  8911. (defun org-email-link-description (&optional fmt)
  8912. "Return the description part of an email link.
  8913. This takes information from `org-store-link-plist' and formats it
  8914. according to FMT (default from `org-email-link-description-format')."
  8915. (setq fmt (or fmt org-email-link-description-format))
  8916. (let* ((p org-store-link-plist)
  8917. (to (plist-get p :toaddress))
  8918. (from (plist-get p :fromaddress))
  8919. (table
  8920. (list
  8921. (cons "%c" (plist-get p :fromto))
  8922. (cons "%F" (plist-get p :from))
  8923. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8924. (cons "%T" (plist-get p :to))
  8925. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8926. (cons "%s" (plist-get p :subject))
  8927. (cons "%d" (plist-get p :date))
  8928. (cons "%m" (plist-get p :message-id)))))
  8929. (when (string-match "%c" fmt)
  8930. ;; Check if the user wrote this message
  8931. (if (and org-from-is-user-regexp from to
  8932. (save-match-data (string-match org-from-is-user-regexp from)))
  8933. (setq fmt (replace-match "to %t" t t fmt))
  8934. (setq fmt (replace-match "from %f" t t fmt))))
  8935. (org-replace-escapes fmt table)))
  8936. (defun org-make-org-heading-search-string (&optional string)
  8937. "Make search string for the current headline or STRING."
  8938. (let ((s (or string
  8939. (and (derived-mode-p 'org-mode)
  8940. (save-excursion
  8941. (org-back-to-heading t)
  8942. (org-element-property :raw-value (org-element-at-point))))))
  8943. (lines org-context-in-file-links))
  8944. (or string (setq s (concat "*" s))) ; Add * for headlines
  8945. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8946. (when (and string (integerp lines) (> lines 0))
  8947. (let ((slines (org-split-string s "\n")))
  8948. (when (< lines (length slines))
  8949. (setq s (mapconcat
  8950. 'identity
  8951. (reverse (nthcdr (- (length slines) lines)
  8952. (reverse slines))) "\n")))))
  8953. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8954. (defun org-make-link-string (link &optional description)
  8955. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8956. (unless (org-string-nw-p link) (error "Empty link"))
  8957. (let ((uri (cond ((string-match org-link-types-re link)
  8958. (concat (match-string 1 link)
  8959. (org-link-escape (substring link (match-end 1)))))
  8960. ;; For readability, url-encode internal links only
  8961. ;; when absolutely needed (i.e, when they contain
  8962. ;; square brackets). File links however, are
  8963. ;; encoded since, e.g., spaces are significant.
  8964. ((or (file-name-absolute-p link)
  8965. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8966. (org-link-escape link))
  8967. (t link)))
  8968. (description
  8969. (and (org-string-nw-p description)
  8970. ;; Remove brackets from description, as they are fatal.
  8971. (replace-regexp-in-string
  8972. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8973. (org-trim description)))))
  8974. (format "[[%s]%s]"
  8975. uri
  8976. (if description (format "[%s]" description) ""))))
  8977. (defconst org-link-escape-chars
  8978. ;;%20 %5B %5D %25
  8979. '(?\s ?\[ ?\] ?%)
  8980. "List of characters that should be escaped in a link when stored to Org.
  8981. This is the list that is used for internal purposes.")
  8982. (defun org-link-escape (text &optional table merge)
  8983. "Return percent escaped representation of TEXT.
  8984. TEXT is a string with the text to escape.
  8985. Optional argument TABLE is a list with characters that should be
  8986. escaped. When nil, `org-link-escape-chars' is used.
  8987. If optional argument MERGE is set, merge TABLE into
  8988. `org-link-escape-chars'."
  8989. (let ((characters-to-encode
  8990. (cond ((null table) org-link-escape-chars)
  8991. (merge (append org-link-escape-chars table))
  8992. (t table))))
  8993. (mapconcat
  8994. (lambda (c)
  8995. (if (or (memq c characters-to-encode)
  8996. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8997. (mapconcat (lambda (e) (format "%%%.2X" e))
  8998. (or (encode-coding-char c 'utf-8)
  8999. (error "Unable to percent escape character: %c" c))
  9000. "")
  9001. (char-to-string c)))
  9002. text "")))
  9003. (defun org-link-unescape (str)
  9004. "Unhex hexified Unicode parts in string STR.
  9005. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9006. reciprocal of `org-link-escape', which see."
  9007. (if (org-string-nw-p str)
  9008. (replace-regexp-in-string
  9009. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9010. str))
  9011. (defun org-link-unescape-compound (hex)
  9012. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9013. Note: this function also decodes single byte encodings like
  9014. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9015. (save-match-data
  9016. (let* ((bytes (cdr (split-string hex "%")))
  9017. (ret "")
  9018. (eat 0)
  9019. (sum 0))
  9020. (while bytes
  9021. (let* ((val (string-to-number (pop bytes) 16))
  9022. (shift-xor
  9023. (if (= 0 eat)
  9024. (cond
  9025. ((>= val 252) (cons 6 252))
  9026. ((>= val 248) (cons 5 248))
  9027. ((>= val 240) (cons 4 240))
  9028. ((>= val 224) (cons 3 224))
  9029. ((>= val 192) (cons 2 192))
  9030. (t (cons 0 0)))
  9031. (cons 6 128))))
  9032. (when (>= val 192) (setq eat (car shift-xor)))
  9033. (setq val (logxor val (cdr shift-xor)))
  9034. (setq sum (+ (lsh sum (car shift-xor)) val))
  9035. (when (> eat 0) (setq eat (- eat 1)))
  9036. (cond
  9037. ((= 0 eat) ;multi byte
  9038. (setq ret (concat ret (char-to-string sum)))
  9039. (setq sum 0))
  9040. ((not bytes) ; single byte(s)
  9041. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9042. ret)))
  9043. (defun org-link-unescape-single-byte-sequence (hex)
  9044. "Unhexify hex-encoded single byte character sequences."
  9045. (mapconcat (lambda (byte)
  9046. (char-to-string (string-to-number byte 16)))
  9047. (cdr (split-string hex "%")) ""))
  9048. (defun org-xor (a b)
  9049. "Exclusive or."
  9050. (if a (not b) b))
  9051. (defun org-fixup-message-id-for-http (s)
  9052. "Replace special characters in a message id, so it can be used in an http query."
  9053. (when (string-match "%" s)
  9054. (setq s (mapconcat (lambda (c)
  9055. (if (eq c ?%)
  9056. "%25"
  9057. (char-to-string c)))
  9058. s "")))
  9059. (while (string-match "<" s)
  9060. (setq s (replace-match "%3C" t t s)))
  9061. (while (string-match ">" s)
  9062. (setq s (replace-match "%3E" t t s)))
  9063. (while (string-match "@" s)
  9064. (setq s (replace-match "%40" t t s)))
  9065. s)
  9066. (defun org-link-prettify (link)
  9067. "Return a human-readable representation of LINK.
  9068. The car of LINK must be a raw link.
  9069. The cdr of LINK must be either a link description or nil."
  9070. (let ((desc (or (cadr link) "<no description>")))
  9071. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9072. "<" (car link) ">")))
  9073. ;;;###autoload
  9074. (defun org-insert-link-global ()
  9075. "Insert a link like Org mode does.
  9076. This command can be called in any mode to insert a link in Org syntax."
  9077. (interactive)
  9078. (org-load-modules-maybe)
  9079. (org-run-like-in-org-mode 'org-insert-link))
  9080. (defun org-insert-all-links (arg &optional pre post)
  9081. "Insert all links in `org-stored-links'.
  9082. When a universal prefix, do not delete the links from `org-stored-links'.
  9083. When `ARG' is a number, insert the last N link(s).
  9084. `PRE' and `POST' are optional arguments to define a string to
  9085. prepend or to append."
  9086. (interactive "P")
  9087. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9088. (links (copy-sequence org-stored-links))
  9089. (pr (or pre "- "))
  9090. (po (or post "\n"))
  9091. (cnt 1) l)
  9092. (if (null org-stored-links)
  9093. (message "No link to insert")
  9094. (while (and (or (listp arg) (>= arg cnt))
  9095. (setq l (if (listp arg)
  9096. (pop links)
  9097. (pop org-stored-links))))
  9098. (setq cnt (1+ cnt))
  9099. (insert pr)
  9100. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9101. (insert po)))))
  9102. (defun org-insert-last-stored-link (arg)
  9103. "Insert the last link stored in `org-stored-links'."
  9104. (interactive "p")
  9105. (org-insert-all-links arg "" "\n"))
  9106. (defun org-link-fontify-links-to-this-file ()
  9107. "Fontify links to the current file in `org-stored-links'."
  9108. (let ((f (buffer-file-name)) a b)
  9109. (setq a (mapcar (lambda(l)
  9110. (let ((ll (car l)))
  9111. (when (and (string-match "^file:\\(.+\\)::" ll)
  9112. (equal f (expand-file-name (match-string 1 ll))))
  9113. ll)))
  9114. org-stored-links))
  9115. (when (featurep 'org-id)
  9116. (setq b (mapcar (lambda(l)
  9117. (let ((ll (car l)))
  9118. (when (and (string-match "^id:\\(.+\\)$" ll)
  9119. (equal f (expand-file-name
  9120. (or (org-id-find-id-file
  9121. (match-string 1 ll)) ""))))
  9122. ll)))
  9123. org-stored-links)))
  9124. (mapcar (lambda(l)
  9125. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9126. (delq nil (append a b)))))
  9127. (defvar org--links-history nil)
  9128. (defun org-insert-link (&optional complete-file link-location default-description)
  9129. "Insert a link. At the prompt, enter the link.
  9130. Completion can be used to insert any of the link protocol prefixes in use.
  9131. The history can be used to select a link previously stored with
  9132. `org-store-link'. When the empty string is entered (i.e. if you just
  9133. press `RET' at the prompt), the link defaults to the most recently
  9134. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9135. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9136. You will also be prompted for a description, and if one is given, it will
  9137. be displayed in the buffer instead of the link.
  9138. If there is already a link at point, this command will allow you to edit
  9139. link and description parts.
  9140. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9141. file name can be
  9142. selected using completion. The path to the file will be relative to the
  9143. current directory if the file is in the current directory or a subdirectory.
  9144. Otherwise, the link will be the absolute path as completed in the minibuffer
  9145. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9146. option `org-link-file-path-type'.
  9147. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9148. absolute path even if the file is in
  9149. the current directory or below.
  9150. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9151. prefix negates `org-keep-stored-link-after-insertion'.
  9152. If `org-make-link-description-function' is non-nil, this function will be
  9153. called with the link target, and the result will be the default
  9154. link description.
  9155. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9156. the link location instead of reading one interactively.
  9157. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9158. as the default description."
  9159. (interactive "P")
  9160. (let* ((wcf (current-window-configuration))
  9161. (origbuf (current-buffer))
  9162. (region (when (org-region-active-p)
  9163. (buffer-substring (region-beginning) (region-end))))
  9164. (remove (and region (list (region-beginning) (region-end))))
  9165. (desc region)
  9166. (link link-location)
  9167. (abbrevs org-link-abbrev-alist-local)
  9168. entry all-prefixes auto-desc)
  9169. (cond
  9170. (link-location) ; specified by arg, just use it.
  9171. ((org-in-regexp org-bracket-link-regexp 1)
  9172. ;; We do have a link at point, and we are going to edit it.
  9173. (setq remove (list (match-beginning 0) (match-end 0)))
  9174. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9175. (setq link (read-string "Link: "
  9176. (org-link-unescape
  9177. (match-string-no-properties 1)))))
  9178. ((or (org-in-regexp org-angle-link-re)
  9179. (org-in-regexp org-plain-link-re))
  9180. ;; Convert to bracket link
  9181. (setq remove (list (match-beginning 0) (match-end 0))
  9182. link (read-string "Link: "
  9183. (org-unbracket-string "<" ">" (match-string 0)))))
  9184. ((member complete-file '((4) (16)))
  9185. ;; Completing read for file names.
  9186. (setq link (org-file-complete-link complete-file)))
  9187. (t
  9188. ;; Read link, with completion for stored links.
  9189. (org-link-fontify-links-to-this-file)
  9190. (org-switch-to-buffer-other-window "*Org Links*")
  9191. (with-current-buffer "*Org Links*"
  9192. (erase-buffer)
  9193. (insert "Insert a link.
  9194. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9195. (when org-stored-links
  9196. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9197. (insert (mapconcat 'org-link-prettify
  9198. (reverse org-stored-links) "\n")))
  9199. (goto-char (point-min)))
  9200. (let ((cw (selected-window)))
  9201. (select-window (get-buffer-window "*Org Links*" 'visible))
  9202. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9203. (unless (pos-visible-in-window-p (point-max))
  9204. (org-fit-window-to-buffer))
  9205. (and (window-live-p cw) (select-window cw)))
  9206. (setq all-prefixes (append (mapcar 'car abbrevs)
  9207. (mapcar 'car org-link-abbrev-alist)
  9208. (org-link-types)))
  9209. (unwind-protect
  9210. ;; Fake a link history, containing the stored links.
  9211. (let ((org--links-history
  9212. (append (mapcar #'car org-stored-links)
  9213. org-insert-link-history)))
  9214. (setq link
  9215. (org-completing-read
  9216. "Link: "
  9217. (append
  9218. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9219. (mapcar #'car org-stored-links))
  9220. nil nil nil
  9221. 'org--links-history
  9222. (caar org-stored-links)))
  9223. (unless (org-string-nw-p link) (user-error "No link selected"))
  9224. (dolist (l org-stored-links)
  9225. (when (equal link (cadr l))
  9226. (setq link (car l))
  9227. (setq auto-desc t)))
  9228. (when (or (member link all-prefixes)
  9229. (and (equal ":" (substring link -1))
  9230. (member (substring link 0 -1) all-prefixes)
  9231. (setq link (substring link 0 -1))))
  9232. (setq link (with-current-buffer origbuf
  9233. (org-link-try-special-completion link)))))
  9234. (set-window-configuration wcf)
  9235. (kill-buffer "*Org Links*"))
  9236. (setq entry (assoc link org-stored-links))
  9237. (or entry (push link org-insert-link-history))
  9238. (setq desc (or desc (nth 1 entry)))))
  9239. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9240. (not org-keep-stored-link-after-insertion))
  9241. (setq org-stored-links (delq (assoc link org-stored-links)
  9242. org-stored-links)))
  9243. (when (and (string-match org-plain-link-re link)
  9244. (not (string-match org-ts-regexp link)))
  9245. ;; URL-like link, normalize the use of angular brackets.
  9246. (setq link (org-unbracket-string "<" ">" link)))
  9247. ;; Check if we are linking to the current file with a search
  9248. ;; option If yes, simplify the link by using only the search
  9249. ;; option.
  9250. (when (and buffer-file-name
  9251. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9252. (let* ((path (match-string 1 link))
  9253. (case-fold-search nil)
  9254. (search (match-string 2 link)))
  9255. (save-match-data
  9256. (when (equal (file-truename buffer-file-name) (file-truename path))
  9257. ;; We are linking to this same file, with a search option
  9258. (setq link search)))))
  9259. ;; Check if we can/should use a relative path. If yes, simplify the link
  9260. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9261. (let* ((type (match-string 1 link))
  9262. (path (match-string 2 link))
  9263. (origpath path)
  9264. (case-fold-search nil))
  9265. (cond
  9266. ((or (eq org-link-file-path-type 'absolute)
  9267. (equal complete-file '(16)))
  9268. (setq path (abbreviate-file-name (expand-file-name path))))
  9269. ((eq org-link-file-path-type 'noabbrev)
  9270. (setq path (expand-file-name path)))
  9271. ((eq org-link-file-path-type 'relative)
  9272. (setq path (file-relative-name path)))
  9273. (t
  9274. (save-match-data
  9275. (if (string-match (concat "^" (regexp-quote
  9276. (expand-file-name
  9277. (file-name-as-directory
  9278. default-directory))))
  9279. (expand-file-name path))
  9280. ;; We are linking a file with relative path name.
  9281. (setq path (substring (expand-file-name path)
  9282. (match-end 0)))
  9283. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9284. (setq link (concat type path))
  9285. (when (equal desc origpath)
  9286. (setq desc path))))
  9287. (if org-make-link-description-function
  9288. (setq desc
  9289. (or (condition-case nil
  9290. (funcall org-make-link-description-function link desc)
  9291. (error (progn (message "Can't get link description from `%s'"
  9292. (symbol-name org-make-link-description-function))
  9293. (sit-for 2) nil)))
  9294. (read-string "Description: " default-description)))
  9295. (if default-description (setq desc default-description)
  9296. (setq desc (or (and auto-desc desc)
  9297. (read-string "Description: " desc)))))
  9298. (unless (string-match "\\S-" desc) (setq desc nil))
  9299. (when remove (apply 'delete-region remove))
  9300. (insert (org-make-link-string link desc))
  9301. ;; Redisplay so as the new link has proper invisible characters.
  9302. (sit-for 0)))
  9303. (defun org-link-try-special-completion (type)
  9304. "If there is completion support for link type TYPE, offer it."
  9305. (let ((fun (org-link-get-parameter type :complete)))
  9306. (if (functionp fun)
  9307. (funcall fun)
  9308. (read-string "Link (no completion support): " (concat type ":")))))
  9309. (defun org-file-complete-link (&optional arg)
  9310. "Create a file link using completion."
  9311. (let ((file (read-file-name "File: "))
  9312. (pwd (file-name-as-directory (expand-file-name ".")))
  9313. (pwd1 (file-name-as-directory (abbreviate-file-name
  9314. (expand-file-name ".")))))
  9315. (cond ((equal arg '(16))
  9316. (concat "file:"
  9317. (abbreviate-file-name (expand-file-name file))))
  9318. ((string-match
  9319. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9320. (concat "file:" (match-string 1 file)))
  9321. ((string-match
  9322. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9323. (expand-file-name file))
  9324. (concat "file:"
  9325. (match-string 1 (expand-file-name file))))
  9326. (t (concat "file:" file)))))
  9327. (defun org-completing-read (&rest args)
  9328. "Completing-read with SPACE being a normal character."
  9329. (let ((enable-recursive-minibuffers t)
  9330. (minibuffer-local-completion-map
  9331. (copy-keymap minibuffer-local-completion-map)))
  9332. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9333. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9334. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9335. 'org-time-stamp-inactive)
  9336. (apply #'completing-read args)))
  9337. ;;; Opening/following a link
  9338. (defvar org-link-search-failed nil)
  9339. (defvar org-open-link-functions nil
  9340. "Hook for functions finding a plain text link.
  9341. These functions must take a single argument, the link content.
  9342. They will be called for links that look like [[link text][description]]
  9343. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9344. like a filename (e.g. \"./blue.png\").
  9345. These functions will be called *before* Org attempts to resolve the
  9346. link by doing text searches in the current buffer - so if you want a
  9347. link \"[[target]]\" to still find \"<<target>>\", your function should
  9348. handle this as a special case.
  9349. When the function does handle the link, it must return a non-nil value.
  9350. If it decides that it is not responsible for this link, it must return
  9351. nil to indicate that that Org can continue with other options like
  9352. exact and fuzzy text search.")
  9353. (defun org-next-link (&optional search-backward)
  9354. "Move forward to the next link.
  9355. If the link is in hidden text, expose it."
  9356. (interactive "P")
  9357. (when (and org-link-search-failed (eq this-command last-command))
  9358. (goto-char (point-min))
  9359. (message "Link search wrapped back to beginning of buffer"))
  9360. (setq org-link-search-failed nil)
  9361. (let* ((pos (point))
  9362. (ct (org-context))
  9363. (a (assq :link ct))
  9364. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9365. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9366. ((looking-at org-any-link-re)
  9367. ;; Don't stay stuck at link without an org-link face
  9368. (forward-char (if search-backward -1 1))))
  9369. (if (funcall srch-fun org-any-link-re nil t)
  9370. (progn
  9371. (goto-char (match-beginning 0))
  9372. (when (outline-invisible-p) (org-show-context)))
  9373. (goto-char pos)
  9374. (setq org-link-search-failed t)
  9375. (message "No further link found"))))
  9376. (defun org-previous-link ()
  9377. "Move backward to the previous link.
  9378. If the link is in hidden text, expose it."
  9379. (interactive)
  9380. (funcall 'org-next-link t))
  9381. (defun org-translate-link (s)
  9382. "Translate a link string if a translation function has been defined."
  9383. (with-temp-buffer
  9384. (insert (org-trim s))
  9385. (org-trim (org-element-interpret-data (org-element-context)))))
  9386. (defun org-translate-link-from-planner (type path)
  9387. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9388. This is still an experimental function, your mileage may vary."
  9389. (cond
  9390. ((member type '("http" "https" "news" "ftp"))
  9391. ;; standard Internet links are the same.
  9392. nil)
  9393. ((and (equal type "irc") (string-match "^//" path))
  9394. ;; Planner has two / at the beginning of an irc link, we have 1.
  9395. ;; We should have zero, actually....
  9396. (setq path (substring path 1)))
  9397. ((and (equal type "lisp") (string-match "^/" path))
  9398. ;; Planner has a slash, we do not.
  9399. (setq type "elisp" path (substring path 1)))
  9400. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9401. ;; A typical message link. Planner has the id after the final slash,
  9402. ;; we separate it with a hash mark
  9403. (setq path (concat (match-string 1 path) "#"
  9404. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9405. (cons type path))
  9406. (defun org-find-file-at-mouse (ev)
  9407. "Open file link or URL at mouse."
  9408. (interactive "e")
  9409. (mouse-set-point ev)
  9410. (org-open-at-point 'in-emacs))
  9411. (defun org-open-at-mouse (ev)
  9412. "Open file link or URL at mouse.
  9413. See the docstring of `org-open-file' for details."
  9414. (interactive "e")
  9415. (mouse-set-point ev)
  9416. (when (eq major-mode 'org-agenda-mode)
  9417. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9418. (org-open-at-point))
  9419. (defvar org-window-config-before-follow-link nil
  9420. "The window configuration before following a link.
  9421. This is saved in case the need arises to restore it.")
  9422. ;;;###autoload
  9423. (defun org-open-at-point-global ()
  9424. "Follow a link or time-stamp like Org mode does.
  9425. This command can be called in any mode to follow an external link
  9426. or a time-stamp that has Org mode syntax. Its behavior is
  9427. undefined when called on internal links (e.g., fuzzy links).
  9428. Raise an error when there is nothing to follow. "
  9429. (interactive)
  9430. (cond ((org-in-regexp org-any-link-re)
  9431. (org-open-link-from-string (match-string-no-properties 0)))
  9432. ((or (org-in-regexp org-ts-regexp-both nil t)
  9433. (org-in-regexp org-tsr-regexp-both nil t))
  9434. (org-follow-timestamp-link))
  9435. (t (user-error "No link found"))))
  9436. ;;;###autoload
  9437. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9438. "Open a link in the string S, as if it was in Org mode."
  9439. (interactive "sLink: \nP")
  9440. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9441. (with-temp-buffer
  9442. (let ((org-inhibit-startup (not reference-buffer)))
  9443. (org-mode)
  9444. (insert s)
  9445. (goto-char (point-min))
  9446. (when reference-buffer
  9447. (setq org-link-abbrev-alist-local
  9448. (with-current-buffer reference-buffer
  9449. org-link-abbrev-alist-local)))
  9450. (org-open-at-point arg reference-buffer)))))
  9451. (defvar org-open-at-point-functions nil
  9452. "Hook that is run when following a link at point.
  9453. Functions in this hook must return t if they identify and follow
  9454. a link at point. If they don't find anything interesting at point,
  9455. they must return nil.")
  9456. (defvar org-link-search-inhibit-query nil)
  9457. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9458. (defun org--open-doi-link (path)
  9459. "Open a \"doi\" type link.
  9460. PATH is a the path to search for, as a string."
  9461. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9462. (defun org--open-elisp-link (path)
  9463. "Open a \"elisp\" type link.
  9464. PATH is the sexp to evaluate, as a string."
  9465. (let ((cmd path))
  9466. (if (or (and (org-string-nw-p
  9467. org-confirm-elisp-link-not-regexp)
  9468. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9469. (not org-confirm-elisp-link-function)
  9470. (funcall org-confirm-elisp-link-function
  9471. (format "Execute \"%s\" as elisp? "
  9472. (org-add-props cmd nil 'face 'org-warning))))
  9473. (message "%s => %s" cmd
  9474. (if (eq (string-to-char cmd) ?\()
  9475. (eval (read cmd))
  9476. (call-interactively (read cmd))))
  9477. (user-error "Abort"))))
  9478. (defun org--open-help-link (path)
  9479. "Open a \"help\" type link.
  9480. PATH is a symbol name, as a string."
  9481. (pcase (intern path)
  9482. ((and (pred fboundp) variable) (describe-function variable))
  9483. ((and (pred boundp) function) (describe-variable function))
  9484. (name (user-error "Unknown function or variable: %s" name))))
  9485. (defun org--open-shell-link (path)
  9486. "Open a \"shell\" type link.
  9487. PATH is the command to execute, as a string."
  9488. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9489. (cmd path))
  9490. (if (or (and (org-string-nw-p
  9491. org-confirm-shell-link-not-regexp)
  9492. (string-match
  9493. org-confirm-shell-link-not-regexp cmd))
  9494. (not org-confirm-shell-link-function)
  9495. (funcall org-confirm-shell-link-function
  9496. (format "Execute \"%s\" in shell? "
  9497. (org-add-props cmd nil
  9498. 'face 'org-warning))))
  9499. (progn
  9500. (message "Executing %s" cmd)
  9501. (shell-command cmd buf)
  9502. (when (featurep 'midnight)
  9503. (setq clean-buffer-list-kill-buffer-names
  9504. (cons (buffer-name buf)
  9505. clean-buffer-list-kill-buffer-names))))
  9506. (user-error "Abort"))))
  9507. (defun org-open-at-point (&optional arg reference-buffer)
  9508. "Open link, timestamp, footnote or tags at point.
  9509. When point is on a link, follow it. Normally, files will be
  9510. opened by an appropriate application. If the optional prefix
  9511. argument ARG is non-nil, Emacs will visit the file. With
  9512. a double prefix argument, try to open outside of Emacs, in the
  9513. application the system uses for this file type.
  9514. When point is on a timestamp, open the agenda at the day
  9515. specified.
  9516. When point is a footnote definition, move to the first reference
  9517. found. If it is on a reference, move to the associated
  9518. definition.
  9519. When point is on a headline, display a list of every link in the
  9520. entry, so it is possible to pick one, or all, of them. If point
  9521. is on a tag, call `org-tags-view' instead.
  9522. When optional argument REFERENCE-BUFFER is non-nil, it should
  9523. specify a buffer from where the link search should happen. This
  9524. is used internally by `org-open-link-from-string'.
  9525. On top of syntactically correct links, this function will open
  9526. the link at point in comments or comment blocks and the first
  9527. link in a property drawer line."
  9528. (interactive "P")
  9529. ;; On a code block, open block's results.
  9530. (unless (call-interactively 'org-babel-open-src-block-result)
  9531. (org-load-modules-maybe)
  9532. (setq org-window-config-before-follow-link (current-window-configuration))
  9533. (org-remove-occur-highlights nil nil t)
  9534. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9535. (let* ((context
  9536. ;; Only consider supported types, even if they are not
  9537. ;; the closest one.
  9538. (org-element-lineage
  9539. (org-element-context)
  9540. '(clock comment comment-block footnote-definition
  9541. footnote-reference headline inlinetask keyword link
  9542. node-property timestamp)
  9543. t))
  9544. (type (org-element-type context))
  9545. (value (org-element-property :value context)))
  9546. (cond
  9547. ((not context) (user-error "No link found"))
  9548. ;; Exception: open timestamps and links in properties
  9549. ;; drawers, keywords and comments.
  9550. ((memq type '(comment comment-block keyword node-property))
  9551. (call-interactively #'org-open-at-point-global))
  9552. ;; On a headline or an inlinetask, but not on a timestamp,
  9553. ;; a link, a footnote reference or on tags.
  9554. ((and (memq type '(headline inlinetask))
  9555. ;; Not on tags.
  9556. (let ((case-fold-search nil))
  9557. (save-excursion
  9558. (beginning-of-line)
  9559. (looking-at org-complex-heading-regexp))
  9560. (or (not (match-beginning 5))
  9561. (< (point) (match-beginning 5)))))
  9562. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9563. (links (car data))
  9564. (links-end (cdr data)))
  9565. (if links
  9566. (dolist (link (if (stringp links) (list links) links))
  9567. (search-forward link nil links-end)
  9568. (goto-char (match-beginning 0))
  9569. (org-open-at-point))
  9570. (require 'org-attach)
  9571. (org-attach-reveal 'if-exists))))
  9572. ;; On a clock line, make sure point is on the timestamp
  9573. ;; before opening it.
  9574. ((and (eq type 'clock)
  9575. value
  9576. (>= (point) (org-element-property :begin value))
  9577. (<= (point) (org-element-property :end value)))
  9578. (org-follow-timestamp-link))
  9579. ;; Do nothing on white spaces after an object.
  9580. ((>= (point)
  9581. (save-excursion
  9582. (goto-char (org-element-property :end context))
  9583. (skip-chars-backward " \t")
  9584. (point)))
  9585. (user-error "No link found"))
  9586. ((eq type 'timestamp) (org-follow-timestamp-link))
  9587. ;; On tags within a headline or an inlinetask.
  9588. ((and (memq type '(headline inlinetask))
  9589. (let ((case-fold-search nil))
  9590. (save-excursion (beginning-of-line)
  9591. (looking-at org-complex-heading-regexp))
  9592. (and (match-beginning 5)
  9593. (>= (point) (match-beginning 5)))))
  9594. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9595. ((eq type 'link)
  9596. (let ((type (org-element-property :type context))
  9597. (path (org-link-unescape (org-element-property :path context))))
  9598. ;; Switch back to REFERENCE-BUFFER needed when called in
  9599. ;; a temporary buffer through `org-open-link-from-string'.
  9600. (with-current-buffer (or reference-buffer (current-buffer))
  9601. (cond
  9602. ((equal type "file")
  9603. (if (string-match "[*?{]" (file-name-nondirectory path))
  9604. (dired path)
  9605. ;; Look into `org-link-parameters' in order to find
  9606. ;; a DEDICATED-FUNCTION to open file. The function
  9607. ;; will be applied on raw link instead of parsed
  9608. ;; link due to the limitation in `org-add-link-type'
  9609. ;; ("open" function called with a single argument).
  9610. ;; If no such function is found, fallback to
  9611. ;; `org-open-file'.
  9612. (let* ((option (org-element-property :search-option context))
  9613. (app (org-element-property :application context))
  9614. (dedicated-function
  9615. (org-link-get-parameter
  9616. (if app (concat type "+" app) type)
  9617. :follow)))
  9618. (if dedicated-function
  9619. (funcall dedicated-function
  9620. (concat path
  9621. (and option (concat "::" option))))
  9622. (apply #'org-open-file
  9623. path
  9624. (cond (arg)
  9625. ((equal app "emacs") 'emacs)
  9626. ((equal app "sys") 'system))
  9627. (cond ((not option) nil)
  9628. ((string-match-p "\\`[0-9]+\\'" option)
  9629. (list (string-to-number option)))
  9630. (t (list nil
  9631. (org-link-unescape option)))))))))
  9632. ((functionp (org-link-get-parameter type :follow))
  9633. (funcall (org-link-get-parameter type :follow) path))
  9634. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9635. (unless (run-hook-with-args-until-success
  9636. 'org-open-link-functions path)
  9637. (if (not arg) (org-mark-ring-push)
  9638. (switch-to-buffer-other-window
  9639. (org-get-buffer-for-internal-link (current-buffer))))
  9640. (let ((destination
  9641. (org-with-wide-buffer
  9642. (if (equal type "radio")
  9643. (org-search-radio-target
  9644. (org-element-property :path context))
  9645. (org-link-search
  9646. (if (member type '("custom-id" "coderef"))
  9647. (org-element-property :raw-link context)
  9648. path)
  9649. ;; Prevent fuzzy links from matching
  9650. ;; themselves.
  9651. (and (equal type "fuzzy")
  9652. (+ 2 (org-element-property :begin context)))))
  9653. (point))))
  9654. (unless (and (<= (point-min) destination)
  9655. (>= (point-max) destination))
  9656. (widen))
  9657. (goto-char destination))))
  9658. (t (browse-url-at-point))))))
  9659. ;; On a footnote reference or at a footnote definition's label.
  9660. ((or (eq type 'footnote-reference)
  9661. (and (eq type 'footnote-definition)
  9662. (save-excursion
  9663. ;; Do not validate action when point is on the
  9664. ;; spaces right after the footnote label, in
  9665. ;; order to be on par with behaviour on links.
  9666. (skip-chars-forward " \t")
  9667. (let ((begin
  9668. (org-element-property :contents-begin context)))
  9669. (if begin (< (point) begin)
  9670. (= (org-element-property :post-affiliated context)
  9671. (line-beginning-position)))))))
  9672. (org-footnote-action))
  9673. (t (user-error "No link found")))))
  9674. (run-hook-with-args 'org-follow-link-hook)))
  9675. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9676. "Offer links in the current entry and return the selected link.
  9677. If there is only one link, return it.
  9678. If NTH is an integer, return the NTH link found.
  9679. If ZERO is a string, check also this string for a link, and if
  9680. there is one, return it."
  9681. (with-current-buffer buffer
  9682. (org-with-wide-buffer
  9683. (goto-char marker)
  9684. (let ((cnt ?0)
  9685. have-zero end links link c)
  9686. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9687. (push (match-string 0 zero) links)
  9688. (setq cnt (1- cnt) have-zero t))
  9689. (save-excursion
  9690. (org-back-to-heading t)
  9691. (setq end (save-excursion (outline-next-heading) (point)))
  9692. (while (re-search-forward org-any-link-re end t)
  9693. (push (match-string 0) links))
  9694. (setq links (org-uniquify (reverse links))))
  9695. (cond
  9696. ((null links)
  9697. (message "No links"))
  9698. ((equal (length links) 1)
  9699. (setq link (car links)))
  9700. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9701. (setq link (nth (if have-zero nth (1- nth)) links)))
  9702. (t ; we have to select a link
  9703. (save-excursion
  9704. (save-window-excursion
  9705. (delete-other-windows)
  9706. (with-output-to-temp-buffer "*Select Link*"
  9707. (dolist (l links)
  9708. (cond
  9709. ((not (string-match org-bracket-link-regexp l))
  9710. (princ (format "[%c] %s\n" (cl-incf cnt)
  9711. (org-unbracket-string "<" ">" l))))
  9712. ((match-end 3)
  9713. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9714. (match-string 3 l) (match-string 1 l))))
  9715. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9716. (match-string 1 l)))))))
  9717. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9718. (message "Select link to open, RET to open all:")
  9719. (setq c (read-char-exclusive))
  9720. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9721. (when (equal c ?q) (user-error "Abort"))
  9722. (if (equal c ?\C-m)
  9723. (setq link links)
  9724. (setq nth (- c ?0))
  9725. (when have-zero (setq nth (1+ nth)))
  9726. (unless (and (integerp nth) (>= (length links) nth))
  9727. (user-error "Invalid link selection"))
  9728. (setq link (nth (1- nth) links)))))
  9729. (cons link end)))))
  9730. ;; TODO: These functions are deprecated since `org-open-at-point'
  9731. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9732. (defun org-open-file-with-system (path)
  9733. "Open file at PATH using the system way of opening it."
  9734. (org-open-file path 'system))
  9735. (defun org-open-file-with-emacs (path)
  9736. "Open file at PATH in Emacs."
  9737. (org-open-file path 'emacs))
  9738. ;;; File search
  9739. (defvar org-create-file-search-functions nil
  9740. "List of functions to construct the right search string for a file link.
  9741. These functions are called in turn with point at the location to
  9742. which the link should point.
  9743. A function in the hook should first test if it would like to
  9744. handle this file type, for example by checking the `major-mode'
  9745. or the file extension. If it decides not to handle this file, it
  9746. should just return nil to give other functions a chance. If it
  9747. does handle the file, it must return the search string to be used
  9748. when following the link. The search string will be part of the
  9749. file link, given after a double colon, and `org-open-at-point'
  9750. will automatically search for it. If special measures must be
  9751. taken to make the search successful, another function should be
  9752. added to the companion hook `org-execute-file-search-functions',
  9753. which see.
  9754. A function in this hook may also use `setq' to set the variable
  9755. `description' to provide a suggestion for the descriptive text to
  9756. be used for this link when it gets inserted into an Org buffer
  9757. with \\[org-insert-link].")
  9758. (defvar org-execute-file-search-functions nil
  9759. "List of functions to execute a file search triggered by a link.
  9760. Functions added to this hook must accept a single argument, the
  9761. search string that was part of the file link, the part after the
  9762. double colon. The function must first check if it would like to
  9763. handle this search, for example by checking the `major-mode' or
  9764. the file extension. If it decides not to handle this search, it
  9765. should just return nil to give other functions a chance. If it
  9766. does handle the search, it must return a non-nil value to keep
  9767. other functions from trying.
  9768. Each function can access the current prefix argument through the
  9769. variable `current-prefix-arg'. Note that a single prefix is used
  9770. to force opening a link in Emacs, so it may be good to only use a
  9771. numeric or double prefix to guide the search function.
  9772. In case this is needed, a function in this hook can also restore
  9773. the window configuration before `org-open-at-point' was called using:
  9774. (set-window-configuration org-window-config-before-follow-link)")
  9775. (defun org-search-radio-target (target)
  9776. "Search a radio target matching TARGET in current buffer.
  9777. White spaces are not significant."
  9778. (let ((re (format "<<<%s>>>"
  9779. (mapconcat #'regexp-quote
  9780. (org-split-string target "[ \t\n]+")
  9781. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9782. (origin (point)))
  9783. (goto-char (point-min))
  9784. (catch :radio-match
  9785. (while (re-search-forward re nil t)
  9786. (backward-char)
  9787. (let ((object (org-element-context)))
  9788. (when (eq (org-element-type object) 'radio-target)
  9789. (goto-char (org-element-property :begin object))
  9790. (org-show-context 'link-search)
  9791. (throw :radio-match nil))))
  9792. (goto-char origin)
  9793. (user-error "No match for radio target: %s" target))))
  9794. (defun org-link-search (s &optional avoid-pos stealth)
  9795. "Search for a search string S.
  9796. If S starts with \"#\", it triggers a custom ID search.
  9797. If S is enclosed within parenthesis, it initiates a coderef
  9798. search.
  9799. If S is surrounded by forward slashes, it is interpreted as
  9800. a regular expression. In Org mode files, this will create an
  9801. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9802. to list matches. If the current buffer is in `dired-mode', grep
  9803. will be used to search in all files.
  9804. When AVOID-POS is given, ignore matches near that position.
  9805. When optional argument STEALTH is non-nil, do not modify
  9806. visibility around point, thus ignoring `org-show-context-detail'
  9807. variable.
  9808. Search is case-insensitive and ignores white spaces. Return type
  9809. of matched result, which is either `dedicated' or `fuzzy'."
  9810. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9811. (let* ((case-fold-search t)
  9812. (origin (point))
  9813. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9814. (starred (eq (string-to-char normalized) ?*))
  9815. (words (split-string (if starred (substring s 1) s)))
  9816. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9817. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9818. type)
  9819. (cond
  9820. ;; Check if there are any special search functions.
  9821. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9822. ((eq (string-to-char s) ?#)
  9823. ;; Look for a custom ID S if S starts with "#".
  9824. (let* ((id (substring normalized 1))
  9825. (match (org-find-property "CUSTOM_ID" id)))
  9826. (if match (progn (goto-char match) (setf type 'dedicated))
  9827. (error "No match for custom ID: %s" id))))
  9828. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9829. ;; Look for coderef targets if S is enclosed within parenthesis.
  9830. (let ((coderef (match-string-no-properties 1 normalized))
  9831. (re (substring s-single-re 1 -1)))
  9832. (goto-char (point-min))
  9833. (catch :coderef-match
  9834. (while (re-search-forward re nil t)
  9835. (let ((element (org-element-at-point)))
  9836. (when (and (memq (org-element-type element)
  9837. '(example-block src-block))
  9838. ;; Build proper regexp according to current
  9839. ;; block's label format.
  9840. (let ((label-fmt
  9841. (regexp-quote
  9842. (or (org-element-property :label-fmt element)
  9843. org-coderef-label-format))))
  9844. (save-excursion
  9845. (beginning-of-line)
  9846. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9847. (format label-fmt coderef))))))
  9848. (setq type 'dedicated)
  9849. (goto-char (match-beginning 1))
  9850. (throw :coderef-match nil))))
  9851. (goto-char origin)
  9852. (error "No match for coderef: %s" coderef))))
  9853. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9854. ;; Look for a regular expression.
  9855. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9856. (match-string 1 s)))
  9857. ;; From here, we handle fuzzy links.
  9858. ;;
  9859. ;; Look for targets, only if not in a headline search.
  9860. ((and (not starred)
  9861. (let ((target (format "<<%s>>" s-multi-re)))
  9862. (catch :target-match
  9863. (goto-char (point-min))
  9864. (while (re-search-forward target nil t)
  9865. (backward-char)
  9866. (let ((context (org-element-context)))
  9867. (when (eq (org-element-type context) 'target)
  9868. (setq type 'dedicated)
  9869. (goto-char (org-element-property :begin context))
  9870. (throw :target-match t))))
  9871. nil))))
  9872. ;; Look for elements named after S, only if not in a headline
  9873. ;; search.
  9874. ((and (not starred)
  9875. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9876. (catch :name-match
  9877. (goto-char (point-min))
  9878. (while (re-search-forward name nil t)
  9879. (let ((element (org-element-at-point)))
  9880. (when (equal words
  9881. (split-string
  9882. (org-element-property :name element)))
  9883. (setq type 'dedicated)
  9884. (beginning-of-line)
  9885. (throw :name-match t))))
  9886. nil))))
  9887. ;; Regular text search. Prefer headlines in Org mode buffers.
  9888. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9889. ;; statistics cookies and tags.
  9890. ((and (derived-mode-p 'org-mode)
  9891. (let ((title-re
  9892. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9893. org-outline-regexp-bol
  9894. org-comment-string
  9895. (mapconcat #'regexp-quote words ".+")))
  9896. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9897. (comment-re (eval-when-compile
  9898. (format "\\`%s[ \t]+" org-comment-string))))
  9899. (goto-char (point-min))
  9900. (catch :found
  9901. (while (re-search-forward title-re nil t)
  9902. (when (equal words
  9903. (split-string
  9904. (replace-regexp-in-string
  9905. cookie-re ""
  9906. (replace-regexp-in-string
  9907. comment-re "" (org-get-heading t t t)))))
  9908. (throw :found t)))
  9909. nil)))
  9910. (beginning-of-line)
  9911. (setq type 'dedicated))
  9912. ;; Offer to create non-existent headline depending on
  9913. ;; `org-link-search-must-match-exact-headline'.
  9914. ((and (derived-mode-p 'org-mode)
  9915. (not org-link-search-inhibit-query)
  9916. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9917. (yes-or-no-p "No match - create this as a new heading? "))
  9918. (goto-char (point-max))
  9919. (unless (bolp) (newline))
  9920. (org-insert-heading nil t t)
  9921. (insert s "\n")
  9922. (beginning-of-line 0))
  9923. ;; Only headlines are looked after. No need to process
  9924. ;; further: throw an error.
  9925. ((and (derived-mode-p 'org-mode)
  9926. (or starred org-link-search-must-match-exact-headline))
  9927. (goto-char origin)
  9928. (error "No match for fuzzy expression: %s" normalized))
  9929. ;; Regular text search.
  9930. ((catch :fuzzy-match
  9931. (goto-char (point-min))
  9932. (while (re-search-forward s-multi-re nil t)
  9933. ;; Skip match if it contains AVOID-POS or it is included in
  9934. ;; a link with a description but outside the description.
  9935. (unless (or (and avoid-pos
  9936. (<= (match-beginning 0) avoid-pos)
  9937. (> (match-end 0) avoid-pos))
  9938. (and (save-match-data
  9939. (org-in-regexp org-bracket-link-regexp))
  9940. (match-beginning 3)
  9941. (or (> (match-beginning 3) (point))
  9942. (<= (match-end 3) (point)))
  9943. (org-element-lineage
  9944. (save-match-data (org-element-context))
  9945. '(link) t)))
  9946. (goto-char (match-beginning 0))
  9947. (setq type 'fuzzy)
  9948. (throw :fuzzy-match t)))
  9949. nil))
  9950. ;; All failed. Throw an error.
  9951. (t (goto-char origin)
  9952. (error "No match for fuzzy expression: %s" normalized)))
  9953. ;; Disclose surroundings of match, if appropriate.
  9954. (when (and (derived-mode-p 'org-mode) (not stealth))
  9955. (org-show-context 'link-search))
  9956. type))
  9957. (defun org-get-buffer-for-internal-link (buffer)
  9958. "Return a buffer to be used for displaying the link target of internal links."
  9959. (cond
  9960. ((not org-display-internal-link-with-indirect-buffer)
  9961. buffer)
  9962. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9963. (message "Buffer is already a clone, not making another one")
  9964. ;; we also do not modify visibility in this case
  9965. buffer)
  9966. (t ; make a new indirect buffer for displaying the link
  9967. (let* ((bn (buffer-name buffer))
  9968. (ibn (concat bn "(Clone)"))
  9969. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9970. (with-current-buffer ib (org-overview))
  9971. ib))))
  9972. (defun org-do-occur (regexp &optional cleanup)
  9973. "Call the Emacs command `occur'.
  9974. If CLEANUP is non-nil, remove the printout of the regular expression
  9975. in the *Occur* buffer. This is useful if the regex is long and not useful
  9976. to read."
  9977. (occur regexp)
  9978. (when cleanup
  9979. (let ((cwin (selected-window)) win beg end)
  9980. (when (setq win (get-buffer-window "*Occur*"))
  9981. (select-window win))
  9982. (goto-char (point-min))
  9983. (when (re-search-forward "match[a-z]+" nil t)
  9984. (setq beg (match-end 0))
  9985. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9986. (setq end (1- (match-beginning 0)))))
  9987. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9988. (goto-char (point-min))
  9989. (select-window cwin))))
  9990. ;;; The mark ring for links jumps
  9991. (defvar org-mark-ring nil
  9992. "Mark ring for positions before jumps in Org mode.")
  9993. (defvar org-mark-ring-last-goto nil
  9994. "Last position in the mark ring used to go back.")
  9995. ;; Fill and close the ring
  9996. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9997. (dotimes (_ org-mark-ring-length)
  9998. (push (make-marker) org-mark-ring))
  9999. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10000. org-mark-ring)
  10001. (defun org-mark-ring-push (&optional pos buffer)
  10002. "Put the current position or POS into the mark ring and rotate it."
  10003. (interactive)
  10004. (setq pos (or pos (point)))
  10005. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10006. (move-marker (car org-mark-ring)
  10007. (or pos (point))
  10008. (or buffer (current-buffer)))
  10009. (message "%s"
  10010. (substitute-command-keys
  10011. "Position saved to mark ring, go back with \
  10012. `\\[org-mark-ring-goto]'.")))
  10013. (defun org-mark-ring-goto (&optional n)
  10014. "Jump to the previous position in the mark ring.
  10015. With prefix arg N, jump back that many stored positions. When
  10016. called several times in succession, walk through the entire ring.
  10017. Org mode commands jumping to a different position in the current file,
  10018. or to another Org file, automatically push the old position onto the ring."
  10019. (interactive "p")
  10020. (let (p m)
  10021. (if (eq last-command this-command)
  10022. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10023. (setq p org-mark-ring))
  10024. (setq org-mark-ring-last-goto p)
  10025. (setq m (car p))
  10026. (pop-to-buffer-same-window (marker-buffer m))
  10027. (goto-char m)
  10028. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10029. (defun org-add-angle-brackets (s)
  10030. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10031. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10032. s)
  10033. ;;; Following specific links
  10034. (defvar org-agenda-buffer-tmp-name)
  10035. (defvar org-agenda-start-on-weekday)
  10036. (defun org-follow-timestamp-link ()
  10037. "Open an agenda view for the time-stamp date/range at point."
  10038. (cond
  10039. ((org-at-date-range-p t)
  10040. (let ((org-agenda-start-on-weekday)
  10041. (t1 (match-string 1))
  10042. (t2 (match-string 2)) tt1 tt2)
  10043. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10044. tt2 (time-to-days (org-time-string-to-time t2)))
  10045. (let ((org-agenda-buffer-tmp-name
  10046. (format "*Org Agenda(a:%s)"
  10047. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10048. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10049. ((org-at-timestamp-p t)
  10050. (let ((org-agenda-buffer-tmp-name
  10051. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10052. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10053. (substring (match-string 1) 0 10)))
  10054. 1)))
  10055. (t (error "This should not happen"))))
  10056. ;;; Following file links
  10057. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10058. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10059. (declare-function mailcap-mime-info
  10060. "mailcap" (string &optional request no-decode))
  10061. (defvar org-wait nil)
  10062. (defun org-open-file (path &optional in-emacs line search)
  10063. "Open the file at PATH.
  10064. First, this expands any special file name abbreviations. Then the
  10065. configuration variable `org-file-apps' is checked if it contains an
  10066. entry for this file type, and if yes, the corresponding command is launched.
  10067. If no application is found, Emacs simply visits the file.
  10068. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10069. With a double \\[universal-argument] \\[universal-argument] \
  10070. prefix arg, Org tries to avoid opening in Emacs
  10071. and to use an external application to visit the file.
  10072. Optional LINE specifies a line to go to, optional SEARCH a string
  10073. to search for. If LINE or SEARCH is given, the file will be
  10074. opened in Emacs, unless an entry from org-file-apps that makes
  10075. use of groups in a regexp matches.
  10076. If you want to change the way frames are used when following a
  10077. link, please customize `org-link-frame-setup'.
  10078. If the file does not exist, an error is thrown."
  10079. (let* ((file (if (equal path "")
  10080. buffer-file-name
  10081. (substitute-in-file-name (expand-file-name path))))
  10082. (file-apps (append org-file-apps (org-default-apps)))
  10083. (apps (cl-remove-if
  10084. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10085. (apps-dlink (cl-remove-if-not
  10086. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10087. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10088. (dirp (unless remp (file-directory-p file)))
  10089. (file (if (and dirp org-open-directory-means-index-dot-org)
  10090. (concat (file-name-as-directory file) "index.org")
  10091. file))
  10092. (a-m-a-p (assq 'auto-mode apps))
  10093. (dfile (downcase file))
  10094. ;; Reconstruct the original link from the PATH, LINE and
  10095. ;; SEARCH args.
  10096. (link (cond (line (concat file "::" (number-to-string line)))
  10097. (search (concat file "::" search))
  10098. (t file)))
  10099. (dlink (downcase link))
  10100. (ext
  10101. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10102. (match-string 1 dfile)))
  10103. (save-position-maybe
  10104. (let ((old-buffer (current-buffer))
  10105. (old-pos (point))
  10106. (old-mode major-mode))
  10107. (lambda ()
  10108. (and (derived-mode-p 'org-mode)
  10109. (eq old-mode 'org-mode)
  10110. (or (not (eq old-buffer (current-buffer)))
  10111. (not (eq old-pos (point))))
  10112. (org-mark-ring-push old-pos old-buffer)))))
  10113. cmd link-match-data)
  10114. (cond
  10115. ((member in-emacs '((16) system))
  10116. (setq cmd (cdr (assq 'system apps))))
  10117. (in-emacs (setq cmd 'emacs))
  10118. (t
  10119. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10120. (and dirp (cdr (assq 'directory apps)))
  10121. ;; First, try matching against apps-dlink if we
  10122. ;; get a match here, store the match data for
  10123. ;; later.
  10124. (let ((match (assoc-default dlink apps-dlink
  10125. 'string-match)))
  10126. (if match
  10127. (progn (setq link-match-data (match-data))
  10128. match)
  10129. (progn (setq in-emacs (or in-emacs line search))
  10130. nil))) ; if we have no match in apps-dlink,
  10131. ; always open the file in emacs if line or search
  10132. ; is given (for backwards compatibility)
  10133. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10134. 'string-match)
  10135. (cdr (assoc ext apps))
  10136. (cdr (assq t apps))))))
  10137. (when (eq cmd 'system)
  10138. (setq cmd (cdr (assq 'system apps))))
  10139. (when (eq cmd 'default)
  10140. (setq cmd (cdr (assoc t apps))))
  10141. (when (eq cmd 'mailcap)
  10142. (require 'mailcap)
  10143. (mailcap-parse-mailcaps)
  10144. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10145. (command (mailcap-mime-info mime-type)))
  10146. (if (stringp command)
  10147. (setq cmd command)
  10148. (setq cmd 'emacs))))
  10149. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10150. (not (file-exists-p file))
  10151. (not org-open-non-existing-files))
  10152. (user-error "No such file: %s" file))
  10153. (cond
  10154. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10155. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10156. (while (string-match "['\"]%s['\"]" cmd)
  10157. (setq cmd (replace-match "%s" t t cmd)))
  10158. (setq cmd (replace-regexp-in-string
  10159. "%s"
  10160. (shell-quote-argument (convert-standard-filename file))
  10161. cmd
  10162. nil t))
  10163. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10164. (save-match-data
  10165. (let ((match-index 1)
  10166. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10167. (set-match-data link-match-data)
  10168. (while (<= match-index number-of-groups)
  10169. (let ((regex (concat "%" (number-to-string match-index)))
  10170. (replace-with (match-string match-index dlink)))
  10171. (while (string-match regex cmd)
  10172. (setq cmd (replace-match replace-with t t cmd))))
  10173. (setq match-index (+ match-index 1)))))
  10174. (save-window-excursion
  10175. (message "Running %s...done" cmd)
  10176. (start-process-shell-command cmd nil cmd)
  10177. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10178. ((or (stringp cmd)
  10179. (eq cmd 'emacs))
  10180. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10181. (widen)
  10182. (cond (line (org-goto-line line)
  10183. (when (derived-mode-p 'org-mode) (org-reveal)))
  10184. (search (condition-case err
  10185. (org-link-search search)
  10186. ;; Save position before error-ing out so user
  10187. ;; can easily move back to the original buffer.
  10188. (error (funcall save-position-maybe)
  10189. (error (nth 1 err)))))))
  10190. ((functionp cmd)
  10191. (save-match-data
  10192. (set-match-data link-match-data)
  10193. (condition-case nil
  10194. (funcall cmd file link)
  10195. ;; FIXME: Remove this check when most default installations
  10196. ;; of Emacs have at least Org 9.0.
  10197. ((debug wrong-number-of-arguments wrong-type-argument
  10198. invalid-function)
  10199. (user-error "Please see Org News for version 9.0 about \
  10200. `org-file-apps'--Lisp error: %S" cmd)))))
  10201. ((consp cmd)
  10202. ;; FIXME: Remove this check when most default installations of
  10203. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10204. ;; fall back to `org-link-frame-setup' for an old usage of
  10205. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10206. (user-error "Please see Org News for version 9.0 about \
  10207. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10208. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10209. (funcall save-position-maybe)))
  10210. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10211. "This function returns non-nil if `entry' uses a regular
  10212. expression which should be matched against the whole link by
  10213. org-open-file.
  10214. It assumes that is the case when the entry uses a regular
  10215. expression which has at least one grouping construct and the
  10216. action is either a lisp form or a command string containing
  10217. `%1', i.e. using at least one subexpression match as a
  10218. parameter."
  10219. (let ((selector (car entry))
  10220. (action (cdr entry)))
  10221. (if (stringp selector)
  10222. (and (> (regexp-opt-depth selector) 0)
  10223. (or (and (stringp action)
  10224. (string-match "%[0-9]" action))
  10225. (consp action)))
  10226. nil)))
  10227. (defun org-default-apps ()
  10228. "Return the default applications for this operating system."
  10229. (cond
  10230. ((eq system-type 'darwin)
  10231. org-file-apps-defaults-macosx)
  10232. ((eq system-type 'windows-nt)
  10233. org-file-apps-defaults-windowsnt)
  10234. (t org-file-apps-defaults-gnu)))
  10235. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10236. "Convert extensions to regular expressions in the cars of LIST.
  10237. Also, weed out any non-string entries, because the return value is used
  10238. only for regexp matching.
  10239. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10240. point to the symbol `emacs', indicating that the file should
  10241. be opened in Emacs."
  10242. (append
  10243. (delq nil
  10244. (mapcar (lambda (x)
  10245. (unless (not (stringp (car x)))
  10246. (if (string-match "\\W" (car x))
  10247. x
  10248. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10249. list))
  10250. (when add-auto-mode
  10251. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10252. (defvar ange-ftp-name-format)
  10253. (defun org-file-remote-p (file)
  10254. "Test whether FILE specifies a location on a remote system.
  10255. Return non-nil if the location is indeed remote.
  10256. For example, the filename \"/user@host:/foo\" specifies a location
  10257. on the system \"/user@host:\"."
  10258. (cond ((fboundp 'file-remote-p)
  10259. (file-remote-p file))
  10260. ((fboundp 'tramp-handle-file-remote-p)
  10261. (tramp-handle-file-remote-p file))
  10262. ((and (boundp 'ange-ftp-name-format)
  10263. (string-match (car ange-ftp-name-format) file))
  10264. t)))
  10265. ;;;; Refiling
  10266. (defun org-get-org-file ()
  10267. "Read a filename, with default directory `org-directory'."
  10268. (let ((default (or org-default-notes-file remember-data-file)))
  10269. (read-file-name (format "File name [%s]: " default)
  10270. (file-name-as-directory org-directory)
  10271. default)))
  10272. (defun org-notes-order-reversed-p ()
  10273. "Check if the current file should receive notes in reversed order."
  10274. (cond
  10275. ((not org-reverse-note-order) nil)
  10276. ((eq t org-reverse-note-order) t)
  10277. ((not (listp org-reverse-note-order)) nil)
  10278. (t (catch 'exit
  10279. (dolist (entry org-reverse-note-order)
  10280. (when (string-match (car entry) buffer-file-name)
  10281. (throw 'exit (cdr entry))))))))
  10282. (defvar org-refile-target-table nil
  10283. "The list of refile targets, created by `org-refile'.")
  10284. (defvar org-agenda-new-buffers nil
  10285. "Buffers created to visit agenda files.")
  10286. (defvar org-refile-cache nil
  10287. "Cache for refile targets.")
  10288. (defvar org-refile-markers nil
  10289. "All the markers used for caching refile locations.")
  10290. (defun org-refile-marker (pos)
  10291. "Get a new refile marker, but only if caching is in use."
  10292. (if (not org-refile-use-cache)
  10293. pos
  10294. (let ((m (make-marker)))
  10295. (move-marker m pos)
  10296. (push m org-refile-markers)
  10297. m)))
  10298. (defun org-refile-cache-clear ()
  10299. "Clear the refile cache and disable all the markers."
  10300. (dolist (m org-refile-markers) (move-marker m nil))
  10301. (setq org-refile-markers nil)
  10302. (setq org-refile-cache nil)
  10303. (message "Refile cache has been cleared"))
  10304. (defun org-refile-cache-check-set (set)
  10305. "Check if all the markers in the cache still have live buffers."
  10306. (let (marker)
  10307. (catch 'exit
  10308. (while (and set (setq marker (nth 3 (pop set))))
  10309. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10310. (when (and marker (null (marker-buffer marker)))
  10311. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10312. (sit-for 3)
  10313. (throw 'exit nil)))
  10314. t)))
  10315. (defun org-refile-cache-put (set &rest identifiers)
  10316. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10317. (let* ((key (sha1 (prin1-to-string identifiers)))
  10318. (entry (assoc key org-refile-cache)))
  10319. (if entry
  10320. (setcdr entry set)
  10321. (push (cons key set) org-refile-cache))))
  10322. (defun org-refile-cache-get (&rest identifiers)
  10323. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10324. (cond
  10325. ((not org-refile-cache) nil)
  10326. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10327. (t
  10328. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10329. org-refile-cache))))
  10330. (and set (org-refile-cache-check-set set) set)))))
  10331. (defvar org-outline-path-cache nil
  10332. "Alist between buffer positions and outline paths.
  10333. It value is an alist (POSITION . PATH) where POSITION is the
  10334. buffer position at the beginning of an entry and PATH is a list
  10335. of strings describing the outline path for that entry, in reverse
  10336. order.")
  10337. (defun org-refile-get-targets (&optional default-buffer)
  10338. "Produce a table with refile targets."
  10339. (let ((case-fold-search nil)
  10340. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10341. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10342. targets tgs files desc descre)
  10343. (message "Getting targets...")
  10344. (with-current-buffer (or default-buffer (current-buffer))
  10345. (dolist (entry entries)
  10346. (setq files (car entry) desc (cdr entry))
  10347. (cond
  10348. ((null files) (setq files (list (current-buffer))))
  10349. ((eq files 'org-agenda-files)
  10350. (setq files (org-agenda-files 'unrestricted)))
  10351. ((and (symbolp files) (fboundp files))
  10352. (setq files (funcall files)))
  10353. ((and (symbolp files) (boundp files))
  10354. (setq files (symbol-value files))))
  10355. (when (stringp files) (setq files (list files)))
  10356. (cond
  10357. ((eq (car desc) :tag)
  10358. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10359. ((eq (car desc) :todo)
  10360. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10361. ((eq (car desc) :regexp)
  10362. (setq descre (cdr desc)))
  10363. ((eq (car desc) :level)
  10364. (setq descre (concat "^\\*\\{" (number-to-string
  10365. (if org-odd-levels-only
  10366. (1- (* 2 (cdr desc)))
  10367. (cdr desc)))
  10368. "\\}[ \t]")))
  10369. ((eq (car desc) :maxlevel)
  10370. (setq descre (concat "^\\*\\{1," (number-to-string
  10371. (if org-odd-levels-only
  10372. (1- (* 2 (cdr desc)))
  10373. (cdr desc)))
  10374. "\\}[ \t]")))
  10375. (t (error "Bad refiling target description %s" desc)))
  10376. (dolist (f files)
  10377. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10378. (or
  10379. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10380. (progn
  10381. (when (bufferp f)
  10382. (setq f (buffer-file-name (buffer-base-buffer f))))
  10383. (setq f (and f (expand-file-name f)))
  10384. (when (eq org-refile-use-outline-path 'file)
  10385. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10386. (org-with-wide-buffer
  10387. (goto-char (point-min))
  10388. (setq org-outline-path-cache nil)
  10389. (while (re-search-forward descre nil t)
  10390. (beginning-of-line)
  10391. (let ((case-fold-search nil))
  10392. (looking-at org-complex-heading-regexp))
  10393. (let ((begin (point))
  10394. (heading (match-string-no-properties 4)))
  10395. (unless (or (and
  10396. org-refile-target-verify-function
  10397. (not
  10398. (funcall org-refile-target-verify-function)))
  10399. (not heading))
  10400. (let ((re (format org-complex-heading-regexp-format
  10401. (regexp-quote heading)))
  10402. (target
  10403. (if (not org-refile-use-outline-path) heading
  10404. (mapconcat
  10405. #'org-protect-slash
  10406. (append
  10407. (pcase org-refile-use-outline-path
  10408. (`file (list (file-name-nondirectory
  10409. (buffer-file-name
  10410. (buffer-base-buffer)))))
  10411. (`full-file-path
  10412. (list (buffer-file-name
  10413. (buffer-base-buffer))))
  10414. (_ nil))
  10415. (org-get-outline-path t t))
  10416. "/"))))
  10417. (push (list target f re (org-refile-marker (point)))
  10418. tgs)))
  10419. (when (= (point) begin)
  10420. ;; Verification function has not moved point.
  10421. (end-of-line)))))))
  10422. (when org-refile-use-cache
  10423. (org-refile-cache-put tgs (buffer-file-name) descre))
  10424. (setq targets (append tgs targets))))))
  10425. (message "Getting targets...done")
  10426. (nreverse targets)))
  10427. (defun org-protect-slash (s)
  10428. (replace-regexp-in-string "/" "\\/" s nil t))
  10429. (defun org--get-outline-path-1 (&optional use-cache)
  10430. "Return outline path to current headline.
  10431. Outline path is a list of strings, in reverse order. When
  10432. optional argument USE-CACHE is non-nil, make use of a cache. See
  10433. `org-get-outline-path' for details.
  10434. Assume buffer is widened and point is on a headline."
  10435. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10436. (let ((p (point))
  10437. (heading (let ((case-fold-search nil))
  10438. (looking-at org-complex-heading-regexp)
  10439. (if (not (match-end 4)) ""
  10440. ;; Remove statistics cookies.
  10441. (org-trim
  10442. (org-link-display-format
  10443. (replace-regexp-in-string
  10444. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10445. (match-string-no-properties 4))))))))
  10446. (if (org-up-heading-safe)
  10447. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10448. (when use-cache
  10449. (push (cons p path) org-outline-path-cache))
  10450. path)
  10451. ;; This is a new root node. Since we assume we are moving
  10452. ;; forward, we can drop previous cache so as to limit number
  10453. ;; of associations there.
  10454. (let ((path (list heading)))
  10455. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10456. path)))))
  10457. (defun org-get-outline-path (&optional with-self use-cache)
  10458. "Return the outline path to the current entry.
  10459. An outline path is a list of ancestors for current headline, as
  10460. a list of strings. Statistics cookies are removed and links are
  10461. replaced with their description, if any, or their path otherwise.
  10462. When optional argument WITH-SELF is non-nil, the path also
  10463. includes the current headline.
  10464. When optional argument USE-CACHE is non-nil, cache outline paths
  10465. between calls to this function so as to avoid backtracking. This
  10466. argument is useful when planning to find more than one outline
  10467. path in the same document. In that case, there are two
  10468. conditions to satisfy:
  10469. - `org-outline-path-cache' is set to nil before starting the
  10470. process;
  10471. - outline paths are computed by increasing buffer positions."
  10472. (org-with-wide-buffer
  10473. (and (or (and with-self (org-back-to-heading t))
  10474. (org-up-heading-safe))
  10475. (reverse (org--get-outline-path-1 use-cache)))))
  10476. (defun org-format-outline-path (path &optional width prefix separator)
  10477. "Format the outline path PATH for display.
  10478. WIDTH is the maximum number of characters that is available.
  10479. PREFIX is a prefix to be included in the returned string,
  10480. such as the file name.
  10481. SEPARATOR is inserted between the different parts of the path,
  10482. the default is \"/\"."
  10483. (setq width (or width 79))
  10484. (setq path (delq nil path))
  10485. (unless (> width 0)
  10486. (user-error "Argument `width' must be positive"))
  10487. (setq separator (or separator "/"))
  10488. (let* ((org-odd-levels-only nil)
  10489. (fpath (concat
  10490. prefix (and prefix path separator)
  10491. (mapconcat
  10492. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10493. (cl-loop for head in path
  10494. for n from 0
  10495. collect (org-add-props
  10496. head nil 'face
  10497. (nth (% n org-n-level-faces) org-level-faces)))
  10498. separator))))
  10499. (when (> (length fpath) width)
  10500. (if (< width 7)
  10501. ;; It's unlikely that `width' will be this small, but don't
  10502. ;; waste characters by adding ".." if it is.
  10503. (setq fpath (substring fpath 0 width))
  10504. (setf (substring fpath (- width 2)) "..")))
  10505. fpath))
  10506. (defun org-display-outline-path (&optional file current separator just-return-string)
  10507. "Display the current outline path in the echo area.
  10508. If FILE is non-nil, prepend the output with the file name.
  10509. If CURRENT is non-nil, append the current heading to the output.
  10510. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10511. the different parts of the path and defaults to \"/\".
  10512. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10513. (interactive "P")
  10514. (let* (case-fold-search
  10515. (bfn (buffer-file-name (buffer-base-buffer)))
  10516. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10517. res)
  10518. (when current (setq path (append path
  10519. (save-excursion
  10520. (org-back-to-heading t)
  10521. (when (looking-at org-complex-heading-regexp)
  10522. (list (match-string 4)))))))
  10523. (setq res
  10524. (org-format-outline-path
  10525. path
  10526. (1- (frame-width))
  10527. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10528. separator))
  10529. (if just-return-string
  10530. (org-no-properties res)
  10531. (org-unlogged-message "%s" res))))
  10532. (defvar org-refile-history nil
  10533. "History for refiling operations.")
  10534. (defvar org-after-refile-insert-hook nil
  10535. "Hook run after `org-refile' has inserted its stuff at the new location.
  10536. Note that this is still *before* the stuff will be removed from
  10537. the *old* location.")
  10538. (defvar org-capture-last-stored-marker)
  10539. (defvar org-refile-keep nil
  10540. "Non-nil means `org-refile' will copy instead of refile.")
  10541. (defun org-copy ()
  10542. "Like `org-refile', but copy."
  10543. (interactive)
  10544. (let ((org-refile-keep t))
  10545. (funcall 'org-refile nil nil nil "Copy")))
  10546. (defun org-refile (&optional arg default-buffer rfloc msg)
  10547. "Move the entry or entries at point to another heading.
  10548. The list of target headings is compiled using the information in
  10549. `org-refile-targets', which see.
  10550. At the target location, the entry is filed as a subitem of the
  10551. target heading. Depending on `org-reverse-note-order', the new
  10552. subitem will either be the first or the last subitem.
  10553. If there is an active region, all entries in that region will be
  10554. refiled. However, the region must fulfill the requirement that
  10555. the first heading sets the top-level of the moved text.
  10556. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10557. location
  10558. and not actually move anything.
  10559. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10560. location where the last
  10561. refiling operation has put the subtree.
  10562. With a numeric prefix argument of `2', refile to the running clock.
  10563. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10564. being set to t and copy to the target location, don't move it.
  10565. Beware that keeping refiled entries may result in duplicated ID
  10566. properties.
  10567. RFLOC can be a refile location obtained in a different way.
  10568. MSG is a string to replace \"Refile\" in the default prompt with
  10569. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10570. See also `org-refile-use-outline-path'.
  10571. If you are using target caching (see `org-refile-use-cache'), you
  10572. have to clear the target cache in order to find new targets.
  10573. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10574. prefix argument (`C-u C-u C-u C-c C-w')."
  10575. (interactive "P")
  10576. (if (member arg '(0 (64)))
  10577. (org-refile-cache-clear)
  10578. (let* ((actionmsg (cond (msg msg)
  10579. ((equal arg 3) "Refile (and keep)")
  10580. (t "Refile")))
  10581. (regionp (org-region-active-p))
  10582. (region-start (and regionp (region-beginning)))
  10583. (region-end (and regionp (region-end)))
  10584. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10585. pos it nbuf file level reversed)
  10586. (setq last-command nil)
  10587. (when regionp
  10588. (goto-char region-start)
  10589. (or (bolp) (goto-char (point-at-bol)))
  10590. (setq region-start (point))
  10591. (unless (or (org-kill-is-subtree-p
  10592. (buffer-substring region-start region-end))
  10593. (prog1 org-refile-active-region-within-subtree
  10594. (let ((s (point-at-eol)))
  10595. (org-toggle-heading)
  10596. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10597. (user-error "The region is not a (sequence of) subtree(s)")))
  10598. (if (equal arg '(16))
  10599. (org-refile-goto-last-stored)
  10600. (when (or
  10601. (and (equal arg 2)
  10602. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10603. (prog1
  10604. (setq it (list (or org-clock-heading "running clock")
  10605. (buffer-file-name
  10606. (marker-buffer org-clock-hd-marker))
  10607. ""
  10608. (marker-position org-clock-hd-marker)))
  10609. (setq arg nil)))
  10610. (setq it
  10611. (or rfloc
  10612. (let (heading-text)
  10613. (save-excursion
  10614. (unless (and arg (listp arg))
  10615. (org-back-to-heading t)
  10616. (setq heading-text
  10617. (replace-regexp-in-string
  10618. org-bracket-link-regexp
  10619. "\\3"
  10620. (or (nth 4 (org-heading-components))
  10621. ""))))
  10622. (org-refile-get-location
  10623. (cond ((and arg (listp arg)) "Goto")
  10624. (regionp (concat actionmsg " region to"))
  10625. (t (concat actionmsg " subtree \""
  10626. heading-text "\" to")))
  10627. default-buffer
  10628. (and (not (equal '(4) arg))
  10629. org-refile-allow-creating-parent-nodes)))))))
  10630. (setq file (nth 1 it)
  10631. pos (nth 3 it))
  10632. (when (and (not arg)
  10633. pos
  10634. (equal (buffer-file-name) file)
  10635. (if regionp
  10636. (and (>= pos region-start)
  10637. (<= pos region-end))
  10638. (and (>= pos (point))
  10639. (< pos (save-excursion
  10640. (org-end-of-subtree t t))))))
  10641. (error "Cannot refile to position inside the tree or region"))
  10642. (setq nbuf (or (find-buffer-visiting file)
  10643. (find-file-noselect file)))
  10644. (if (and arg (not (equal arg 3)))
  10645. (progn
  10646. (pop-to-buffer-same-window nbuf)
  10647. (goto-char pos)
  10648. (org-show-context 'org-goto))
  10649. (if regionp
  10650. (progn
  10651. (org-kill-new (buffer-substring region-start region-end))
  10652. (org-save-markers-in-region region-start region-end))
  10653. (org-copy-subtree 1 nil t))
  10654. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10655. (find-file-noselect file)))
  10656. (setq reversed (org-notes-order-reversed-p))
  10657. (org-with-wide-buffer
  10658. (if pos
  10659. (progn
  10660. (goto-char pos)
  10661. (setq level (org-get-valid-level (funcall outline-level) 1))
  10662. (goto-char
  10663. (if reversed
  10664. (or (outline-next-heading) (point-max))
  10665. (or (save-excursion (org-get-next-sibling))
  10666. (org-end-of-subtree t t)
  10667. (point-max)))))
  10668. (setq level 1)
  10669. (if (not reversed)
  10670. (goto-char (point-max))
  10671. (goto-char (point-min))
  10672. (or (outline-next-heading) (goto-char (point-max)))))
  10673. (unless (bolp) (newline))
  10674. (org-paste-subtree level nil nil t)
  10675. (when org-log-refile
  10676. (org-add-log-setup 'refile nil nil org-log-refile)
  10677. (unless (eq org-log-refile 'note)
  10678. (save-excursion (org-add-log-note))))
  10679. (and org-auto-align-tags
  10680. (let ((org-loop-over-headlines-in-active-region nil))
  10681. (org-set-tags nil t)))
  10682. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10683. :last-refile)))
  10684. (when bookmark-name
  10685. (with-demoted-errors
  10686. (bookmark-set bookmark-name))))
  10687. ;; If we are refiling for capture, make sure that the
  10688. ;; last-capture pointers point here
  10689. (when (bound-and-true-p org-capture-is-refiling)
  10690. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10691. :last-capture-marker)))
  10692. (when bookmark-name
  10693. (with-demoted-errors
  10694. (bookmark-set bookmark-name))))
  10695. (move-marker org-capture-last-stored-marker (point)))
  10696. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10697. (run-hooks 'org-after-refile-insert-hook)))
  10698. (unless org-refile-keep
  10699. (if regionp
  10700. (delete-region (point) (+ (point) (- region-end region-start)))
  10701. (delete-region
  10702. (and (org-back-to-heading t) (point))
  10703. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10704. (when (featurep 'org-inlinetask)
  10705. (org-inlinetask-remove-END-maybe))
  10706. (setq org-markers-to-move nil)
  10707. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10708. (defun org-refile-goto-last-stored ()
  10709. "Go to the location where the last refile was stored."
  10710. (interactive)
  10711. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10712. (message "This is the location of the last refile"))
  10713. (defun org-refile--get-location (refloc tbl)
  10714. "When user refile to REFLOC, find the associated target in TBL.
  10715. Also check `org-refile-target-table'."
  10716. (car (delq
  10717. nil
  10718. (mapcar
  10719. (lambda (r) (or (assoc r tbl)
  10720. (assoc r org-refile-target-table)))
  10721. (list (replace-regexp-in-string "/$" "" refloc)
  10722. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10723. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10724. "Prompt the user for a refile location, using PROMPT.
  10725. PROMPT should not be suffixed with a colon and a space, because
  10726. this function appends the default value from
  10727. `org-refile-history' automatically, if that is not empty."
  10728. (let ((org-refile-targets org-refile-targets)
  10729. (org-refile-use-outline-path org-refile-use-outline-path))
  10730. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10731. (unless org-refile-target-table
  10732. (user-error "No refile targets"))
  10733. (let* ((cbuf (current-buffer))
  10734. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10735. (cfunc (if (and org-refile-use-outline-path
  10736. org-outline-path-complete-in-steps)
  10737. #'org-olpath-completing-read
  10738. #'completing-read))
  10739. (extra (if org-refile-use-outline-path "/" ""))
  10740. (cbnex (concat (buffer-name) extra))
  10741. (filename (and cfn (expand-file-name cfn)))
  10742. (tbl (mapcar
  10743. (lambda (x)
  10744. (if (and (not (member org-refile-use-outline-path
  10745. '(file full-file-path)))
  10746. (not (equal filename (nth 1 x))))
  10747. (cons (concat (car x) extra " ("
  10748. (file-name-nondirectory (nth 1 x)) ")")
  10749. (cdr x))
  10750. (cons (concat (car x) extra) (cdr x))))
  10751. org-refile-target-table))
  10752. (completion-ignore-case t)
  10753. cdef
  10754. (prompt (concat prompt
  10755. (or (and (car org-refile-history)
  10756. (concat " (default " (car org-refile-history) ")"))
  10757. (and (assoc cbnex tbl) (setq cdef cbnex)
  10758. (concat " (default " cbnex ")"))) ": "))
  10759. pa answ parent-target child parent old-hist)
  10760. (setq old-hist org-refile-history)
  10761. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10762. nil 'org-refile-history (or cdef (car org-refile-history))))
  10763. (if (setq pa (org-refile--get-location answ tbl))
  10764. (progn
  10765. (org-refile-check-position pa)
  10766. (when (or (not org-refile-history)
  10767. (not (eq old-hist org-refile-history))
  10768. (not (equal (car pa) (car org-refile-history))))
  10769. (setq org-refile-history
  10770. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10771. org-refile-history
  10772. (cdr org-refile-history))))
  10773. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10774. (pop org-refile-history)))
  10775. pa)
  10776. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10777. (progn
  10778. (setq parent (match-string 1 answ)
  10779. child (match-string 2 answ))
  10780. (setq parent-target (org-refile--get-location parent tbl))
  10781. (when (and parent-target
  10782. (or (eq new-nodes t)
  10783. (and (eq new-nodes 'confirm)
  10784. (y-or-n-p (format "Create new node \"%s\"? "
  10785. child)))))
  10786. (org-refile-new-child parent-target child)))
  10787. (user-error "Invalid target location")))))
  10788. (declare-function org-string-nw-p "org-macs" (s))
  10789. (defun org-refile-check-position (refile-pointer)
  10790. "Check if the refile pointer matches the headline to which it points."
  10791. (let* ((file (nth 1 refile-pointer))
  10792. (re (nth 2 refile-pointer))
  10793. (pos (nth 3 refile-pointer))
  10794. buffer)
  10795. (if (and (not (markerp pos)) (not file))
  10796. (user-error "Please indicate a target file in the refile path")
  10797. (when (org-string-nw-p re)
  10798. (setq buffer (if (markerp pos)
  10799. (marker-buffer pos)
  10800. (or (find-buffer-visiting file)
  10801. (find-file-noselect file))))
  10802. (with-current-buffer buffer
  10803. (org-with-wide-buffer
  10804. (goto-char pos)
  10805. (beginning-of-line 1)
  10806. (unless (looking-at-p re)
  10807. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10808. (defun org-refile-new-child (parent-target child)
  10809. "Use refile target PARENT-TARGET to add new CHILD below it."
  10810. (unless parent-target
  10811. (error "Cannot find parent for new node"))
  10812. (let ((file (nth 1 parent-target))
  10813. (pos (nth 3 parent-target))
  10814. level)
  10815. (with-current-buffer (or (find-buffer-visiting file)
  10816. (find-file-noselect file))
  10817. (org-with-wide-buffer
  10818. (if pos
  10819. (goto-char pos)
  10820. (goto-char (point-max))
  10821. (unless (bolp) (newline)))
  10822. (when (looking-at org-outline-regexp)
  10823. (setq level (funcall outline-level))
  10824. (org-end-of-subtree t t))
  10825. (org-back-over-empty-lines)
  10826. (insert "\n" (make-string
  10827. (if pos (org-get-valid-level level 1) 1) ?*)
  10828. " " child "\n")
  10829. (beginning-of-line 0)
  10830. (list (concat (car parent-target) "/" child) file "" (point))))))
  10831. (defun org-olpath-completing-read (prompt collection &rest args)
  10832. "Read an outline path like a file name."
  10833. (let ((thetable collection))
  10834. (apply #'completing-read
  10835. prompt
  10836. (lambda (string predicate &optional flag)
  10837. (cond
  10838. ((eq flag nil) (try-completion string thetable))
  10839. ((eq flag t)
  10840. (let ((l (length string)))
  10841. (mapcar (lambda (x)
  10842. (let ((r (substring x l))
  10843. (f (if (string-match " ([^)]*)$" x)
  10844. (match-string 0 x)
  10845. "")))
  10846. (if (string-match "/" r)
  10847. (concat string (substring r 0 (match-end 0)) f)
  10848. x)))
  10849. (all-completions string thetable predicate))))
  10850. ;; Exact match?
  10851. ((eq flag 'lambda) (assoc string thetable))))
  10852. args)))
  10853. ;;;; Dynamic blocks
  10854. (defun org-find-dblock (name)
  10855. "Find the first dynamic block with name NAME in the buffer.
  10856. If not found, stay at current position and return nil."
  10857. (let ((case-fold-search t) pos)
  10858. (save-excursion
  10859. (goto-char (point-min))
  10860. (setq pos (and (re-search-forward
  10861. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10862. (match-beginning 0))))
  10863. (when pos (goto-char pos))
  10864. pos))
  10865. (defun org-create-dblock (plist)
  10866. "Create a dynamic block section, with parameters taken from PLIST.
  10867. PLIST must contain a :name entry which is used as the name of the block."
  10868. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10869. (end-of-line 1)
  10870. (newline))
  10871. (let ((col (current-column))
  10872. (name (plist-get plist :name)))
  10873. (insert "#+BEGIN: " name)
  10874. (while plist
  10875. (if (eq (car plist) :name)
  10876. (setq plist (cddr plist))
  10877. (insert " " (prin1-to-string (pop plist)))))
  10878. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10879. (beginning-of-line -2)))
  10880. (defun org-prepare-dblock ()
  10881. "Prepare dynamic block for refresh.
  10882. This empties the block, puts the cursor at the insert position and returns
  10883. the property list including an extra property :name with the block name."
  10884. (unless (looking-at org-dblock-start-re)
  10885. (user-error "Not at a dynamic block"))
  10886. (let* ((begdel (1+ (match-end 0)))
  10887. (name (org-no-properties (match-string 1)))
  10888. (params (append (list :name name)
  10889. (read (concat "(" (match-string 3) ")")))))
  10890. (save-excursion
  10891. (beginning-of-line 1)
  10892. (skip-chars-forward " \t")
  10893. (setq params (plist-put params :indentation-column (current-column))))
  10894. (unless (re-search-forward org-dblock-end-re nil t)
  10895. (error "Dynamic block not terminated"))
  10896. (setq params
  10897. (append params
  10898. (list :content (buffer-substring
  10899. begdel (match-beginning 0)))))
  10900. (delete-region begdel (match-beginning 0))
  10901. (goto-char begdel)
  10902. (open-line 1)
  10903. params))
  10904. (defun org-map-dblocks (&optional command)
  10905. "Apply COMMAND to all dynamic blocks in the current buffer.
  10906. If COMMAND is not given, use `org-update-dblock'."
  10907. (let ((cmd (or command 'org-update-dblock)))
  10908. (save-excursion
  10909. (goto-char (point-min))
  10910. (while (re-search-forward org-dblock-start-re nil t)
  10911. (goto-char (match-beginning 0))
  10912. (save-excursion
  10913. (condition-case nil
  10914. (funcall cmd)
  10915. (error (message "Error during update of dynamic block"))))
  10916. (unless (re-search-forward org-dblock-end-re nil t)
  10917. (error "Dynamic block not terminated"))))))
  10918. (defun org-dblock-update (&optional arg)
  10919. "User command for updating dynamic blocks.
  10920. Update the dynamic block at point. With prefix ARG, update all dynamic
  10921. blocks in the buffer."
  10922. (interactive "P")
  10923. (if arg
  10924. (org-update-all-dblocks)
  10925. (or (looking-at org-dblock-start-re)
  10926. (org-beginning-of-dblock))
  10927. (org-update-dblock)))
  10928. (defun org-update-dblock ()
  10929. "Update the dynamic block at point.
  10930. This means to empty the block, parse for parameters and then call
  10931. the correct writing function."
  10932. (interactive)
  10933. (save-excursion
  10934. (let* ((win (selected-window))
  10935. (pos (point))
  10936. (line (org-current-line))
  10937. (params (org-prepare-dblock))
  10938. (name (plist-get params :name))
  10939. (indent (plist-get params :indentation-column))
  10940. (cmd (intern (concat "org-dblock-write:" name))))
  10941. (message "Updating dynamic block `%s' at line %d..." name line)
  10942. (funcall cmd params)
  10943. (message "Updating dynamic block `%s' at line %d...done" name line)
  10944. (goto-char pos)
  10945. (when (and indent (> indent 0))
  10946. (setq indent (make-string indent ?\ ))
  10947. (save-excursion
  10948. (select-window win)
  10949. (org-beginning-of-dblock)
  10950. (forward-line 1)
  10951. (while (not (looking-at org-dblock-end-re))
  10952. (insert indent)
  10953. (beginning-of-line 2))
  10954. (when (looking-at org-dblock-end-re)
  10955. (and (looking-at "[ \t]+")
  10956. (replace-match ""))
  10957. (insert indent)))))))
  10958. (defun org-beginning-of-dblock ()
  10959. "Find the beginning of the dynamic block at point.
  10960. Error if there is no such block at point."
  10961. (let ((pos (point))
  10962. beg)
  10963. (end-of-line 1)
  10964. (if (and (re-search-backward org-dblock-start-re nil t)
  10965. (setq beg (match-beginning 0))
  10966. (re-search-forward org-dblock-end-re nil t)
  10967. (> (match-end 0) pos))
  10968. (goto-char beg)
  10969. (goto-char pos)
  10970. (error "Not in a dynamic block"))))
  10971. (defun org-update-all-dblocks ()
  10972. "Update all dynamic blocks in the buffer.
  10973. This function can be used in a hook."
  10974. (interactive)
  10975. (when (derived-mode-p 'org-mode)
  10976. (org-map-dblocks 'org-update-dblock)))
  10977. ;;;; Completion
  10978. (declare-function org-export-backend-options "ox" (cl-x) t)
  10979. (defun org-get-export-keywords ()
  10980. "Return a list of all currently understood export keywords.
  10981. Export keywords include options, block names, attributes and
  10982. keywords relative to each registered export back-end."
  10983. (let (keywords)
  10984. (dolist (backend
  10985. (bound-and-true-p org-export-registered-backends)
  10986. (delq nil keywords))
  10987. ;; Back-end name (for keywords, like #+LATEX:)
  10988. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10989. (dolist (option-entry (org-export-backend-options backend))
  10990. ;; Back-end options.
  10991. (push (nth 1 option-entry) keywords)))))
  10992. (defconst org-options-keywords
  10993. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10994. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10995. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10996. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10997. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10998. (defcustom org-structure-template-alist
  10999. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11000. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11001. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11002. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11003. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11004. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11005. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11006. ("L" "#+LaTeX: ")
  11007. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11008. ("H" "#+HTML: ")
  11009. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11010. ("A" "#+ASCII: ")
  11011. ("i" "#+INDEX: ?")
  11012. ("I" "#+INCLUDE: %file ?"))
  11013. "Structure completion elements.
  11014. This is a list of abbreviation keys and values. The value gets inserted
  11015. if you type `<' followed by the key and then press the completion key,
  11016. usually `TAB'. %file will be replaced by a file name after prompting
  11017. for the file using completion. The cursor will be placed at the position
  11018. of the `?' in the template.
  11019. There are two templates for each key, the first uses the original Org syntax,
  11020. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11021. the default when the /org-mtags.el/ module has been loaded. See also the
  11022. variable `org-mtags-prefer-muse-templates'."
  11023. :group 'org-completion
  11024. :type '(repeat
  11025. (list
  11026. (string :tag "Key")
  11027. (string :tag "Template")))
  11028. :version "26.1"
  11029. :package-version '(Org . "8.3"))
  11030. (defun org-try-structure-completion ()
  11031. "Try to complete a structure template before point.
  11032. This looks for strings like \"<e\" on an otherwise empty line and
  11033. expands them."
  11034. (let ((l (buffer-substring (point-at-bol) (point)))
  11035. a)
  11036. (when (and (looking-at "[ \t]*$")
  11037. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11038. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11039. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11040. (match-beginning 1)) a)
  11041. t)))
  11042. (defun org-complete-expand-structure-template (start cell)
  11043. "Expand a structure template."
  11044. (let ((rpl (nth 1 cell))
  11045. (ind ""))
  11046. (delete-region start (point))
  11047. (when (string-match "\\`[ \t]*#\\+" rpl)
  11048. (cond
  11049. ((bolp))
  11050. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11051. (setq ind (buffer-substring (point-at-bol) (point))))
  11052. (t (newline))))
  11053. (setq start (point))
  11054. (when (string-match "%file" rpl)
  11055. (setq rpl (replace-match
  11056. (concat
  11057. "\""
  11058. (save-match-data
  11059. (abbreviate-file-name (read-file-name "Include file: ")))
  11060. "\"")
  11061. t t rpl)))
  11062. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11063. (concat "\n" ind)))
  11064. (insert rpl)
  11065. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11066. ;;;; TODO, DEADLINE, Comments
  11067. (defun org-toggle-comment ()
  11068. "Change the COMMENT state of an entry."
  11069. (interactive)
  11070. (save-excursion
  11071. (org-back-to-heading)
  11072. (let ((case-fold-search nil))
  11073. (looking-at org-complex-heading-regexp))
  11074. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11075. (skip-chars-forward " \t")
  11076. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11077. (if (org-in-commented-heading-p t)
  11078. (delete-region (point)
  11079. (progn (search-forward " " (line-end-position) 'move)
  11080. (skip-chars-forward " \t")
  11081. (point)))
  11082. (insert org-comment-string)
  11083. (unless (eolp) (insert " ")))))
  11084. (defvar org-last-todo-state-is-todo nil
  11085. "This is non-nil when the last TODO state change led to a TODO state.
  11086. If the last change removed the TODO tag or switched to DONE, then
  11087. this is nil.")
  11088. (defvar org-setting-tags nil) ; dynamically skipped
  11089. (defvar org-todo-setup-filter-hook nil
  11090. "Hook for functions that pre-filter todo specs.
  11091. Each function takes a todo spec and returns either nil or the spec
  11092. transformed into canonical form." )
  11093. (defvar org-todo-get-default-hook nil
  11094. "Hook for functions that get a default item for todo.
  11095. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11096. nil or a string to be used for the todo mark." )
  11097. (defvar org-agenda-headline-snapshot-before-repeat)
  11098. (defun org-current-effective-time ()
  11099. "Return current time adjusted for `org-extend-today-until' variable."
  11100. (let* ((ct (org-current-time))
  11101. (dct (decode-time ct))
  11102. (ct1
  11103. (cond
  11104. (org-use-last-clock-out-time-as-effective-time
  11105. (or (org-clock-get-last-clock-out-time) ct))
  11106. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11107. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11108. (t ct))))
  11109. ct1))
  11110. (defun org-todo-yesterday (&optional arg)
  11111. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11112. (interactive "P")
  11113. (if (eq major-mode 'org-agenda-mode)
  11114. (apply 'org-agenda-todo-yesterday arg)
  11115. (let* ((org-use-effective-time t)
  11116. (hour (nth 2 (decode-time (org-current-time))))
  11117. (org-extend-today-until (1+ hour)))
  11118. (org-todo arg))))
  11119. (defvar org-block-entry-blocking ""
  11120. "First entry preventing the TODO state change.")
  11121. (defun org-cancel-repeater ()
  11122. "Cancel a repeater by setting its numeric value to zero."
  11123. (interactive)
  11124. (save-excursion
  11125. (org-back-to-heading t)
  11126. (let ((bound1 (point))
  11127. (bound0 (save-excursion (outline-next-heading) (point))))
  11128. (when (and (re-search-forward
  11129. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11130. org-deadline-time-regexp "\\)\\|\\("
  11131. org-ts-regexp "\\)")
  11132. bound0 t)
  11133. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11134. bound1 t))
  11135. (replace-match "0" t nil nil 1)))))
  11136. (defvar org-state) ;; dynamically scoped into this function
  11137. (defun org-todo (&optional arg)
  11138. "Change the TODO state of an item.
  11139. The state of an item is given by a keyword at the start of the heading,
  11140. like
  11141. *** TODO Write paper
  11142. *** DONE Call mom
  11143. The different keywords are specified in the variable `org-todo-keywords'.
  11144. By default the available states are \"TODO\" and \"DONE\". So, for this
  11145. example: when the item starts with TODO, it is changed to DONE.
  11146. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11147. DONE are present, add TODO at the beginning of the heading.
  11148. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11149. state.
  11150. With numeric prefix ARG, switch to that state.
  11151. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11152. next set of TODO \
  11153. keywords (nextset).
  11154. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11155. prefix, circumvent any state blocking.
  11156. With a numeric prefix arg of 0, inhibit note taking for the change.
  11157. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11158. When called through ELisp, arg is also interpreted in the following way:
  11159. `none' -> empty state
  11160. \"\" -> switch to empty state
  11161. `done' -> switch to DONE
  11162. `nextset' -> switch to the next set of keywords
  11163. `previousset' -> switch to the previous set of keywords
  11164. \"WAITING\" -> switch to the specified keyword, but only if it
  11165. really is a member of `org-todo-keywords'."
  11166. (interactive "P")
  11167. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11168. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11169. 'region-start-level 'region))
  11170. org-loop-over-headlines-in-active-region)
  11171. (org-map-entries
  11172. `(org-todo ,arg)
  11173. org-loop-over-headlines-in-active-region
  11174. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11175. (when (equal arg '(16)) (setq arg 'nextset))
  11176. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11177. (let ((org-blocker-hook org-blocker-hook)
  11178. commentp
  11179. case-fold-search)
  11180. (when (equal arg '(64))
  11181. (setq arg nil org-blocker-hook nil))
  11182. (when (and org-blocker-hook
  11183. (or org-inhibit-blocking
  11184. (org-entry-get nil "NOBLOCKING")))
  11185. (setq org-blocker-hook nil))
  11186. (save-excursion
  11187. (catch 'exit
  11188. (org-back-to-heading t)
  11189. (when (org-in-commented-heading-p t)
  11190. (org-toggle-comment)
  11191. (setq commentp t))
  11192. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11193. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11194. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11195. (let* ((match-data (match-data))
  11196. (startpos (point-at-bol))
  11197. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11198. (org-log-done org-log-done)
  11199. (org-log-repeat org-log-repeat)
  11200. (org-todo-log-states org-todo-log-states)
  11201. (org-inhibit-logging
  11202. (if (equal arg 0)
  11203. (progn (setq arg nil) 'note) org-inhibit-logging))
  11204. (this (match-string 1))
  11205. (hl-pos (match-beginning 0))
  11206. (head (org-get-todo-sequence-head this))
  11207. (ass (assoc head org-todo-kwd-alist))
  11208. (interpret (nth 1 ass))
  11209. (done-word (nth 3 ass))
  11210. (final-done-word (nth 4 ass))
  11211. (org-last-state (or this ""))
  11212. (completion-ignore-case t)
  11213. (member (member this org-todo-keywords-1))
  11214. (tail (cdr member))
  11215. (org-state (cond
  11216. ((and org-todo-key-trigger
  11217. (or (and (equal arg '(4))
  11218. (eq org-use-fast-todo-selection 'prefix))
  11219. (and (not arg) org-use-fast-todo-selection
  11220. (not (eq org-use-fast-todo-selection
  11221. 'prefix)))))
  11222. ;; Use fast selection
  11223. (org-fast-todo-selection))
  11224. ((and (equal arg '(4))
  11225. (or (not org-use-fast-todo-selection)
  11226. (not org-todo-key-trigger)))
  11227. ;; Read a state with completion
  11228. (completing-read
  11229. "State: " (mapcar #'list org-todo-keywords-1)
  11230. nil t))
  11231. ((eq arg 'right)
  11232. (if this
  11233. (if tail (car tail) nil)
  11234. (car org-todo-keywords-1)))
  11235. ((eq arg 'left)
  11236. (unless (equal member org-todo-keywords-1)
  11237. (if this
  11238. (nth (- (length org-todo-keywords-1)
  11239. (length tail) 2)
  11240. org-todo-keywords-1)
  11241. (org-last org-todo-keywords-1))))
  11242. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11243. (setq arg nil))) ; hack to fall back to cycling
  11244. (arg
  11245. ;; user or caller requests a specific state
  11246. (cond
  11247. ((equal arg "") nil)
  11248. ((eq arg 'none) nil)
  11249. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11250. ((eq arg 'nextset)
  11251. (or (car (cdr (member head org-todo-heads)))
  11252. (car org-todo-heads)))
  11253. ((eq arg 'previousset)
  11254. (let ((org-todo-heads (reverse org-todo-heads)))
  11255. (or (car (cdr (member head org-todo-heads)))
  11256. (car org-todo-heads))))
  11257. ((car (member arg org-todo-keywords-1)))
  11258. ((stringp arg)
  11259. (user-error "State `%s' not valid in this file" arg))
  11260. ((nth (1- (prefix-numeric-value arg))
  11261. org-todo-keywords-1))))
  11262. ((null member) (or head (car org-todo-keywords-1)))
  11263. ((equal this final-done-word) nil) ;; -> make empty
  11264. ((null tail) nil) ;; -> first entry
  11265. ((memq interpret '(type priority))
  11266. (if (eq this-command last-command)
  11267. (car tail)
  11268. (if (> (length tail) 0)
  11269. (or done-word (car org-done-keywords))
  11270. nil)))
  11271. (t
  11272. (car tail))))
  11273. (org-state (or
  11274. (run-hook-with-args-until-success
  11275. 'org-todo-get-default-hook org-state org-last-state)
  11276. org-state))
  11277. (next (if org-state (concat " " org-state " ") " "))
  11278. (change-plist (list :type 'todo-state-change :from this :to org-state
  11279. :position startpos))
  11280. dolog now-done-p)
  11281. (when org-blocker-hook
  11282. (setq org-last-todo-state-is-todo
  11283. (not (member this org-done-keywords)))
  11284. (unless (save-excursion
  11285. (save-match-data
  11286. (org-with-wide-buffer
  11287. (run-hook-with-args-until-failure
  11288. 'org-blocker-hook change-plist))))
  11289. (if (called-interactively-p 'interactive)
  11290. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11291. this org-state org-block-entry-blocking)
  11292. ;; fail silently
  11293. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11294. this org-state org-block-entry-blocking)
  11295. (throw 'exit nil))))
  11296. (store-match-data match-data)
  11297. (replace-match next t t)
  11298. (cond ((equal this org-state)
  11299. (message "TODO state was already %s" (org-trim next)))
  11300. ((pos-visible-in-window-p hl-pos)
  11301. (message "TODO state changed to %s" (org-trim next))))
  11302. (unless head
  11303. (setq head (org-get-todo-sequence-head org-state)
  11304. ass (assoc head org-todo-kwd-alist)
  11305. interpret (nth 1 ass)
  11306. done-word (nth 3 ass)
  11307. final-done-word (nth 4 ass)))
  11308. (when (memq arg '(nextset previousset))
  11309. (message "Keyword-Set %d/%d: %s"
  11310. (- (length org-todo-sets) -1
  11311. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11312. (length org-todo-sets)
  11313. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11314. (setq org-last-todo-state-is-todo
  11315. (not (member org-state org-done-keywords)))
  11316. (setq now-done-p (and (member org-state org-done-keywords)
  11317. (not (member this org-done-keywords))))
  11318. (and logging (org-local-logging logging))
  11319. (when (and (or org-todo-log-states org-log-done)
  11320. (not (eq org-inhibit-logging t))
  11321. (not (memq arg '(nextset previousset))))
  11322. ;; we need to look at recording a time and note
  11323. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11324. (nth 2 (assoc this org-todo-log-states))))
  11325. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11326. (setq dolog 'time))
  11327. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11328. (and org-state
  11329. (member org-state org-not-done-keywords)
  11330. (not (member this org-not-done-keywords))))
  11331. ;; This is now a todo state and was not one before
  11332. ;; If there was a CLOSED time stamp, get rid of it.
  11333. (org-add-planning-info nil nil 'closed))
  11334. (when (and now-done-p org-log-done)
  11335. ;; It is now done, and it was not done before
  11336. (org-add-planning-info 'closed (org-current-effective-time))
  11337. (when (and (not dolog) (eq 'note org-log-done))
  11338. (org-add-log-setup 'done org-state this 'note)))
  11339. (when (and org-state dolog)
  11340. ;; This is a non-nil state, and we need to log it
  11341. (org-add-log-setup 'state org-state this dolog)))
  11342. ;; Fixup tag positioning
  11343. (org-todo-trigger-tag-changes org-state)
  11344. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11345. (when org-provide-todo-statistics
  11346. (org-update-parent-todo-statistics))
  11347. (run-hooks 'org-after-todo-state-change-hook)
  11348. (when (and arg (not (member org-state org-done-keywords)))
  11349. (setq head (org-get-todo-sequence-head org-state)))
  11350. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11351. ;; Do we need to trigger a repeat?
  11352. (when now-done-p
  11353. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11354. ;; This is for the agenda, take a snapshot of the headline.
  11355. (save-match-data
  11356. (setq org-agenda-headline-snapshot-before-repeat
  11357. (org-get-heading))))
  11358. (org-auto-repeat-maybe org-state))
  11359. ;; Fixup cursor location if close to the keyword
  11360. (when (and (outline-on-heading-p)
  11361. (not (bolp))
  11362. (save-excursion (beginning-of-line 1)
  11363. (looking-at org-todo-line-regexp))
  11364. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11365. (goto-char (or (match-end 2) (match-end 1)))
  11366. (and (looking-at " ") (just-one-space)))
  11367. (when org-trigger-hook
  11368. (save-excursion
  11369. (run-hook-with-args 'org-trigger-hook change-plist)))
  11370. (when commentp (org-toggle-comment))))))))
  11371. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11372. "Block turning an entry into a TODO, using the hierarchy.
  11373. This checks whether the current task should be blocked from state
  11374. changes. Such blocking occurs when:
  11375. 1. The task has children which are not all in a completed state.
  11376. 2. A task has a parent with the property :ORDERED:, and there
  11377. are siblings prior to the current task with incomplete
  11378. status.
  11379. 3. The parent of the task is blocked because it has siblings that should
  11380. be done first, or is child of a block grandparent TODO entry."
  11381. (if (not org-enforce-todo-dependencies)
  11382. t ; if locally turned off don't block
  11383. (catch 'dont-block
  11384. ;; If this is not a todo state change, or if this entry is already DONE,
  11385. ;; do not block
  11386. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11387. (member (plist-get change-plist :from)
  11388. (cons 'done org-done-keywords))
  11389. (member (plist-get change-plist :to)
  11390. (cons 'todo org-not-done-keywords))
  11391. (not (plist-get change-plist :to)))
  11392. (throw 'dont-block t))
  11393. ;; If this task has children, and any are undone, it's blocked
  11394. (save-excursion
  11395. (org-back-to-heading t)
  11396. (let ((this-level (funcall outline-level)))
  11397. (outline-next-heading)
  11398. (let ((child-level (funcall outline-level)))
  11399. (while (and (not (eobp))
  11400. (> child-level this-level))
  11401. ;; this todo has children, check whether they are all
  11402. ;; completed
  11403. (when (and (not (org-entry-is-done-p))
  11404. (org-entry-is-todo-p))
  11405. (setq org-block-entry-blocking (org-get-heading))
  11406. (throw 'dont-block nil))
  11407. (outline-next-heading)
  11408. (setq child-level (funcall outline-level))))))
  11409. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11410. ;; any previous siblings are undone, it's blocked
  11411. (save-excursion
  11412. (org-back-to-heading t)
  11413. (let* ((pos (point))
  11414. (parent-pos (and (org-up-heading-safe) (point)))
  11415. (case-fold-search nil))
  11416. (unless parent-pos (throw 'dont-block t)) ; no parent
  11417. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11418. (forward-line 1)
  11419. (re-search-forward org-not-done-heading-regexp pos t))
  11420. (setq org-block-entry-blocking (match-string 0))
  11421. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11422. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11423. (while t
  11424. (goto-char parent-pos)
  11425. (unless (looking-at org-not-done-heading-regexp)
  11426. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11427. (setq pos (point))
  11428. (setq parent-pos (and (org-up-heading-safe) (point)))
  11429. (unless parent-pos (throw 'dont-block t)) ; no parent
  11430. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11431. (forward-line 1)
  11432. (re-search-forward org-not-done-heading-regexp pos t)
  11433. (setq org-block-entry-blocking (org-get-heading)))
  11434. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11435. (defcustom org-track-ordered-property-with-tag nil
  11436. "Should the ORDERED property also be shown as a tag?
  11437. The ORDERED property decides if an entry should require subtasks to be
  11438. completed in sequence. Since a property is not very visible, setting
  11439. this option means that toggling the ORDERED property with the command
  11440. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11441. not relevant for the behavior, but it makes things more visible.
  11442. Note that toggling the tag with tags commands will not change the property
  11443. and therefore not influence behavior!
  11444. This can be t, meaning the tag ORDERED should be used, It can also be a
  11445. string to select a different tag for this task."
  11446. :group 'org-todo
  11447. :type '(choice
  11448. (const :tag "No tracking" nil)
  11449. (const :tag "Track with ORDERED tag" t)
  11450. (string :tag "Use other tag")))
  11451. (defun org-toggle-ordered-property ()
  11452. "Toggle the ORDERED property of the current entry.
  11453. For better visibility, you can track the value of this property with a tag.
  11454. See variable `org-track-ordered-property-with-tag'."
  11455. (interactive)
  11456. (let* ((t1 org-track-ordered-property-with-tag)
  11457. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11458. (save-excursion
  11459. (org-back-to-heading)
  11460. (if (org-entry-get nil "ORDERED")
  11461. (progn
  11462. (org-delete-property "ORDERED")
  11463. (and tag (org-toggle-tag tag 'off))
  11464. (message "Subtasks can be completed in arbitrary order"))
  11465. (org-entry-put nil "ORDERED" "t")
  11466. (and tag (org-toggle-tag tag 'on))
  11467. (message "Subtasks must be completed in sequence")))))
  11468. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11469. (defun org-block-todo-from-checkboxes (change-plist)
  11470. "Block turning an entry into a TODO, using checkboxes.
  11471. This checks whether the current task should be blocked from state
  11472. changes because there are unchecked boxes in this entry."
  11473. (if (not org-enforce-todo-checkbox-dependencies)
  11474. t ; if locally turned off don't block
  11475. (catch 'dont-block
  11476. ;; If this is not a todo state change, or if this entry is already DONE,
  11477. ;; do not block
  11478. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11479. (member (plist-get change-plist :from)
  11480. (cons 'done org-done-keywords))
  11481. (member (plist-get change-plist :to)
  11482. (cons 'todo org-not-done-keywords))
  11483. (not (plist-get change-plist :to)))
  11484. (throw 'dont-block t))
  11485. ;; If this task has checkboxes that are not checked, it's blocked
  11486. (save-excursion
  11487. (org-back-to-heading t)
  11488. (let ((beg (point)) end)
  11489. (outline-next-heading)
  11490. (setq end (point))
  11491. (goto-char beg)
  11492. (when (org-list-search-forward
  11493. (concat (org-item-beginning-re)
  11494. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11495. "\\[[- ]\\]")
  11496. end t)
  11497. (when (boundp 'org-blocked-by-checkboxes)
  11498. (setq org-blocked-by-checkboxes t))
  11499. (throw 'dont-block nil))))
  11500. t))) ; do not block
  11501. (defun org-entry-blocked-p ()
  11502. "Non-nil if entry at point is blocked."
  11503. (and (not (org-entry-get nil "NOBLOCKING"))
  11504. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11505. (not (run-hook-with-args-until-failure
  11506. 'org-blocker-hook
  11507. (list :type 'todo-state-change
  11508. :position (point)
  11509. :from 'todo
  11510. :to 'done)))))
  11511. (defun org-update-statistics-cookies (all)
  11512. "Update the statistics cookie, either from TODO or from checkboxes.
  11513. This should be called with the cursor in a line with a statistics
  11514. cookie. When called with a \\[universal-argument] prefix, update
  11515. all statistics cookies in the buffer."
  11516. (interactive "P")
  11517. (if all
  11518. (progn
  11519. (org-update-checkbox-count 'all)
  11520. (org-map-entries 'org-update-parent-todo-statistics))
  11521. (if (not (org-at-heading-p))
  11522. (org-update-checkbox-count)
  11523. (let ((pos (point-marker))
  11524. end l1 l2)
  11525. (ignore-errors (org-back-to-heading t))
  11526. (if (not (org-at-heading-p))
  11527. (org-update-checkbox-count)
  11528. (setq l1 (org-outline-level))
  11529. (setq end (save-excursion
  11530. (outline-next-heading)
  11531. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11532. (point)))
  11533. (if (and (save-excursion
  11534. (re-search-forward
  11535. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11536. (not (save-excursion (re-search-forward
  11537. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11538. (org-update-checkbox-count)
  11539. (if (and l2 (> l2 l1))
  11540. (progn
  11541. (goto-char end)
  11542. (org-update-parent-todo-statistics))
  11543. (goto-char pos)
  11544. (beginning-of-line 1)
  11545. (while (re-search-forward
  11546. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11547. (point-at-eol) t)
  11548. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11549. (goto-char pos)
  11550. (move-marker pos nil)))))
  11551. (defvar org-entry-property-inherited-from) ;; defined below
  11552. (defun org-update-parent-todo-statistics ()
  11553. "Update any statistics cookie in the parent of the current headline.
  11554. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11555. the entire subtree and this will travel up the hierarchy and update
  11556. statistics everywhere."
  11557. (let* ((prop (save-excursion (org-up-heading-safe)
  11558. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11559. (recursive (or (not org-hierarchical-todo-statistics)
  11560. (and prop (string-match "\\<recursive\\>" prop))))
  11561. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11562. 0))
  11563. (first t)
  11564. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11565. level ltoggle l1 new ndel
  11566. (cnt-all 0) (cnt-done 0) is-percent kwd
  11567. checkbox-beg cookie-present)
  11568. (catch 'exit
  11569. (save-excursion
  11570. (beginning-of-line 1)
  11571. (setq ltoggle (funcall outline-level))
  11572. ;; Three situations are to consider:
  11573. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11574. ;; to the top-level ancestor on the headline;
  11575. ;; 2. If parent has "recursive" property, repeat up to the
  11576. ;; headline setting that property, taking inheritance into
  11577. ;; account;
  11578. ;; 3. Else, move up to direct parent and proceed only once.
  11579. (while (and (setq level (org-up-heading-safe))
  11580. (or recursive first)
  11581. (>= (point) lim))
  11582. (setq first nil cookie-present nil)
  11583. (unless (and level
  11584. (not (string-match
  11585. "\\<checkbox\\>"
  11586. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11587. "")))))
  11588. (throw 'exit nil))
  11589. (while (re-search-forward box-re (point-at-eol) t)
  11590. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11591. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11592. (save-match-data
  11593. (unless (outline-next-heading) (throw 'exit nil))
  11594. (while (and (looking-at org-complex-heading-regexp)
  11595. (> (setq l1 (length (match-string 1))) level))
  11596. (setq kwd (and (or recursive (= l1 ltoggle))
  11597. (match-string 2)))
  11598. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11599. (and (eq org-provide-todo-statistics t)
  11600. (or (member kwd org-done-keywords)))
  11601. (and (listp org-provide-todo-statistics)
  11602. (stringp (car org-provide-todo-statistics))
  11603. (or (member kwd org-provide-todo-statistics)
  11604. (member kwd org-done-keywords)))
  11605. (and (listp org-provide-todo-statistics)
  11606. (listp (car org-provide-todo-statistics))
  11607. (or (member kwd (car org-provide-todo-statistics))
  11608. (and (member kwd org-done-keywords)
  11609. (member kwd (cadr org-provide-todo-statistics))))))
  11610. (setq cnt-all (1+ cnt-all))
  11611. (and (eq org-provide-todo-statistics t)
  11612. kwd
  11613. (setq cnt-all (1+ cnt-all))))
  11614. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11615. (member kwd org-done-keywords))
  11616. (and (listp org-provide-todo-statistics)
  11617. (listp (car org-provide-todo-statistics))
  11618. (member kwd org-done-keywords)
  11619. (member kwd (cadr org-provide-todo-statistics)))
  11620. (and (listp org-provide-todo-statistics)
  11621. (stringp (car org-provide-todo-statistics))
  11622. (member kwd org-done-keywords)))
  11623. (setq cnt-done (1+ cnt-done)))
  11624. (outline-next-heading)))
  11625. (setq new
  11626. (if is-percent
  11627. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11628. (max 1 cnt-all)))
  11629. (format "[%d/%d]" cnt-done cnt-all))
  11630. ndel (- (match-end 0) checkbox-beg))
  11631. (goto-char checkbox-beg)
  11632. (insert new)
  11633. (delete-region (point) (+ (point) ndel))
  11634. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11635. (when cookie-present
  11636. (run-hook-with-args 'org-after-todo-statistics-hook
  11637. cnt-done (- cnt-all cnt-done))))))
  11638. (run-hooks 'org-todo-statistics-hook)))
  11639. (defvar org-after-todo-statistics-hook nil
  11640. "Hook that is called after a TODO statistics cookie has been updated.
  11641. Each function is called with two arguments: the number of not-done entries
  11642. and the number of done entries.
  11643. For example, the following function, when added to this hook, will switch
  11644. an entry to DONE when all children are done, and back to TODO when new
  11645. entries are set to a TODO status. Note that this hook is only called
  11646. when there is a statistics cookie in the headline!
  11647. (defun org-summary-todo (n-done n-not-done)
  11648. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11649. (let (org-log-done org-log-states) ; turn off logging
  11650. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11651. ")
  11652. (defvar org-todo-statistics-hook nil
  11653. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11654. This hook runs even if there is no statistics cookie present, in which case
  11655. `org-after-todo-statistics-hook' would not run.")
  11656. (defun org-todo-trigger-tag-changes (state)
  11657. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11658. (let ((l org-todo-state-tags-triggers)
  11659. changes)
  11660. (when (or (not state) (equal state ""))
  11661. (setq changes (append changes (cdr (assoc "" l)))))
  11662. (when (and (stringp state) (> (length state) 0))
  11663. (setq changes (append changes (cdr (assoc state l)))))
  11664. (when (member state org-not-done-keywords)
  11665. (setq changes (append changes (cdr (assq 'todo l)))))
  11666. (when (member state org-done-keywords)
  11667. (setq changes (append changes (cdr (assq 'done l)))))
  11668. (dolist (c changes)
  11669. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11670. (defun org-local-logging (value)
  11671. "Get logging settings from a property VALUE."
  11672. ;; Directly set the variables, they are already local.
  11673. (setq org-log-done nil
  11674. org-log-repeat nil
  11675. org-todo-log-states nil)
  11676. (dolist (w (org-split-string value))
  11677. (let (a)
  11678. (cond
  11679. ((setq a (assoc w org-startup-options))
  11680. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11681. (set (nth 1 a) (nth 2 a))))
  11682. ((setq a (org-extract-log-state-settings w))
  11683. (and (member (car a) org-todo-keywords-1)
  11684. (push a org-todo-log-states)))))))
  11685. (defun org-get-todo-sequence-head (kwd)
  11686. "Return the head of the TODO sequence to which KWD belongs.
  11687. If KWD is not set, check if there is a text property remembering the
  11688. right sequence."
  11689. (let (p)
  11690. (cond
  11691. ((not kwd)
  11692. (or (get-text-property (point-at-bol) 'org-todo-head)
  11693. (progn
  11694. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11695. nil (point-at-eol)))
  11696. (get-text-property p 'org-todo-head))))
  11697. ((not (member kwd org-todo-keywords-1))
  11698. (car org-todo-keywords-1))
  11699. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11700. (defun org-fast-todo-selection ()
  11701. "Fast TODO keyword selection with single keys.
  11702. Returns the new TODO keyword, or nil if no state change should occur."
  11703. (let* ((fulltable org-todo-key-alist)
  11704. (done-keywords org-done-keywords) ;; needed for the faces.
  11705. (maxlen (apply 'max (mapcar
  11706. (lambda (x)
  11707. (if (stringp (car x)) (string-width (car x)) 0))
  11708. fulltable)))
  11709. (expert nil)
  11710. (fwidth (+ maxlen 3 1 3))
  11711. (ncol (/ (- (window-width) 4) fwidth))
  11712. tg cnt e c tbl
  11713. groups ingroup)
  11714. (save-excursion
  11715. (save-window-excursion
  11716. (if expert
  11717. (set-buffer (get-buffer-create " *Org todo*"))
  11718. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11719. (erase-buffer)
  11720. (setq-local org-done-keywords done-keywords)
  11721. (setq tbl fulltable cnt 0)
  11722. (while (setq e (pop tbl))
  11723. (cond
  11724. ((equal e '(:startgroup))
  11725. (push '() groups) (setq ingroup t)
  11726. (unless (= cnt 0)
  11727. (setq cnt 0)
  11728. (insert "\n"))
  11729. (insert "{ "))
  11730. ((equal e '(:endgroup))
  11731. (setq ingroup nil cnt 0)
  11732. (insert "}\n"))
  11733. ((equal e '(:newline))
  11734. (unless (= cnt 0)
  11735. (setq cnt 0)
  11736. (insert "\n")
  11737. (setq e (car tbl))
  11738. (while (equal (car tbl) '(:newline))
  11739. (insert "\n")
  11740. (setq tbl (cdr tbl)))))
  11741. (t
  11742. (setq tg (car e) c (cdr e))
  11743. (when ingroup (push tg (car groups)))
  11744. (setq tg (org-add-props tg nil 'face
  11745. (org-get-todo-face tg)))
  11746. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11747. (insert "[" c "] " tg (make-string
  11748. (- fwidth 4 (length tg)) ?\ ))
  11749. (when (= (setq cnt (1+ cnt)) ncol)
  11750. (insert "\n")
  11751. (when ingroup (insert " "))
  11752. (setq cnt 0)))))
  11753. (insert "\n")
  11754. (goto-char (point-min))
  11755. (unless expert (org-fit-window-to-buffer))
  11756. (message "[a-z..]:Set [SPC]:clear")
  11757. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11758. (cond
  11759. ((or (= c ?\C-g)
  11760. (and (= c ?q) (not (rassoc c fulltable))))
  11761. (setq quit-flag t))
  11762. ((= c ?\ ) nil)
  11763. ((setq e (rassoc c fulltable) tg (car e))
  11764. tg)
  11765. (t (setq quit-flag t)))))))
  11766. (defun org-entry-is-todo-p ()
  11767. (member (org-get-todo-state) org-not-done-keywords))
  11768. (defun org-entry-is-done-p ()
  11769. (member (org-get-todo-state) org-done-keywords))
  11770. (defun org-get-todo-state ()
  11771. "Return the TODO keyword of the current subtree."
  11772. (save-excursion
  11773. (org-back-to-heading t)
  11774. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11775. (match-end 2)
  11776. (match-string 2))))
  11777. (defun org-at-date-range-p (&optional inactive-ok)
  11778. "Non-nil if point is inside a date range.
  11779. When optional argument INACTIVE-OK is non-nil, also consider
  11780. inactive time ranges.
  11781. When this function returns a non-nil value, match data is set
  11782. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11783. on INACTIVE-OK."
  11784. (interactive)
  11785. (save-excursion
  11786. (catch 'exit
  11787. (let ((pos (point)))
  11788. (skip-chars-backward "^[<\r\n")
  11789. (skip-chars-backward "<[")
  11790. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11791. (>= (match-end 0) pos)
  11792. (throw 'exit t))
  11793. (skip-chars-backward "^<[\r\n")
  11794. (skip-chars-backward "<[")
  11795. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11796. (>= (match-end 0) pos)
  11797. (throw 'exit t)))
  11798. nil)))
  11799. (defun org-get-repeat (&optional timestamp)
  11800. "Check if there is a time-stamp with repeater in this entry.
  11801. Return the repeater, as a string, or nil. Also return nil when
  11802. this function is called before first heading.
  11803. When optional argument TIMESTAMP is a string, extract the
  11804. repeater from there instead."
  11805. (save-match-data
  11806. (cond (timestamp
  11807. (and (string-match org-repeat-re timestamp)
  11808. (match-string-no-properties 1 timestamp)))
  11809. ((org-before-first-heading-p) nil)
  11810. (t
  11811. (save-excursion
  11812. (org-back-to-heading t)
  11813. (let ((end (org-entry-end-position)))
  11814. (catch :repeat
  11815. (while (re-search-forward org-repeat-re end t)
  11816. (when (save-match-data (org-at-timestamp-p))
  11817. (throw :repeat (match-string-no-properties 1)))))))))))
  11818. (defvar org-last-changed-timestamp)
  11819. (defvar org-last-inserted-timestamp)
  11820. (defvar org-log-post-message)
  11821. (defvar org-log-note-purpose)
  11822. (defvar org-log-note-how nil)
  11823. (defvar org-log-note-extra)
  11824. (defun org-auto-repeat-maybe (done-word)
  11825. "Check if the current headline contains a repeated time-stamp.
  11826. If yes, set TODO state back to what it was and change the base date
  11827. of repeating deadline/scheduled time stamps to new date.
  11828. This function is run automatically after each state change to a DONE state."
  11829. (let* ((repeat (org-get-repeat))
  11830. (aa (assoc org-last-state org-todo-kwd-alist))
  11831. (interpret (nth 1 aa))
  11832. (head (nth 2 aa))
  11833. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11834. (msg "Entry repeats: ")
  11835. (org-log-done nil)
  11836. (org-todo-log-states nil)
  11837. (end (copy-marker (org-entry-end-position))))
  11838. (unwind-protect
  11839. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11840. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11841. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11842. org-todo-repeat-to-state)))
  11843. (org-todo (cond
  11844. ((and to-state (member to-state org-todo-keywords-1))
  11845. to-state)
  11846. ((eq interpret 'type) org-last-state)
  11847. (head)
  11848. (t 'none))))
  11849. (org-back-to-heading t)
  11850. (org-add-planning-info nil nil 'closed)
  11851. ;; When `org-log-repeat' is non-nil or entry contains
  11852. ;; a clock, set LAST_REPEAT property.
  11853. (when (or org-log-repeat
  11854. (catch :clock
  11855. (while (re-search-forward org-clock-line-re end t)
  11856. (when (org-at-clock-log-p) (throw :clock t)))))
  11857. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11858. (org-time-stamp-format t t)
  11859. (current-time))))
  11860. (when org-log-repeat
  11861. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11862. (memq 'org-add-log-note post-command-hook))
  11863. ;; We are already setup for some record.
  11864. (when (eq org-log-repeat 'note)
  11865. ;; Make sure we take a note, not only a time stamp.
  11866. (setq org-log-note-how 'note))
  11867. ;; Set up for taking a record.
  11868. (org-add-log-setup 'state
  11869. (or done-word (car org-done-keywords))
  11870. org-last-state
  11871. org-log-repeat)))
  11872. (let ((planning-re (regexp-opt
  11873. (list org-scheduled-string org-deadline-string))))
  11874. (while (re-search-forward org-ts-regexp end t)
  11875. (let* ((ts (match-string 0))
  11876. (planning? (org-at-planning-p))
  11877. (type (if (not planning?) "Plain:"
  11878. (save-excursion
  11879. (re-search-backward
  11880. planning-re (line-beginning-position) t)
  11881. (match-string 0)))))
  11882. (cond
  11883. ;; Ignore fake time-stamps (e.g., within comments).
  11884. ((not (org-at-timestamp-p t)))
  11885. ;; Time-stamps without a repeater are usually
  11886. ;; skipped. However, a SCHEDULED time-stamp without
  11887. ;; one is removed, as they are no longer relevant.
  11888. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11889. ts))
  11890. (when (equal type org-scheduled-string)
  11891. (org-remove-timestamp-with-keyword type)))
  11892. (t
  11893. (let ((n (string-to-number (match-string 2 ts)))
  11894. (what (match-string 3 ts)))
  11895. (when (equal what "w") (setq n (* n 7) what "d"))
  11896. (when (and (equal what "h")
  11897. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11898. ts)))
  11899. (user-error
  11900. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11901. has been set"
  11902. n))
  11903. ;; Preparation, see if we need to modify the start
  11904. ;; date for the change.
  11905. (when (match-end 1)
  11906. (let ((time (save-match-data
  11907. (org-time-string-to-time ts))))
  11908. (cond
  11909. ((equal (match-string 1 ts) ".")
  11910. ;; Shift starting date to today
  11911. (org-timestamp-change
  11912. (- (org-today) (time-to-days time))
  11913. 'day))
  11914. ((equal (match-string 1 ts) "+")
  11915. (let ((nshiftmax 10)
  11916. (nshift 0))
  11917. (while (or (= nshift 0)
  11918. (not (time-less-p (current-time) time)))
  11919. (when (= (cl-incf nshift) nshiftmax)
  11920. (or (y-or-n-p
  11921. (format "%d repeater intervals were not \
  11922. enough to shift date past today. Continue? "
  11923. nshift))
  11924. (user-error "Abort")))
  11925. (org-timestamp-change n (cdr (assoc what whata)))
  11926. (org-in-regexp org-ts-regexp3)
  11927. (setq ts (match-string 1))
  11928. (setq time
  11929. (save-match-data
  11930. (org-time-string-to-time ts)))))
  11931. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11932. ;; Rematch, so that we have everything in place
  11933. ;; for the real shift.
  11934. (org-in-regexp org-ts-regexp3)
  11935. (setq ts (match-string 1))
  11936. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11937. ts)))))
  11938. (save-excursion
  11939. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11940. (setq msg
  11941. (concat
  11942. msg type " " org-last-changed-timestamp " "))))))))
  11943. (setq org-log-post-message msg)
  11944. (message "%s" msg))
  11945. (set-marker end nil))))
  11946. (defun org-show-todo-tree (arg)
  11947. "Make a compact tree which shows all headlines marked with TODO.
  11948. The tree will show the lines where the regexp matches, and all higher
  11949. headlines above the match.
  11950. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11951. With a numeric prefix N, construct a sparse tree for the Nth element
  11952. of `org-todo-keywords-1'."
  11953. (interactive "P")
  11954. (let ((case-fold-search nil)
  11955. (kwd-re
  11956. (cond ((null arg) org-not-done-regexp)
  11957. ((equal arg '(4))
  11958. (let ((kwd
  11959. (completing-read "Keyword (or KWD1|KWD2|...): "
  11960. (mapcar #'list org-todo-keywords-1))))
  11961. (concat "\\("
  11962. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11963. "\\)\\>")))
  11964. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11965. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11966. org-todo-keywords-1)))
  11967. (t (user-error "Invalid prefix argument: %s" arg)))))
  11968. (message "%d TODO entries found"
  11969. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11970. (defun org--deadline-or-schedule (arg type time)
  11971. "Insert DEADLINE or SCHEDULE information in current entry.
  11972. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11973. `org-schedule' for information about ARG and TIME arguments."
  11974. (let* ((deadline? (eq type 'deadline))
  11975. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11976. (log (if deadline? org-log-redeadline org-log-reschedule))
  11977. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11978. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11979. ;; Save repeater cookie from either TIME or current scheduled
  11980. ;; time stamp. We are going to insert it back at the end of
  11981. ;; the process.
  11982. (repeater (or (and (org-string-nw-p time)
  11983. ;; We use `org-repeat-re' because we need
  11984. ;; to tell the difference between a real
  11985. ;; repeater and a time delta, e.g. "+2d".
  11986. (string-match org-repeat-re time)
  11987. (match-string 1 time))
  11988. (and (org-string-nw-p old-date)
  11989. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11990. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11991. old-date)
  11992. (match-string 1 old-date)))))
  11993. (pcase arg
  11994. (`(4)
  11995. (when (and old-date log)
  11996. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11997. nil old-date log))
  11998. (org-remove-timestamp-with-keyword keyword)
  11999. (message (if deadline? "Item no longer has a deadline."
  12000. "Item is no longer scheduled.")))
  12001. (`(16)
  12002. (save-excursion
  12003. (org-back-to-heading t)
  12004. (let ((regexp (if deadline? org-deadline-time-regexp
  12005. org-scheduled-time-regexp)))
  12006. (if (not (re-search-forward regexp (line-end-position 2) t))
  12007. (user-error (if deadline? "No deadline information to update"
  12008. "No scheduled information to update"))
  12009. (let* ((rpl0 (match-string 1))
  12010. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  12011. (msg (if deadline? "Warn starting from" "Delay until")))
  12012. (replace-match
  12013. (concat keyword
  12014. " <" rpl
  12015. (format " -%dd"
  12016. (abs (- (time-to-days
  12017. (save-match-data
  12018. (org-read-date
  12019. nil t nil msg old-date-time)))
  12020. (time-to-days old-date-time))))
  12021. ">") t t))))))
  12022. (_
  12023. (org-add-planning-info type time 'closed)
  12024. (when (and old-date
  12025. log
  12026. (not (equal old-date org-last-inserted-timestamp)))
  12027. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  12028. org-last-inserted-timestamp
  12029. old-date
  12030. log))
  12031. (when repeater
  12032. (save-excursion
  12033. (org-back-to-heading t)
  12034. (when (re-search-forward
  12035. (concat keyword " " org-last-inserted-timestamp)
  12036. (line-end-position 2)
  12037. t)
  12038. (goto-char (1- (match-end 0)))
  12039. (insert " " repeater)
  12040. (setq org-last-inserted-timestamp
  12041. (concat (substring org-last-inserted-timestamp 0 -1)
  12042. " " repeater
  12043. (substring org-last-inserted-timestamp -1))))))
  12044. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12045. org-last-inserted-timestamp)))))
  12046. (defun org-deadline (arg &optional time)
  12047. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12048. With one universal prefix argument, remove any deadline from the item.
  12049. With two universal prefix arguments, prompt for a warning delay.
  12050. With argument TIME, set the deadline at the corresponding date. TIME
  12051. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12052. (interactive "P")
  12053. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12054. (org-map-entries
  12055. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12056. nil
  12057. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12058. 'region-start-level
  12059. 'region)
  12060. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12061. (org--deadline-or-schedule arg 'deadline time)))
  12062. (defun org-schedule (arg &optional time)
  12063. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12064. With one universal prefix argument, remove any scheduling date from the item.
  12065. With two universal prefix arguments, prompt for a delay cookie.
  12066. With argument TIME, scheduled at the corresponding date. TIME can
  12067. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12068. (interactive "P")
  12069. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12070. (org-map-entries
  12071. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12072. nil
  12073. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12074. 'region-start-level
  12075. 'region)
  12076. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12077. (org--deadline-or-schedule arg 'scheduled time)))
  12078. (defun org-get-scheduled-time (pom &optional inherit)
  12079. "Get the scheduled time as a time tuple, of a format suitable
  12080. for calling org-schedule with, or if there is no scheduling,
  12081. returns nil."
  12082. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12083. (when time
  12084. (apply 'encode-time (org-parse-time-string time)))))
  12085. (defun org-get-deadline-time (pom &optional inherit)
  12086. "Get the deadline as a time tuple, of a format suitable for
  12087. calling org-deadline with, or if there is no scheduling, returns
  12088. nil."
  12089. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12090. (when time
  12091. (apply 'encode-time (org-parse-time-string time)))))
  12092. (defun org-remove-timestamp-with-keyword (keyword)
  12093. "Remove all time stamps with KEYWORD in the current entry."
  12094. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12095. beg)
  12096. (save-excursion
  12097. (org-back-to-heading t)
  12098. (setq beg (point))
  12099. (outline-next-heading)
  12100. (while (re-search-backward re beg t)
  12101. (replace-match "")
  12102. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12103. (equal (char-before) ?\ ))
  12104. (backward-delete-char 1)
  12105. (when (string-match "^[ \t]*$" (buffer-substring
  12106. (point-at-bol) (point-at-eol)))
  12107. (delete-region (point-at-bol)
  12108. (min (point-max) (1+ (point-at-eol))))))))))
  12109. (defvar org-time-was-given) ; dynamically scoped parameter
  12110. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12111. (defun org-at-planning-p ()
  12112. "Non-nil when point is on a planning info line."
  12113. ;; This is as accurate and faster than `org-element-at-point' since
  12114. ;; planning info location is fixed in the section.
  12115. (org-with-wide-buffer
  12116. (beginning-of-line)
  12117. (and (looking-at-p org-planning-line-re)
  12118. (eq (point)
  12119. (ignore-errors
  12120. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12121. (org-back-to-heading t)
  12122. (org-with-limited-levels (org-back-to-heading t)))
  12123. (line-beginning-position 2))))))
  12124. (defun org-add-planning-info (what &optional time &rest remove)
  12125. "Insert new timestamp with keyword in the planning line.
  12126. WHAT indicates what kind of time stamp to add. It is a symbol
  12127. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12128. the time to use. If none is given, the user is prompted for
  12129. a date. REMOVE indicates what kind of entries to remove. An old
  12130. WHAT entry will also be removed."
  12131. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12132. (catch 'exit
  12133. (when (and (memq what '(scheduled deadline))
  12134. (or (not time)
  12135. (and (stringp time)
  12136. (string-match "^[-+]+[0-9]" time))))
  12137. ;; Try to get a default date/time from existing timestamp
  12138. (save-excursion
  12139. (org-back-to-heading t)
  12140. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12141. (when (re-search-forward (if (eq what 'scheduled)
  12142. org-scheduled-time-regexp
  12143. org-deadline-time-regexp)
  12144. end t)
  12145. (setq ts (match-string 1)
  12146. default-time (apply 'encode-time (org-parse-time-string ts))
  12147. default-input (and ts (org-get-compact-tod ts)))))))
  12148. (when what
  12149. (setq time
  12150. (if (stringp time)
  12151. ;; This is a string (relative or absolute), set
  12152. ;; proper date.
  12153. (apply #'encode-time
  12154. (org-read-date-analyze
  12155. time default-time (decode-time default-time)))
  12156. ;; If necessary, get the time from the user
  12157. (or time (org-read-date nil 'to-time nil nil
  12158. default-time default-input)))))
  12159. (org-with-wide-buffer
  12160. (org-back-to-heading t)
  12161. (forward-line)
  12162. (unless (bolp) (insert "\n"))
  12163. (cond ((looking-at-p org-planning-line-re)
  12164. ;; Move to current indentation.
  12165. (skip-chars-forward " \t")
  12166. ;; Check if we have to remove something.
  12167. (dolist (type (if what (cons what remove) remove))
  12168. (save-excursion
  12169. (when (re-search-forward
  12170. (cl-case type
  12171. (closed org-closed-time-regexp)
  12172. (deadline org-deadline-time-regexp)
  12173. (scheduled org-scheduled-time-regexp)
  12174. (otherwise
  12175. (error "Invalid planning type: %s" type)))
  12176. (line-end-position) t)
  12177. ;; Delete until next keyword or end of line.
  12178. (delete-region
  12179. (match-beginning 0)
  12180. (if (re-search-forward org-keyword-time-not-clock-regexp
  12181. (line-end-position)
  12182. t)
  12183. (match-beginning 0)
  12184. (line-end-position))))))
  12185. ;; If there is nothing more to add and no more keyword
  12186. ;; is left, remove the line completely.
  12187. (if (and (looking-at-p "[ \t]*$") (not what))
  12188. (delete-region (line-beginning-position)
  12189. (line-beginning-position 2))
  12190. ;; If we removed last keyword, do not leave trailing
  12191. ;; white space at the end of line.
  12192. (let ((p (point)))
  12193. (save-excursion
  12194. (end-of-line)
  12195. (unless (= (skip-chars-backward " \t" p) 0)
  12196. (delete-region (point) (line-end-position)))))))
  12197. ((not what) (throw 'exit nil)) ; Nothing to do.
  12198. (t (insert-before-markers "\n")
  12199. (backward-char 1)
  12200. (when org-adapt-indentation
  12201. (indent-to-column (1+ (org-outline-level))))))
  12202. (when what
  12203. ;; Insert planning keyword.
  12204. (insert (cl-case what
  12205. (closed org-closed-string)
  12206. (deadline org-deadline-string)
  12207. (scheduled org-scheduled-string)
  12208. (otherwise (error "Invalid planning type: %s" what)))
  12209. " ")
  12210. ;; Insert associated timestamp.
  12211. (let ((ts (org-insert-time-stamp
  12212. time
  12213. (or org-time-was-given
  12214. (and (eq what 'closed) org-log-done-with-time))
  12215. (eq what 'closed)
  12216. nil nil (list org-end-time-was-given))))
  12217. (unless (eolp) (insert " "))
  12218. ts))))))
  12219. (defvar org-log-note-marker (make-marker)
  12220. "Marker pointing at the entry where the note is to be inserted.")
  12221. (defvar org-log-note-purpose nil)
  12222. (defvar org-log-note-state nil)
  12223. (defvar org-log-note-previous-state nil)
  12224. (defvar org-log-note-extra nil)
  12225. (defvar org-log-note-window-configuration nil)
  12226. (defvar org-log-note-return-to (make-marker))
  12227. (defvar org-log-note-effective-time nil
  12228. "Remembered current time so that dynamically scoped
  12229. `org-extend-today-until' affects timestamps in state change log")
  12230. (defvar org-log-post-message nil
  12231. "Message to be displayed after a log note has been stored.
  12232. The auto-repeater uses this.")
  12233. (defun org-add-note ()
  12234. "Add a note to the current entry.
  12235. This is done in the same way as adding a state change note."
  12236. (interactive)
  12237. (org-add-log-setup 'note))
  12238. (defun org-log-beginning (&optional create)
  12239. "Return expected start of log notes in current entry.
  12240. When optional argument CREATE is non-nil, the function creates
  12241. a drawer to store notes, if necessary. Returned position ignores
  12242. narrowing."
  12243. (org-with-wide-buffer
  12244. (let ((drawer (org-log-into-drawer)))
  12245. (cond
  12246. (drawer
  12247. (org-end-of-meta-data)
  12248. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12249. (end (if (org-at-heading-p) (point)
  12250. (save-excursion (outline-next-heading) (point))))
  12251. (case-fold-search t))
  12252. (catch 'exit
  12253. ;; Try to find existing drawer.
  12254. (while (re-search-forward regexp end t)
  12255. (let ((element (org-element-at-point)))
  12256. (when (eq (org-element-type element) 'drawer)
  12257. (let ((cend (org-element-property :contents-end element)))
  12258. (when (and (not org-log-states-order-reversed) cend)
  12259. (goto-char cend)))
  12260. (throw 'exit nil))))
  12261. ;; No drawer found. Create one, if permitted.
  12262. (when create
  12263. (unless (bolp) (insert "\n"))
  12264. (let ((beg (point)))
  12265. (insert ":" drawer ":\n:END:\n")
  12266. (org-indent-region beg (point)))
  12267. (end-of-line -1)))))
  12268. (t
  12269. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12270. (skip-chars-forward " \t\n")
  12271. (beginning-of-line)
  12272. (unless org-log-states-order-reversed
  12273. (org-skip-over-state-notes)
  12274. (skip-chars-backward " \t\n")
  12275. (forward-line)))))
  12276. (if (bolp) (point) (line-beginning-position 2))))
  12277. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12278. "Set up the post command hook to take a note.
  12279. If this is about to TODO state change, the new state is expected in STATE.
  12280. HOW is an indicator what kind of note should be created.
  12281. EXTRA is additional text that will be inserted into the notes buffer."
  12282. (move-marker org-log-note-marker (point))
  12283. (setq org-log-note-purpose purpose
  12284. org-log-note-state state
  12285. org-log-note-previous-state prev-state
  12286. org-log-note-how how
  12287. org-log-note-extra extra
  12288. org-log-note-effective-time (org-current-effective-time))
  12289. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12290. (defun org-skip-over-state-notes ()
  12291. "Skip past the list of State notes in an entry."
  12292. (when (ignore-errors (goto-char (org-in-item-p)))
  12293. (let* ((struct (org-list-struct))
  12294. (prevs (org-list-prevs-alist struct))
  12295. (regexp
  12296. (concat "[ \t]*- +"
  12297. (replace-regexp-in-string
  12298. " +" " +"
  12299. (org-replace-escapes
  12300. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12301. `(("%d" . ,org-ts-regexp-inactive)
  12302. ("%D" . ,org-ts-regexp)
  12303. ("%s" . "\"\\S-+\"")
  12304. ("%S" . "\"\\S-+\"")
  12305. ("%t" . ,org-ts-regexp-inactive)
  12306. ("%T" . ,org-ts-regexp)
  12307. ("%u" . ".*?")
  12308. ("%U" . ".*?")))))))
  12309. (while (looking-at-p regexp)
  12310. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12311. (org-list-get-item-end (point) struct)))))))
  12312. (defun org-add-log-note (&optional _purpose)
  12313. "Pop up a window for taking a note, and add this note later."
  12314. (remove-hook 'post-command-hook 'org-add-log-note)
  12315. (setq org-log-note-window-configuration (current-window-configuration))
  12316. (delete-other-windows)
  12317. (move-marker org-log-note-return-to (point))
  12318. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12319. (goto-char org-log-note-marker)
  12320. (org-switch-to-buffer-other-window "*Org Note*")
  12321. (erase-buffer)
  12322. (if (memq org-log-note-how '(time state))
  12323. (let (current-prefix-arg) (org-store-log-note))
  12324. (let ((org-inhibit-startup t)) (org-mode))
  12325. (insert (format "# Insert note for %s.
  12326. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12327. (cond
  12328. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12329. ((eq org-log-note-purpose 'done) "closed todo item")
  12330. ((eq org-log-note-purpose 'state)
  12331. (format "state change from \"%s\" to \"%s\""
  12332. (or org-log-note-previous-state "")
  12333. (or org-log-note-state "")))
  12334. ((eq org-log-note-purpose 'reschedule)
  12335. "rescheduling")
  12336. ((eq org-log-note-purpose 'delschedule)
  12337. "no longer scheduled")
  12338. ((eq org-log-note-purpose 'redeadline)
  12339. "changing deadline")
  12340. ((eq org-log-note-purpose 'deldeadline)
  12341. "removing deadline")
  12342. ((eq org-log-note-purpose 'refile)
  12343. "refiling")
  12344. ((eq org-log-note-purpose 'note)
  12345. "this entry")
  12346. (t (error "This should not happen")))))
  12347. (when org-log-note-extra (insert org-log-note-extra))
  12348. (setq-local org-finish-function 'org-store-log-note)
  12349. (run-hooks 'org-log-buffer-setup-hook)))
  12350. (defvar org-note-abort nil) ; dynamically scoped
  12351. (defun org-store-log-note ()
  12352. "Finish taking a log note, and insert it to where it belongs."
  12353. (let ((txt (prog1 (buffer-string)
  12354. (kill-buffer)))
  12355. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12356. lines)
  12357. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12358. (setq txt (replace-match "" t t txt)))
  12359. (when (string-match "\\s-+\\'" txt)
  12360. (setq txt (replace-match "" t t txt)))
  12361. (setq lines (org-split-string txt "\n"))
  12362. (when (org-string-nw-p note)
  12363. (setq note
  12364. (org-replace-escapes
  12365. note
  12366. (list (cons "%u" (user-login-name))
  12367. (cons "%U" user-full-name)
  12368. (cons "%t" (format-time-string
  12369. (org-time-stamp-format 'long 'inactive)
  12370. org-log-note-effective-time))
  12371. (cons "%T" (format-time-string
  12372. (org-time-stamp-format 'long nil)
  12373. org-log-note-effective-time))
  12374. (cons "%d" (format-time-string
  12375. (org-time-stamp-format nil 'inactive)
  12376. org-log-note-effective-time))
  12377. (cons "%D" (format-time-string
  12378. (org-time-stamp-format nil nil)
  12379. org-log-note-effective-time))
  12380. (cons "%s" (cond
  12381. ((not org-log-note-state) "")
  12382. ((string-match-p org-ts-regexp
  12383. org-log-note-state)
  12384. (format "\"[%s]\""
  12385. (substring org-log-note-state 1 -1)))
  12386. (t (format "\"%s\"" org-log-note-state))))
  12387. (cons "%S"
  12388. (cond
  12389. ((not org-log-note-previous-state) "")
  12390. ((string-match-p org-ts-regexp
  12391. org-log-note-previous-state)
  12392. (format "\"[%s]\""
  12393. (substring
  12394. org-log-note-previous-state 1 -1)))
  12395. (t (format "\"%s\""
  12396. org-log-note-previous-state)))))))
  12397. (when lines (setq note (concat note " \\\\")))
  12398. (push note lines))
  12399. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12400. (with-current-buffer (marker-buffer org-log-note-marker)
  12401. (org-with-wide-buffer
  12402. ;; Find location for the new note.
  12403. (goto-char org-log-note-marker)
  12404. (set-marker org-log-note-marker nil)
  12405. ;; Note associated to a clock is to be located right after
  12406. ;; the clock. Do not move point.
  12407. (unless (eq org-log-note-purpose 'clock-out)
  12408. (goto-char (org-log-beginning t)))
  12409. ;; Make sure point is at the beginning of an empty line.
  12410. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12411. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12412. ;; In an existing list, add a new item at the top level.
  12413. ;; Otherwise, indent line like a regular one.
  12414. (let ((itemp (org-in-item-p)))
  12415. (if itemp
  12416. (indent-line-to
  12417. (let ((struct (save-excursion
  12418. (goto-char itemp) (org-list-struct))))
  12419. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12420. (org-indent-line)))
  12421. (insert (org-list-bullet-string "-") (pop lines))
  12422. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12423. (dolist (line lines)
  12424. (insert "\n")
  12425. (indent-line-to ind)
  12426. (insert line)))
  12427. (message "Note stored")
  12428. (org-back-to-heading t)
  12429. (org-cycle-hide-drawers 'children))
  12430. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12431. ;; from within `org-add-log-note' because `buffer-undo-list'
  12432. ;; is then modified outside of `org-with-remote-undo'.
  12433. (when (eq this-command 'org-agenda-todo)
  12434. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12435. ;; Don't add undo information when called from `org-agenda-todo'.
  12436. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12437. (set-window-configuration org-log-note-window-configuration)
  12438. (with-current-buffer (marker-buffer org-log-note-return-to)
  12439. (goto-char org-log-note-return-to))
  12440. (move-marker org-log-note-return-to nil)
  12441. (when org-log-post-message (message "%s" org-log-post-message))))
  12442. (defun org-remove-empty-drawer-at (pos)
  12443. "Remove an empty drawer at position POS.
  12444. POS may also be a marker."
  12445. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12446. (org-with-wide-buffer
  12447. (goto-char pos)
  12448. (let ((drawer (org-element-at-point)))
  12449. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12450. (not (org-element-property :contents-begin drawer)))
  12451. (delete-region (org-element-property :begin drawer)
  12452. (progn (goto-char (org-element-property :end drawer))
  12453. (skip-chars-backward " \r\t\n")
  12454. (forward-line)
  12455. (point))))))))
  12456. (defvar org-ts-type nil)
  12457. (defun org-sparse-tree (&optional arg type)
  12458. "Create a sparse tree, prompt for the details.
  12459. This command can create sparse trees. You first need to select the type
  12460. of match used to create the tree:
  12461. t Show all TODO entries.
  12462. T Show entries with a specific TODO keyword.
  12463. m Show entries selected by a tags/property match.
  12464. p Enter a property name and its value (both with completion on existing
  12465. names/values) and show entries with that property.
  12466. r Show entries matching a regular expression (`/' can be used as well).
  12467. b Show deadlines and scheduled items before a date.
  12468. a Show deadlines and scheduled items after a date.
  12469. d Show deadlines due within `org-deadline-warning-days'.
  12470. D Show deadlines and scheduled items between a date range."
  12471. (interactive "P")
  12472. (setq type (or type org-sparse-tree-default-date-type))
  12473. (setq org-ts-type type)
  12474. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12475. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12476. \[c]ycle through date types: %s"
  12477. (cl-case type
  12478. (all "all timestamps")
  12479. (scheduled "only scheduled")
  12480. (deadline "only deadline")
  12481. (active "only active timestamps")
  12482. (inactive "only inactive timestamps")
  12483. (closed "with a closed time-stamp")
  12484. (otherwise "scheduled/deadline")))
  12485. (let ((answer (read-char-exclusive)))
  12486. (cl-case answer
  12487. (?c
  12488. (org-sparse-tree
  12489. arg
  12490. (cadr
  12491. (memq type '(nil all scheduled deadline active inactive closed)))))
  12492. (?d (call-interactively 'org-check-deadlines))
  12493. (?b (call-interactively 'org-check-before-date))
  12494. (?a (call-interactively 'org-check-after-date))
  12495. (?D (call-interactively 'org-check-dates-range))
  12496. (?t (call-interactively 'org-show-todo-tree))
  12497. (?T (org-show-todo-tree '(4)))
  12498. (?m (call-interactively 'org-match-sparse-tree))
  12499. ((?p ?P)
  12500. (let* ((kwd (completing-read
  12501. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12502. (value (completing-read
  12503. "Value: " (mapcar #'list (org-property-values kwd)))))
  12504. (unless (string-match "\\`{.*}\\'" value)
  12505. (setq value (concat "\"" value "\"")))
  12506. (org-match-sparse-tree arg (concat kwd "=" value))))
  12507. ((?r ?R ?/) (call-interactively 'org-occur))
  12508. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12509. (defvar-local org-occur-highlights nil
  12510. "List of overlays used for occur matches.")
  12511. (defvar-local org-occur-parameters nil
  12512. "Parameters of the active org-occur calls.
  12513. This is a list, each call to org-occur pushes as cons cell,
  12514. containing the regular expression and the callback, onto the list.
  12515. The list can contain several entries if `org-occur' has been called
  12516. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12517. will only contain one set of parameters. When the highlights are
  12518. removed (for example with `C-c C-c', or with the next edit (depending
  12519. on `org-remove-highlights-with-change'), this variable is emptied
  12520. as well.")
  12521. (defun org-occur (regexp &optional keep-previous callback)
  12522. "Make a compact tree which shows all matches of REGEXP.
  12523. The tree will show the lines where the regexp matches, and any other context
  12524. defined in `org-show-context-detail', which see.
  12525. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12526. done by a previous call to `org-occur' will be kept, to allow stacking of
  12527. calls to this command.
  12528. Optional argument CALLBACK can be a function of no argument. In this case,
  12529. it is called with point at the end of the match, match data being set
  12530. accordingly. Current match is shown only if the return value is non-nil.
  12531. The function must neither move point nor alter narrowing."
  12532. (interactive "sRegexp: \nP")
  12533. (when (equal regexp "")
  12534. (user-error "Regexp cannot be empty"))
  12535. (unless keep-previous
  12536. (org-remove-occur-highlights nil nil t))
  12537. (push (cons regexp callback) org-occur-parameters)
  12538. (let ((cnt 0))
  12539. (save-excursion
  12540. (goto-char (point-min))
  12541. (when (or (not keep-previous) ; do not want to keep
  12542. (not org-occur-highlights)) ; no previous matches
  12543. ;; hide everything
  12544. (org-overview))
  12545. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12546. (isearch-no-upper-case-p regexp t)
  12547. org-occur-case-fold-search)))
  12548. (while (re-search-forward regexp nil t)
  12549. (when (or (not callback)
  12550. (save-match-data (funcall callback)))
  12551. (setq cnt (1+ cnt))
  12552. (when org-highlight-sparse-tree-matches
  12553. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12554. (org-show-context 'occur-tree)))))
  12555. (when org-remove-highlights-with-change
  12556. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12557. nil 'local))
  12558. (unless org-sparse-tree-open-archived-trees
  12559. (org-hide-archived-subtrees (point-min) (point-max)))
  12560. (run-hooks 'org-occur-hook)
  12561. (when (called-interactively-p 'interactive)
  12562. (message "%d match(es) for regexp %s" cnt regexp))
  12563. cnt))
  12564. (defun org-occur-next-match (&optional n _reset)
  12565. "Function for `next-error-function' to find sparse tree matches.
  12566. N is the number of matches to move, when negative move backwards.
  12567. This function always goes back to the starting point when no
  12568. match is found."
  12569. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12570. (search-func (if (< n 0)
  12571. 'previous-single-char-property-change
  12572. 'next-single-char-property-change))
  12573. (n (abs n))
  12574. (pos (point))
  12575. p1)
  12576. (catch 'exit
  12577. (while (setq p1 (funcall search-func (point) 'org-type))
  12578. (when (equal p1 limit)
  12579. (goto-char pos)
  12580. (user-error "No more matches"))
  12581. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12582. (setq n (1- n))
  12583. (when (= n 0)
  12584. (goto-char p1)
  12585. (throw 'exit (point))))
  12586. (goto-char p1))
  12587. (goto-char p1)
  12588. (user-error "No more matches"))))
  12589. (defun org-show-context (&optional key)
  12590. "Make sure point and context are visible.
  12591. Optional argument KEY, when non-nil, is a symbol. See
  12592. `org-show-context-detail' for allowed values and how much is to
  12593. be shown."
  12594. (org-show-set-visibility
  12595. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12596. ((cdr (assq key org-show-context-detail)))
  12597. (t (cdr (assq 'default org-show-context-detail))))))
  12598. (defun org-show-set-visibility (detail)
  12599. "Set visibility around point according to DETAIL.
  12600. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12601. `tree', `canonical' or t. See `org-show-context-detail' for more
  12602. information."
  12603. ;; Show current heading and possibly its entry, following headline
  12604. ;; or all children.
  12605. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12606. (org-flag-heading nil)
  12607. (org-show-entry)
  12608. ;; If point is hidden within a drawer or a block, make sure to
  12609. ;; expose it.
  12610. (dolist (o (overlays-at (point)))
  12611. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12612. (delete-overlay o)))
  12613. (unless (org-before-first-heading-p)
  12614. (org-with-limited-levels
  12615. (cl-case detail
  12616. ((tree canonical t) (org-show-children))
  12617. ((nil minimal ancestors))
  12618. (t (save-excursion
  12619. (outline-next-heading)
  12620. (org-flag-heading nil)))))))
  12621. ;; Show all siblings.
  12622. (when (eq detail 'lineage) (org-show-siblings))
  12623. ;; Show ancestors, possibly with their children.
  12624. (when (memq detail '(ancestors lineage tree canonical t))
  12625. (save-excursion
  12626. (while (org-up-heading-safe)
  12627. (org-flag-heading nil)
  12628. (when (memq detail '(canonical t)) (org-show-entry))
  12629. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12630. (defvar org-reveal-start-hook nil
  12631. "Hook run before revealing a location.")
  12632. (defun org-reveal (&optional siblings)
  12633. "Show current entry, hierarchy above it, and the following headline.
  12634. This can be used to show a consistent set of context around
  12635. locations exposed with `org-show-context'.
  12636. With optional argument SIBLINGS, on each level of the hierarchy all
  12637. siblings are shown. This repairs the tree structure to what it would
  12638. look like when opened with hierarchical calls to `org-cycle'.
  12639. With a \\[universal-argument] \\[universal-argument] prefix, \
  12640. go to the parent and show the entire tree."
  12641. (interactive "P")
  12642. (run-hooks 'org-reveal-start-hook)
  12643. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12644. ((equal siblings '(16))
  12645. (save-excursion
  12646. (when (org-up-heading-safe)
  12647. (org-show-subtree)
  12648. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12649. (t (org-show-set-visibility 'lineage))))
  12650. (defun org-highlight-new-match (beg end)
  12651. "Highlight from BEG to END and mark the highlight is an occur headline."
  12652. (let ((ov (make-overlay beg end)))
  12653. (overlay-put ov 'face 'secondary-selection)
  12654. (overlay-put ov 'org-type 'org-occur)
  12655. (push ov org-occur-highlights)))
  12656. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12657. "Remove the occur highlights from the buffer.
  12658. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12659. from the `before-change-functions' in the current buffer."
  12660. (interactive)
  12661. (unless org-inhibit-highlight-removal
  12662. (mapc #'delete-overlay org-occur-highlights)
  12663. (setq org-occur-highlights nil)
  12664. (setq org-occur-parameters nil)
  12665. (unless noremove
  12666. (remove-hook 'before-change-functions
  12667. 'org-remove-occur-highlights 'local))))
  12668. ;;;; Priorities
  12669. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12670. "Regular expression matching the priority indicator.")
  12671. (defvar org-remove-priority-next-time nil)
  12672. (defun org-priority-up ()
  12673. "Increase the priority of the current item."
  12674. (interactive)
  12675. (org-priority 'up))
  12676. (defun org-priority-down ()
  12677. "Decrease the priority of the current item."
  12678. (interactive)
  12679. (org-priority 'down))
  12680. (defun org-priority (&optional action _show)
  12681. "Change the priority of an item.
  12682. ACTION can be `set', `up', `down', or a character."
  12683. (interactive "P")
  12684. (if (equal action '(4))
  12685. (org-show-priority)
  12686. (unless org-enable-priority-commands
  12687. (user-error "Priority commands are disabled"))
  12688. (setq action (or action 'set))
  12689. (let (current new news have remove)
  12690. (save-excursion
  12691. (org-back-to-heading t)
  12692. (when (looking-at org-priority-regexp)
  12693. (setq current (string-to-char (match-string 2))
  12694. have t))
  12695. (cond
  12696. ((eq action 'remove)
  12697. (setq remove t new ?\ ))
  12698. ((or (eq action 'set)
  12699. (integerp action))
  12700. (if (not (eq action 'set))
  12701. (setq new action)
  12702. (message "Priority %c-%c, SPC to remove: "
  12703. org-highest-priority org-lowest-priority)
  12704. (save-match-data
  12705. (setq new (read-char-exclusive))))
  12706. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12707. (= (upcase org-lowest-priority) org-lowest-priority))
  12708. (setq new (upcase new)))
  12709. (cond ((equal new ?\ ) (setq remove t))
  12710. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12711. (user-error "Priority must be between `%c' and `%c'"
  12712. org-highest-priority org-lowest-priority))))
  12713. ((eq action 'up)
  12714. (setq new (if have
  12715. (1- current) ; normal cycling
  12716. ;; last priority was empty
  12717. (if (eq last-command this-command)
  12718. org-lowest-priority ; wrap around empty to lowest
  12719. ;; default
  12720. (if org-priority-start-cycle-with-default
  12721. org-default-priority
  12722. (1- org-default-priority))))))
  12723. ((eq action 'down)
  12724. (setq new (if have
  12725. (1+ current) ; normal cycling
  12726. ;; last priority was empty
  12727. (if (eq last-command this-command)
  12728. org-highest-priority ; wrap around empty to highest
  12729. ;; default
  12730. (if org-priority-start-cycle-with-default
  12731. org-default-priority
  12732. (1+ org-default-priority))))))
  12733. (t (user-error "Invalid action")))
  12734. (when (or (< (upcase new) org-highest-priority)
  12735. (> (upcase new) org-lowest-priority))
  12736. (if (and (memq action '(up down))
  12737. (not have) (not (eq last-command this-command)))
  12738. ;; `new' is from default priority
  12739. (error
  12740. "The default can not be set, see `org-default-priority' why")
  12741. ;; normal cycling: `new' is beyond highest/lowest priority
  12742. ;; and is wrapped around to the empty priority
  12743. (setq remove t)))
  12744. (setq news (format "%c" new))
  12745. (if have
  12746. (if remove
  12747. (replace-match "" t t nil 1)
  12748. (replace-match news t t nil 2))
  12749. (if remove
  12750. (user-error "No priority cookie found in line")
  12751. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12752. (if (match-end 2)
  12753. (progn
  12754. (goto-char (match-end 2))
  12755. (insert " [#" news "]"))
  12756. (goto-char (match-beginning 3))
  12757. (insert "[#" news "] "))))
  12758. (org-set-tags nil 'align))
  12759. (if remove
  12760. (message "Priority removed")
  12761. (message "Priority of current item set to %s" news)))))
  12762. (defun org-show-priority ()
  12763. "Show the priority of the current item.
  12764. This priority is composed of the main priority given with the [#A] cookies,
  12765. and by additional input from the age of a schedules or deadline entry."
  12766. (interactive)
  12767. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12768. (org-get-at-bol 'priority)
  12769. (save-excursion
  12770. (save-match-data
  12771. (beginning-of-line)
  12772. (and (looking-at org-heading-regexp)
  12773. (org-get-priority (match-string 0))))))))
  12774. (message "Priority is %d" (if pri pri -1000))))
  12775. (defun org-get-priority (s)
  12776. "Find priority cookie and return priority."
  12777. (save-match-data
  12778. (if (functionp org-get-priority-function)
  12779. (funcall org-get-priority-function)
  12780. (if (not (string-match org-priority-regexp s))
  12781. (* 1000 (- org-lowest-priority org-default-priority))
  12782. (* 1000 (- org-lowest-priority
  12783. (string-to-char (match-string 2 s))))))))
  12784. ;;;; Tags
  12785. (defvar org-agenda-archives-mode)
  12786. (defvar org-map-continue-from nil
  12787. "Position from where mapping should continue.
  12788. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12789. (defvar org-scanner-tags nil
  12790. "The current tag list while the tags scanner is running.")
  12791. (defvar org-trust-scanner-tags nil
  12792. "Should `org-get-tags-at' use the tags for the scanner.
  12793. This is for internal dynamical scoping only.
  12794. When this is non-nil, the function `org-get-tags-at' will return the value
  12795. of `org-scanner-tags' instead of building the list by itself. This
  12796. can lead to large speed-ups when the tags scanner is used in a file with
  12797. many entries, and when the list of tags is retrieved, for example to
  12798. obtain a list of properties. Building the tags list for each entry in such
  12799. a file becomes an N^2 operation - but with this variable set, it scales
  12800. as N.")
  12801. (defvar org--matcher-tags-todo-only nil)
  12802. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12803. "Scan headline tags with inheritance and produce output ACTION.
  12804. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12805. or `agenda' to produce an entry list for an agenda view. It can also be
  12806. a Lisp form or a function that should be called at each matched headline, in
  12807. this case the return value is a list of all return values from these calls.
  12808. MATCHER is a function accepting three arguments, returning
  12809. a non-nil value whenever a given set of tags qualifies a headline
  12810. for inclusion. See `org-make-tags-matcher' for more information.
  12811. As a special case, it can also be set to t (respectively nil) in
  12812. order to match all (respectively none) headline.
  12813. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12814. keyword are included in the output.
  12815. START-LEVEL can be a string with asterisks, reducing the scope to
  12816. headlines matching this string."
  12817. (require 'org-agenda)
  12818. (let* ((re (concat "^"
  12819. (if start-level
  12820. ;; Get the correct level to match
  12821. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12822. org-outline-regexp)
  12823. " *\\(\\<\\("
  12824. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12825. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12826. (props (list 'face 'default
  12827. 'done-face 'org-agenda-done
  12828. 'undone-face 'default
  12829. 'mouse-face 'highlight
  12830. 'org-not-done-regexp org-not-done-regexp
  12831. 'org-todo-regexp org-todo-regexp
  12832. 'org-complex-heading-regexp org-complex-heading-regexp
  12833. 'help-echo
  12834. (format "mouse-2 or RET jump to org file %s"
  12835. (abbreviate-file-name
  12836. (or (buffer-file-name (buffer-base-buffer))
  12837. (buffer-name (buffer-base-buffer)))))))
  12838. (org-map-continue-from nil)
  12839. lspos tags tags-list
  12840. (tags-alist (list (cons 0 org-file-tags)))
  12841. (llast 0) rtn rtn1 level category i txt
  12842. todo marker entry priority
  12843. ts-date ts-date-type ts-date-pair)
  12844. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12845. (setq action (list 'lambda nil action)))
  12846. (save-excursion
  12847. (goto-char (point-min))
  12848. (when (eq action 'sparse-tree)
  12849. (org-overview)
  12850. (org-remove-occur-highlights))
  12851. (while (let (case-fold-search)
  12852. (re-search-forward re nil t))
  12853. (setq org-map-continue-from nil)
  12854. (catch :skip
  12855. (setq todo
  12856. ;; TODO: is the 1-2 difference a bug?
  12857. (when (match-end 1) (match-string-no-properties 2))
  12858. tags (when (match-end 4) (match-string-no-properties 4)))
  12859. (goto-char (setq lspos (match-beginning 0)))
  12860. (setq level (org-reduced-level (org-outline-level))
  12861. category (org-get-category))
  12862. (when (eq action 'agenda)
  12863. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12864. ts-date (car ts-date-pair)
  12865. ts-date-type (cdr ts-date-pair)))
  12866. (setq i llast llast level)
  12867. ;; remove tag lists from same and sublevels
  12868. (while (>= i level)
  12869. (when (setq entry (assoc i tags-alist))
  12870. (setq tags-alist (delete entry tags-alist)))
  12871. (setq i (1- i)))
  12872. ;; add the next tags
  12873. (when tags
  12874. (setq tags (org-split-string tags ":")
  12875. tags-alist
  12876. (cons (cons level tags) tags-alist)))
  12877. ;; compile tags for current headline
  12878. (setq tags-list
  12879. (if org-use-tag-inheritance
  12880. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12881. tags)
  12882. org-scanner-tags tags-list)
  12883. (when org-use-tag-inheritance
  12884. (setcdr (car tags-alist)
  12885. (mapcar (lambda (x)
  12886. (setq x (copy-sequence x))
  12887. (org-add-prop-inherited x))
  12888. (cdar tags-alist))))
  12889. (when (and tags org-use-tag-inheritance
  12890. (or (not (eq t org-use-tag-inheritance))
  12891. org-tags-exclude-from-inheritance))
  12892. ;; Selective inheritance, remove uninherited ones.
  12893. (setcdr (car tags-alist)
  12894. (org-remove-uninherited-tags (cdar tags-alist))))
  12895. (when (and
  12896. ;; eval matcher only when the todo condition is OK
  12897. (and (or (not todo-only) (member todo org-not-done-keywords))
  12898. (if (functionp matcher)
  12899. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12900. (funcall matcher todo tags-list level))
  12901. matcher))
  12902. ;; Call the skipper, but return t if it does not
  12903. ;; skip, so that the `and' form continues evaluating.
  12904. (progn
  12905. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12906. t)
  12907. ;; Check if timestamps are deselecting this entry
  12908. (or (not todo-only)
  12909. (and (member todo org-not-done-keywords)
  12910. (or (not org-agenda-tags-todo-honor-ignore-options)
  12911. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12912. ;; select this headline
  12913. (cond
  12914. ((eq action 'sparse-tree)
  12915. (and org-highlight-sparse-tree-matches
  12916. (org-get-heading) (match-end 0)
  12917. (org-highlight-new-match
  12918. (match-beginning 1) (match-end 1)))
  12919. (org-show-context 'tags-tree))
  12920. ((eq action 'agenda)
  12921. (setq txt (org-agenda-format-item
  12922. ""
  12923. (concat
  12924. (if (eq org-tags-match-list-sublevels 'indented)
  12925. (make-string (1- level) ?.) "")
  12926. (org-get-heading))
  12927. (make-string level ?\s)
  12928. category
  12929. tags-list)
  12930. priority (org-get-priority txt))
  12931. (goto-char lspos)
  12932. (setq marker (org-agenda-new-marker))
  12933. (org-add-props txt props
  12934. 'org-marker marker 'org-hd-marker marker 'org-category category
  12935. 'todo-state todo
  12936. 'ts-date ts-date
  12937. 'priority priority
  12938. 'type (concat "tagsmatch" ts-date-type))
  12939. (push txt rtn))
  12940. ((functionp action)
  12941. (setq org-map-continue-from nil)
  12942. (save-excursion
  12943. (setq rtn1 (funcall action))
  12944. (push rtn1 rtn)))
  12945. (t (user-error "Invalid action")))
  12946. ;; if we are to skip sublevels, jump to end of subtree
  12947. (unless org-tags-match-list-sublevels
  12948. (org-end-of-subtree t)
  12949. (backward-char 1))))
  12950. ;; Get the correct position from where to continue
  12951. (if org-map-continue-from
  12952. (goto-char org-map-continue-from)
  12953. (and (= (point) lspos) (end-of-line 1)))))
  12954. (when (and (eq action 'sparse-tree)
  12955. (not org-sparse-tree-open-archived-trees))
  12956. (org-hide-archived-subtrees (point-min) (point-max)))
  12957. (nreverse rtn)))
  12958. (defun org-remove-uninherited-tags (tags)
  12959. "Remove all tags that are not inherited from the list TAGS."
  12960. (cond
  12961. ((eq org-use-tag-inheritance t)
  12962. (if org-tags-exclude-from-inheritance
  12963. (org-delete-all org-tags-exclude-from-inheritance tags)
  12964. tags))
  12965. ((not org-use-tag-inheritance) nil)
  12966. ((stringp org-use-tag-inheritance)
  12967. (delq nil (mapcar
  12968. (lambda (x)
  12969. (if (and (string-match org-use-tag-inheritance x)
  12970. (not (member x org-tags-exclude-from-inheritance)))
  12971. x nil))
  12972. tags)))
  12973. ((listp org-use-tag-inheritance)
  12974. (delq nil (mapcar
  12975. (lambda (x)
  12976. (if (member x org-use-tag-inheritance) x nil))
  12977. tags)))))
  12978. (defun org-match-sparse-tree (&optional todo-only match)
  12979. "Create a sparse tree according to tags string MATCH.
  12980. MATCH is a string with match syntax. It can contain a selection
  12981. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12982. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12983. those. See the manual for details.
  12984. If optional argument TODO-ONLY is non-nil, only select lines that
  12985. are also TODO tasks."
  12986. (interactive "P")
  12987. (org-agenda-prepare-buffers (list (current-buffer)))
  12988. (let ((org--matcher-tags-todo-only todo-only))
  12989. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12990. org--matcher-tags-todo-only)))
  12991. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12992. (defvar org-cached-props nil)
  12993. (defun org-cached-entry-get (pom property)
  12994. (if (or (eq t org-use-property-inheritance)
  12995. (and (stringp org-use-property-inheritance)
  12996. (let ((case-fold-search t))
  12997. (string-match-p org-use-property-inheritance property)))
  12998. (and (listp org-use-property-inheritance)
  12999. (member-ignore-case property org-use-property-inheritance)))
  13000. ;; Caching is not possible, check it directly.
  13001. (org-entry-get pom property 'inherit)
  13002. ;; Get all properties, so we can do complicated checks easily.
  13003. (cdr (assoc-string property
  13004. (or org-cached-props
  13005. (setq org-cached-props (org-entry-properties pom)))
  13006. t))))
  13007. (defun org-global-tags-completion-table (&optional files)
  13008. "Return the list of all tags in all agenda buffer/files.
  13009. Optional FILES argument is a list of files which can be used
  13010. instead of the agenda files."
  13011. (save-excursion
  13012. (org-uniquify
  13013. (delq nil
  13014. (apply #'append
  13015. (mapcar
  13016. (lambda (file)
  13017. (set-buffer (find-file-noselect file))
  13018. (mapcar (lambda (x)
  13019. (and (stringp (car-safe x))
  13020. (list (car-safe x))))
  13021. (or org-current-tag-alist (org-get-buffer-tags))))
  13022. (if (car-safe files) files
  13023. (org-agenda-files))))))))
  13024. (defun org-make-tags-matcher (match)
  13025. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13026. Returns a cons of the selection string MATCH and a function
  13027. implementing the matcher.
  13028. The matcher is to be called at an Org entry, with point on the
  13029. headline, and returns non-nil if the entry matches the selection
  13030. string MATCH. It must be called with three arguments: the TODO
  13031. keyword at the entry (or nil if none), the list of all tags at
  13032. the entry including inherited ones and the reduced level of the
  13033. headline. Additionally, the category of the entry, if any, must
  13034. be specified as the text property `org-category' on the headline.
  13035. This function sets the variable `org--matcher-tags-todo-only' to
  13036. a non-nil value if the matcher restricts matching to TODO
  13037. entries, otherwise it is not touched.
  13038. See also `org-scan-tags'."
  13039. (unless match
  13040. ;; Get a new match request, with completion against the global
  13041. ;; tags table and the local tags in current buffer.
  13042. (let ((org-last-tags-completion-table
  13043. (org-uniquify
  13044. (delq nil (append (org-get-buffer-tags)
  13045. (org-global-tags-completion-table))))))
  13046. (setq match
  13047. (completing-read
  13048. "Match: "
  13049. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13050. (let ((match0 match)
  13051. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13052. (start 0)
  13053. tagsmatch todomatch tagsmatcher todomatcher)
  13054. ;; Expand group tags.
  13055. (setq match (org-tags-expand match))
  13056. ;; Check if there is a TODO part of this match, which would be the
  13057. ;; part after a "/". To make sure that this slash is not part of
  13058. ;; a property value to be matched against, we also check that
  13059. ;; there is no / after that slash. First, find the last slash.
  13060. (let ((s 0))
  13061. (while (string-match "/+" match s)
  13062. (setq start (match-beginning 0))
  13063. (setq s (match-end 0))))
  13064. (if (and (string-match "/+" match start)
  13065. (not (string-match-p "\"" match start)))
  13066. ;; Match contains also a TODO-matching request.
  13067. (progn
  13068. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13069. (setq todomatch (substring match (match-end 0)))
  13070. (when (string-prefix-p "!" todomatch)
  13071. (setq org--matcher-tags-todo-only t)
  13072. (setq todomatch (substring todomatch 1)))
  13073. (when (string-match "\\`\\s-*\\'" todomatch)
  13074. (setq todomatch nil)))
  13075. ;; Only matching tags.
  13076. (setq tagsmatch match)
  13077. (setq todomatch nil))
  13078. ;; Make the tags matcher.
  13079. (when (org-string-nw-p tagsmatch)
  13080. (let ((orlist nil)
  13081. (orterms (org-split-string tagsmatch "|"))
  13082. term)
  13083. (while (setq term (pop orterms))
  13084. (while (and (equal (substring term -1) "\\") orterms)
  13085. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13086. (while (string-match re term)
  13087. (let* ((rest (substring term (match-end 0)))
  13088. (minus (and (match-end 1)
  13089. (equal (match-string 1 term) "-")))
  13090. (tag (save-match-data
  13091. (replace-regexp-in-string
  13092. "\\\\-" "-" (match-string 2 term))))
  13093. (regexp (eq (string-to-char tag) ?{))
  13094. (levelp (match-end 4))
  13095. (propp (match-end 5))
  13096. (mm
  13097. (cond
  13098. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13099. (levelp
  13100. `(,(org-op-to-function (match-string 3 term))
  13101. level
  13102. ,(string-to-number (match-string 4 term))))
  13103. (propp
  13104. (let* ((gv (pcase (upcase (match-string 5 term))
  13105. ("CATEGORY"
  13106. '(get-text-property (point) 'org-category))
  13107. ("TODO" 'todo)
  13108. (p `(org-cached-entry-get nil ,p))))
  13109. (pv (match-string 7 term))
  13110. (regexp (eq (string-to-char pv) ?{))
  13111. (strp (eq (string-to-char pv) ?\"))
  13112. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13113. (po (org-op-to-function (match-string 6 term)
  13114. (if timep 'time strp))))
  13115. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13116. (when timep (setq pv (org-matcher-time pv)))
  13117. (cond ((and regexp (eq po 'org<>))
  13118. `(not (string-match ,pv (or ,gv ""))))
  13119. (regexp `(string-match ,pv (or ,gv "")))
  13120. (strp `(,po (or ,gv "") ,pv))
  13121. (t
  13122. `(,po
  13123. (string-to-number (or ,gv ""))
  13124. ,(string-to-number pv))))))
  13125. (t `(member ,tag tags-list)))))
  13126. (push (if minus `(not ,mm) mm) tagsmatcher)
  13127. (setq term rest)))
  13128. (push `(and ,@tagsmatcher) orlist)
  13129. (setq tagsmatcher nil))
  13130. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13131. ;; Make the TODO matcher.
  13132. (when (org-string-nw-p todomatch)
  13133. (let ((orlist nil))
  13134. (dolist (term (org-split-string todomatch "|"))
  13135. (while (string-match re term)
  13136. (let* ((minus (and (match-end 1)
  13137. (equal (match-string 1 term) "-")))
  13138. (kwd (match-string 2 term))
  13139. (regexp (eq (string-to-char kwd) ?{))
  13140. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13141. `(equal todo ,kwd))))
  13142. (push (if minus `(not ,mm) mm) todomatcher))
  13143. (setq term (substring term (match-end 0))))
  13144. (push (if (> (length todomatcher) 1)
  13145. (cons 'and todomatcher)
  13146. (car todomatcher))
  13147. orlist)
  13148. (setq todomatcher nil))
  13149. (setq todomatcher (cons 'or orlist))))
  13150. ;; Return the string and function of the matcher. If no
  13151. ;; tags-specific or todo-specific matcher exists, match
  13152. ;; everything.
  13153. (let ((matcher (if (and tagsmatcher todomatcher)
  13154. `(and ,tagsmatcher ,todomatcher)
  13155. (or tagsmatcher todomatcher t))))
  13156. (when org--matcher-tags-todo-only
  13157. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13158. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13159. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13160. "Expand group tags in MATCH.
  13161. This replaces every group tag in MATCH with a regexp tag search.
  13162. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13163. will be replaced like this:
  13164. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13165. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13166. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13167. Replacing by a regexp preserves the structure of the match.
  13168. E.g., this expansion
  13169. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13170. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13171. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13172. A group tag in MATCH can contain regular expressions of its own.
  13173. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13174. will be replaced like this:
  13175. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13176. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13177. assumed to be a single group tag, and the function will return
  13178. the list of tags in this group.
  13179. When DOWNCASE is non-nil, expand downcased TAGS."
  13180. (if org-group-tags
  13181. (let* ((case-fold-search t)
  13182. (stable org-mode-syntax-table)
  13183. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13184. (taggroups (if downcased
  13185. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13186. taggroups)
  13187. taggroups))
  13188. (taggroups-keys (mapcar #'car taggroups))
  13189. (return-match (if downcased (downcase match) match))
  13190. (count 0)
  13191. (work-already-expanded tags-already-expanded)
  13192. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13193. ;; @ and _ are allowed as word-components in tags.
  13194. (modify-syntax-entry ?@ "w" stable)
  13195. (modify-syntax-entry ?_ "w" stable)
  13196. ;; Temporarily replace regexp-expressions in the match-expression.
  13197. (while (string-match "{.+?}" return-match)
  13198. (cl-incf count)
  13199. (push (match-string 0 return-match) regexps-in-match)
  13200. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13201. (while (and taggroups-keys
  13202. (with-syntax-table stable
  13203. (string-match
  13204. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13205. (regexp-opt taggroups-keys) "\\>\\)")
  13206. return-match)))
  13207. (let* ((dir (match-string 1 return-match))
  13208. (tag (match-string 2 return-match))
  13209. (tag (if downcased (downcase tag) tag)))
  13210. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13211. (member tag work-already-expanded))
  13212. (setq tags-in-group (assoc tag taggroups))
  13213. (push tag work-already-expanded)
  13214. ;; Recursively expand each tag in the group, if the tag hasn't
  13215. ;; already been expanded. Restore the match-data after all recursive calls.
  13216. (save-match-data
  13217. (let (tags-expanded)
  13218. (dolist (x (cdr tags-in-group))
  13219. (if (and (member x taggroups-keys)
  13220. (not (member x work-already-expanded)))
  13221. (setq tags-expanded
  13222. (delete-dups
  13223. (append
  13224. (org-tags-expand x t downcased
  13225. work-already-expanded)
  13226. tags-expanded)))
  13227. (setq tags-expanded
  13228. (append (list x) tags-expanded)))
  13229. (setq work-already-expanded
  13230. (delete-dups
  13231. (append tags-expanded
  13232. work-already-expanded))))
  13233. (setq tags-in-group
  13234. (delete-dups (cons (car tags-in-group)
  13235. tags-expanded)))))
  13236. ;; Filter tag-regexps from tags.
  13237. (setq regexp-in-group-escaped
  13238. (delq nil (mapcar (lambda (x)
  13239. (if (stringp x)
  13240. (and (equal "{" (substring x 0 1))
  13241. (equal "}" (substring x -1))
  13242. x)
  13243. x))
  13244. tags-in-group))
  13245. regexp-in-group
  13246. (mapcar (lambda (x)
  13247. (substring x 1 -1))
  13248. regexp-in-group-escaped)
  13249. tags-in-group
  13250. (delq nil (mapcar (lambda (x)
  13251. (if (stringp x)
  13252. (and (not (equal "{" (substring x 0 1)))
  13253. (not (equal "}" (substring x -1)))
  13254. x)
  13255. x))
  13256. tags-in-group)))
  13257. ;; If single-as-list, do no more in the while-loop.
  13258. (if (not single-as-list)
  13259. (progn
  13260. (when regexp-in-group
  13261. (setq regexp-in-group
  13262. (concat "\\|"
  13263. (mapconcat 'identity regexp-in-group
  13264. "\\|"))))
  13265. (setq tags-in-group
  13266. (concat dir
  13267. "{\\<"
  13268. (regexp-opt tags-in-group)
  13269. "\\>"
  13270. regexp-in-group
  13271. "}"))
  13272. (when (stringp tags-in-group)
  13273. (org-add-props tags-in-group '(grouptag t)))
  13274. (setq return-match
  13275. (replace-match tags-in-group t t return-match)))
  13276. (setq tags-in-group
  13277. (append regexp-in-group-escaped tags-in-group))))
  13278. (setq taggroups-keys (delete tag taggroups-keys))))
  13279. ;; Add the regular expressions back into the match-expression again.
  13280. (while regexps-in-match
  13281. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13282. (pop regexps-in-match)
  13283. return-match t t))
  13284. (cl-decf count))
  13285. (if single-as-list
  13286. (if tags-in-group tags-in-group (list return-match))
  13287. return-match))
  13288. (if single-as-list
  13289. (list (if downcased (downcase match) match))
  13290. match)))
  13291. (defun org-op-to-function (op &optional stringp)
  13292. "Turn an operator into the appropriate function."
  13293. (setq op
  13294. (cond
  13295. ((equal op "<" ) '(< string< org-time<))
  13296. ((equal op ">" ) '(> org-string> org-time>))
  13297. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13298. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13299. ((member op '("=" "==")) '(= string= org-time=))
  13300. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13301. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13302. (defun org<> (a b) (not (= a b)))
  13303. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13304. (defun org-string>= (a b) (not (string< a b)))
  13305. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13306. (defun org-string<> (a b) (not (string= a b)))
  13307. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13308. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13309. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13310. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13311. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13312. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13313. (defun org-2ft (s)
  13314. "Convert S to a floating point time.
  13315. If S is already a number, just return it. If it is a string, parse
  13316. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13317. (cond
  13318. ((numberp s) s)
  13319. ((stringp s)
  13320. (condition-case nil
  13321. (float-time (apply 'encode-time (org-parse-time-string s)))
  13322. (error 0.)))
  13323. (t 0.)))
  13324. (defun org-time-today ()
  13325. "Time in seconds today at 0:00.
  13326. Returns the float number of seconds since the beginning of the
  13327. epoch to the beginning of today (00:00)."
  13328. (float-time (apply 'encode-time
  13329. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13330. (defun org-matcher-time (s)
  13331. "Interpret a time comparison value."
  13332. (save-match-data
  13333. (cond
  13334. ((string= s "<now>") (float-time))
  13335. ((string= s "<today>") (org-time-today))
  13336. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13337. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13338. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13339. (+ (org-time-today)
  13340. (* (string-to-number (match-string 1 s))
  13341. (cdr (assoc (match-string 2 s)
  13342. '(("d" . 86400.0) ("w" . 604800.0)
  13343. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13344. (t (org-2ft s)))))
  13345. (defun org-match-any-p (re list)
  13346. "Does re match any element of list?"
  13347. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13348. (delq nil list))
  13349. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13350. (defvar org-tags-overlay (make-overlay 1 1))
  13351. (delete-overlay org-tags-overlay)
  13352. (defun org-get-local-tags-at (&optional pos)
  13353. "Get a list of tags defined in the current headline."
  13354. (org-get-tags-at pos 'local))
  13355. (defun org-get-local-tags ()
  13356. "Get a list of tags defined in the current headline."
  13357. (org-get-tags-at nil 'local))
  13358. (defun org-get-tags-at (&optional pos local)
  13359. "Get a list of all headline tags applicable at POS.
  13360. POS defaults to point. If tags are inherited, the list contains
  13361. the targets in the same sequence as the headlines appear, i.e.
  13362. the tags of the current headline come last.
  13363. When LOCAL is non-nil, only return tags from the current headline,
  13364. ignore inherited ones."
  13365. (interactive)
  13366. (if (and org-trust-scanner-tags
  13367. (or (not pos) (equal pos (point)))
  13368. (not local))
  13369. org-scanner-tags
  13370. (let (tags ltags lastpos parent)
  13371. (save-excursion
  13372. (save-restriction
  13373. (widen)
  13374. (goto-char (or pos (point)))
  13375. (save-match-data
  13376. (catch 'done
  13377. (condition-case nil
  13378. (progn
  13379. (org-back-to-heading t)
  13380. (while (not (equal lastpos (point)))
  13381. (setq lastpos (point))
  13382. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13383. (setq ltags (org-split-string
  13384. (match-string-no-properties 1) ":"))
  13385. (when parent
  13386. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13387. (setq tags (append
  13388. (if parent
  13389. (org-remove-uninherited-tags ltags)
  13390. ltags)
  13391. tags)))
  13392. (or org-use-tag-inheritance (throw 'done t))
  13393. (when local (throw 'done t))
  13394. (or (org-up-heading-safe) (error nil))
  13395. (setq parent t)))
  13396. (error nil)))))
  13397. (if local
  13398. tags
  13399. (reverse (delete-dups
  13400. (reverse (append
  13401. (org-remove-uninherited-tags
  13402. org-file-tags)
  13403. tags)))))))))
  13404. (defun org-add-prop-inherited (s)
  13405. (add-text-properties 0 (length s) '(inherited t) s)
  13406. s)
  13407. (defun org-toggle-tag (tag &optional onoff)
  13408. "Toggle the tag TAG for the current line.
  13409. If ONOFF is `on' or `off', don't toggle but set to this state."
  13410. (let (res current)
  13411. (save-excursion
  13412. (org-back-to-heading t)
  13413. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13414. (point-at-eol) t)
  13415. (progn
  13416. (setq current (match-string 1))
  13417. (replace-match ""))
  13418. (setq current ""))
  13419. (setq current (nreverse (org-split-string current ":")))
  13420. (cond
  13421. ((eq onoff 'on)
  13422. (setq res t)
  13423. (or (member tag current) (push tag current)))
  13424. ((eq onoff 'off)
  13425. (or (not (member tag current)) (setq current (delete tag current))))
  13426. (t (if (member tag current)
  13427. (setq current (delete tag current))
  13428. (setq res t)
  13429. (push tag current))))
  13430. (end-of-line 1)
  13431. (if current
  13432. (progn
  13433. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13434. (org-set-tags nil t))
  13435. (delete-horizontal-space))
  13436. (run-hooks 'org-after-tags-change-hook))
  13437. res))
  13438. (defun org--align-tags-here (to-col)
  13439. "Align tags on the current headline to TO-COL.
  13440. Assume point is on a headline."
  13441. (let ((pos (point)))
  13442. (beginning-of-line)
  13443. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13444. (>= pos (match-beginning 2)))
  13445. ;; No tags or point within tags: do not align.
  13446. (goto-char pos)
  13447. (goto-char (match-beginning 1))
  13448. (let ((shift (max (- (if (>= to-col 0) to-col
  13449. (- (abs to-col) (string-width (match-string 2))))
  13450. (current-column))
  13451. 1)))
  13452. (replace-match (make-string shift ?\s) nil nil nil 1)
  13453. ;; Preserve initial position, if possible. In any case, stop
  13454. ;; before tags.
  13455. (when (< pos (point)) (goto-char pos))))))
  13456. (defun org-set-tags-command (&optional arg just-align)
  13457. "Call the set-tags command for the current entry."
  13458. (interactive "P")
  13459. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13460. (org-set-tags arg just-align)
  13461. (save-excursion
  13462. (unless (and (org-region-active-p)
  13463. org-loop-over-headlines-in-active-region)
  13464. (org-back-to-heading t))
  13465. (org-set-tags arg just-align))))
  13466. (defun org-set-tags-to (data)
  13467. "Set the tags of the current entry to DATA, replacing the current tags.
  13468. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13469. If DATA is nil or the empty string, any tags will be removed."
  13470. (interactive "sTags: ")
  13471. (setq data
  13472. (cond
  13473. ((eq data nil) "")
  13474. ((equal data "") "")
  13475. ((stringp data)
  13476. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13477. ":"))
  13478. ((listp data)
  13479. (concat ":" (mapconcat 'identity data ":") ":"))))
  13480. (when data
  13481. (save-excursion
  13482. (org-back-to-heading t)
  13483. (when (let ((case-fold-search nil))
  13484. (looking-at org-complex-heading-regexp))
  13485. (if (match-end 5)
  13486. (progn
  13487. (goto-char (match-beginning 5))
  13488. (insert data)
  13489. (delete-region (point) (point-at-eol))
  13490. (org-set-tags nil 'align))
  13491. (goto-char (point-at-eol))
  13492. (insert " " data)
  13493. (org-set-tags nil 'align)))
  13494. (beginning-of-line 1)
  13495. (when (looking-at ".*?\\([ \t]+\\)$")
  13496. (delete-region (match-beginning 1) (match-end 1))))))
  13497. (defun org-align-all-tags ()
  13498. "Align the tags in all headings."
  13499. (interactive)
  13500. (save-excursion
  13501. (or (ignore-errors (org-back-to-heading t))
  13502. (outline-next-heading))
  13503. (if (org-at-heading-p)
  13504. (org-set-tags t)
  13505. (message "No headings"))))
  13506. (defvar org-indent-indentation-per-level)
  13507. (defun org-set-tags (&optional arg just-align)
  13508. "Set the tags for the current headline.
  13509. With prefix ARG, realign all tags in headings in the current buffer.
  13510. When JUST-ALIGN is non-nil, only align tags."
  13511. (interactive "P")
  13512. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13513. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13514. 'region-start-level
  13515. 'region))
  13516. org-loop-over-headlines-in-active-region)
  13517. (org-map-entries
  13518. ;; We don't use ARG and JUST-ALIGN here because these args
  13519. ;; are not useful when looping over headlines.
  13520. #'org-set-tags
  13521. org-loop-over-headlines-in-active-region
  13522. cl
  13523. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13524. (let ((org-setting-tags t))
  13525. (if arg
  13526. (save-excursion
  13527. (goto-char (point-min))
  13528. (while (re-search-forward org-outline-regexp-bol nil t)
  13529. (org-set-tags nil t)
  13530. (end-of-line))
  13531. (message "All tags realigned to column %d" org-tags-column))
  13532. (let* ((current (org-get-tags-string))
  13533. (tags
  13534. (if just-align current
  13535. ;; Get a new set of tags from the user.
  13536. (save-excursion
  13537. (let* ((seen)
  13538. (table
  13539. (setq
  13540. org-last-tags-completion-table
  13541. ;; Uniquify tags in alists, yet preserve
  13542. ;; structure (i.e., keywords).
  13543. (delq nil
  13544. (mapcar
  13545. (lambda (pair)
  13546. (let ((head (car pair)))
  13547. (cond ((symbolp head) pair)
  13548. ((member head seen) nil)
  13549. (t (push head seen)
  13550. pair))))
  13551. (append
  13552. (or org-current-tag-alist
  13553. (org-get-buffer-tags))
  13554. (and
  13555. org-complete-tags-always-offer-all-agenda-tags
  13556. (org-global-tags-completion-table
  13557. (org-agenda-files))))))))
  13558. (current-tags (org-split-string current ":"))
  13559. (inherited-tags
  13560. (nreverse (nthcdr (length current-tags)
  13561. (nreverse (org-get-tags-at))))))
  13562. (replace-regexp-in-string
  13563. "\\([-+&]+\\|,\\)"
  13564. ":"
  13565. (if (or (eq t org-use-fast-tag-selection)
  13566. (and org-use-fast-tag-selection
  13567. (delq nil (mapcar #'cdr table))))
  13568. (org-fast-tag-selection
  13569. current-tags inherited-tags table
  13570. (and org-fast-tag-selection-include-todo
  13571. org-todo-key-alist))
  13572. (let ((org-add-colon-after-tag-completion
  13573. (< 1 (length table))))
  13574. (org-trim
  13575. (completing-read
  13576. "Tags: "
  13577. #'org-tags-completion-function
  13578. nil nil current 'org-tags-history))))))))))
  13579. (when org-tags-sort-function
  13580. (setq tags
  13581. (mapconcat
  13582. #'identity
  13583. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13584. org-tags-sort-function)
  13585. ":")))
  13586. (if (not (org-string-nw-p tags)) (setq tags "")
  13587. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13588. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13589. ;; Insert new tags at the correct column.
  13590. (unless (equal current tags)
  13591. (save-excursion
  13592. (beginning-of-line)
  13593. (let ((case-fold-search nil))
  13594. (looking-at org-complex-heading-regexp))
  13595. ;; Remove current tags, if any.
  13596. (when (match-end 5) (replace-match "" nil nil nil 5))
  13597. ;; Insert new tags, if any. Otherwise, remove trailing
  13598. ;; white spaces.
  13599. (end-of-line)
  13600. (if (not (equal tags ""))
  13601. ;; When text is being inserted on an invisible
  13602. ;; region boundary, it can be inadvertently sucked
  13603. ;; into invisibility.
  13604. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13605. (skip-chars-backward " \t")
  13606. (delete-region (point) (line-end-position)))))
  13607. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13608. ;; is on.
  13609. (unless (equal tags "")
  13610. (let* ((level (save-excursion
  13611. (beginning-of-line)
  13612. (skip-chars-forward "\\*")))
  13613. (offset (if (bound-and-true-p org-indent-mode)
  13614. (* (1- org-indent-indentation-per-level)
  13615. (1- level))
  13616. 0))
  13617. (tags-column
  13618. (+ org-tags-column
  13619. (if (> org-tags-column 0) (- offset) offset))))
  13620. (org--align-tags-here tags-column))))
  13621. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13622. (defun org-change-tag-in-region (beg end tag off)
  13623. "Add or remove TAG for each entry in the region.
  13624. This works in the agenda, and also in an Org buffer."
  13625. (interactive
  13626. (list (region-beginning) (region-end)
  13627. (let ((org-last-tags-completion-table
  13628. (if (derived-mode-p 'org-mode)
  13629. (org-uniquify
  13630. (delq nil (append (org-get-buffer-tags)
  13631. (org-global-tags-completion-table))))
  13632. (org-global-tags-completion-table))))
  13633. (completing-read
  13634. "Tag: " 'org-tags-completion-function nil nil nil
  13635. 'org-tags-history))
  13636. (progn
  13637. (message "[s]et or [r]emove? ")
  13638. (equal (read-char-exclusive) ?r))))
  13639. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13640. (let ((agendap (equal major-mode 'org-agenda-mode))
  13641. l1 l2 m buf pos newhead (cnt 0))
  13642. (goto-char end)
  13643. (setq l2 (1- (org-current-line)))
  13644. (goto-char beg)
  13645. (setq l1 (org-current-line))
  13646. (cl-loop for l from l1 to l2 do
  13647. (org-goto-line l)
  13648. (setq m (get-text-property (point) 'org-hd-marker))
  13649. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13650. (and agendap m))
  13651. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13652. pos (if agendap m (point)))
  13653. (with-current-buffer buf
  13654. (save-excursion
  13655. (save-restriction
  13656. (goto-char pos)
  13657. (setq cnt (1+ cnt))
  13658. (org-toggle-tag tag (if off 'off 'on))
  13659. (setq newhead (org-get-heading)))))
  13660. (and agendap (org-agenda-change-all-lines newhead m))))
  13661. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13662. (defun org-tags-completion-function (string _predicate &optional flag)
  13663. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13664. (confirm (lambda (x) (stringp (car x)))))
  13665. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13666. (setq s1 (match-string 1 string)
  13667. s2 (match-string 2 string))
  13668. (setq s1 "" s2 string))
  13669. (cond
  13670. ((eq flag nil)
  13671. ;; try completion
  13672. (setq rtn (try-completion s2 ctable confirm))
  13673. (when (stringp rtn)
  13674. (setq rtn
  13675. (concat s1 s2 (substring rtn (length s2))
  13676. (if (and org-add-colon-after-tag-completion
  13677. (assoc rtn ctable))
  13678. ":" ""))))
  13679. rtn)
  13680. ((eq flag t)
  13681. ;; all-completions
  13682. (all-completions s2 ctable confirm))
  13683. ((eq flag 'lambda)
  13684. ;; exact match?
  13685. (assoc s2 ctable)))))
  13686. (defun org-fast-tag-insert (kwd tags face &optional end)
  13687. "Insert KDW, and the TAGS, the latter with face FACE.
  13688. Also insert END."
  13689. (insert (format "%-12s" (concat kwd ":"))
  13690. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13691. (or end "")))
  13692. (defun org-fast-tag-show-exit (flag)
  13693. (save-excursion
  13694. (org-goto-line 3)
  13695. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13696. (replace-match ""))
  13697. (when flag
  13698. (end-of-line 1)
  13699. (org-move-to-column (- (window-width) 19) t)
  13700. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13701. (defun org-set-current-tags-overlay (current prefix)
  13702. "Add an overlay to CURRENT tag with PREFIX."
  13703. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13704. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13705. (org-overlay-display org-tags-overlay (concat prefix s))))
  13706. (defvar org-last-tag-selection-key nil)
  13707. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13708. "Fast tag selection with single keys.
  13709. CURRENT is the current list of tags in the headline, INHERITED is the
  13710. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13711. possibly with grouping information. TODO-TABLE is a similar table with
  13712. TODO keywords, should these have keys assigned to them.
  13713. If the keys are nil, a-z are automatically assigned.
  13714. Returns the new tags string, or nil to not change the current settings."
  13715. (let* ((fulltable (append table todo-table))
  13716. (maxlen (apply 'max (mapcar
  13717. (lambda (x)
  13718. (if (stringp (car x)) (string-width (car x)) 0))
  13719. fulltable)))
  13720. (buf (current-buffer))
  13721. (expert (eq org-fast-tag-selection-single-key 'expert))
  13722. (buffer-tags nil)
  13723. (fwidth (+ maxlen 3 1 3))
  13724. (ncol (/ (- (window-width) 4) fwidth))
  13725. (i-face 'org-done)
  13726. (c-face 'org-todo)
  13727. tg cnt e c char c1 c2 ntable tbl rtn
  13728. ov-start ov-end ov-prefix
  13729. (exit-after-next org-fast-tag-selection-single-key)
  13730. (done-keywords org-done-keywords)
  13731. groups ingroup intaggroup)
  13732. (save-excursion
  13733. (beginning-of-line 1)
  13734. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13735. (setq ov-start (match-beginning 1)
  13736. ov-end (match-end 1)
  13737. ov-prefix "")
  13738. (setq ov-start (1- (point-at-eol))
  13739. ov-end (1+ ov-start))
  13740. (skip-chars-forward "^\n\r")
  13741. (setq ov-prefix
  13742. (concat
  13743. (buffer-substring (1- (point)) (point))
  13744. (if (> (current-column) org-tags-column)
  13745. " "
  13746. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13747. (move-overlay org-tags-overlay ov-start ov-end)
  13748. (save-window-excursion
  13749. (if expert
  13750. (set-buffer (get-buffer-create " *Org tags*"))
  13751. (delete-other-windows)
  13752. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13753. (org-switch-to-buffer-other-window " *Org tags*"))
  13754. (erase-buffer)
  13755. (setq-local org-done-keywords done-keywords)
  13756. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13757. (org-fast-tag-insert "Current" current c-face "\n\n")
  13758. (org-fast-tag-show-exit exit-after-next)
  13759. (org-set-current-tags-overlay current ov-prefix)
  13760. (setq tbl fulltable char ?a cnt 0)
  13761. (while (setq e (pop tbl))
  13762. (cond
  13763. ((eq (car e) :startgroup)
  13764. (push '() groups) (setq ingroup t)
  13765. (unless (zerop cnt)
  13766. (setq cnt 0)
  13767. (insert "\n"))
  13768. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13769. ((eq (car e) :endgroup)
  13770. (setq ingroup nil cnt 0)
  13771. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13772. ((eq (car e) :startgrouptag)
  13773. (setq intaggroup t)
  13774. (unless (zerop cnt)
  13775. (setq cnt 0)
  13776. (insert "\n"))
  13777. (insert "[ "))
  13778. ((eq (car e) :endgrouptag)
  13779. (setq intaggroup nil cnt 0)
  13780. (insert "]\n"))
  13781. ((equal e '(:newline))
  13782. (unless (zerop cnt)
  13783. (setq cnt 0)
  13784. (insert "\n")
  13785. (setq e (car tbl))
  13786. (while (equal (car tbl) '(:newline))
  13787. (insert "\n")
  13788. (setq tbl (cdr tbl)))))
  13789. ((equal e '(:grouptags)) (insert " : "))
  13790. (t
  13791. (setq tg (copy-sequence (car e)) c2 nil)
  13792. (if (cdr e)
  13793. (setq c (cdr e))
  13794. ;; automatically assign a character.
  13795. (setq c1 (string-to-char
  13796. (downcase (substring
  13797. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13798. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13799. (while (or (rassoc char ntable) (rassoc char table))
  13800. (setq char (1+ char)))
  13801. (setq c2 c1))
  13802. (setq c (or c2 char)))
  13803. (when ingroup (push tg (car groups)))
  13804. (setq tg (org-add-props tg nil 'face
  13805. (cond
  13806. ((not (assoc tg table))
  13807. (org-get-todo-face tg))
  13808. ((member tg current) c-face)
  13809. ((member tg inherited) i-face))))
  13810. (when (equal (caar tbl) :grouptags)
  13811. (org-add-props tg nil 'face 'org-tag-group))
  13812. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13813. (insert "[" c "] " tg (make-string
  13814. (- fwidth 4 (length tg)) ?\ ))
  13815. (push (cons tg c) ntable)
  13816. (when (= (cl-incf cnt) ncol)
  13817. (insert "\n")
  13818. (when (or ingroup intaggroup) (insert " "))
  13819. (setq cnt 0)))))
  13820. (setq ntable (nreverse ntable))
  13821. (insert "\n")
  13822. (goto-char (point-min))
  13823. (unless expert (org-fit-window-to-buffer))
  13824. (setq rtn
  13825. (catch 'exit
  13826. (while t
  13827. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13828. (if (not groups) "no " "")
  13829. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13830. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13831. (setq org-last-tag-selection-key c)
  13832. (cond
  13833. ((= c ?\r) (throw 'exit t))
  13834. ((= c ?!)
  13835. (setq groups (not groups))
  13836. (goto-char (point-min))
  13837. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13838. ((= c ?\C-c)
  13839. (if (not expert)
  13840. (org-fast-tag-show-exit
  13841. (setq exit-after-next (not exit-after-next)))
  13842. (setq expert nil)
  13843. (delete-other-windows)
  13844. (set-window-buffer (split-window-vertically) " *Org tags*")
  13845. (org-switch-to-buffer-other-window " *Org tags*")
  13846. (org-fit-window-to-buffer)))
  13847. ((or (= c ?\C-g)
  13848. (and (= c ?q) (not (rassoc c ntable))))
  13849. (delete-overlay org-tags-overlay)
  13850. (setq quit-flag t))
  13851. ((= c ?\ )
  13852. (setq current nil)
  13853. (when exit-after-next (setq exit-after-next 'now)))
  13854. ((= c ?\t)
  13855. (condition-case nil
  13856. (setq tg (completing-read
  13857. "Tag: "
  13858. (or buffer-tags
  13859. (with-current-buffer buf
  13860. (setq buffer-tags
  13861. (org-get-buffer-tags))))))
  13862. (quit (setq tg "")))
  13863. (when (string-match "\\S-" tg)
  13864. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13865. (if (member tg current)
  13866. (setq current (delete tg current))
  13867. (push tg current)))
  13868. (when exit-after-next (setq exit-after-next 'now)))
  13869. ((setq e (rassoc c todo-table) tg (car e))
  13870. (with-current-buffer buf
  13871. (save-excursion (org-todo tg)))
  13872. (when exit-after-next (setq exit-after-next 'now)))
  13873. ((setq e (rassoc c ntable) tg (car e))
  13874. (if (member tg current)
  13875. (setq current (delete tg current))
  13876. (cl-loop for g in groups do
  13877. (when (member tg g)
  13878. (dolist (x g) (setq current (delete x current)))))
  13879. (push tg current))
  13880. (when exit-after-next (setq exit-after-next 'now))))
  13881. ;; Create a sorted list
  13882. (setq current
  13883. (sort current
  13884. (lambda (a b)
  13885. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13886. (when (eq exit-after-next 'now) (throw 'exit t))
  13887. (goto-char (point-min))
  13888. (beginning-of-line 2)
  13889. (delete-region (point) (point-at-eol))
  13890. (org-fast-tag-insert "Current" current c-face)
  13891. (org-set-current-tags-overlay current ov-prefix)
  13892. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13893. (setq tg (match-string 1))
  13894. (add-text-properties
  13895. (match-beginning 1) (match-end 1)
  13896. (list 'face
  13897. (cond
  13898. ((member tg current) c-face)
  13899. ((member tg inherited) i-face)
  13900. (t (get-text-property (match-beginning 1) 'face))))))
  13901. (goto-char (point-min)))))
  13902. (delete-overlay org-tags-overlay)
  13903. (if rtn
  13904. (mapconcat 'identity current ":")
  13905. nil))))
  13906. (defun org-get-tags-string ()
  13907. "Get the TAGS string in the current headline."
  13908. (unless (org-at-heading-p t)
  13909. (user-error "Not on a heading"))
  13910. (save-excursion
  13911. (beginning-of-line 1)
  13912. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13913. (match-string-no-properties 1)
  13914. "")))
  13915. (defun org-get-tags ()
  13916. "Get the list of tags specified in the current headline."
  13917. (org-split-string (org-get-tags-string) ":"))
  13918. (defun org-get-buffer-tags ()
  13919. "Get a table of all tags used in the buffer, for completion."
  13920. (org-with-wide-buffer
  13921. (goto-char (point-min))
  13922. (let ((tag-re (concat org-outline-regexp-bol
  13923. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13924. tags)
  13925. (while (re-search-forward tag-re nil t)
  13926. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13927. (push tag tags)))
  13928. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13929. ;;;; The mapping API
  13930. (defvar org-agenda-skip-comment-trees)
  13931. (defvar org-agenda-skip-function)
  13932. (defun org-map-entries (func &optional match scope &rest skip)
  13933. "Call FUNC at each headline selected by MATCH in SCOPE.
  13934. FUNC is a function or a lisp form. The function will be called without
  13935. arguments, with the cursor positioned at the beginning of the headline.
  13936. The return values of all calls to the function will be collected and
  13937. returned as a list.
  13938. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13939. does not need to preserve point. After evaluation, the cursor will be
  13940. moved to the end of the line (presumably of the headline of the
  13941. processed entry) and search continues from there. Under some
  13942. circumstances, this may not produce the wanted results. For example,
  13943. if you have removed (e.g. archived) the current (sub)tree it could
  13944. mean that the next entry will be skipped entirely. In such cases, you
  13945. can specify the position from where search should continue by making
  13946. FUNC set the variable `org-map-continue-from' to the desired buffer
  13947. position.
  13948. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13949. Only headlines that are matched by this query will be considered during
  13950. the iteration. When MATCH is nil or t, all headlines will be
  13951. visited by the iteration.
  13952. SCOPE determines the scope of this command. It can be any of:
  13953. nil The current buffer, respecting the restriction if any
  13954. tree The subtree started with the entry at point
  13955. region The entries within the active region, if any
  13956. region-start-level
  13957. The entries within the active region, but only those at
  13958. the same level than the first one.
  13959. file The current buffer, without restriction
  13960. file-with-archives
  13961. The current buffer, and any archives associated with it
  13962. agenda All agenda files
  13963. agenda-with-archives
  13964. All agenda files with any archive files associated with them
  13965. \(file1 file2 ...)
  13966. If this is a list, all files in the list will be scanned
  13967. The remaining args are treated as settings for the skipping facilities of
  13968. the scanner. The following items can be given here:
  13969. archive skip trees with the archive tag
  13970. comment skip trees with the COMMENT keyword
  13971. function or Emacs Lisp form:
  13972. will be used as value for `org-agenda-skip-function', so
  13973. whenever the function returns a position, FUNC will not be
  13974. called for that entry and search will continue from the
  13975. position returned
  13976. If your function needs to retrieve the tags including inherited tags
  13977. at the *current* entry, you can use the value of the variable
  13978. `org-scanner-tags' which will be much faster than getting the value
  13979. with `org-get-tags-at'. If your function gets properties with
  13980. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13981. to t around the call to `org-entry-properties' to get the same speedup.
  13982. Note that if your function moves around to retrieve tags and properties at
  13983. a *different* entry, you cannot use these techniques."
  13984. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13985. (not (org-region-active-p)))
  13986. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13987. (org-agenda-skip-archived-trees (memq 'archive skip))
  13988. (org-agenda-skip-comment-trees (memq 'comment skip))
  13989. (org-agenda-skip-function
  13990. (car (org-delete-all '(comment archive) skip)))
  13991. (org-tags-match-list-sublevels t)
  13992. (start-level (eq scope 'region-start-level))
  13993. matcher res
  13994. org-todo-keywords-for-agenda
  13995. org-done-keywords-for-agenda
  13996. org-todo-keyword-alist-for-agenda
  13997. org-tag-alist-for-agenda
  13998. org--matcher-tags-todo-only)
  13999. (cond
  14000. ((eq match t) (setq matcher t))
  14001. ((eq match nil) (setq matcher t))
  14002. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14003. (save-excursion
  14004. (save-restriction
  14005. (cond ((eq scope 'tree)
  14006. (org-back-to-heading t)
  14007. (org-narrow-to-subtree)
  14008. (setq scope nil))
  14009. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14010. (org-region-active-p))
  14011. ;; If needed, set start-level to a string like "2"
  14012. (when start-level
  14013. (save-excursion
  14014. (goto-char (region-beginning))
  14015. (unless (org-at-heading-p) (outline-next-heading))
  14016. (setq start-level (org-current-level))))
  14017. (narrow-to-region (region-beginning)
  14018. (save-excursion
  14019. (goto-char (region-end))
  14020. (unless (and (bolp) (org-at-heading-p))
  14021. (outline-next-heading))
  14022. (point)))
  14023. (setq scope nil)))
  14024. (if (not scope)
  14025. (progn
  14026. (org-agenda-prepare-buffers
  14027. (and buffer-file-name (list buffer-file-name)))
  14028. (setq res
  14029. (org-scan-tags
  14030. func matcher org--matcher-tags-todo-only start-level)))
  14031. ;; Get the right scope
  14032. (cond
  14033. ((and scope (listp scope) (symbolp (car scope)))
  14034. (setq scope (eval scope)))
  14035. ((eq scope 'agenda)
  14036. (setq scope (org-agenda-files t)))
  14037. ((eq scope 'agenda-with-archives)
  14038. (setq scope (org-agenda-files t))
  14039. (setq scope (org-add-archive-files scope)))
  14040. ((eq scope 'file)
  14041. (setq scope (and buffer-file-name (list buffer-file-name))))
  14042. ((eq scope 'file-with-archives)
  14043. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14044. (org-agenda-prepare-buffers scope)
  14045. (dolist (file scope)
  14046. (with-current-buffer (org-find-base-buffer-visiting file)
  14047. (org-with-wide-buffer
  14048. (goto-char (point-min))
  14049. (setq res
  14050. (append
  14051. res
  14052. (org-scan-tags
  14053. func matcher org--matcher-tags-todo-only)))))))))
  14054. res)))
  14055. ;;; Properties API
  14056. (defconst org-special-properties
  14057. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14058. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14059. "The special properties valid in Org mode.
  14060. These are properties that are not defined in the property drawer,
  14061. but in some other way.")
  14062. (defconst org-default-properties
  14063. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14064. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14065. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14066. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14067. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14068. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14069. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14070. "Some properties that are used by Org mode for various purposes.
  14071. Being in this list makes sure that they are offered for completion.")
  14072. (defun org--valid-property-p (property)
  14073. "Non nil when string PROPERTY is a valid property name."
  14074. (not
  14075. (or (equal property "")
  14076. (string-match-p "\\s-" property))))
  14077. (defun org--update-property-plist (key val props)
  14078. "Associate KEY to VAL in alist PROPS.
  14079. Modifications are made by side-effect. Return new alist."
  14080. (let* ((appending (string= (substring key -1) "+"))
  14081. (key (if appending (substring key 0 -1) key))
  14082. (old (assoc-string key props t)))
  14083. (if (not old) (cons (cons key val) props)
  14084. (setcdr old (if appending (concat (cdr old) " " val) val))
  14085. props)))
  14086. (defun org-get-property-block (&optional beg force)
  14087. "Return the (beg . end) range of the body of the property drawer.
  14088. BEG is the beginning of the current subtree, or of the part
  14089. before the first headline. If it is not given, it will be found.
  14090. If the drawer does not exist, create it if FORCE is non-nil, or
  14091. return nil."
  14092. (org-with-wide-buffer
  14093. (when beg (goto-char beg))
  14094. (unless (org-before-first-heading-p)
  14095. (let ((beg (cond (beg)
  14096. ((or (not (featurep 'org-inlinetask))
  14097. (org-inlinetask-in-task-p))
  14098. (org-back-to-heading t))
  14099. (t (org-with-limited-levels (org-back-to-heading t))))))
  14100. (forward-line)
  14101. (when (looking-at-p org-planning-line-re) (forward-line))
  14102. (cond ((looking-at org-property-drawer-re)
  14103. (forward-line)
  14104. (cons (point) (progn (goto-char (match-end 0))
  14105. (line-beginning-position))))
  14106. (force
  14107. (goto-char beg)
  14108. (org-insert-property-drawer)
  14109. (let ((pos (save-excursion (search-forward ":END:")
  14110. (line-beginning-position))))
  14111. (cons pos pos))))))))
  14112. (defun org-at-property-p ()
  14113. "Non-nil when point is inside a property drawer.
  14114. See `org-property-re' for match data, if applicable."
  14115. (save-excursion
  14116. (beginning-of-line)
  14117. (and (looking-at org-property-re)
  14118. (let ((property-drawer (save-match-data (org-get-property-block))))
  14119. (and property-drawer
  14120. (>= (point) (car property-drawer))
  14121. (< (point) (cdr property-drawer)))))))
  14122. (defun org-property-action ()
  14123. "Do an action on properties."
  14124. (interactive)
  14125. (unless (org-at-property-p) (user-error "Not at a property"))
  14126. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14127. (let ((c (read-char-exclusive)))
  14128. (cl-case c
  14129. (?s (call-interactively #'org-set-property))
  14130. (?d (call-interactively #'org-delete-property))
  14131. (?D (call-interactively #'org-delete-property-globally))
  14132. (?c (call-interactively #'org-compute-property-at-point))
  14133. (otherwise (user-error "No such property action %c" c)))))
  14134. (defun org-inc-effort ()
  14135. "Increment the value of the effort property in the current entry."
  14136. (interactive)
  14137. (org-set-effort nil t))
  14138. (defvar org-clock-effort) ; Defined in org-clock.el.
  14139. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14140. (defun org-set-effort (&optional value increment)
  14141. "Set the effort property of the current entry.
  14142. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14143. 10th allowed value.
  14144. When INCREMENT is non-nil, set the property to the next allowed value."
  14145. (interactive "P")
  14146. (when (equal value 0) (setq value 10))
  14147. (let* ((completion-ignore-case t)
  14148. (prop org-effort-property)
  14149. (cur (org-entry-get nil prop))
  14150. (allowed (org-property-get-allowed-values nil prop 'table))
  14151. (existing (mapcar 'list (org-property-values prop)))
  14152. (heading (nth 4 (org-heading-components)))
  14153. rpl
  14154. (val (cond
  14155. ((stringp value) value)
  14156. ((and allowed (integerp value))
  14157. (or (car (nth (1- value) allowed))
  14158. (car (org-last allowed))))
  14159. ((and allowed increment)
  14160. (or (cl-caadr (member (list cur) allowed))
  14161. (user-error "Allowed effort values are not set")))
  14162. (allowed
  14163. (message "Select 1-9,0, [RET%s]: %s"
  14164. (if cur (concat "=" cur) "")
  14165. (mapconcat 'car allowed " "))
  14166. (setq rpl (read-char-exclusive))
  14167. (if (equal rpl ?\r)
  14168. cur
  14169. (setq rpl (- rpl ?0))
  14170. (when (equal rpl 0) (setq rpl 10))
  14171. (if (and (> rpl 0) (<= rpl (length allowed)))
  14172. (car (nth (1- rpl) allowed))
  14173. (org-completing-read "Effort: " allowed nil))))
  14174. (t
  14175. (org-completing-read
  14176. (concat "Effort" (and cur (string-match "\\S-" cur)
  14177. (concat " [" cur "]"))
  14178. ": ")
  14179. existing nil nil "" nil cur)))))
  14180. (unless (equal (org-entry-get nil prop) val)
  14181. (org-entry-put nil prop val))
  14182. (org-refresh-property
  14183. '((effort . identity)
  14184. (effort-minutes . org-duration-to-minutes))
  14185. val)
  14186. (when (equal heading (bound-and-true-p org-clock-current-task))
  14187. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14188. (org-clock-update-mode-line))
  14189. (message "%s is now %s" prop val)))
  14190. (defun org-entry-properties (&optional pom which)
  14191. "Get all properties of the current entry.
  14192. When POM is a buffer position, get all properties from the entry
  14193. there instead.
  14194. This includes the TODO keyword, the tags, time strings for
  14195. deadline, scheduled, and clocking, and any additional properties
  14196. defined in the entry.
  14197. If WHICH is nil or `all', get all properties. If WHICH is
  14198. `special' or `standard', only get that subclass. If WHICH is
  14199. a string, only get that property.
  14200. Return value is an alist. Keys are properties, as upcased
  14201. strings."
  14202. (org-with-point-at pom
  14203. (when (and (derived-mode-p 'org-mode)
  14204. (ignore-errors (org-back-to-heading t)))
  14205. (catch 'exit
  14206. (let* ((beg (point))
  14207. (specific (and (stringp which) (upcase which)))
  14208. (which (cond ((not specific) which)
  14209. ((member specific org-special-properties) 'special)
  14210. (t 'standard)))
  14211. props)
  14212. ;; Get the special properties, like TODO and TAGS.
  14213. (when (memq which '(nil all special))
  14214. (when (or (not specific) (string= specific "CLOCKSUM"))
  14215. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14216. (when clocksum
  14217. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14218. props)))
  14219. (when specific (throw 'exit props)))
  14220. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14221. (let ((clocksumt (get-text-property (point)
  14222. :org-clock-minutes-today)))
  14223. (when clocksumt
  14224. (push (cons "CLOCKSUM_T"
  14225. (org-duration-from-minutes clocksumt))
  14226. props)))
  14227. (when specific (throw 'exit props)))
  14228. (when (or (not specific) (string= specific "ITEM"))
  14229. (let ((case-fold-search nil))
  14230. (when (looking-at org-complex-heading-regexp)
  14231. (push (cons "ITEM"
  14232. (let ((title (match-string-no-properties 4)))
  14233. (if (org-string-nw-p title)
  14234. (org-remove-tabs title)
  14235. "")))
  14236. props)))
  14237. (when specific (throw 'exit props)))
  14238. (when (or (not specific) (string= specific "TODO"))
  14239. (let ((case-fold-search nil))
  14240. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14241. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14242. (when specific (throw 'exit props)))
  14243. (when (or (not specific) (string= specific "PRIORITY"))
  14244. (push (cons "PRIORITY"
  14245. (if (looking-at org-priority-regexp)
  14246. (match-string-no-properties 2)
  14247. (char-to-string org-default-priority)))
  14248. props)
  14249. (when specific (throw 'exit props)))
  14250. (when (or (not specific) (string= specific "FILE"))
  14251. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14252. props)
  14253. (when specific (throw 'exit props)))
  14254. (when (or (not specific) (string= specific "TAGS"))
  14255. (let ((value (org-string-nw-p (org-get-tags-string))))
  14256. (when value (push (cons "TAGS" value) props)))
  14257. (when specific (throw 'exit props)))
  14258. (when (or (not specific) (string= specific "ALLTAGS"))
  14259. (let ((value (org-get-tags-at)))
  14260. (when value
  14261. (push (cons "ALLTAGS"
  14262. (format ":%s:" (mapconcat #'identity value ":")))
  14263. props)))
  14264. (when specific (throw 'exit props)))
  14265. (when (or (not specific) (string= specific "BLOCKED"))
  14266. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14267. (when specific (throw 'exit props)))
  14268. (when (or (not specific)
  14269. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14270. (forward-line)
  14271. (when (looking-at-p org-planning-line-re)
  14272. (end-of-line)
  14273. (let ((bol (line-beginning-position))
  14274. ;; Backward compatibility: time keywords used to
  14275. ;; be configurable (before 8.3). Make sure we
  14276. ;; get the correct keyword.
  14277. (key-assoc `(("CLOSED" . ,org-closed-string)
  14278. ("DEADLINE" . ,org-deadline-string)
  14279. ("SCHEDULED" . ,org-scheduled-string))))
  14280. (dolist (pair (if specific (list (assoc specific key-assoc))
  14281. key-assoc))
  14282. (save-excursion
  14283. (when (search-backward (cdr pair) bol t)
  14284. (goto-char (match-end 0))
  14285. (skip-chars-forward " \t")
  14286. (and (looking-at org-ts-regexp-both)
  14287. (push (cons (car pair)
  14288. (match-string-no-properties 0))
  14289. props)))))))
  14290. (when specific (throw 'exit props)))
  14291. (when (or (not specific)
  14292. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14293. (let ((find-ts
  14294. (lambda (end ts)
  14295. ;; Fix next time-stamp before END. TS is the
  14296. ;; list of time-stamps found so far.
  14297. (let ((ts ts)
  14298. (regexp (cond
  14299. ((string= specific "TIMESTAMP")
  14300. org-ts-regexp)
  14301. ((string= specific "TIMESTAMP_IA")
  14302. org-ts-regexp-inactive)
  14303. ((assoc "TIMESTAMP_IA" ts)
  14304. org-ts-regexp)
  14305. ((assoc "TIMESTAMP" ts)
  14306. org-ts-regexp-inactive)
  14307. (t org-ts-regexp-both))))
  14308. (catch 'next
  14309. (while (re-search-forward regexp end t)
  14310. (backward-char)
  14311. (let ((object (org-element-context)))
  14312. ;; Accept to match timestamps in node
  14313. ;; properties, too.
  14314. (when (memq (org-element-type object)
  14315. '(node-property timestamp))
  14316. (let ((type
  14317. (org-element-property :type object)))
  14318. (cond
  14319. ((and (memq type '(active active-range))
  14320. (not (equal specific "TIMESTAMP_IA")))
  14321. (unless (assoc "TIMESTAMP" ts)
  14322. (push (cons "TIMESTAMP"
  14323. (org-element-property
  14324. :raw-value object))
  14325. ts)
  14326. (when specific (throw 'exit ts))))
  14327. ((and (memq type '(inactive inactive-range))
  14328. (not (string= specific "TIMESTAMP")))
  14329. (unless (assoc "TIMESTAMP_IA" ts)
  14330. (push (cons "TIMESTAMP_IA"
  14331. (org-element-property
  14332. :raw-value object))
  14333. ts)
  14334. (when specific (throw 'exit ts))))))
  14335. ;; Both timestamp types are found,
  14336. ;; move to next part.
  14337. (when (= (length ts) 2) (throw 'next ts)))))
  14338. ts)))))
  14339. (goto-char beg)
  14340. ;; First look for timestamps within headline.
  14341. (let ((ts (funcall find-ts (line-end-position) nil)))
  14342. (if (= (length ts) 2) (setq props (nconc ts props))
  14343. ;; Then find timestamps in the section, skipping
  14344. ;; planning line.
  14345. (let ((end (save-excursion (outline-next-heading))))
  14346. (forward-line)
  14347. (when (looking-at-p org-planning-line-re) (forward-line))
  14348. (setq props (nconc (funcall find-ts end ts) props))))))))
  14349. ;; Get the standard properties, like :PROP:.
  14350. (when (memq which '(nil all standard))
  14351. ;; If we are looking after a specific property, delegate
  14352. ;; to `org-entry-get', which is faster. However, make an
  14353. ;; exception for "CATEGORY", since it can be also set
  14354. ;; through keywords (i.e. #+CATEGORY).
  14355. (if (and specific (not (equal specific "CATEGORY")))
  14356. (let ((value (org-entry-get beg specific nil t)))
  14357. (throw 'exit (and value (list (cons specific value)))))
  14358. (let ((range (org-get-property-block beg)))
  14359. (when range
  14360. (let ((end (cdr range)) seen-base)
  14361. (goto-char (car range))
  14362. ;; Unlike to `org--update-property-plist', we
  14363. ;; handle the case where base values is found
  14364. ;; after its extension. We also forbid standard
  14365. ;; properties to be named as special properties.
  14366. (while (re-search-forward org-property-re end t)
  14367. (let* ((key (upcase (match-string-no-properties 2)))
  14368. (extendp (string-match-p "\\+\\'" key))
  14369. (key-base (if extendp (substring key 0 -1) key))
  14370. (value (match-string-no-properties 3)))
  14371. (cond
  14372. ((member-ignore-case key-base org-special-properties))
  14373. (extendp
  14374. (setq props
  14375. (org--update-property-plist key value props)))
  14376. ((member key seen-base))
  14377. (t (push key seen-base)
  14378. (let ((p (assoc-string key props t)))
  14379. (if p (setcdr p (concat value " " (cdr p)))
  14380. (push (cons key value) props))))))))))))
  14381. (unless (assoc "CATEGORY" props)
  14382. (push (cons "CATEGORY" (org-get-category beg)) props)
  14383. (when (string= specific "CATEGORY") (throw 'exit props)))
  14384. ;; Return value.
  14385. props)))))
  14386. (defun org--property-local-values (property literal-nil)
  14387. "Return value for PROPERTY in current entry.
  14388. Value is a list whose car is the base value for PROPERTY and cdr
  14389. a list of accumulated values. Return nil if neither is found in
  14390. the entry. Also return nil when PROPERTY is set to \"nil\",
  14391. unless LITERAL-NIL is non-nil."
  14392. (let ((range (org-get-property-block)))
  14393. (when range
  14394. (goto-char (car range))
  14395. (let* ((case-fold-search t)
  14396. (end (cdr range))
  14397. (value
  14398. ;; Base value.
  14399. (save-excursion
  14400. (let ((v (and (re-search-forward
  14401. (org-re-property property nil t) end t)
  14402. (match-string-no-properties 3))))
  14403. (list (if literal-nil v (org-not-nil v)))))))
  14404. ;; Find additional values.
  14405. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14406. (while (re-search-forward property+ end t)
  14407. (push (match-string-no-properties 3) value)))
  14408. ;; Return final values.
  14409. (and (not (equal value '(nil))) (nreverse value))))))
  14410. (defun org--property-global-value (property literal-nil)
  14411. "Return value for PROPERTY in current buffer.
  14412. Return value is a string. Return nil if property is not set
  14413. globally. Also return nil when PROPERTY is set to \"nil\",
  14414. unless LITERAL-NIL is non-nil."
  14415. (let ((global
  14416. (cdr (or (assoc-string property org-file-properties t)
  14417. (assoc-string property org-global-properties t)
  14418. (assoc-string property org-global-properties-fixed t)))))
  14419. (if literal-nil global (org-not-nil global))))
  14420. (defun org-entry-get (pom property &optional inherit literal-nil)
  14421. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14422. If INHERIT is non-nil and the entry does not have the property,
  14423. then also check higher levels of the hierarchy. If INHERIT is
  14424. the symbol `selective', use inheritance only if the setting in
  14425. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14426. If the property is present but empty, the return value is the
  14427. empty string. If the property is not present at all, nil is
  14428. returned. In any other case, return the value as a string.
  14429. Search is case-insensitive.
  14430. If LITERAL-NIL is set, return the string value \"nil\" as
  14431. a string, do not interpret it as the list atom nil. This is used
  14432. for inheritance when a \"nil\" value can supersede a non-nil
  14433. value higher up the hierarchy."
  14434. (org-with-point-at pom
  14435. (cond
  14436. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14437. ;; We need a special property. Use `org-entry-properties' to
  14438. ;; retrieve it, but specify the wanted property.
  14439. (cdr (assoc-string property (org-entry-properties nil property))))
  14440. ((and inherit
  14441. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14442. (org-entry-get-with-inheritance property literal-nil))
  14443. (t
  14444. (let* ((local (org--property-local-values property literal-nil))
  14445. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14446. (if literal-nil value (org-not-nil value)))))))
  14447. (defun org-property-or-variable-value (var &optional inherit)
  14448. "Check if there is a property fixing the value of VAR.
  14449. If yes, return this value. If not, return the current value of the variable."
  14450. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14451. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14452. (read prop)
  14453. (symbol-value var))))
  14454. (defun org-entry-delete (pom property)
  14455. "Delete PROPERTY from entry at point-or-marker POM.
  14456. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14457. non-nil when a property was removed."
  14458. (org-with-point-at pom
  14459. (pcase (org-get-property-block)
  14460. (`(,begin . ,origin)
  14461. (let* ((end (copy-marker origin))
  14462. (re (org-re-property
  14463. (concat (regexp-quote property) "\\+?") t t)))
  14464. (goto-char begin)
  14465. (while (re-search-forward re end t)
  14466. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14467. ;; If drawer is empty, remove it altogether.
  14468. (when (= begin end)
  14469. (delete-region (line-beginning-position 0)
  14470. (line-beginning-position 2)))
  14471. ;; Return non-nil if some property was removed.
  14472. (prog1 (/= end origin) (set-marker end nil))))
  14473. (_ nil))))
  14474. ;; Multi-values properties are properties that contain multiple values
  14475. ;; These values are assumed to be single words, separated by whitespace.
  14476. (defun org-entry-add-to-multivalued-property (pom property value)
  14477. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14478. (let* ((old (org-entry-get pom property))
  14479. (values (and old (org-split-string old "[ \t]"))))
  14480. (setq value (org-entry-protect-space value))
  14481. (unless (member value values)
  14482. (setq values (append values (list value)))
  14483. (org-entry-put pom property
  14484. (mapconcat 'identity values " ")))))
  14485. (defun org-entry-remove-from-multivalued-property (pom property value)
  14486. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14487. (let* ((old (org-entry-get pom property))
  14488. (values (and old (org-split-string old "[ \t]"))))
  14489. (setq value (org-entry-protect-space value))
  14490. (when (member value values)
  14491. (setq values (delete value values))
  14492. (org-entry-put pom property
  14493. (mapconcat 'identity values " ")))))
  14494. (defun org-entry-member-in-multivalued-property (pom property value)
  14495. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14496. (let* ((old (org-entry-get pom property))
  14497. (values (and old (org-split-string old "[ \t]"))))
  14498. (setq value (org-entry-protect-space value))
  14499. (member value values)))
  14500. (defun org-entry-get-multivalued-property (pom property)
  14501. "Return a list of values in a multivalued property."
  14502. (let* ((value (org-entry-get pom property))
  14503. (values (and value (org-split-string value "[ \t]"))))
  14504. (mapcar 'org-entry-restore-space values)))
  14505. (defun org-entry-put-multivalued-property (pom property &rest values)
  14506. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14507. VALUES should be a list of strings. Spaces will be protected."
  14508. (org-entry-put pom property
  14509. (mapconcat 'org-entry-protect-space values " "))
  14510. (let* ((value (org-entry-get pom property))
  14511. (values (and value (org-split-string value "[ \t]"))))
  14512. (mapcar 'org-entry-restore-space values)))
  14513. (defun org-entry-protect-space (s)
  14514. "Protect spaces and newline in string S."
  14515. (while (string-match " " s)
  14516. (setq s (replace-match "%20" t t s)))
  14517. (while (string-match "\n" s)
  14518. (setq s (replace-match "%0A" t t s)))
  14519. s)
  14520. (defun org-entry-restore-space (s)
  14521. "Restore spaces and newline in string S."
  14522. (while (string-match "%20" s)
  14523. (setq s (replace-match " " t t s)))
  14524. (while (string-match "%0A" s)
  14525. (setq s (replace-match "\n" t t s)))
  14526. s)
  14527. (defvar org-entry-property-inherited-from (make-marker)
  14528. "Marker pointing to the entry from where a property was inherited.
  14529. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14530. location of the entry where the inheritance search matched. If there was
  14531. no match, the marker will point nowhere.
  14532. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14533. is set.")
  14534. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14535. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14536. The search will stop at the first ancestor which has the property defined.
  14537. If the value found is \"nil\", return nil to show that the property
  14538. should be considered as undefined (this is the meaning of nil here).
  14539. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14540. (move-marker org-entry-property-inherited-from nil)
  14541. (org-with-wide-buffer
  14542. (let (value)
  14543. (catch 'exit
  14544. (while t
  14545. (let ((v (org--property-local-values property literal-nil)))
  14546. (when v
  14547. (setq value
  14548. (concat (mapconcat #'identity (delq nil v) " ")
  14549. (and value " ")
  14550. value)))
  14551. (cond
  14552. ((car v)
  14553. (org-back-to-heading t)
  14554. (move-marker org-entry-property-inherited-from (point))
  14555. (throw 'exit nil))
  14556. ((org-up-heading-safe))
  14557. (t
  14558. (let ((global (org--property-global-value property literal-nil)))
  14559. (cond ((not global))
  14560. (value (setq value (concat global " " value)))
  14561. (t (setq value global))))
  14562. (throw 'exit nil))))))
  14563. (if literal-nil value (org-not-nil value)))))
  14564. (defvar org-property-changed-functions nil
  14565. "Hook called when the value of a property has changed.
  14566. Each hook function should accept two arguments, the name of the property
  14567. and the new value.")
  14568. (defun org-entry-put (pom property value)
  14569. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14570. If the value is nil, it is converted to the empty string. If it
  14571. is not a string, an error is raised. Also raise an error on
  14572. invalid property names.
  14573. PROPERTY can be any regular property (see
  14574. `org-special-properties'). It can also be \"TODO\",
  14575. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14576. For the last two properties, VALUE may have any of the special
  14577. values \"earlier\" and \"later\". The function then increases or
  14578. decreases scheduled or deadline date by one day."
  14579. (cond ((null value) (setq value ""))
  14580. ((not (stringp value)) (error "Properties values should be strings"))
  14581. ((not (org--valid-property-p property))
  14582. (user-error "Invalid property name: \"%s\"" property)))
  14583. (org-with-point-at pom
  14584. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14585. (org-back-to-heading t)
  14586. (org-with-limited-levels (org-back-to-heading t)))
  14587. (let ((beg (point)))
  14588. (cond
  14589. ((equal property "TODO")
  14590. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14591. ((not (member value org-todo-keywords-1))
  14592. (user-error "\"%s\" is not a valid TODO state" value)))
  14593. (org-todo value)
  14594. (org-set-tags nil 'align))
  14595. ((equal property "PRIORITY")
  14596. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14597. (org-set-tags nil 'align))
  14598. ((equal property "SCHEDULED")
  14599. (forward-line)
  14600. (if (and (looking-at-p org-planning-line-re)
  14601. (re-search-forward
  14602. org-scheduled-time-regexp (line-end-position) t))
  14603. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14604. ((string= value "later") (org-timestamp-change 1 'day))
  14605. ((string= value "") (org-schedule '(4)))
  14606. (t (org-schedule nil value)))
  14607. (if (member value '("earlier" "later" ""))
  14608. (call-interactively #'org-schedule)
  14609. (org-schedule nil value))))
  14610. ((equal property "DEADLINE")
  14611. (forward-line)
  14612. (if (and (looking-at-p org-planning-line-re)
  14613. (re-search-forward
  14614. org-deadline-time-regexp (line-end-position) t))
  14615. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14616. ((string= value "later") (org-timestamp-change 1 'day))
  14617. ((string= value "") (org-deadline '(4)))
  14618. (t (org-deadline nil value)))
  14619. (if (member value '("earlier" "later" ""))
  14620. (call-interactively #'org-deadline)
  14621. (org-deadline nil value))))
  14622. ((member property org-special-properties)
  14623. (error "The %s property cannot be set with `org-entry-put'" property))
  14624. (t
  14625. (let* ((range (org-get-property-block beg 'force))
  14626. (end (cdr range))
  14627. (case-fold-search t))
  14628. (goto-char (car range))
  14629. (if (re-search-forward (org-re-property property nil t) end t)
  14630. (progn (delete-region (match-beginning 0) (match-end 0))
  14631. (goto-char (match-beginning 0)))
  14632. (goto-char end)
  14633. (insert "\n")
  14634. (backward-char))
  14635. (insert ":" property ":")
  14636. (when value (insert " " value))
  14637. (org-indent-line)))))
  14638. (run-hook-with-args 'org-property-changed-functions property value)))
  14639. (defun org-buffer-property-keys
  14640. (&optional specials defaults columns ignore-malformed)
  14641. "Get all property keys in the current buffer.
  14642. When SPECIALS is non-nil, also list the special properties that
  14643. reflect things like tags and TODO state.
  14644. When DEFAULTS is non-nil, also include properties that has
  14645. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14646. DESCRIPTION, LOCATION, and LOGGING and others.
  14647. When COLUMNS in non-nil, also include property names given in
  14648. COLUMN formats in the current buffer.
  14649. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14650. automatically performed, such drawers will be silently ignored."
  14651. (let ((case-fold-search t)
  14652. (props (append
  14653. (and specials org-special-properties)
  14654. (and defaults (cons org-effort-property org-default-properties))
  14655. nil)))
  14656. (org-with-wide-buffer
  14657. (goto-char (point-min))
  14658. (while (re-search-forward org-property-start-re nil t)
  14659. (let ((range (org-get-property-block)))
  14660. (catch 'skip
  14661. (unless range
  14662. (when (and (not ignore-malformed)
  14663. (not (org-before-first-heading-p))
  14664. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14665. (line-beginning-position))))
  14666. (org-get-property-block nil t))
  14667. (throw 'skip nil))
  14668. (goto-char (car range))
  14669. (let ((begin (car range))
  14670. (end (cdr range)))
  14671. ;; Make sure that found property block is not located
  14672. ;; before current point, as it would generate an infloop.
  14673. ;; It can happen, for example, in the following
  14674. ;; situation:
  14675. ;;
  14676. ;; * Headline
  14677. ;; :PROPERTIES:
  14678. ;; ...
  14679. ;; :END:
  14680. ;; *************** Inlinetask
  14681. ;; #+BEGIN_EXAMPLE
  14682. ;; :PROPERTIES:
  14683. ;; #+END_EXAMPLE
  14684. ;;
  14685. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14686. (while (< (point) end)
  14687. (let ((p (progn (looking-at org-property-re)
  14688. (match-string-no-properties 2))))
  14689. ;; Only add true property name, not extension symbol.
  14690. (push (if (not (string-match-p "\\+\\'" p)) p
  14691. (substring p 0 -1))
  14692. props))
  14693. (forward-line))))
  14694. (outline-next-heading)))
  14695. (when columns
  14696. (goto-char (point-min))
  14697. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14698. (let ((element (org-element-at-point)))
  14699. (when (memq (org-element-type element) '(keyword node-property))
  14700. (let ((value (org-element-property :value element))
  14701. (start 0))
  14702. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14703. (setq start (match-end 0))
  14704. (let ((p (match-string-no-properties 1 value)))
  14705. (unless (member-ignore-case p org-special-properties)
  14706. (push p props))))))))))
  14707. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14708. (defun org-property-values (key)
  14709. "List all non-nil values of property KEY in current buffer."
  14710. (org-with-wide-buffer
  14711. (goto-char (point-min))
  14712. (let ((case-fold-search t)
  14713. (re (org-re-property key))
  14714. values)
  14715. (while (re-search-forward re nil t)
  14716. (push (org-entry-get (point) key) values))
  14717. (delete-dups values))))
  14718. (defun org-insert-property-drawer ()
  14719. "Insert a property drawer into the current entry."
  14720. (org-with-wide-buffer
  14721. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14722. (org-back-to-heading t)
  14723. (org-with-limited-levels (org-back-to-heading t)))
  14724. (forward-line)
  14725. (when (looking-at-p org-planning-line-re) (forward-line))
  14726. (unless (looking-at-p org-property-drawer-re)
  14727. ;; Make sure we start editing a line from current entry, not from
  14728. ;; next one. It prevents extending text properties or overlays
  14729. ;; belonging to the latter.
  14730. (when (bolp) (backward-char))
  14731. (let ((begin (1+ (point)))
  14732. (inhibit-read-only t))
  14733. (insert "\n:PROPERTIES:\n:END:")
  14734. (when (eobp) (insert "\n"))
  14735. (org-indent-region begin (point))))))
  14736. (defun org-insert-drawer (&optional arg drawer)
  14737. "Insert a drawer at point.
  14738. When optional argument ARG is non-nil, insert a property drawer.
  14739. Optional argument DRAWER, when non-nil, is a string representing
  14740. drawer's name. Otherwise, the user is prompted for a name.
  14741. If a region is active, insert the drawer around that region
  14742. instead.
  14743. Point is left between drawer's boundaries."
  14744. (interactive "P")
  14745. (let* ((drawer (if arg "PROPERTIES"
  14746. (or drawer (read-from-minibuffer "Drawer: ")))))
  14747. (cond
  14748. ;; With C-u, fall back on `org-insert-property-drawer'
  14749. (arg (org-insert-property-drawer))
  14750. ;; Check validity of suggested drawer's name.
  14751. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14752. (user-error "Invalid drawer name"))
  14753. ;; With an active region, insert a drawer at point.
  14754. ((not (org-region-active-p))
  14755. (progn
  14756. (unless (bolp) (insert "\n"))
  14757. (insert (format ":%s:\n\n:END:\n" drawer))
  14758. (forward-line -2)))
  14759. ;; Otherwise, insert the drawer at point
  14760. (t
  14761. (let ((rbeg (region-beginning))
  14762. (rend (copy-marker (region-end))))
  14763. (unwind-protect
  14764. (progn
  14765. (goto-char rbeg)
  14766. (beginning-of-line)
  14767. (when (save-excursion
  14768. (re-search-forward org-outline-regexp-bol rend t))
  14769. (user-error "Drawers cannot contain headlines"))
  14770. ;; Position point at the beginning of the first
  14771. ;; non-blank line in region. Insert drawer's opening
  14772. ;; there, then indent it.
  14773. (org-skip-whitespace)
  14774. (beginning-of-line)
  14775. (insert ":" drawer ":\n")
  14776. (forward-line -1)
  14777. (indent-for-tab-command)
  14778. ;; Move point to the beginning of the first blank line
  14779. ;; after the last non-blank line in region. Insert
  14780. ;; drawer's closing, then indent it.
  14781. (goto-char rend)
  14782. (skip-chars-backward " \r\t\n")
  14783. (insert "\n:END:")
  14784. (deactivate-mark t)
  14785. (indent-for-tab-command)
  14786. (unless (eolp) (insert "\n")))
  14787. ;; Clear marker, whatever the outcome of insertion is.
  14788. (set-marker rend nil)))))))
  14789. (defvar org-property-set-functions-alist nil
  14790. "Property set function alist.
  14791. Each entry should have the following format:
  14792. (PROPERTY . READ-FUNCTION)
  14793. The read function will be called with the same argument as
  14794. `org-completing-read'.")
  14795. (defun org-set-property-function (property)
  14796. "Get the function that should be used to set PROPERTY.
  14797. This is computed according to `org-property-set-functions-alist'."
  14798. (or (cdr (assoc property org-property-set-functions-alist))
  14799. 'org-completing-read))
  14800. (defun org-read-property-value (property)
  14801. "Read PROPERTY value from user."
  14802. (let* ((completion-ignore-case t)
  14803. (allowed (org-property-get-allowed-values nil property 'table))
  14804. (cur (org-entry-get nil property))
  14805. (prompt (concat property " value"
  14806. (if (and cur (string-match "\\S-" cur))
  14807. (concat " [" cur "]") "") ": "))
  14808. (set-function (org-set-property-function property))
  14809. (val (if allowed
  14810. (funcall set-function prompt allowed nil
  14811. (not (get-text-property 0 'org-unrestricted
  14812. (caar allowed))))
  14813. (funcall set-function prompt
  14814. (mapcar 'list (org-property-values property))
  14815. nil nil "" nil cur))))
  14816. (org-trim val)))
  14817. (defvar org-last-set-property nil)
  14818. (defvar org-last-set-property-value nil)
  14819. (defun org-read-property-name ()
  14820. "Read a property name."
  14821. (let ((completion-ignore-case t)
  14822. (default-prop (or (and (org-at-property-p)
  14823. (match-string-no-properties 2))
  14824. org-last-set-property)))
  14825. (org-completing-read
  14826. (concat "Property"
  14827. (if default-prop (concat " [" default-prop "]") "")
  14828. ": ")
  14829. (mapcar #'list (org-buffer-property-keys nil t t))
  14830. nil nil nil nil default-prop)))
  14831. (defun org-set-property-and-value (use-last)
  14832. "Allow to set [PROPERTY]: [value] direction from prompt.
  14833. When use-default, don't even ask, just use the last
  14834. \"[PROPERTY]: [value]\" string from the history."
  14835. (interactive "P")
  14836. (let* ((completion-ignore-case t)
  14837. (pv (or (and use-last org-last-set-property-value)
  14838. (org-completing-read
  14839. "Enter a \"[Property]: [value]\" pair: "
  14840. nil nil nil nil nil
  14841. org-last-set-property-value)))
  14842. prop val)
  14843. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14844. (setq prop (match-string 1 pv)
  14845. val (match-string 2 pv))
  14846. (org-set-property prop val))))
  14847. (defun org-set-property (property value)
  14848. "In the current entry, set PROPERTY to VALUE.
  14849. When called interactively, this will prompt for a property name, offering
  14850. completion on existing and default properties. And then it will prompt
  14851. for a value, offering completion either on allowed values (via an inherited
  14852. xxx_ALL property) or on existing values in other instances of this property
  14853. in the current file.
  14854. Throw an error when trying to set a property with an invalid name."
  14855. (interactive (list nil nil))
  14856. (let ((property (or property (org-read-property-name))))
  14857. ;; `org-entry-put' also makes the following check, but this one
  14858. ;; avoids polluting `org-last-set-property' and
  14859. ;; `org-last-set-property-value' needlessly.
  14860. (unless (org--valid-property-p property)
  14861. (user-error "Invalid property name: \"%s\"" property))
  14862. (let ((value (or value (org-read-property-value property)))
  14863. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14864. (setq org-last-set-property property)
  14865. (setq org-last-set-property-value (concat property ": " value))
  14866. ;; Possibly postprocess the inserted value:
  14867. (when fn (setq value (funcall fn value)))
  14868. (unless (equal (org-entry-get nil property) value)
  14869. (org-entry-put nil property value)))))
  14870. (defun org-find-property (property &optional value)
  14871. "Find first entry in buffer that sets PROPERTY.
  14872. When optional argument VALUE is non-nil, only consider an entry
  14873. if it contains PROPERTY set to this value. If PROPERTY should be
  14874. explicitly set to nil, use string \"nil\" for VALUE.
  14875. Return position where the entry begins, or nil if there is no
  14876. such entry. If narrowing is in effect, only search the visible
  14877. part of the buffer."
  14878. (save-excursion
  14879. (goto-char (point-min))
  14880. (let ((case-fold-search t)
  14881. (re (org-re-property property nil (not value) value)))
  14882. (catch 'exit
  14883. (while (re-search-forward re nil t)
  14884. (when (if value (org-at-property-p)
  14885. (org-entry-get (point) property nil t))
  14886. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14887. (defun org-delete-property (property)
  14888. "In the current entry, delete PROPERTY."
  14889. (interactive
  14890. (let* ((completion-ignore-case t)
  14891. (cat (org-entry-get (point) "CATEGORY"))
  14892. (props0 (org-entry-properties nil 'standard))
  14893. (props (if cat props0
  14894. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14895. (prop (if (< 1 (length props))
  14896. (completing-read "Property: " props nil t)
  14897. (caar props))))
  14898. (list prop)))
  14899. (if (not property)
  14900. (message "No property to delete in this entry")
  14901. (org-entry-delete nil property)
  14902. (message "Property \"%s\" deleted" property)))
  14903. (defun org-delete-property-globally (property)
  14904. "Remove PROPERTY globally, from all entries.
  14905. This function ignores narrowing, if any."
  14906. (interactive
  14907. (let* ((completion-ignore-case t)
  14908. (prop (completing-read
  14909. "Globally remove property: "
  14910. (mapcar #'list (org-buffer-property-keys)))))
  14911. (list prop)))
  14912. (org-with-wide-buffer
  14913. (goto-char (point-min))
  14914. (let ((count 0)
  14915. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14916. (while (re-search-forward re nil t)
  14917. (when (org-entry-delete (point) property) (cl-incf count)))
  14918. (message "Property \"%s\" removed from %d entries" property count))))
  14919. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14920. (defun org-compute-property-at-point ()
  14921. "Compute the property at point.
  14922. This looks for an enclosing column format, extracts the operator and
  14923. then applies it to the property in the column format's scope."
  14924. (interactive)
  14925. (unless (org-at-property-p)
  14926. (user-error "Not at a property"))
  14927. (let ((prop (match-string-no-properties 2)))
  14928. (org-columns-get-format-and-top-level)
  14929. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14930. (user-error "No operator defined for property %s" prop))
  14931. (org-columns-compute prop)))
  14932. (defvar org-property-allowed-value-functions nil
  14933. "Hook for functions supplying allowed values for a specific property.
  14934. The functions must take a single argument, the name of the property, and
  14935. return a flat list of allowed values. If \":ETC\" is one of
  14936. the values, this means that these values are intended as defaults for
  14937. completion, but that other values should be allowed too.
  14938. The functions must return nil if they are not responsible for this
  14939. property.")
  14940. (defun org-property-get-allowed-values (pom property &optional table)
  14941. "Get allowed values for the property PROPERTY.
  14942. When TABLE is non-nil, return an alist that can directly be used for
  14943. completion."
  14944. (let (vals)
  14945. (cond
  14946. ((equal property "TODO")
  14947. (setq vals (org-with-point-at pom
  14948. (append org-todo-keywords-1 '("")))))
  14949. ((equal property "PRIORITY")
  14950. (let ((n org-lowest-priority))
  14951. (while (>= n org-highest-priority)
  14952. (push (char-to-string n) vals)
  14953. (setq n (1- n)))))
  14954. ((equal property "CATEGORY"))
  14955. ((member property org-special-properties))
  14956. ((setq vals (run-hook-with-args-until-success
  14957. 'org-property-allowed-value-functions property)))
  14958. (t
  14959. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14960. (when (and vals (string-match "\\S-" vals))
  14961. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14962. (setq vals (mapcar (lambda (x)
  14963. (cond ((stringp x) x)
  14964. ((numberp x) (number-to-string x))
  14965. ((symbolp x) (symbol-name x))
  14966. (t "???")))
  14967. vals)))))
  14968. (when (member ":ETC" vals)
  14969. (setq vals (remove ":ETC" vals))
  14970. (org-add-props (car vals) '(org-unrestricted t)))
  14971. (if table (mapcar 'list vals) vals)))
  14972. (defun org-property-previous-allowed-value (&optional _previous)
  14973. "Switch to the next allowed value for this property."
  14974. (interactive)
  14975. (org-property-next-allowed-value t))
  14976. (defun org-property-next-allowed-value (&optional previous)
  14977. "Switch to the next allowed value for this property."
  14978. (interactive)
  14979. (unless (org-at-property-p)
  14980. (user-error "Not at a property"))
  14981. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14982. (key (match-string 2))
  14983. (value (match-string 3))
  14984. (allowed (or (org-property-get-allowed-values (point) key)
  14985. (and (member value '("[ ]" "[-]" "[X]"))
  14986. '("[ ]" "[X]"))))
  14987. (heading (save-match-data (nth 4 (org-heading-components))))
  14988. nval)
  14989. (unless allowed
  14990. (user-error "Allowed values for this property have not been defined"))
  14991. (when previous (setq allowed (reverse allowed)))
  14992. (when (member value allowed)
  14993. (setq nval (car (cdr (member value allowed)))))
  14994. (setq nval (or nval (car allowed)))
  14995. (when (equal nval value)
  14996. (user-error "Only one allowed value for this property"))
  14997. (org-at-property-p)
  14998. (replace-match (concat " :" key ": " nval) t t)
  14999. (org-indent-line)
  15000. (beginning-of-line 1)
  15001. (skip-chars-forward " \t")
  15002. (when (equal prop org-effort-property)
  15003. (org-refresh-property
  15004. '((effort . identity)
  15005. (effort-minutes . org-duration-to-minutes))
  15006. nval)
  15007. (when (string= org-clock-current-task heading)
  15008. (setq org-clock-effort nval)
  15009. (org-clock-update-mode-line)))
  15010. (run-hook-with-args 'org-property-changed-functions key nval)))
  15011. (defun org-find-olp (path &optional this-buffer)
  15012. "Return a marker pointing to the entry at outline path OLP.
  15013. If anything goes wrong, throw an error.
  15014. You can wrap this call to catch the error like this:
  15015. (condition-case msg
  15016. (org-mobile-locate-entry (match-string 4))
  15017. (error (nth 1 msg)))
  15018. The return value will then be either a string with the error message,
  15019. or a marker if everything is OK.
  15020. If THIS-BUFFER is set, the outline path does not contain a file,
  15021. only headings."
  15022. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15023. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15024. (level 1)
  15025. (lmin 1)
  15026. (lmax 1)
  15027. end found flevel)
  15028. (unless buffer (error "File not found :%s" file))
  15029. (with-current-buffer buffer
  15030. (org-with-wide-buffer
  15031. (goto-char (point-min))
  15032. (dolist (heading path)
  15033. (let ((re (format org-complex-heading-regexp-format
  15034. (regexp-quote heading)))
  15035. (cnt 0))
  15036. (while (re-search-forward re end t)
  15037. (setq level (- (match-end 1) (match-beginning 1)))
  15038. (when (and (>= level lmin) (<= level lmax))
  15039. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15040. (when (= cnt 0)
  15041. (error "Heading not found on level %d: %s" lmax heading))
  15042. (when (> cnt 1)
  15043. (error "Heading not unique on level %d: %s" lmax heading))
  15044. (goto-char found)
  15045. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15046. (setq end (save-excursion (org-end-of-subtree t t)))))
  15047. (when (org-at-heading-p)
  15048. (point-marker))))))
  15049. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15050. "Find node HEADING in BUFFER.
  15051. Return a marker to the heading if it was found, or nil if not.
  15052. If POS-ONLY is set, return just the position instead of a marker.
  15053. The heading text must match exact, but it may have a TODO keyword,
  15054. a priority cookie and tags in the standard locations."
  15055. (with-current-buffer (or buffer (current-buffer))
  15056. (org-with-wide-buffer
  15057. (goto-char (point-min))
  15058. (let (case-fold-search)
  15059. (when (re-search-forward
  15060. (format org-complex-heading-regexp-format
  15061. (regexp-quote heading)) nil t)
  15062. (if pos-only
  15063. (match-beginning 0)
  15064. (move-marker (make-marker) (match-beginning 0))))))))
  15065. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15066. "Find Org node headline HEADING in all .org files in directory DIR.
  15067. When the target headline is found, return a marker to this location."
  15068. (let ((files (directory-files (or dir default-directory)
  15069. t "\\`[^.#].*\\.org\\'"))
  15070. visiting m buffer)
  15071. (catch 'found
  15072. (dolist (file files)
  15073. (message "trying %s" file)
  15074. (setq visiting (org-find-base-buffer-visiting file))
  15075. (setq buffer (or visiting (find-file-noselect file)))
  15076. (setq m (org-find-exact-headline-in-buffer
  15077. heading buffer))
  15078. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15079. (and m (throw 'found m))))))
  15080. (defun org-find-entry-with-id (ident)
  15081. "Locate the entry that contains the ID property with exact value IDENT.
  15082. IDENT can be a string, a symbol or a number, this function will search for
  15083. the string representation of it.
  15084. Return the position where this entry starts, or nil if there is no such entry."
  15085. (interactive "sID: ")
  15086. (let ((id (cond
  15087. ((stringp ident) ident)
  15088. ((symbolp ident) (symbol-name ident))
  15089. ((numberp ident) (number-to-string ident))
  15090. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15091. (org-with-wide-buffer (org-find-property "ID" id))))
  15092. ;;;; Timestamps
  15093. (defvar org-last-changed-timestamp nil)
  15094. (defvar org-last-inserted-timestamp nil
  15095. "The last time stamp inserted with `org-insert-time-stamp'.")
  15096. (defun org-time-stamp (arg &optional inactive)
  15097. "Prompt for a date/time and insert a time stamp.
  15098. If the user specifies a time like HH:MM or if this command is
  15099. called with at least one prefix argument, the time stamp contains
  15100. the date and the time. Otherwise, only the date is included.
  15101. All parts of a date not specified by the user are filled in from
  15102. the timestamp at point, if any, or the current date/time
  15103. otherwise.
  15104. If there is already a timestamp at the cursor, it is replaced.
  15105. With two universal prefix arguments, insert an active timestamp
  15106. with the current time without prompting the user.
  15107. When called from lisp, the timestamp is inactive if INACTIVE is
  15108. non-nil."
  15109. (interactive "P")
  15110. (let* ((ts (cond
  15111. ((org-at-date-range-p t)
  15112. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15113. ((org-at-timestamp-p t) (match-string 0))))
  15114. ;; Default time is either the timestamp at point or today.
  15115. ;; When entering a range, only the range start is considered.
  15116. (default-time (if (not ts) (current-time)
  15117. (apply #'encode-time (org-parse-time-string ts))))
  15118. (default-input (and ts (org-get-compact-tod ts)))
  15119. (repeater (and ts
  15120. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15121. (match-string 0 ts)))
  15122. org-time-was-given
  15123. org-end-time-was-given
  15124. (time
  15125. (and (if (equal arg '(16)) (current-time)
  15126. ;; Preserve `this-command' and `last-command'.
  15127. (let ((this-command this-command)
  15128. (last-command last-command))
  15129. (org-read-date
  15130. arg 'totime nil nil default-time default-input
  15131. inactive))))))
  15132. (cond
  15133. ((and ts
  15134. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15135. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15136. (insert "--")
  15137. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15138. (ts
  15139. ;; Make sure we're on a timestamp. When in the middle of a date
  15140. ;; range, move arbitrarily to range end.
  15141. (unless (org-at-timestamp-p t)
  15142. (skip-chars-forward "-")
  15143. (org-at-timestamp-p t))
  15144. (replace-match "")
  15145. (setq org-last-changed-timestamp
  15146. (org-insert-time-stamp
  15147. time (or org-time-was-given arg)
  15148. inactive nil nil (list org-end-time-was-given)))
  15149. (when repeater
  15150. (backward-char)
  15151. (insert " " repeater)
  15152. (setq org-last-changed-timestamp
  15153. (concat (substring org-last-inserted-timestamp 0 -1)
  15154. " " repeater ">")))
  15155. (message "Timestamp updated"))
  15156. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15157. (t (org-insert-time-stamp
  15158. time (or org-time-was-given arg) inactive nil nil
  15159. (list org-end-time-was-given))))))
  15160. ;; FIXME: can we use this for something else, like computing time differences?
  15161. (defun org-get-compact-tod (s)
  15162. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15163. (let* ((t1 (match-string 1 s))
  15164. (h1 (string-to-number (match-string 2 s)))
  15165. (m1 (string-to-number (match-string 3 s)))
  15166. (t2 (and (match-end 4) (match-string 5 s)))
  15167. (h2 (and t2 (string-to-number (match-string 6 s))))
  15168. (m2 (and t2 (string-to-number (match-string 7 s))))
  15169. dh dm)
  15170. (if (not t2)
  15171. t1
  15172. (setq dh (- h2 h1) dm (- m2 m1))
  15173. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15174. (concat t1 "+" (number-to-string dh)
  15175. (and (/= 0 dm) (format ":%02d" dm)))))))
  15176. (defun org-time-stamp-inactive (&optional arg)
  15177. "Insert an inactive time stamp.
  15178. An inactive time stamp is enclosed in square brackets instead of angle
  15179. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15180. does not link to the calendar and cannot be changed with the S-cursor keys.
  15181. So these are more for recording a certain time/date."
  15182. (interactive "P")
  15183. (org-time-stamp arg 'inactive))
  15184. (defvar org-date-ovl (make-overlay 1 1))
  15185. (overlay-put org-date-ovl 'face 'org-date-selected)
  15186. (delete-overlay org-date-ovl)
  15187. (defvar org-ans1) ; dynamically scoped parameter
  15188. (defvar org-ans2) ; dynamically scoped parameter
  15189. (defvar org-plain-time-of-day-regexp) ; defined below
  15190. (defvar org-overriding-default-time nil) ; dynamically scoped
  15191. (defvar org-read-date-overlay nil)
  15192. (defvar org-dcst nil) ; dynamically scoped
  15193. (defvar org-read-date-history nil)
  15194. (defvar org-read-date-final-answer nil)
  15195. (defvar org-read-date-analyze-futurep nil)
  15196. (defvar org-read-date-analyze-forced-year nil)
  15197. (defvar org-read-date-inactive)
  15198. (defvar org-read-date-minibuffer-local-map
  15199. (let* ((map (make-sparse-keymap)))
  15200. (set-keymap-parent map minibuffer-local-map)
  15201. (org-defkey map (kbd ".")
  15202. (lambda () (interactive)
  15203. ;; Are we at the beginning of the prompt?
  15204. (if (looking-back "^[^:]+: "
  15205. (let ((inhibit-field-text-motion t))
  15206. (line-beginning-position)))
  15207. (org-eval-in-calendar '(calendar-goto-today))
  15208. (insert "."))))
  15209. (org-defkey map (kbd "C-.")
  15210. (lambda () (interactive)
  15211. (org-eval-in-calendar '(calendar-goto-today))))
  15212. (org-defkey map [(meta shift left)]
  15213. (lambda () (interactive)
  15214. (org-eval-in-calendar '(calendar-backward-month 1))))
  15215. (org-defkey map [(meta shift right)]
  15216. (lambda () (interactive)
  15217. (org-eval-in-calendar '(calendar-forward-month 1))))
  15218. (org-defkey map [(meta shift up)]
  15219. (lambda () (interactive)
  15220. (org-eval-in-calendar '(calendar-backward-year 1))))
  15221. (org-defkey map [(meta shift down)]
  15222. (lambda () (interactive)
  15223. (org-eval-in-calendar '(calendar-forward-year 1))))
  15224. (org-defkey map [?\e (shift left)]
  15225. (lambda () (interactive)
  15226. (org-eval-in-calendar '(calendar-backward-month 1))))
  15227. (org-defkey map [?\e (shift right)]
  15228. (lambda () (interactive)
  15229. (org-eval-in-calendar '(calendar-forward-month 1))))
  15230. (org-defkey map [?\e (shift up)]
  15231. (lambda () (interactive)
  15232. (org-eval-in-calendar '(calendar-backward-year 1))))
  15233. (org-defkey map [?\e (shift down)]
  15234. (lambda () (interactive)
  15235. (org-eval-in-calendar '(calendar-forward-year 1))))
  15236. (org-defkey map [(shift up)]
  15237. (lambda () (interactive)
  15238. (org-eval-in-calendar '(calendar-backward-week 1))))
  15239. (org-defkey map [(shift down)]
  15240. (lambda () (interactive)
  15241. (org-eval-in-calendar '(calendar-forward-week 1))))
  15242. (org-defkey map [(shift left)]
  15243. (lambda () (interactive)
  15244. (org-eval-in-calendar '(calendar-backward-day 1))))
  15245. (org-defkey map [(shift right)]
  15246. (lambda () (interactive)
  15247. (org-eval-in-calendar '(calendar-forward-day 1))))
  15248. (org-defkey map "!"
  15249. (lambda () (interactive)
  15250. (org-eval-in-calendar '(diary-view-entries))
  15251. (message "")))
  15252. (org-defkey map ">"
  15253. (lambda () (interactive)
  15254. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15255. (org-defkey map "<"
  15256. (lambda () (interactive)
  15257. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15258. (org-defkey map "\C-v"
  15259. (lambda () (interactive)
  15260. (org-eval-in-calendar
  15261. '(calendar-scroll-left-three-months 1))))
  15262. (org-defkey map "\M-v"
  15263. (lambda () (interactive)
  15264. (org-eval-in-calendar
  15265. '(calendar-scroll-right-three-months 1))))
  15266. map)
  15267. "Keymap for minibuffer commands when using `org-read-date'.")
  15268. (defvar org-def)
  15269. (defvar org-defdecode)
  15270. (defvar org-with-time)
  15271. (defvar calendar-setup) ; Dynamically scoped.
  15272. (defun org-read-date (&optional with-time to-time from-string prompt
  15273. default-time default-input inactive)
  15274. "Read a date, possibly a time, and make things smooth for the user.
  15275. The prompt will suggest to enter an ISO date, but you can also enter anything
  15276. which will at least partially be understood by `parse-time-string'.
  15277. Unrecognized parts of the date will default to the current day, month, year,
  15278. hour and minute. If this command is called to replace a timestamp at point,
  15279. or to enter the second timestamp of a range, the default time is taken
  15280. from the existing stamp. Furthermore, the command prefers the future,
  15281. so if you are giving a date where the year is not given, and the day-month
  15282. combination is already past in the current year, it will assume you
  15283. mean next year. For details, see the manual. A few examples:
  15284. 3-2-5 --> 2003-02-05
  15285. feb 15 --> currentyear-02-15
  15286. 2/15 --> currentyear-02-15
  15287. sep 12 9 --> 2009-09-12
  15288. 12:45 --> today 12:45
  15289. 22 sept 0:34 --> currentyear-09-22 0:34
  15290. 12 --> currentyear-currentmonth-12
  15291. Fri --> nearest Friday after today
  15292. -Tue --> last Tuesday
  15293. etc.
  15294. Furthermore you can specify a relative date by giving, as the *first* thing
  15295. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15296. change in days weeks, months, years.
  15297. With a single plus or minus, the date is relative to today. With a double
  15298. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15299. +4d --> four days from today
  15300. +4 --> same as above
  15301. +2w --> two weeks from today
  15302. ++5 --> five days from default date
  15303. The function understands only English month and weekday abbreviations.
  15304. While prompting, a calendar is popped up - you can also select the
  15305. date with the mouse (button 1). The calendar shows a period of three
  15306. months. To scroll it to other months, use the keys `>' and `<'.
  15307. If you don't like the calendar, turn it off with
  15308. (setq org-read-date-popup-calendar nil)
  15309. With optional argument TO-TIME, the date will immediately be converted
  15310. to an internal time.
  15311. With an optional argument WITH-TIME, the prompt will suggest to
  15312. also insert a time. Note that when WITH-TIME is not set, you can
  15313. still enter a time, and this function will inform the calling routine
  15314. about this change. The calling routine may then choose to change the
  15315. format used to insert the time stamp into the buffer to include the time.
  15316. With optional argument FROM-STRING, read from this string instead from
  15317. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15318. the time/date that is used for everything that is not specified by the
  15319. user."
  15320. (require 'parse-time)
  15321. (let* ((org-with-time with-time)
  15322. (org-time-stamp-rounding-minutes
  15323. (if (equal org-with-time '(16))
  15324. '(0 0)
  15325. org-time-stamp-rounding-minutes))
  15326. (org-dcst org-display-custom-times)
  15327. (ct (org-current-time))
  15328. (org-def (or org-overriding-default-time default-time ct))
  15329. (org-defdecode (decode-time org-def))
  15330. (cur-frame (selected-frame))
  15331. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15332. (calendar-setup
  15333. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15334. (calendar-move-hook nil)
  15335. (calendar-view-diary-initially-flag nil)
  15336. (calendar-view-holidays-initially-flag nil)
  15337. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15338. ;; Rationalize `org-def' and `org-defdecode', if required.
  15339. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15340. (setf (nth 2 org-defdecode) -1)
  15341. (setf (nth 1 org-defdecode) 59)
  15342. (setq org-def (apply #'encode-time org-defdecode))
  15343. (setq org-defdecode (decode-time org-def)))
  15344. (let* ((timestr (format-time-string
  15345. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15346. org-def))
  15347. (prompt (concat (if prompt (concat prompt " ") "")
  15348. (format "Date+time [%s]: " timestr))))
  15349. (cond
  15350. (from-string (setq ans from-string))
  15351. (org-read-date-popup-calendar
  15352. (save-excursion
  15353. (save-window-excursion
  15354. (calendar)
  15355. (when (eq calendar-setup 'calendar-only)
  15356. (setq cal-frame
  15357. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15358. (select-frame cal-frame))
  15359. (org-eval-in-calendar '(setq cursor-type nil) t)
  15360. (unwind-protect
  15361. (progn
  15362. (calendar-forward-day (- (time-to-days org-def)
  15363. (calendar-absolute-from-gregorian
  15364. (calendar-current-date))))
  15365. (org-eval-in-calendar nil t)
  15366. (let* ((old-map (current-local-map))
  15367. (map (copy-keymap calendar-mode-map))
  15368. (minibuffer-local-map
  15369. (copy-keymap org-read-date-minibuffer-local-map)))
  15370. (org-defkey map (kbd "RET") 'org-calendar-select)
  15371. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15372. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15373. (unwind-protect
  15374. (progn
  15375. (use-local-map map)
  15376. (setq org-read-date-inactive inactive)
  15377. (add-hook 'post-command-hook 'org-read-date-display)
  15378. (setq org-ans0
  15379. (read-string prompt
  15380. default-input
  15381. 'org-read-date-history
  15382. nil))
  15383. ;; org-ans0: from prompt
  15384. ;; org-ans1: from mouse click
  15385. ;; org-ans2: from calendar motion
  15386. (setq ans
  15387. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15388. (remove-hook 'post-command-hook 'org-read-date-display)
  15389. (use-local-map old-map)
  15390. (when org-read-date-overlay
  15391. (delete-overlay org-read-date-overlay)
  15392. (setq org-read-date-overlay nil)))))
  15393. (bury-buffer "*Calendar*")
  15394. (when cal-frame
  15395. (delete-frame cal-frame)
  15396. (select-frame-set-input-focus cur-frame))))))
  15397. (t ; Naked prompt only
  15398. (unwind-protect
  15399. (setq ans (read-string prompt default-input
  15400. 'org-read-date-history timestr))
  15401. (when org-read-date-overlay
  15402. (delete-overlay org-read-date-overlay)
  15403. (setq org-read-date-overlay nil))))))
  15404. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15405. (when org-read-date-analyze-forced-year
  15406. (message "Year was forced into %s"
  15407. (if org-read-date-force-compatible-dates
  15408. "compatible range (1970-2037)"
  15409. "range representable on this machine"))
  15410. (ding))
  15411. ;; One round trip to get rid of 34th of August and stuff like that....
  15412. (setq final (decode-time (apply 'encode-time final)))
  15413. (setq org-read-date-final-answer ans)
  15414. (if to-time
  15415. (apply 'encode-time final)
  15416. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15417. (format "%04d-%02d-%02d %02d:%02d"
  15418. (nth 5 final) (nth 4 final) (nth 3 final)
  15419. (nth 2 final) (nth 1 final))
  15420. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15421. (defun org-read-date-display ()
  15422. "Display the current date prompt interpretation in the minibuffer."
  15423. (when org-read-date-display-live
  15424. (when org-read-date-overlay
  15425. (delete-overlay org-read-date-overlay))
  15426. (when (minibufferp (current-buffer))
  15427. (save-excursion
  15428. (end-of-line 1)
  15429. (while (not (equal (buffer-substring
  15430. (max (point-min) (- (point) 4)) (point))
  15431. " "))
  15432. (insert " ")))
  15433. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15434. " " (or org-ans1 org-ans2)))
  15435. (org-end-time-was-given nil)
  15436. (f (org-read-date-analyze ans org-def org-defdecode))
  15437. (fmts (if org-dcst
  15438. org-time-stamp-custom-formats
  15439. org-time-stamp-formats))
  15440. (fmt (if (or org-with-time
  15441. (and (boundp 'org-time-was-given) org-time-was-given))
  15442. (cdr fmts)
  15443. (car fmts)))
  15444. (txt (format-time-string fmt (apply 'encode-time f)))
  15445. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15446. (txt (concat "=> " txt)))
  15447. (when (and org-end-time-was-given
  15448. (string-match org-plain-time-of-day-regexp txt))
  15449. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15450. org-end-time-was-given
  15451. (substring txt (match-end 0)))))
  15452. (when org-read-date-analyze-futurep
  15453. (setq txt (concat txt " (=>F)")))
  15454. (setq org-read-date-overlay
  15455. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15456. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15457. (defun org-read-date-analyze (ans def defdecode)
  15458. "Analyze the combined answer of the date prompt."
  15459. ;; FIXME: cleanup and comment
  15460. ;; Pass `current-time' result to `decode-time' (instead of calling
  15461. ;; without arguments) so that only `current-time' has to be
  15462. ;; overriden in tests.
  15463. (let ((org-def def)
  15464. (org-defdecode defdecode)
  15465. (nowdecode (decode-time (current-time)))
  15466. delta deltan deltaw deltadef year month day
  15467. hour minute second wday pm h2 m2 tl wday1
  15468. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15469. (setq org-read-date-analyze-futurep nil
  15470. org-read-date-analyze-forced-year nil)
  15471. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15472. (setq ans "+0"))
  15473. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15474. (setq ans (replace-match "" t t ans)
  15475. deltan (car delta)
  15476. deltaw (nth 1 delta)
  15477. deltadef (nth 2 delta)))
  15478. ;; Check if there is an iso week date in there. If yes, store the
  15479. ;; info and postpone interpreting it until the rest of the parsing
  15480. ;; is done.
  15481. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15482. (setq iso-year (when (match-end 1)
  15483. (org-small-year-to-year
  15484. (string-to-number (match-string 1 ans))))
  15485. iso-weekday (when (match-end 3)
  15486. (string-to-number (match-string 3 ans)))
  15487. iso-week (string-to-number (match-string 2 ans)))
  15488. (setq ans (replace-match "" t t ans)))
  15489. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15490. (when (string-match
  15491. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15492. (setq year (if (match-end 2)
  15493. (string-to-number (match-string 2 ans))
  15494. (progn (setq kill-year t)
  15495. (string-to-number (format-time-string "%Y"))))
  15496. month (string-to-number (match-string 3 ans))
  15497. day (string-to-number (match-string 4 ans)))
  15498. (setq year (org-small-year-to-year year))
  15499. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15500. t nil ans)))
  15501. ;; Help matching dotted european dates
  15502. (when (string-match
  15503. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15504. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15505. (setq kill-year t)
  15506. (string-to-number (format-time-string "%Y")))
  15507. day (string-to-number (match-string 1 ans))
  15508. month (string-to-number (match-string 2 ans))
  15509. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15510. t nil ans)))
  15511. ;; Help matching american dates, like 5/30 or 5/30/7
  15512. (when (string-match
  15513. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15514. (setq year (if (match-end 4)
  15515. (string-to-number (match-string 4 ans))
  15516. (progn (setq kill-year t)
  15517. (string-to-number (format-time-string "%Y"))))
  15518. month (string-to-number (match-string 1 ans))
  15519. day (string-to-number (match-string 2 ans)))
  15520. (setq year (org-small-year-to-year year))
  15521. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15522. t nil ans)))
  15523. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15524. ;; If there is a time with am/pm, and *no* time without it, we convert
  15525. ;; so that matching will be successful.
  15526. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15527. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15528. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15529. (setq hour (string-to-number (match-string 1 ans))
  15530. minute (if (match-end 3)
  15531. (string-to-number (match-string 3 ans))
  15532. 0)
  15533. pm (equal ?p
  15534. (string-to-char (downcase (match-string 4 ans)))))
  15535. (if (and (= hour 12) (not pm))
  15536. (setq hour 0)
  15537. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15538. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15539. t t ans))))
  15540. ;; Check if a time range is given as a duration
  15541. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15542. (setq hour (string-to-number (match-string 1 ans))
  15543. h2 (+ hour (string-to-number (match-string 3 ans)))
  15544. minute (string-to-number (match-string 2 ans))
  15545. m2 (+ minute (if (match-end 5) (string-to-number
  15546. (match-string 5 ans))0)))
  15547. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15548. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15549. t t ans)))
  15550. ;; Check if there is a time range
  15551. (when (boundp 'org-end-time-was-given)
  15552. (setq org-time-was-given nil)
  15553. (when (and (string-match org-plain-time-of-day-regexp ans)
  15554. (match-end 8))
  15555. (setq org-end-time-was-given (match-string 8 ans))
  15556. (setq ans (concat (substring ans 0 (match-beginning 7))
  15557. (substring ans (match-end 7))))))
  15558. (setq tl (parse-time-string ans)
  15559. day (or (nth 3 tl) (nth 3 org-defdecode))
  15560. month
  15561. (cond ((nth 4 tl))
  15562. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15563. ;; Day was specified. Make sure DAY+MONTH
  15564. ;; combination happens in the future.
  15565. ((nth 3 tl)
  15566. (setq futurep t)
  15567. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15568. (nth 4 nowdecode)))
  15569. (t (nth 4 org-defdecode)))
  15570. year
  15571. (cond ((and (not kill-year) (nth 5 tl)))
  15572. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15573. ;; Month was guessed in the future and is at least
  15574. ;; equal to NOWDECODE's. Fix year accordingly.
  15575. (futurep
  15576. (if (or (> month (nth 4 nowdecode))
  15577. (>= day (nth 3 nowdecode)))
  15578. (nth 5 nowdecode)
  15579. (1+ (nth 5 nowdecode))))
  15580. ;; Month was specified. Make sure MONTH+YEAR
  15581. ;; combination happens in the future.
  15582. ((nth 4 tl)
  15583. (setq futurep t)
  15584. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15585. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15586. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15587. (t (nth 5 nowdecode))))
  15588. (t (nth 5 org-defdecode)))
  15589. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15590. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15591. second (or (nth 0 tl) 0)
  15592. wday (nth 6 tl))
  15593. (when (and (eq org-read-date-prefer-future 'time)
  15594. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15595. (equal day (nth 3 nowdecode))
  15596. (equal month (nth 4 nowdecode))
  15597. (equal year (nth 5 nowdecode))
  15598. (nth 2 tl)
  15599. (or (< (nth 2 tl) (nth 2 nowdecode))
  15600. (and (= (nth 2 tl) (nth 2 nowdecode))
  15601. (nth 1 tl)
  15602. (< (nth 1 tl) (nth 1 nowdecode)))))
  15603. (setq day (1+ day)
  15604. futurep t))
  15605. ;; Special date definitions below
  15606. (cond
  15607. (iso-week
  15608. ;; There was an iso week
  15609. (require 'cal-iso)
  15610. (setq futurep nil)
  15611. (setq year (or iso-year year)
  15612. day (or iso-weekday wday 1)
  15613. wday nil ; to make sure that the trigger below does not match
  15614. iso-date (calendar-gregorian-from-absolute
  15615. (calendar-iso-to-absolute
  15616. (list iso-week day year))))
  15617. ; FIXME: Should we also push ISO weeks into the future?
  15618. ; (when (and org-read-date-prefer-future
  15619. ; (not iso-year)
  15620. ; (< (calendar-absolute-from-gregorian iso-date)
  15621. ; (time-to-days (current-time))))
  15622. ; (setq year (1+ year)
  15623. ; iso-date (calendar-gregorian-from-absolute
  15624. ; (calendar-iso-to-absolute
  15625. ; (list iso-week day year)))))
  15626. (setq month (car iso-date)
  15627. year (nth 2 iso-date)
  15628. day (nth 1 iso-date)))
  15629. (deltan
  15630. (setq futurep nil)
  15631. (unless deltadef
  15632. ;; Pass `current-time' result to `decode-time' (instead of
  15633. ;; calling without arguments) so that only `current-time' has
  15634. ;; to be overriden in tests.
  15635. (let ((now (decode-time (current-time))))
  15636. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15637. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15638. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15639. ((equal deltaw "m") (setq month (+ month deltan)))
  15640. ((equal deltaw "y") (setq year (+ year deltan)))))
  15641. ((and wday (not (nth 3 tl)))
  15642. ;; Weekday was given, but no day, so pick that day in the week
  15643. ;; on or after the derived date.
  15644. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15645. (unless (equal wday wday1)
  15646. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15647. (when (and (boundp 'org-time-was-given)
  15648. (nth 2 tl))
  15649. (setq org-time-was-given t))
  15650. (when (< year 100) (setq year (+ 2000 year)))
  15651. ;; Check of the date is representable
  15652. (if org-read-date-force-compatible-dates
  15653. (progn
  15654. (when (< year 1970)
  15655. (setq year 1970 org-read-date-analyze-forced-year t))
  15656. (when (> year 2037)
  15657. (setq year 2037 org-read-date-analyze-forced-year t)))
  15658. (condition-case nil
  15659. (ignore (encode-time second minute hour day month year))
  15660. (error
  15661. (setq year (nth 5 org-defdecode))
  15662. (setq org-read-date-analyze-forced-year t))))
  15663. (setq org-read-date-analyze-futurep futurep)
  15664. (list second minute hour day month year)))
  15665. (defvar parse-time-weekdays)
  15666. (defun org-read-date-get-relative (s today default)
  15667. "Check string S for special relative date string.
  15668. TODAY and DEFAULT are internal times, for today and for a default.
  15669. Return shift list (N what def-flag)
  15670. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15671. N is the number of WHATs to shift.
  15672. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15673. the DEFAULT date rather than TODAY."
  15674. (require 'parse-time)
  15675. (when (and
  15676. (string-match
  15677. (concat
  15678. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15679. "\\([0-9]+\\)?"
  15680. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15681. "\\([ \t]\\|$\\)") s)
  15682. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15683. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15684. (string-to-char (substring (match-string 1 s) -1))
  15685. ?+))
  15686. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15687. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15688. (what (if (match-end 3) (match-string 3 s) "d"))
  15689. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15690. (date (if rel default today))
  15691. (wday (nth 6 (decode-time date)))
  15692. delta)
  15693. (if wday1
  15694. (progn
  15695. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15696. (when (= delta 0) (setq delta 7))
  15697. (when (= dir ?-)
  15698. (setq delta (- delta 7))
  15699. (when (= delta 0) (setq delta -7)))
  15700. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15701. (list delta "d" rel))
  15702. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15703. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15704. "Turn a user-specified date into the internal representation.
  15705. The internal representation needed by the calendar is (month day year).
  15706. This is a wrapper to handle the brain-dead convention in calendar that
  15707. user function argument order change dependent on argument order."
  15708. (pcase calendar-date-style
  15709. (`american (list arg1 arg2 arg3))
  15710. (`european (list arg2 arg1 arg3))
  15711. (`iso (list arg2 arg3 arg1))))
  15712. (defun org-eval-in-calendar (form &optional keepdate)
  15713. "Eval FORM in the calendar window and return to current window.
  15714. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15715. (let ((sf (selected-frame))
  15716. (sw (selected-window)))
  15717. (select-window (get-buffer-window "*Calendar*" t))
  15718. (eval form)
  15719. (when (and (not keepdate) (calendar-cursor-to-date))
  15720. (let* ((date (calendar-cursor-to-date))
  15721. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15722. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15723. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15724. (select-window sw)
  15725. (select-frame-set-input-focus sf)))
  15726. (defun org-calendar-select ()
  15727. "Return to `org-read-date' with the date currently selected.
  15728. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15729. (interactive)
  15730. (when (calendar-cursor-to-date)
  15731. (let* ((date (calendar-cursor-to-date))
  15732. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15733. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15734. (when (active-minibuffer-window) (exit-minibuffer))))
  15735. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15736. "Insert a date stamp for the date given by the internal TIME.
  15737. See `format-time-string' for the format of TIME.
  15738. WITH-HM means use the stamp format that includes the time of the day.
  15739. INACTIVE means use square brackets instead of angular ones, so that the
  15740. stamp will not contribute to the agenda.
  15741. PRE and POST are optional strings to be inserted before and after the
  15742. stamp.
  15743. The command returns the inserted time stamp."
  15744. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15745. stamp)
  15746. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15747. (insert-before-markers (or pre ""))
  15748. (when (listp extra)
  15749. (setq extra (car extra))
  15750. (if (and (stringp extra)
  15751. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15752. (setq extra (format "-%02d:%02d"
  15753. (string-to-number (match-string 1 extra))
  15754. (string-to-number (match-string 2 extra))))
  15755. (setq extra nil)))
  15756. (when extra
  15757. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15758. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15759. (insert-before-markers (or post ""))
  15760. (setq org-last-inserted-timestamp stamp)))
  15761. (defun org-toggle-time-stamp-overlays ()
  15762. "Toggle the use of custom time stamp formats."
  15763. (interactive)
  15764. (setq org-display-custom-times (not org-display-custom-times))
  15765. (unless org-display-custom-times
  15766. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15767. (while (setq p (next-single-property-change p 'display))
  15768. (when (and (get-text-property p 'display)
  15769. (eq (get-text-property p 'face) 'org-date))
  15770. (remove-text-properties
  15771. p (setq p (next-single-property-change p 'display))
  15772. '(display t))))
  15773. (set-buffer-modified-p bmp)))
  15774. (org-restart-font-lock)
  15775. (setq org-table-may-need-update t)
  15776. (if org-display-custom-times
  15777. (message "Time stamps are overlaid with custom format")
  15778. (message "Time stamp overlays removed")))
  15779. (defun org-display-custom-time (beg end)
  15780. "Overlay modified time stamp format over timestamp between BEG and END."
  15781. (let* ((ts (buffer-substring beg end))
  15782. t1 w1 with-hm tf time str w2 (off 0))
  15783. (save-match-data
  15784. (setq t1 (org-parse-time-string ts t))
  15785. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15786. (setq off (- (match-end 0) (match-beginning 0)))))
  15787. (setq end (- end off))
  15788. (setq w1 (- end beg)
  15789. with-hm (and (nth 1 t1) (nth 2 t1))
  15790. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15791. time (org-fix-decoded-time t1)
  15792. str (org-add-props
  15793. (format-time-string
  15794. (substring tf 1 -1) (apply 'encode-time time))
  15795. nil 'mouse-face 'highlight)
  15796. w2 (length str))
  15797. (unless (= w2 w1)
  15798. (add-text-properties (1+ beg) (+ 2 beg)
  15799. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15800. (put-text-property beg end 'display str)))
  15801. (defun org-fix-decoded-time (time)
  15802. "Set 0 instead of nil for the first 6 elements of time.
  15803. Don't touch the rest."
  15804. (let ((n 0))
  15805. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15806. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15807. "Difference between TIMESTAMP-STRING and now in days.
  15808. If SECONDS is non-nil, return the difference in seconds."
  15809. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15810. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15811. (funcall fdiff (current-time)))))
  15812. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15813. "Is the time in TIMESTAMP-STRING close to the current date?"
  15814. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15815. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15816. (not (org-entry-is-done-p))))
  15817. (defun org-get-wdays (ts &optional delay zero-delay)
  15818. "Get the deadline lead time appropriate for timestring TS.
  15819. When DELAY is non-nil, get the delay time for scheduled items
  15820. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15821. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15822. don't try to find the delay cookie in the scheduled timestamp."
  15823. (let ((tv (if delay org-scheduled-delay-days
  15824. org-deadline-warning-days)))
  15825. (cond
  15826. ((or (and delay (< tv 0))
  15827. (and delay zero-delay (<= tv 0))
  15828. (and (not delay) (<= tv 0)))
  15829. ;; Enforce this value no matter what
  15830. (- tv))
  15831. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15832. ;; lead time is specified.
  15833. (floor (* (string-to-number (match-string 1 ts))
  15834. (cdr (assoc (match-string 2 ts)
  15835. '(("d" . 1) ("w" . 7)
  15836. ("m" . 30.4) ("y" . 365.25)
  15837. ("h" . 0.041667)))))))
  15838. ;; go for the default.
  15839. (t tv))))
  15840. (defun org-calendar-select-mouse (ev)
  15841. "Return to `org-read-date' with the date currently selected.
  15842. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15843. (interactive "e")
  15844. (mouse-set-point ev)
  15845. (when (calendar-cursor-to-date)
  15846. (let* ((date (calendar-cursor-to-date))
  15847. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15848. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15849. (when (active-minibuffer-window) (exit-minibuffer))))
  15850. (defun org-check-deadlines (ndays)
  15851. "Check if there are any deadlines due or past due.
  15852. A deadline is considered due if it happens within `org-deadline-warning-days'
  15853. days from today's date. If the deadline appears in an entry marked DONE,
  15854. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15855. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15856. are shown."
  15857. (interactive "P")
  15858. (let* ((org-warn-days
  15859. (cond
  15860. ((equal ndays '(4)) 100000)
  15861. (ndays (prefix-numeric-value ndays))
  15862. (t (abs org-deadline-warning-days))))
  15863. (case-fold-search nil)
  15864. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15865. (callback
  15866. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15867. (message "%d deadlines past-due or due within %d days"
  15868. (org-occur regexp nil callback)
  15869. org-warn-days)))
  15870. (defsubst org-re-timestamp (type)
  15871. "Return a regexp for timestamp TYPE.
  15872. Allowed values for TYPE are:
  15873. all: all timestamps
  15874. active: only active timestamps (<...>)
  15875. inactive: only inactive timestamps ([...])
  15876. scheduled: only scheduled timestamps
  15877. deadline: only deadline timestamps
  15878. closed: only closed time-stamps
  15879. When TYPE is nil, fall back on returning a regexp that matches
  15880. both scheduled and deadline timestamps."
  15881. (cl-case type
  15882. (all org-ts-regexp-both)
  15883. (active org-ts-regexp)
  15884. (inactive org-ts-regexp-inactive)
  15885. (scheduled org-scheduled-time-regexp)
  15886. (deadline org-deadline-time-regexp)
  15887. (closed org-closed-time-regexp)
  15888. (otherwise
  15889. (concat "\\<"
  15890. (regexp-opt (list org-deadline-string org-scheduled-string))
  15891. " *<\\([^>]+\\)>"))))
  15892. (defun org-check-before-date (d)
  15893. "Check if there are deadlines or scheduled entries before date D."
  15894. (interactive (list (org-read-date)))
  15895. (let* ((case-fold-search nil)
  15896. (regexp (org-re-timestamp org-ts-type))
  15897. (ts-type org-ts-type)
  15898. (callback
  15899. (lambda ()
  15900. (let ((match (match-string 1)))
  15901. (and (if (memq ts-type '(active inactive all))
  15902. (eq (org-element-type (save-excursion
  15903. (backward-char)
  15904. (org-element-context)))
  15905. 'timestamp)
  15906. (org-at-planning-p))
  15907. (time-less-p
  15908. (org-time-string-to-time match)
  15909. (org-time-string-to-time d)))))))
  15910. (message "%d entries before %s"
  15911. (org-occur regexp nil callback)
  15912. d)))
  15913. (defun org-check-after-date (d)
  15914. "Check if there are deadlines or scheduled entries after date D."
  15915. (interactive (list (org-read-date)))
  15916. (let* ((case-fold-search nil)
  15917. (regexp (org-re-timestamp org-ts-type))
  15918. (ts-type org-ts-type)
  15919. (callback
  15920. (lambda ()
  15921. (let ((match (match-string 1)))
  15922. (and (if (memq ts-type '(active inactive all))
  15923. (eq (org-element-type (save-excursion
  15924. (backward-char)
  15925. (org-element-context)))
  15926. 'timestamp)
  15927. (org-at-planning-p))
  15928. (not (time-less-p
  15929. (org-time-string-to-time match)
  15930. (org-time-string-to-time d))))))))
  15931. (message "%d entries after %s"
  15932. (org-occur regexp nil callback)
  15933. d)))
  15934. (defun org-check-dates-range (start-date end-date)
  15935. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15936. (interactive (list (org-read-date nil nil nil "Range starts")
  15937. (org-read-date nil nil nil "Range end")))
  15938. (let ((case-fold-search nil)
  15939. (regexp (org-re-timestamp org-ts-type))
  15940. (callback
  15941. (let ((type org-ts-type))
  15942. (lambda ()
  15943. (let ((match (match-string 1)))
  15944. (and
  15945. (if (memq type '(active inactive all))
  15946. (eq (org-element-type (save-excursion
  15947. (backward-char)
  15948. (org-element-context)))
  15949. 'timestamp)
  15950. (org-at-planning-p))
  15951. (not (time-less-p
  15952. (org-time-string-to-time match)
  15953. (org-time-string-to-time start-date)))
  15954. (time-less-p
  15955. (org-time-string-to-time match)
  15956. (org-time-string-to-time end-date))))))))
  15957. (message "%d entries between %s and %s"
  15958. (org-occur regexp nil callback) start-date end-date)))
  15959. (defun org-evaluate-time-range (&optional to-buffer)
  15960. "Evaluate a time range by computing the difference between start and end.
  15961. Normally the result is just printed in the echo area, but with prefix arg
  15962. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15963. If the time range is actually in a table, the result is inserted into the
  15964. next column.
  15965. For time difference computation, a year is assumed to be exactly 365
  15966. days in order to avoid rounding problems."
  15967. (interactive "P")
  15968. (or
  15969. (org-clock-update-time-maybe)
  15970. (save-excursion
  15971. (unless (org-at-date-range-p t)
  15972. (goto-char (point-at-bol))
  15973. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15974. (unless (org-at-date-range-p t)
  15975. (user-error "Not at a time-stamp range, and none found in current line")))
  15976. (let* ((ts1 (match-string 1))
  15977. (ts2 (match-string 2))
  15978. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15979. (match-end (match-end 0))
  15980. (time1 (org-time-string-to-time ts1))
  15981. (time2 (org-time-string-to-time ts2))
  15982. (t1 (float-time time1))
  15983. (t2 (float-time time2))
  15984. (diff (abs (- t2 t1)))
  15985. (negative (< (- t2 t1) 0))
  15986. ;; (ys (floor (* 365 24 60 60)))
  15987. (ds (* 24 60 60))
  15988. (hs (* 60 60))
  15989. (fy "%dy %dd %02d:%02d")
  15990. (fy1 "%dy %dd")
  15991. (fd "%dd %02d:%02d")
  15992. (fd1 "%dd")
  15993. (fh "%02d:%02d")
  15994. y d h m align)
  15995. (if havetime
  15996. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15997. y 0
  15998. d (floor (/ diff ds)) diff (mod diff ds)
  15999. h (floor (/ diff hs)) diff (mod diff hs)
  16000. m (floor (/ diff 60)))
  16001. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16002. y 0
  16003. d (floor (+ (/ diff ds) 0.5))
  16004. h 0 m 0))
  16005. (if (not to-buffer)
  16006. (message "%s" (org-make-tdiff-string y d h m))
  16007. (if (org-at-table-p)
  16008. (progn
  16009. (goto-char match-end)
  16010. (setq align t)
  16011. (and (looking-at " *|") (goto-char (match-end 0))))
  16012. (goto-char match-end))
  16013. (when (looking-at
  16014. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16015. (replace-match ""))
  16016. (when negative (insert " -"))
  16017. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16018. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16019. (insert " " (format fh h m))))
  16020. (when align (org-table-align))
  16021. (message "Time difference inserted")))))
  16022. (defun org-make-tdiff-string (y d h m)
  16023. (let ((fmt "")
  16024. (l nil))
  16025. (when (> y 0)
  16026. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16027. (push y l))
  16028. (when (> d 0)
  16029. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16030. (push d l))
  16031. (when (> h 0)
  16032. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16033. (push h l))
  16034. (when (> m 0)
  16035. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16036. (push m l))
  16037. (apply 'format fmt (nreverse l))))
  16038. (defun org-time-string-to-time (s &optional buffer pos)
  16039. "Convert a timestamp string into internal time."
  16040. (condition-case errdata
  16041. (apply 'encode-time (org-parse-time-string s))
  16042. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16043. s (if (not (and buffer pos))
  16044. ""
  16045. (format-message " at %d in buffer `%s'" pos buffer))
  16046. (cdr errdata)))))
  16047. (defun org-time-string-to-seconds (s)
  16048. "Convert a timestamp string to a number of seconds."
  16049. (float-time (org-time-string-to-time s)))
  16050. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16051. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16052. "Convert time stamp S to an absolute day number.
  16053. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16054. stamp, get the closest date to DAYNR. If PREFER is
  16055. `past' (respectively `future') return a date past (respectively
  16056. after) or equal to DAYNR.
  16057. POS is the location of time stamp S, as a buffer position in
  16058. BUFFER.
  16059. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16060. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16061. signalled."
  16062. (cond
  16063. ((string-match "\\`%%\\((.*)\\)" s)
  16064. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16065. ;; only able to match individual dates. If it fails, raise an
  16066. ;; error.
  16067. (if (and daynr
  16068. (org-diary-sexp-entry
  16069. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16070. daynr
  16071. (signal 'org-diary-sexp-no-match (list s))))
  16072. (daynr (org-closest-date s daynr prefer))
  16073. (t (time-to-days
  16074. (condition-case errdata
  16075. (apply #'encode-time (org-parse-time-string s))
  16076. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16077. s
  16078. (if (not (and buffer pos)) ""
  16079. (format-message " at %d in buffer `%s'" pos buffer))
  16080. (cdr errdata))))))))
  16081. (defun org-days-to-iso-week (days)
  16082. "Return the iso week number."
  16083. (require 'cal-iso)
  16084. (car (calendar-iso-from-absolute days)))
  16085. (defun org-small-year-to-year (year)
  16086. "Convert 2-digit years into 4-digit years.
  16087. YEAR is expanded into one of the 30 next years, if possible, or
  16088. into a past one. Any year larger than 99 is returned unchanged."
  16089. (if (>= year 100) year
  16090. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16091. (century (/ current 100))
  16092. (offset (- year (% current 100))))
  16093. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16094. ((> offset -70) (+ (* century 100) year))
  16095. (t (+ (* (1+ century) 100) year))))))
  16096. (defun org-time-from-absolute (d)
  16097. "Return the time corresponding to date D.
  16098. D may be an absolute day number, or a calendar-type list (month day year)."
  16099. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16100. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16101. (defvar org-agenda-current-date)
  16102. (defun org-calendar-holiday ()
  16103. "List of holidays, for Diary display in Org mode."
  16104. (require 'holidays)
  16105. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16106. (and hl (mapconcat #'identity hl "; "))))
  16107. (defun org-diary-sexp-entry (sexp entry d)
  16108. "Process a SEXP diary ENTRY for date D."
  16109. (require 'diary-lib)
  16110. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16111. ;; dynamically.
  16112. (let* ((sexp `(let ((entry ,entry)
  16113. (date ',d))
  16114. ,(car (read-from-string sexp))))
  16115. (result (if calendar-debug-sexp (eval sexp)
  16116. (condition-case nil
  16117. (eval sexp)
  16118. (error
  16119. (beep)
  16120. (message "Bad sexp at line %d in %s: %s"
  16121. (org-current-line)
  16122. (buffer-file-name) sexp)
  16123. (sleep-for 2))))))
  16124. (cond ((stringp result) (split-string result "; "))
  16125. ((and (consp result)
  16126. (not (consp (cdr result)))
  16127. (stringp (cdr result))) (cdr result))
  16128. ((and (consp result)
  16129. (stringp (car result))) result)
  16130. (result entry))))
  16131. (defun org-diary-to-ical-string (frombuf)
  16132. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16133. This uses the icalendar.el library."
  16134. (let* ((tmpdir temporary-file-directory)
  16135. (tmpfile (make-temp-name
  16136. (expand-file-name "orgics" tmpdir)))
  16137. buf rtn b e)
  16138. (with-current-buffer frombuf
  16139. (icalendar-export-region (point-min) (point-max) tmpfile)
  16140. (setq buf (find-buffer-visiting tmpfile))
  16141. (set-buffer buf)
  16142. (goto-char (point-min))
  16143. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16144. (setq b (match-beginning 0)))
  16145. (goto-char (point-max))
  16146. (when (re-search-backward "^END:VEVENT" nil t)
  16147. (setq e (match-end 0)))
  16148. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16149. (kill-buffer buf)
  16150. (delete-file tmpfile)
  16151. rtn))
  16152. (defun org-closest-date (start current prefer)
  16153. "Return closest date to CURRENT starting from START.
  16154. CURRENT and START are both time stamps.
  16155. When PREFER is `past', return a date that is either CURRENT or
  16156. past. When PREFER is `future', return a date that is either
  16157. CURRENT or future.
  16158. Only time stamps with a repeater are modified. Any other time
  16159. stamp stay unchanged. In any case, return value is an absolute
  16160. day number."
  16161. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16162. ;; No repeater. Do not shift time stamp.
  16163. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16164. (let ((value (string-to-number (match-string 1 start)))
  16165. (type (match-string 2 start)))
  16166. (if (= 0 value)
  16167. ;; Repeater with a 0-value is considered as void.
  16168. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16169. (let* ((base (org-date-to-gregorian start))
  16170. (target (org-date-to-gregorian current))
  16171. (sday (calendar-absolute-from-gregorian base))
  16172. (cday (calendar-absolute-from-gregorian target))
  16173. n1 n2)
  16174. ;; If START is already past CURRENT, just return START.
  16175. (if (<= cday sday) sday
  16176. ;; Compute closest date before (N1) and closest date past
  16177. ;; (N2) CURRENT.
  16178. (pcase type
  16179. ("h"
  16180. (let ((missing-hours
  16181. (mod (+ (- (* 24 (- cday sday))
  16182. (nth 2 (org-parse-time-string start)))
  16183. org-extend-today-until)
  16184. value)))
  16185. (setf n1 (if (= missing-hours 0) cday
  16186. (- cday (1+ (/ missing-hours 24)))))
  16187. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16188. ((or "d" "w")
  16189. (let ((value (if (equal type "w") (* 7 value) value)))
  16190. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16191. (setf n2 (+ n1 value))))
  16192. ("m"
  16193. (let* ((add-months
  16194. (lambda (d n)
  16195. ;; Add N months to gregorian date D, i.e.,
  16196. ;; a list (MONTH DAY YEAR). Return a valid
  16197. ;; gregorian date.
  16198. (let ((m (+ (nth 0 d) n)))
  16199. (list (mod m 12)
  16200. (nth 1 d)
  16201. (+ (/ m 12) (nth 2 d))))))
  16202. (months ; Complete months to TARGET.
  16203. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16204. (- (nth 0 target) (nth 0 base))
  16205. ;; If START's day is greater than
  16206. ;; TARGET's, remove incomplete month.
  16207. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16208. value)
  16209. value))
  16210. (before (funcall add-months base months)))
  16211. (setf n1 (calendar-absolute-from-gregorian before))
  16212. (setf n2
  16213. (calendar-absolute-from-gregorian
  16214. (funcall add-months before value)))))
  16215. (_
  16216. (let* ((d (nth 1 base))
  16217. (m (nth 0 base))
  16218. (y (nth 2 base))
  16219. (years ; Complete years to TARGET.
  16220. (* (/ (- (nth 2 target)
  16221. y
  16222. ;; If START's month and day are
  16223. ;; greater than TARGET's, remove
  16224. ;; incomplete year.
  16225. (if (or (> (nth 0 target) m)
  16226. (and (= (nth 0 target) m)
  16227. (> (nth 1 target) d)))
  16228. 0
  16229. 1))
  16230. value)
  16231. value))
  16232. (before (list m d (+ y years))))
  16233. (setf n1 (calendar-absolute-from-gregorian before))
  16234. (setf n2 (calendar-absolute-from-gregorian
  16235. (list m d (+ (nth 2 before) value)))))))
  16236. ;; Handle PREFER parameter, if any.
  16237. (cond
  16238. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16239. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16240. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16241. (defun org-date-to-gregorian (d)
  16242. "Turn any specification of date D into a Gregorian date for the calendar."
  16243. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16244. ((and (listp d) (= (length d) 3)) d)
  16245. ((stringp d)
  16246. (let ((d (org-parse-time-string d)))
  16247. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16248. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16249. (defun org-parse-time-string (s &optional nodefault)
  16250. "Parse the standard Org time string.
  16251. This should be a lot faster than the normal `parse-time-string'.
  16252. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16253. hour and minute fields will be nil if not given."
  16254. (cond ((string-match org-ts-regexp0 s)
  16255. (list 0
  16256. (when (or (match-beginning 8) (not nodefault))
  16257. (string-to-number (or (match-string 8 s) "0")))
  16258. (when (or (match-beginning 7) (not nodefault))
  16259. (string-to-number (or (match-string 7 s) "0")))
  16260. (string-to-number (match-string 4 s))
  16261. (string-to-number (match-string 3 s))
  16262. (string-to-number (match-string 2 s))
  16263. nil nil nil))
  16264. ((string-match "^<[^>]+>$" s)
  16265. (decode-time (seconds-to-time (org-matcher-time s))))
  16266. (t (error "Not a standard Org time string: %s" s))))
  16267. (defun org-timestamp-up (&optional arg)
  16268. "Increase the date item at the cursor by one.
  16269. If the cursor is on the year, change the year. If it is on the month,
  16270. the day or the time, change that.
  16271. With prefix ARG, change by that many units."
  16272. (interactive "p")
  16273. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16274. (defun org-timestamp-down (&optional arg)
  16275. "Decrease the date item at the cursor by one.
  16276. If the cursor is on the year, change the year. If it is on the month,
  16277. the day or the time, change that.
  16278. With prefix ARG, change by that many units."
  16279. (interactive "p")
  16280. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16281. (defun org-timestamp-up-day (&optional arg)
  16282. "Increase the date in the time stamp by one day.
  16283. With prefix ARG, change that many days."
  16284. (interactive "p")
  16285. (if (and (not (org-at-timestamp-p t))
  16286. (org-at-heading-p))
  16287. (org-todo 'up)
  16288. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16289. (defun org-timestamp-down-day (&optional arg)
  16290. "Decrease the date in the time stamp by one day.
  16291. With prefix ARG, change that many days."
  16292. (interactive "p")
  16293. (if (and (not (org-at-timestamp-p t))
  16294. (org-at-heading-p))
  16295. (org-todo 'down)
  16296. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16297. (defun org-at-timestamp-p (&optional inactive-ok)
  16298. "Non-nil if point is inside a timestamp.
  16299. When optional argument INACTIVE-OK is non-nil, also consider
  16300. inactive timestamps.
  16301. When this function returns a non-nil value, match data is set
  16302. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16303. INACTIVE-OK.
  16304. Return the position of the point as a symbol among `bracket',
  16305. `after', `year', `month', `hour', `minute', `day' or a number of
  16306. character from the last know part of the time stamp.
  16307. This function checks context and only return non-nil for valid
  16308. time stamps. If you need to match anything looking like a time
  16309. stamp, or if you are sure about the context, consider using
  16310. `org-in-regexp', e.g.,
  16311. (org-in-regexp org-ts-regexp)
  16312. Unlike to `org-element-context', the function recognizes time
  16313. stamps in properties drawers, planning lines and clocks."
  16314. (interactive)
  16315. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16316. (pos (point))
  16317. (match
  16318. (let ((boundaries (org-in-regexp tsr)))
  16319. (save-match-data
  16320. (cond ((null boundaries) nil)
  16321. ((org-at-planning-p))
  16322. ((org-at-property-p))
  16323. ;; CLOCK lines only contain inactive time-stamps.
  16324. ((and inactive-ok (org-at-clock-log-p)))
  16325. (t
  16326. (eq 'timestamp
  16327. (save-excursion
  16328. (when (= pos (cdr boundaries)) (forward-char -1))
  16329. (org-element-type (org-element-context))))))))))
  16330. (cond
  16331. ((not match) nil)
  16332. ((= pos (match-beginning 0)) 'bracket)
  16333. ;; Distinguish location right before the closing bracket from
  16334. ;; right after it.
  16335. ((= pos (1- (match-end 0))) 'bracket)
  16336. ((= pos (match-end 0)) 'after)
  16337. ((org-pos-in-match-range pos 2) 'year)
  16338. ((org-pos-in-match-range pos 3) 'month)
  16339. ((org-pos-in-match-range pos 7) 'hour)
  16340. ((org-pos-in-match-range pos 8) 'minute)
  16341. ((or (org-pos-in-match-range pos 4)
  16342. (org-pos-in-match-range pos 5)) 'day)
  16343. ((and (> pos (or (match-end 8) (match-end 5)))
  16344. (< pos (match-end 0)))
  16345. (- pos (or (match-end 8) (match-end 5))))
  16346. (t 'day))))
  16347. (defun org-toggle-timestamp-type ()
  16348. "Toggle the type (<active> or [inactive]) of a time stamp."
  16349. (interactive)
  16350. (when (org-at-timestamp-p t)
  16351. (let ((beg (match-beginning 0)) (end (match-end 0))
  16352. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16353. (save-excursion
  16354. (goto-char beg)
  16355. (while (re-search-forward "[][<>]" end t)
  16356. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16357. t t)))
  16358. (message "Timestamp is now %sactive"
  16359. (if (equal (char-after beg) ?<) "" "in")))))
  16360. (defun org-at-clock-log-p ()
  16361. "Non-nil if point is on a clock log line."
  16362. (and (org-match-line org-clock-line-re)
  16363. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16364. (defvar org-clock-history) ; defined in org-clock.el
  16365. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16366. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16367. "Change the date in the time stamp at point.
  16368. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16369. `year', `minute', `second'. If WHAT is not given, the cursor position
  16370. in the timestamp determines what will be changed.
  16371. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16372. (let ((origin (point))
  16373. (timestamp? (org-at-timestamp-p t))
  16374. origin-cat
  16375. with-hm inactive
  16376. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16377. extra rem
  16378. ts time time0 fixnext clrgx)
  16379. (unless timestamp? (user-error "Not at a timestamp"))
  16380. (if (and (not what) (eq timestamp? 'bracket))
  16381. (org-toggle-timestamp-type)
  16382. ;; Point isn't on brackets. Remember the part of the time-stamp
  16383. ;; the point was in. Indeed, size of time-stamps may change,
  16384. ;; but point must be kept in the same category nonetheless.
  16385. (setq origin-cat timestamp?)
  16386. (when (and (not what) (not (eq timestamp? 'day))
  16387. org-display-custom-times
  16388. (get-text-property (point) 'display)
  16389. (not (get-text-property (1- (point)) 'display)))
  16390. (setq timestamp? 'day))
  16391. (setq timestamp? (or what timestamp?)
  16392. inactive (= (char-after (match-beginning 0)) ?\[)
  16393. ts (match-string 0))
  16394. (replace-match "")
  16395. (when (string-match
  16396. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16397. ts)
  16398. (setq extra (match-string 1 ts))
  16399. (when suppress-tmp-delay
  16400. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16401. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16402. (setq with-hm t))
  16403. (setq time0 (org-parse-time-string ts))
  16404. (when (and updown
  16405. (eq timestamp? 'minute)
  16406. (not current-prefix-arg))
  16407. ;; This looks like s-up and s-down. Change by one rounding step.
  16408. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16409. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16410. (setcar (cdr time0) (+ (nth 1 time0)
  16411. (if (> n 0) (- rem) (- dm rem))))))
  16412. (setq time
  16413. (apply #'encode-time
  16414. (or (car time0) 0)
  16415. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16416. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16417. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16418. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16419. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16420. (nthcdr 6 time0)))
  16421. (when (and (memq timestamp? '(hour minute))
  16422. extra
  16423. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16424. (setq extra (org-modify-ts-extra
  16425. extra
  16426. (if (eq timestamp? 'hour) 2 5)
  16427. n dm)))
  16428. (when (integerp timestamp?)
  16429. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16430. (when (eq what 'calendar)
  16431. (let ((cal-date (org-get-date-from-calendar)))
  16432. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16433. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16434. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16435. (setcar time0 (or (car time0) 0))
  16436. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16437. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16438. (setq time (apply 'encode-time time0))))
  16439. ;; Insert the new time-stamp, and ensure point stays in the same
  16440. ;; category as before (i.e. not after the last position in that
  16441. ;; category).
  16442. (let ((pos (point)))
  16443. ;; Stay before inserted string. `save-excursion' is of no use.
  16444. (setq org-last-changed-timestamp
  16445. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16446. (goto-char pos))
  16447. (save-match-data
  16448. (looking-at org-ts-regexp3)
  16449. (goto-char
  16450. (pcase origin-cat
  16451. ;; `day' category ends before `hour' if any, or at the end
  16452. ;; of the day name.
  16453. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16454. (`hour (min (match-end 7) origin))
  16455. (`minute (min (1- (match-end 8)) origin))
  16456. ((pred integerp) (min (1- (match-end 0)) origin))
  16457. ;; Point was right after the time-stamp. However, the
  16458. ;; time-stamp length might have changed, so refer to
  16459. ;; (match-end 0) instead.
  16460. (`after (match-end 0))
  16461. ;; `year' and `month' have both fixed size: point couldn't
  16462. ;; have moved into another part.
  16463. (_ origin))))
  16464. ;; Update clock if on a CLOCK line.
  16465. (org-clock-update-time-maybe)
  16466. ;; Maybe adjust the closest clock in `org-clock-history'
  16467. (when org-clock-adjust-closest
  16468. (if (not (and (org-at-clock-log-p)
  16469. (< 1 (length (delq nil (mapcar 'marker-position
  16470. org-clock-history))))))
  16471. (message "No clock to adjust")
  16472. (cond ((save-excursion ; fix previous clock?
  16473. (re-search-backward org-ts-regexp0 nil t)
  16474. (looking-back (concat org-clock-string " \\[")
  16475. (line-beginning-position)))
  16476. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16477. ((save-excursion ; fix next clock?
  16478. (re-search-backward org-ts-regexp0 nil t)
  16479. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16480. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16481. (save-window-excursion
  16482. ;; Find closest clock to point, adjust the previous/next one in history
  16483. (let* ((p (save-excursion (org-back-to-heading t)))
  16484. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16485. (clfixnth
  16486. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16487. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16488. (if (not clfixpos)
  16489. (message "No clock to adjust")
  16490. (save-excursion
  16491. (org-goto-marker-or-bmk clfixpos)
  16492. (org-show-subtree)
  16493. (when (re-search-forward clrgx nil t)
  16494. (goto-char (match-beginning 1))
  16495. (let (org-clock-adjust-closest)
  16496. (org-timestamp-change n timestamp? updown))
  16497. (message "Clock adjusted in %s for heading: %s"
  16498. (file-name-nondirectory (buffer-file-name))
  16499. (org-get-heading t t)))))))))
  16500. ;; Try to recenter the calendar window, if any.
  16501. (when (and org-calendar-follow-timestamp-change
  16502. (get-buffer-window "*Calendar*" t)
  16503. (memq timestamp? '(day month year)))
  16504. (org-recenter-calendar (time-to-days time))))))
  16505. (defun org-modify-ts-extra (s pos n dm)
  16506. "Change the different parts of the lead-time and repeat fields in timestamp."
  16507. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16508. ng h m new rem)
  16509. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16510. (cond
  16511. ((or (org-pos-in-match-range pos 2)
  16512. (org-pos-in-match-range pos 3))
  16513. (setq m (string-to-number (match-string 3 s))
  16514. h (string-to-number (match-string 2 s)))
  16515. (if (org-pos-in-match-range pos 2)
  16516. (setq h (+ h n))
  16517. (setq n (* dm (with-no-warnings (signum n))))
  16518. (unless (= 0 (setq rem (% m dm)))
  16519. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16520. (setq m (+ m n)))
  16521. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16522. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16523. (setq h (mod h 24))
  16524. (setq ng 1 new (format "-%02d:%02d" h m)))
  16525. ((org-pos-in-match-range pos 6)
  16526. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16527. ((org-pos-in-match-range pos 5)
  16528. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16529. ((org-pos-in-match-range pos 9)
  16530. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16531. ((org-pos-in-match-range pos 8)
  16532. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16533. (when ng
  16534. (setq s (concat
  16535. (substring s 0 (match-beginning ng))
  16536. new
  16537. (substring s (match-end ng))))))
  16538. s))
  16539. (defun org-recenter-calendar (d)
  16540. "If the calendar is visible, recenter it to date D."
  16541. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16542. (when cwin
  16543. (let ((calendar-move-hook nil))
  16544. (with-selected-window cwin
  16545. (calendar-goto-date
  16546. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16547. (defun org-goto-calendar (&optional arg)
  16548. "Go to the Emacs calendar at the current date.
  16549. If there is a time stamp in the current line, go to that date.
  16550. A prefix ARG can be used to force the current date."
  16551. (interactive "P")
  16552. (let ((tsr org-ts-regexp) diff
  16553. (calendar-move-hook nil)
  16554. (calendar-view-holidays-initially-flag nil)
  16555. (calendar-view-diary-initially-flag nil))
  16556. (when (or (org-at-timestamp-p)
  16557. (save-excursion
  16558. (beginning-of-line 1)
  16559. (looking-at (concat ".*" tsr))))
  16560. (let ((d1 (time-to-days (current-time)))
  16561. (d2 (time-to-days
  16562. (org-time-string-to-time (match-string 1)))))
  16563. (setq diff (- d2 d1))))
  16564. (calendar)
  16565. (calendar-goto-today)
  16566. (when (and diff (not arg)) (calendar-forward-day diff))))
  16567. (defun org-get-date-from-calendar ()
  16568. "Return a list (month day year) of date at point in calendar."
  16569. (with-current-buffer "*Calendar*"
  16570. (save-match-data
  16571. (calendar-cursor-to-date))))
  16572. (defun org-date-from-calendar ()
  16573. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16574. If there is already a time stamp at the cursor position, update it."
  16575. (interactive)
  16576. (if (org-at-timestamp-p t)
  16577. (org-timestamp-change 0 'calendar)
  16578. (let ((cal-date (org-get-date-from-calendar)))
  16579. (org-insert-time-stamp
  16580. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16581. (defcustom org-effort-durations
  16582. `(("min" . 1)
  16583. ("h" . 60)
  16584. ("d" . ,(* 60 8))
  16585. ("w" . ,(* 60 8 5))
  16586. ("m" . ,(* 60 8 5 4))
  16587. ("y" . ,(* 60 8 5 40)))
  16588. "Conversion factor to minutes for an effort modifier.
  16589. Each entry has the form (MODIFIER . MINUTES).
  16590. In an effort string, a number followed by MODIFIER is multiplied
  16591. by the specified number of MINUTES to obtain an effort in
  16592. minutes.
  16593. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16594. effort string \"2hours\" is equivalent to 120 minutes."
  16595. :group 'org-agenda
  16596. :version "26.1"
  16597. :package-version '(Org . "8.3")
  16598. :type '(alist :key-type (string :tag "Modifier")
  16599. :value-type (number :tag "Minutes")))
  16600. (defcustom org-image-actual-width t
  16601. "Should we use the actual width of images when inlining them?
  16602. When set to t, always use the image width.
  16603. When set to a number, use imagemagick (when available) to set
  16604. the image's width to this value.
  16605. When set to a number in a list, try to get the width from any
  16606. #+ATTR.* keyword if it matches a width specification like
  16607. #+ATTR_HTML: :width 300px
  16608. and fall back on that number if none is found.
  16609. When set to nil, try to get the width from an #+ATTR.* keyword
  16610. and fall back on the original width if none is found.
  16611. This requires Emacs >= 24.1, build with imagemagick support."
  16612. :group 'org-appearance
  16613. :version "24.4"
  16614. :package-version '(Org . "8.0")
  16615. :type '(choice
  16616. (const :tag "Use the image width" t)
  16617. (integer :tag "Use a number of pixels")
  16618. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16619. (const :tag "Use #+ATTR* or don't resize" nil)))
  16620. (defcustom org-agenda-inhibit-startup nil
  16621. "Inhibit startup when preparing agenda buffers.
  16622. When this variable is t, the initialization of the Org agenda
  16623. buffers is inhibited: e.g. the visibility state is not set, the
  16624. tables are not re-aligned, etc."
  16625. :type 'boolean
  16626. :version "24.3"
  16627. :group 'org-agenda)
  16628. (defcustom org-agenda-ignore-properties nil
  16629. "Avoid updating text properties when building the agenda.
  16630. Properties are used to prepare buffers for effort estimates,
  16631. appointments, statistics and subtree-local categories.
  16632. If you don't use these in the agenda, you can add them to this
  16633. list and agenda building will be a bit faster.
  16634. The value is a list, with zero or more of the symbols `effort', `appt',
  16635. `stats' or `category'."
  16636. :type '(set :greedy t
  16637. (const effort)
  16638. (const appt)
  16639. (const stats)
  16640. (const category))
  16641. :version "26.1"
  16642. :package-version '(Org . "8.3")
  16643. :group 'org-agenda)
  16644. ;;;; Files
  16645. (defun org-save-all-org-buffers ()
  16646. "Save all Org buffers without user confirmation."
  16647. (interactive)
  16648. (message "Saving all Org buffers...")
  16649. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16650. (when (featurep 'org-id) (org-id-locations-save))
  16651. (message "Saving all Org buffers... done"))
  16652. (defun org-revert-all-org-buffers ()
  16653. "Revert all Org buffers.
  16654. Prompt for confirmation when there are unsaved changes.
  16655. Be sure you know what you are doing before letting this function
  16656. overwrite your changes.
  16657. This function is useful in a setup where one tracks org files
  16658. with a version control system, to revert on one machine after pulling
  16659. changes from another. I believe the procedure must be like this:
  16660. 1. M-x org-save-all-org-buffers
  16661. 2. Pull changes from the other machine, resolve conflicts
  16662. 3. M-x org-revert-all-org-buffers"
  16663. (interactive)
  16664. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16665. (user-error "Abort"))
  16666. (save-excursion
  16667. (save-window-excursion
  16668. (dolist (b (buffer-list))
  16669. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16670. (with-current-buffer b buffer-file-name))
  16671. (pop-to-buffer-same-window b)
  16672. (revert-buffer t 'no-confirm)))
  16673. (when (and (featurep 'org-id) org-id-track-globally)
  16674. (org-id-locations-load)))))
  16675. ;;;; Agenda files
  16676. ;;;###autoload
  16677. (defun org-switchb (&optional arg)
  16678. "Switch between Org buffers.
  16679. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16680. With `\\[universal-argument] \\[universal-argument]' \
  16681. prefix, restrict available buffers to agenda files."
  16682. (interactive "P")
  16683. (let ((blist (org-buffer-list
  16684. (cond ((equal arg '(4)) 'files)
  16685. ((equal arg '(16)) 'agenda)))))
  16686. (pop-to-buffer-same-window
  16687. (completing-read "Org buffer: "
  16688. (mapcar #'list (mapcar #'buffer-name blist))
  16689. nil t))))
  16690. (defun org-buffer-list (&optional predicate exclude-tmp)
  16691. "Return a list of Org buffers.
  16692. PREDICATE can be `export', `files' or `agenda'.
  16693. export restrict the list to Export buffers.
  16694. files restrict the list to buffers visiting Org files.
  16695. agenda restrict the list to buffers visiting agenda files.
  16696. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16697. (let* ((bfn nil)
  16698. (agenda-files (and (eq predicate 'agenda)
  16699. (mapcar 'file-truename (org-agenda-files t))))
  16700. (filter
  16701. (cond
  16702. ((eq predicate 'files)
  16703. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16704. ((eq predicate 'export)
  16705. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16706. ((eq predicate 'agenda)
  16707. (lambda (b)
  16708. (with-current-buffer b
  16709. (and (derived-mode-p 'org-mode)
  16710. (setq bfn (buffer-file-name b))
  16711. (member (file-truename bfn) agenda-files)))))
  16712. (t (lambda (b) (with-current-buffer b
  16713. (or (derived-mode-p 'org-mode)
  16714. (string-match "\\*Org .*Export"
  16715. (buffer-name b)))))))))
  16716. (delq nil
  16717. (mapcar
  16718. (lambda(b)
  16719. (if (and (funcall filter b)
  16720. (or (not exclude-tmp)
  16721. (not (string-match "tmp" (buffer-name b)))))
  16722. b
  16723. nil))
  16724. (buffer-list)))))
  16725. (defun org-agenda-files (&optional unrestricted archives)
  16726. "Get the list of agenda files.
  16727. Optional UNRESTRICTED means return the full list even if a restriction
  16728. is currently in place.
  16729. When ARCHIVES is t, include all archive files that are really being
  16730. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16731. `org-agenda-archives-mode' is t."
  16732. (let ((files
  16733. (cond
  16734. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16735. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16736. ((listp org-agenda-files) org-agenda-files)
  16737. (t (error "Invalid value of `org-agenda-files'")))))
  16738. (setq files (apply 'append
  16739. (mapcar (lambda (f)
  16740. (if (file-directory-p f)
  16741. (directory-files
  16742. f t org-agenda-file-regexp)
  16743. (list f)))
  16744. files)))
  16745. (when org-agenda-skip-unavailable-files
  16746. (setq files (delq nil
  16747. (mapcar (function
  16748. (lambda (file)
  16749. (and (file-readable-p file) file)))
  16750. files))))
  16751. (when (or (eq archives t)
  16752. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16753. (setq files (org-add-archive-files files)))
  16754. files))
  16755. (defun org-agenda-file-p (&optional file)
  16756. "Return non-nil, if FILE is an agenda file.
  16757. If FILE is omitted, use the file associated with the current
  16758. buffer."
  16759. (let ((fname (or file (buffer-file-name))))
  16760. (and fname
  16761. (member (file-truename fname)
  16762. (mapcar #'file-truename (org-agenda-files t))))))
  16763. (defun org-edit-agenda-file-list ()
  16764. "Edit the list of agenda files.
  16765. Depending on setup, this either uses customize to edit the variable
  16766. `org-agenda-files', or it visits the file that is holding the list. In the
  16767. latter case, the buffer is set up in a way that saving it automatically kills
  16768. the buffer and restores the previous window configuration."
  16769. (interactive)
  16770. (if (stringp org-agenda-files)
  16771. (let ((cw (current-window-configuration)))
  16772. (find-file org-agenda-files)
  16773. (setq-local org-window-configuration cw)
  16774. (add-hook 'after-save-hook
  16775. (lambda ()
  16776. (set-window-configuration
  16777. (prog1 org-window-configuration
  16778. (kill-buffer (current-buffer))))
  16779. (org-install-agenda-files-menu)
  16780. (message "New agenda file list installed"))
  16781. nil 'local)
  16782. (message "%s" (substitute-command-keys
  16783. "Edit list and finish with \\[save-buffer]")))
  16784. (customize-variable 'org-agenda-files)))
  16785. (defun org-store-new-agenda-file-list (list)
  16786. "Set new value for the agenda file list and save it correctly."
  16787. (if (stringp org-agenda-files)
  16788. (let ((fe (org-read-agenda-file-list t)) b u)
  16789. (while (setq b (find-buffer-visiting org-agenda-files))
  16790. (kill-buffer b))
  16791. (with-temp-file org-agenda-files
  16792. (insert
  16793. (mapconcat
  16794. (lambda (f) ;; Keep un-expanded entries.
  16795. (if (setq u (assoc f fe))
  16796. (cdr u)
  16797. f))
  16798. list "\n")
  16799. "\n")))
  16800. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16801. (org-insert-mode-line-in-empty-file nil))
  16802. (setq org-agenda-files list)
  16803. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16804. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16805. "Read the list of agenda files from a file.
  16806. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16807. filenames, used by `org-store-new-agenda-file-list' to write back
  16808. un-expanded file names."
  16809. (when (file-directory-p org-agenda-files)
  16810. (error "`org-agenda-files' cannot be a single directory"))
  16811. (when (stringp org-agenda-files)
  16812. (with-temp-buffer
  16813. (insert-file-contents org-agenda-files)
  16814. (mapcar
  16815. (lambda (f)
  16816. (let ((e (expand-file-name (substitute-in-file-name f)
  16817. org-directory)))
  16818. (if pair-with-expansion
  16819. (cons e f)
  16820. e)))
  16821. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16822. ;;;###autoload
  16823. (defun org-cycle-agenda-files ()
  16824. "Cycle through the files in `org-agenda-files'.
  16825. If the current buffer visits an agenda file, find the next one in the list.
  16826. If the current buffer does not, find the first agenda file."
  16827. (interactive)
  16828. (let* ((fs (or (org-agenda-files t)
  16829. (user-error "No agenda files")))
  16830. (files (copy-sequence fs))
  16831. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16832. file)
  16833. (when tcf
  16834. (while (and (setq file (pop files))
  16835. (not (equal (file-truename file) tcf)))))
  16836. (find-file (car (or files fs)))
  16837. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16838. (defun org-agenda-file-to-front (&optional to-end)
  16839. "Move/add the current file to the top of the agenda file list.
  16840. If the file is not present in the list, it is added to the front. If it is
  16841. present, it is moved there. With optional argument TO-END, add/move to the
  16842. end of the list."
  16843. (interactive "P")
  16844. (let ((org-agenda-skip-unavailable-files nil)
  16845. (file-alist (mapcar (lambda (x)
  16846. (cons (file-truename x) x))
  16847. (org-agenda-files t)))
  16848. (ctf (file-truename
  16849. (or buffer-file-name
  16850. (user-error "Please save the current buffer to a file"))))
  16851. x had)
  16852. (setq x (assoc ctf file-alist) had x)
  16853. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16854. (if to-end
  16855. (setq file-alist (append (delq x file-alist) (list x)))
  16856. (setq file-alist (cons x (delq x file-alist))))
  16857. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16858. (org-install-agenda-files-menu)
  16859. (message "File %s to %s of agenda file list"
  16860. (if had "moved" "added") (if to-end "end" "front"))))
  16861. (defun org-remove-file (&optional file)
  16862. "Remove current file from the list of files in variable `org-agenda-files'.
  16863. These are the files which are being checked for agenda entries.
  16864. Optional argument FILE means use this file instead of the current."
  16865. (interactive)
  16866. (let* ((org-agenda-skip-unavailable-files nil)
  16867. (file (or file buffer-file-name
  16868. (user-error "Current buffer does not visit a file")))
  16869. (true-file (file-truename file))
  16870. (afile (abbreviate-file-name file))
  16871. (files (delq nil (mapcar
  16872. (lambda (x)
  16873. (unless (equal true-file
  16874. (file-truename x))
  16875. x))
  16876. (org-agenda-files t)))))
  16877. (if (not (= (length files) (length (org-agenda-files t))))
  16878. (progn
  16879. (org-store-new-agenda-file-list files)
  16880. (org-install-agenda-files-menu)
  16881. (message "Removed from Org Agenda list: %s" afile))
  16882. (message "File was not in list: %s (not removed)" afile))))
  16883. (defun org-file-menu-entry (file)
  16884. (vector file (list 'find-file file) t))
  16885. (defun org-check-agenda-file (file)
  16886. "Make sure FILE exists. If not, ask user what to do."
  16887. (unless (file-exists-p file)
  16888. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16889. (abbreviate-file-name file))
  16890. (let ((r (downcase (read-char-exclusive))))
  16891. (cond
  16892. ((equal r ?r)
  16893. (org-remove-file file)
  16894. (throw 'nextfile t))
  16895. (t (user-error "Abort"))))))
  16896. (defun org-get-agenda-file-buffer (file)
  16897. "Get an agenda buffer visiting FILE.
  16898. If the buffer needs to be created, add it to the list of buffers
  16899. which might be released later."
  16900. (let ((buf (org-find-base-buffer-visiting file)))
  16901. (if buf
  16902. buf ; just return it
  16903. ;; Make a new buffer and remember it
  16904. (setq buf (find-file-noselect file))
  16905. (when buf (push buf org-agenda-new-buffers))
  16906. buf)))
  16907. (defun org-release-buffers (blist)
  16908. "Release all buffers in list, asking the user for confirmation when needed.
  16909. When a buffer is unmodified, it is just killed. When modified, it is saved
  16910. \(if the user agrees) and then killed."
  16911. (let (file)
  16912. (dolist (buf blist)
  16913. (setq file (buffer-file-name buf))
  16914. (when (and (buffer-modified-p buf)
  16915. file
  16916. (y-or-n-p (format "Save file %s? " file)))
  16917. (with-current-buffer buf (save-buffer)))
  16918. (kill-buffer buf))))
  16919. (defun org-agenda-prepare-buffers (files)
  16920. "Create buffers for all agenda files, protect archived trees and comments."
  16921. (interactive)
  16922. (let ((pa '(:org-archived t))
  16923. (pc '(:org-comment t))
  16924. (pall '(:org-archived t :org-comment t))
  16925. (inhibit-read-only t)
  16926. (org-inhibit-startup org-agenda-inhibit-startup)
  16927. (rea (concat ":" org-archive-tag ":"))
  16928. re pos)
  16929. (setq org-tag-alist-for-agenda nil
  16930. org-tag-groups-alist-for-agenda nil)
  16931. (save-excursion
  16932. (save-restriction
  16933. (dolist (file files)
  16934. (catch 'nextfile
  16935. (if (bufferp file)
  16936. (set-buffer file)
  16937. (org-check-agenda-file file)
  16938. (set-buffer (org-get-agenda-file-buffer file)))
  16939. (widen)
  16940. (org-set-regexps-and-options 'tags-only)
  16941. (setq pos (point))
  16942. (or (memq 'category org-agenda-ignore-properties)
  16943. (org-refresh-category-properties))
  16944. (or (memq 'stats org-agenda-ignore-properties)
  16945. (org-refresh-stats-properties))
  16946. (or (memq 'effort org-agenda-ignore-properties)
  16947. (org-refresh-effort-properties))
  16948. (or (memq 'appt org-agenda-ignore-properties)
  16949. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16950. (setq org-todo-keywords-for-agenda
  16951. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16952. (setq org-done-keywords-for-agenda
  16953. (append org-done-keywords-for-agenda org-done-keywords))
  16954. (setq org-todo-keyword-alist-for-agenda
  16955. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16956. (setq org-tag-alist-for-agenda
  16957. (org-uniquify
  16958. (append org-tag-alist-for-agenda
  16959. org-current-tag-alist)))
  16960. ;; Merge current file's tag groups into global
  16961. ;; `org-tag-groups-alist-for-agenda'.
  16962. (when org-group-tags
  16963. (dolist (alist org-tag-groups-alist)
  16964. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16965. (if old
  16966. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16967. (push alist org-tag-groups-alist-for-agenda)))))
  16968. (org-with-silent-modifications
  16969. (save-excursion
  16970. (remove-text-properties (point-min) (point-max) pall)
  16971. (when org-agenda-skip-archived-trees
  16972. (goto-char (point-min))
  16973. (while (re-search-forward rea nil t)
  16974. (when (org-at-heading-p t)
  16975. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16976. (goto-char (point-min))
  16977. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16978. (while (re-search-forward re nil t)
  16979. (when (save-match-data (org-in-commented-heading-p t))
  16980. (add-text-properties
  16981. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16982. (goto-char pos)))))
  16983. (setq org-todo-keywords-for-agenda
  16984. (org-uniquify org-todo-keywords-for-agenda))
  16985. (setq org-todo-keyword-alist-for-agenda
  16986. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16987. ;;;; CDLaTeX minor mode
  16988. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16989. "Keymap for the minor `org-cdlatex-mode'.")
  16990. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16991. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16992. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16993. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16994. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16995. (defvar org-cdlatex-texmathp-advice-is-done nil
  16996. "Flag remembering if we have applied the advice to texmathp already.")
  16997. (define-minor-mode org-cdlatex-mode
  16998. "Toggle the minor `org-cdlatex-mode'.
  16999. This mode supports entering LaTeX environment and math in LaTeX fragments
  17000. in Org mode.
  17001. \\{org-cdlatex-mode-map}"
  17002. nil " OCDL" nil
  17003. (when org-cdlatex-mode
  17004. (require 'cdlatex)
  17005. (run-hooks 'cdlatex-mode-hook)
  17006. (cdlatex-compute-tables))
  17007. (unless org-cdlatex-texmathp-advice-is-done
  17008. (setq org-cdlatex-texmathp-advice-is-done t)
  17009. (defadvice texmathp (around org-math-always-on activate)
  17010. "Always return t in Org buffers.
  17011. This is because we want to insert math symbols without dollars even outside
  17012. the LaTeX math segments. If Org mode thinks that point is actually inside
  17013. an embedded LaTeX fragment, let `texmathp' do its job.
  17014. `\\[org-cdlatex-mode-map]'"
  17015. (interactive)
  17016. (let (p)
  17017. (cond
  17018. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17019. ((eq this-command 'cdlatex-math-symbol)
  17020. (setq ad-return-value t
  17021. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17022. (t
  17023. (let ((p (org-inside-LaTeX-fragment-p)))
  17024. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17025. (setq ad-return-value t
  17026. texmathp-why '("Org mode embedded math" . 0))
  17027. (when p ad-do-it)))))))))
  17028. (defun turn-on-org-cdlatex ()
  17029. "Unconditionally turn on `org-cdlatex-mode'."
  17030. (org-cdlatex-mode 1))
  17031. (defun org-try-cdlatex-tab ()
  17032. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17033. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17034. - inside a LaTeX fragment, or
  17035. - after the first word in a line, where an abbreviation expansion could
  17036. insert a LaTeX environment."
  17037. (when org-cdlatex-mode
  17038. (cond
  17039. ;; Before any word on the line: No expansion possible.
  17040. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17041. ;; Just after first word on the line: Expand it. Make sure it
  17042. ;; cannot happen on headlines, though.
  17043. ((save-excursion
  17044. (skip-chars-backward "a-zA-Z0-9*")
  17045. (skip-chars-backward " \t")
  17046. (and (bolp) (not (org-at-heading-p))))
  17047. (cdlatex-tab) t)
  17048. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17049. (defun org-cdlatex-underscore-caret (&optional _arg)
  17050. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17051. Revert to the normal definition outside of these fragments."
  17052. (interactive "P")
  17053. (if (org-inside-LaTeX-fragment-p)
  17054. (call-interactively 'cdlatex-sub-superscript)
  17055. (let (org-cdlatex-mode)
  17056. (call-interactively (key-binding (vector last-input-event))))))
  17057. (defun org-cdlatex-math-modify (&optional _arg)
  17058. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17059. Revert to the normal definition outside of these fragments."
  17060. (interactive "P")
  17061. (if (org-inside-LaTeX-fragment-p)
  17062. (call-interactively 'cdlatex-math-modify)
  17063. (let (org-cdlatex-mode)
  17064. (call-interactively (key-binding (vector last-input-event))))))
  17065. (defun org-cdlatex-environment-indent (&optional environment item)
  17066. "Execute `cdlatex-environment' and indent the inserted environment.
  17067. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17068. The inserted environment is indented to current indentation
  17069. unless point is at the beginning of the line, in which the
  17070. environment remains unintended."
  17071. (interactive)
  17072. ;; cdlatex-environment always return nil. Therefore, capture output
  17073. ;; first and determine if an environment was selected.
  17074. (let* ((beg (point-marker))
  17075. (end (copy-marker (point) t))
  17076. (inserted (progn
  17077. (ignore-errors (cdlatex-environment environment item))
  17078. (< beg end)))
  17079. ;; Figure out how many lines to move forward after the
  17080. ;; environment has been inserted.
  17081. (lines (when inserted
  17082. (save-excursion
  17083. (- (cl-loop while (< beg (point))
  17084. with x = 0
  17085. do (forward-line -1)
  17086. (cl-incf x)
  17087. finally return x)
  17088. (if (progn (goto-char beg)
  17089. (and (progn (skip-chars-forward " \t") (eolp))
  17090. (progn (skip-chars-backward " \t") (bolp))))
  17091. 1 0)))))
  17092. (env (org-trim (delete-and-extract-region beg end))))
  17093. (when inserted
  17094. ;; Get indentation of next line unless at column 0.
  17095. (let ((ind (if (bolp) 0
  17096. (save-excursion
  17097. (org-return-indent)
  17098. (prog1 (org-get-indentation)
  17099. (when (progn (skip-chars-forward " \t") (eolp))
  17100. (delete-region beg (point)))))))
  17101. (bol (progn (skip-chars-backward " \t") (bolp))))
  17102. ;; Insert a newline before environment unless at column zero
  17103. ;; to "escape" the current line. Insert a newline if
  17104. ;; something is one the same line as \end{ENVIRONMENT}.
  17105. (insert
  17106. (concat (unless bol "\n") env
  17107. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17108. (unless (zerop ind)
  17109. (save-excursion
  17110. (goto-char beg)
  17111. (while (< (point) end)
  17112. (unless (eolp) (indent-line-to ind))
  17113. (forward-line))))
  17114. (goto-char beg)
  17115. (forward-line lines)
  17116. (indent-line-to ind)))
  17117. (set-marker beg nil)
  17118. (set-marker end nil)))
  17119. ;;;; LaTeX fragments
  17120. (defun org-inside-LaTeX-fragment-p ()
  17121. "Test if point is inside a LaTeX fragment.
  17122. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17123. sequence appearing also before point.
  17124. Even though the matchers for math are configurable, this function assumes
  17125. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17126. delimiters are skipped when they have been removed by customization.
  17127. The return value is nil, or a cons cell with the delimiter and the
  17128. position of this delimiter.
  17129. This function does a reasonably good job, but can locally be fooled by
  17130. for example currency specifications. For example it will assume being in
  17131. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17132. fragments that are properly closed, but during editing, we have to live
  17133. with the uncertainty caused by missing closing delimiters. This function
  17134. looks only before point, not after."
  17135. (catch 'exit
  17136. (let ((pos (point))
  17137. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17138. (lim (progn
  17139. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17140. (point)))
  17141. dd-on str (start 0) m re)
  17142. (goto-char pos)
  17143. (when dodollar
  17144. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17145. re (nth 1 (assoc "$" org-latex-regexps)))
  17146. (while (string-match re str start)
  17147. (cond
  17148. ((= (match-end 0) (length str))
  17149. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17150. ((= (match-end 0) (- (length str) 5))
  17151. (throw 'exit nil))
  17152. (t (setq start (match-end 0))))))
  17153. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17154. (goto-char pos)
  17155. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17156. (and (match-beginning 2) (throw 'exit nil))
  17157. ;; count $$
  17158. (while (re-search-backward "\\$\\$" lim t)
  17159. (setq dd-on (not dd-on)))
  17160. (goto-char pos)
  17161. (when dd-on (cons "$$" m))))))
  17162. (defun org-inside-latex-macro-p ()
  17163. "Is point inside a LaTeX macro or its arguments?"
  17164. (save-match-data
  17165. (org-in-regexp
  17166. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17167. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17168. "Build an overlay between BEG and END using IMAGE file.
  17169. Argument IMAGETYPE is the extension of the displayed image,
  17170. as a string. It defaults to \"png\"."
  17171. (let ((ov (make-overlay beg end))
  17172. (imagetype (or (intern imagetype) 'png)))
  17173. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17174. (overlay-put ov 'evaporate t)
  17175. (overlay-put ov
  17176. 'modification-hooks
  17177. (list (lambda (o _flag _beg _end &optional _l)
  17178. (delete-overlay o))))
  17179. (overlay-put ov
  17180. 'display
  17181. (list 'image :type imagetype :file image :ascent 'center))))
  17182. (defun org--list-latex-overlays (&optional beg end)
  17183. "List all Org LaTeX overlays in current buffer.
  17184. Limit to overlays between BEG and END when those are provided."
  17185. (cl-remove-if-not
  17186. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17187. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17188. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17189. "Remove all overlays with LaTeX fragment images in current buffer.
  17190. When optional arguments BEG and END are non-nil, remove all
  17191. overlays between them instead. Return a non-nil value when some
  17192. overlays were removed, nil otherwise."
  17193. (let ((overlays (org--list-latex-overlays beg end)))
  17194. (mapc #'delete-overlay overlays)
  17195. overlays))
  17196. (defun org-toggle-latex-fragment (&optional arg)
  17197. "Preview the LaTeX fragment at point, or all locally or globally.
  17198. If the cursor is on a LaTeX fragment, create the image and overlay
  17199. it over the source code, if there is none. Remove it otherwise.
  17200. If there is no fragment at point, display all fragments in the
  17201. current section.
  17202. With prefix ARG, preview or clear image for all fragments in the
  17203. current subtree or in the whole buffer when used before the first
  17204. headline. With a prefix ARG `\\[universal-argument] \
  17205. \\[universal-argument]' preview or clear images
  17206. for all fragments in the buffer."
  17207. (interactive "P")
  17208. (when (display-graphic-p)
  17209. (catch 'exit
  17210. (save-excursion
  17211. (let (beg end msg)
  17212. (cond
  17213. ((or (equal arg '(16))
  17214. (and (equal arg '(4))
  17215. (org-with-limited-levels (org-before-first-heading-p))))
  17216. (if (org-remove-latex-fragment-image-overlays)
  17217. (progn (message "LaTeX fragments images removed from buffer")
  17218. (throw 'exit nil))
  17219. (setq msg "Creating images for buffer...")))
  17220. ((equal arg '(4))
  17221. (org-with-limited-levels (org-back-to-heading t))
  17222. (setq beg (point))
  17223. (setq end (progn (org-end-of-subtree t) (point)))
  17224. (if (org-remove-latex-fragment-image-overlays beg end)
  17225. (progn
  17226. (message "LaTeX fragment images removed from subtree")
  17227. (throw 'exit nil))
  17228. (setq msg "Creating images for subtree...")))
  17229. ((let ((datum (org-element-context)))
  17230. (when (memq (org-element-type datum)
  17231. '(latex-environment latex-fragment))
  17232. (setq beg (org-element-property :begin datum))
  17233. (setq end (org-element-property :end datum))
  17234. (if (org-remove-latex-fragment-image-overlays beg end)
  17235. (progn (message "LaTeX fragment image removed")
  17236. (throw 'exit nil))
  17237. (setq msg "Creating image...")))))
  17238. (t
  17239. (org-with-limited-levels
  17240. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17241. (outline-previous-heading)
  17242. (point)))
  17243. (setq end (progn (outline-next-heading) (point)))
  17244. (if (org-remove-latex-fragment-image-overlays beg end)
  17245. (progn
  17246. (message "LaTeX fragment images removed from section")
  17247. (throw 'exit nil))
  17248. (setq msg "Creating images for section...")))))
  17249. (let ((file (buffer-file-name (buffer-base-buffer))))
  17250. (org-format-latex
  17251. (concat org-preview-latex-image-directory "org-ltximg")
  17252. beg end
  17253. ;; Emacs cannot overlay images from remote hosts. Create
  17254. ;; it in `temporary-file-directory' instead.
  17255. (if (or (not file) (file-remote-p file))
  17256. temporary-file-directory
  17257. default-directory)
  17258. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17259. (message (concat msg "done")))))))
  17260. (defun org-format-latex
  17261. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17262. "Replace LaTeX fragments with links to an image.
  17263. The function takes care of creating the replacement image.
  17264. Only consider fragments between BEG and END when those are
  17265. provided.
  17266. When optional argument OVERLAYS is non-nil, display the image on
  17267. top of the fragment instead of replacing it.
  17268. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17269. Some of the options can be changed using the variable
  17270. `org-format-latex-options', which see."
  17271. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17272. (unless (eq processing-type 'verbatim)
  17273. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17274. (cnt 0)
  17275. checkdir-flag)
  17276. (goto-char (or beg (point-min)))
  17277. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17278. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17279. (overlay-recenter (or end (point-max))))
  17280. (while (re-search-forward math-regexp end t)
  17281. (unless (and overlays
  17282. (eq (get-char-property (point) 'org-overlay-type)
  17283. 'org-latex-overlay))
  17284. (let* ((context (org-element-context))
  17285. (type (org-element-type context)))
  17286. (when (memq type '(latex-environment latex-fragment))
  17287. (let ((block-type (eq type 'latex-environment))
  17288. (value (org-element-property :value context))
  17289. (beg (org-element-property :begin context))
  17290. (end (save-excursion
  17291. (goto-char (org-element-property :end context))
  17292. (skip-chars-backward " \r\t\n")
  17293. (point))))
  17294. (cond
  17295. ((eq processing-type 'mathjax)
  17296. ;; Prepare for MathJax processing.
  17297. (if (not (string-match "\\`\\$\\$?" value))
  17298. (goto-char end)
  17299. (delete-region beg end)
  17300. (if (string= (match-string 0 value) "$$")
  17301. (insert "\\[" (substring value 2 -2) "\\]")
  17302. (insert "\\(" (substring value 1 -1) "\\)"))))
  17303. ((assq processing-type org-preview-latex-process-alist)
  17304. ;; Process to an image.
  17305. (cl-incf cnt)
  17306. (goto-char beg)
  17307. (let* ((processing-info
  17308. (cdr (assq processing-type org-preview-latex-process-alist)))
  17309. (face (face-at-point))
  17310. ;; Get the colors from the face at point.
  17311. (fg
  17312. (let ((color (plist-get org-format-latex-options
  17313. :foreground)))
  17314. (if (and forbuffer (eq color 'auto))
  17315. (face-attribute face :foreground nil 'default)
  17316. color)))
  17317. (bg
  17318. (let ((color (plist-get org-format-latex-options
  17319. :background)))
  17320. (if (and forbuffer (eq color 'auto))
  17321. (face-attribute face :background nil 'default)
  17322. color)))
  17323. (hash (sha1 (prin1-to-string
  17324. (list org-format-latex-header
  17325. org-latex-default-packages-alist
  17326. org-latex-packages-alist
  17327. org-format-latex-options
  17328. forbuffer value fg bg))))
  17329. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17330. (absprefix (expand-file-name prefix dir))
  17331. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17332. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17333. (sep (and block-type "\n\n"))
  17334. (link (concat sep "[[file:" linkfile "]]" sep))
  17335. (options
  17336. (org-combine-plists
  17337. org-format-latex-options
  17338. `(:foreground ,fg :background ,bg))))
  17339. (when msg (message msg cnt))
  17340. (unless checkdir-flag ; Ensure the directory exists.
  17341. (setq checkdir-flag t)
  17342. (let ((todir (file-name-directory absprefix)))
  17343. (unless (file-directory-p todir)
  17344. (make-directory todir t))))
  17345. (unless (file-exists-p movefile)
  17346. (org-create-formula-image
  17347. value movefile options forbuffer processing-type))
  17348. (if overlays
  17349. (progn
  17350. (dolist (o (overlays-in beg end))
  17351. (when (eq (overlay-get o 'org-overlay-type)
  17352. 'org-latex-overlay)
  17353. (delete-overlay o)))
  17354. (org--format-latex-make-overlay beg end movefile imagetype)
  17355. (goto-char end))
  17356. (delete-region beg end)
  17357. (insert
  17358. (org-add-props link
  17359. (list 'org-latex-src
  17360. (replace-regexp-in-string "\"" "" value)
  17361. 'org-latex-src-embed-type
  17362. (if block-type 'paragraph 'character)))))))
  17363. ((eq processing-type 'mathml)
  17364. ;; Process to MathML.
  17365. (unless (org-format-latex-mathml-available-p)
  17366. (user-error "LaTeX to MathML converter not configured"))
  17367. (cl-incf cnt)
  17368. (when msg (message msg cnt))
  17369. (goto-char beg)
  17370. (delete-region beg end)
  17371. (insert (org-format-latex-as-mathml
  17372. value block-type prefix dir)))
  17373. (t
  17374. (error "Unknown conversion process %s for LaTeX fragments"
  17375. processing-type)))))))))))
  17376. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17377. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17378. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17379. sucessful, return the portion between \"<math...> </math>\"
  17380. elements otherwise return nil. When MATHML-FILE is specified,
  17381. write the results in to that file. When invoked as an
  17382. interactive command, prompt for LATEX-FRAG, with initial value
  17383. set to the current active region and echo the results for user
  17384. inspection."
  17385. (interactive (list (let ((frag (when (org-region-active-p)
  17386. (buffer-substring-no-properties
  17387. (region-beginning) (region-end)))))
  17388. (read-string "LaTeX Fragment: " frag nil frag))))
  17389. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17390. (let* ((tmp-in-file
  17391. (let ((file (file-relative-name
  17392. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17393. (write-region latex-frag nil file)
  17394. file))
  17395. (tmp-out-file (file-relative-name
  17396. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17397. (cmd (format-spec
  17398. org-latex-to-mathml-convert-command
  17399. `((?j . ,(and org-latex-to-mathml-jar-file
  17400. (shell-quote-argument
  17401. (expand-file-name
  17402. org-latex-to-mathml-jar-file))))
  17403. (?I . ,(shell-quote-argument tmp-in-file))
  17404. (?i . ,latex-frag)
  17405. (?o . ,(shell-quote-argument tmp-out-file)))))
  17406. mathml shell-command-output)
  17407. (when (called-interactively-p 'any)
  17408. (unless (org-format-latex-mathml-available-p)
  17409. (user-error "LaTeX to MathML converter not configured")))
  17410. (message "Running %s" cmd)
  17411. (setq shell-command-output (shell-command-to-string cmd))
  17412. (setq mathml
  17413. (when (file-readable-p tmp-out-file)
  17414. (with-current-buffer (find-file-noselect tmp-out-file t)
  17415. (goto-char (point-min))
  17416. (when (re-search-forward
  17417. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17418. (regexp-quote
  17419. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17420. nil t)
  17421. (prog1 (match-string 0) (kill-buffer))))))
  17422. (cond
  17423. (mathml
  17424. (setq mathml
  17425. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17426. (when mathml-file
  17427. (write-region mathml nil mathml-file))
  17428. (when (called-interactively-p 'any)
  17429. (message mathml)))
  17430. ((message "LaTeX to MathML conversion failed")
  17431. (message shell-command-output)))
  17432. (delete-file tmp-in-file)
  17433. (when (file-exists-p tmp-out-file)
  17434. (delete-file tmp-out-file))
  17435. mathml))
  17436. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17437. prefix &optional dir)
  17438. "Use `org-create-math-formula' but check local cache first."
  17439. (let* ((absprefix (expand-file-name prefix dir))
  17440. (print-length nil) (print-level nil)
  17441. (formula-id (concat
  17442. "formula-"
  17443. (sha1
  17444. (prin1-to-string
  17445. (list latex-frag
  17446. org-latex-to-mathml-convert-command)))))
  17447. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17448. (formula-cache-dir (file-name-directory formula-cache)))
  17449. (unless (file-directory-p formula-cache-dir)
  17450. (make-directory formula-cache-dir t))
  17451. (unless (file-exists-p formula-cache)
  17452. (org-create-math-formula latex-frag formula-cache))
  17453. (if (file-exists-p formula-cache)
  17454. ;; Successful conversion. Return the link to MathML file.
  17455. (org-add-props
  17456. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17457. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17458. 'org-latex-src-embed-type (if latex-frag-type
  17459. 'paragraph 'character)))
  17460. ;; Failed conversion. Return the LaTeX fragment verbatim
  17461. latex-frag)))
  17462. (defun org--get-display-dpi ()
  17463. "Get the DPI of the display.
  17464. The function assumes that the display has the same pixel width in
  17465. the horizontal and vertical directions."
  17466. (if (display-graphic-p)
  17467. (round (/ (display-pixel-height)
  17468. (/ (display-mm-height) 25.4)))
  17469. (error "Attempt to calculate the dpi of a non-graphic display")))
  17470. (defun org-create-formula-image
  17471. (string tofile options buffer &optional processing-type)
  17472. "Create an image from LaTeX source using external processes.
  17473. The LaTeX STRING is saved to a temporary LaTeX file, then
  17474. converted to an image file by process PROCESSING-TYPE defined in
  17475. `org-preview-latex-process-alist'. A nil value defaults to
  17476. `org-preview-latex-default-process'.
  17477. The generated image file is eventually moved to TOFILE.
  17478. The OPTIONS argument controls the size, foreground color and
  17479. background color of the generated image.
  17480. When BUFFER non-nil, this function is used for LaTeX previewing.
  17481. Otherwise, it is used to deal with LaTeX snippets showed in
  17482. a HTML file."
  17483. (let* ((processing-type (or processing-type
  17484. org-preview-latex-default-process))
  17485. (processing-info
  17486. (cdr (assq processing-type org-preview-latex-process-alist)))
  17487. (programs (plist-get processing-info :programs))
  17488. (error-message (or (plist-get processing-info :message) ""))
  17489. (use-xcolor (plist-get processing-info :use-xcolor))
  17490. (image-input-type (plist-get processing-info :image-input-type))
  17491. (image-output-type (plist-get processing-info :image-output-type))
  17492. (post-clean (or (plist-get processing-info :post-clean)
  17493. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17494. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17495. (latex-header
  17496. (or (plist-get processing-info :latex-header)
  17497. (org-latex-make-preamble
  17498. (org-export-get-environment (org-export-get-backend 'latex))
  17499. org-format-latex-header
  17500. 'snippet)))
  17501. (latex-compiler (plist-get processing-info :latex-compiler))
  17502. (image-converter (plist-get processing-info :image-converter))
  17503. (tmpdir temporary-file-directory)
  17504. (texfilebase (make-temp-name
  17505. (expand-file-name "orgtex" tmpdir)))
  17506. (texfile (concat texfilebase ".tex"))
  17507. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17508. '(1.0 . 1.0)))
  17509. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17510. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17511. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17512. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17513. "Black"))
  17514. (bg (or (plist-get options (if buffer :background :html-background))
  17515. "Transparent"))
  17516. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17517. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17518. (dolist (program programs)
  17519. (org-check-external-command program error-message))
  17520. (if use-xcolor
  17521. (progn (if (eq fg 'default)
  17522. (setq fg (org-latex-color :foreground))
  17523. (setq fg (org-latex-color-format fg)))
  17524. (if (eq bg 'default)
  17525. (setq bg (org-latex-color :background))
  17526. (setq bg (org-latex-color-format
  17527. (if (string= bg "Transparent") "white" bg))))
  17528. (with-temp-file texfile
  17529. (insert latex-header)
  17530. (insert "\n\\begin{document}\n"
  17531. "\\definecolor{fg}{rgb}{" fg "}\n"
  17532. "\\definecolor{bg}{rgb}{" bg "}\n"
  17533. "\n\\pagecolor{bg}\n"
  17534. "\n{\\color{fg}\n"
  17535. string
  17536. "\n}\n"
  17537. "\n\\end{document}\n")))
  17538. (if (eq fg 'default)
  17539. (setq fg (org-dvipng-color :foreground))
  17540. (unless (string= fg "Transparent")
  17541. (setq fg (org-dvipng-color-format fg))))
  17542. (if (eq bg 'default)
  17543. (setq bg (org-dvipng-color :background))
  17544. (unless (string= bg "Transparent")
  17545. (setq bg (org-dvipng-color-format bg))))
  17546. (with-temp-file texfile
  17547. (insert latex-header)
  17548. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17549. (let* ((err-msg (format "Please adjust '%s' part of \
  17550. `org-preview-latex-process-alist'."
  17551. processing-type))
  17552. (image-input-file
  17553. (org-compile-file
  17554. texfile latex-compiler image-input-type err-msg log-buf))
  17555. (image-output-file
  17556. (org-compile-file
  17557. image-input-file image-converter image-output-type err-msg log-buf
  17558. `((?F . ,(shell-quote-argument fg))
  17559. (?B . ,(shell-quote-argument bg))
  17560. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17561. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17562. (copy-file image-output-file tofile 'replace)
  17563. (dolist (e post-clean)
  17564. (when (file-exists-p (concat texfilebase e))
  17565. (delete-file (concat texfilebase e))))
  17566. image-output-file)))
  17567. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17568. "Fill a LaTeX header template TPL.
  17569. In the template, the following place holders will be recognized:
  17570. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17571. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17572. [PACKAGES] \\usepackage statements for PKG
  17573. [NO-PACKAGES] do not include PKG
  17574. [EXTRA] the string EXTRA
  17575. [NO-EXTRA] do not include EXTRA
  17576. For backward compatibility, if both the positive and the negative place
  17577. holder is missing, the positive one (without the \"NO-\") will be
  17578. assumed to be present at the end of the template.
  17579. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17580. EXTRA is a string.
  17581. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17582. (let (rpl (end ""))
  17583. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17584. (setq rpl (if (or (match-end 1) (not def-pkg))
  17585. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17586. tpl (replace-match rpl t t tpl))
  17587. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17588. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17589. (setq rpl (if (or (match-end 1) (not pkg))
  17590. "" (org-latex-packages-to-string pkg snippets-p t))
  17591. tpl (replace-match rpl t t tpl))
  17592. (when pkg (setq end
  17593. (concat end "\n"
  17594. (org-latex-packages-to-string pkg snippets-p)))))
  17595. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17596. (setq rpl (if (or (match-end 1) (not extra))
  17597. "" (concat extra "\n"))
  17598. tpl (replace-match rpl t t tpl))
  17599. (when (and extra (string-match "\\S-" extra))
  17600. (setq end (concat end "\n" extra))))
  17601. (if (string-match "\\S-" end)
  17602. (concat tpl "\n" end)
  17603. tpl)))
  17604. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17605. "Turn an alist of packages into a string with the \\usepackage macros."
  17606. (setq pkg (mapconcat (lambda(p)
  17607. (cond
  17608. ((stringp p) p)
  17609. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17610. (format "%% Package %s omitted" (cadr p)))
  17611. ((equal "" (car p))
  17612. (format "\\usepackage{%s}" (cadr p)))
  17613. (t
  17614. (format "\\usepackage[%s]{%s}"
  17615. (car p) (cadr p)))))
  17616. pkg
  17617. "\n"))
  17618. (if newline (concat pkg "\n") pkg))
  17619. (defun org-dvipng-color (attr)
  17620. "Return a RGB color specification for dvipng."
  17621. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17622. (defun org-dvipng-color-format (color-name)
  17623. "Convert COLOR-NAME to a RGB color value for dvipng."
  17624. (apply #'format "rgb %s %s %s"
  17625. (mapcar 'org-normalize-color
  17626. (color-values color-name))))
  17627. (defun org-latex-color (attr)
  17628. "Return a RGB color for the LaTeX color package."
  17629. (org-latex-color-format (face-attribute 'default attr nil)))
  17630. (defun org-latex-color-format (color-name)
  17631. "Convert COLOR-NAME to a RGB color value."
  17632. (apply #'format "%s,%s,%s"
  17633. (mapcar 'org-normalize-color
  17634. (color-values color-name))))
  17635. (defun org-normalize-color (value)
  17636. "Return string to be used as color value for an RGB component."
  17637. (format "%g" (/ value 65535.0)))
  17638. ;; Image display
  17639. (defvar-local org-inline-image-overlays nil)
  17640. (defun org-toggle-inline-images (&optional include-linked)
  17641. "Toggle the display of inline images.
  17642. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17643. (interactive "P")
  17644. (if org-inline-image-overlays
  17645. (progn
  17646. (org-remove-inline-images)
  17647. (when (called-interactively-p 'interactive)
  17648. (message "Inline image display turned off")))
  17649. (org-display-inline-images include-linked)
  17650. (when (called-interactively-p 'interactive)
  17651. (message (if org-inline-image-overlays
  17652. (format "%d images displayed inline"
  17653. (length org-inline-image-overlays))
  17654. "No images to display inline")))))
  17655. (defun org-redisplay-inline-images ()
  17656. "Refresh the display of inline images."
  17657. (interactive)
  17658. (if (not org-inline-image-overlays)
  17659. (org-toggle-inline-images)
  17660. (org-toggle-inline-images)
  17661. (org-toggle-inline-images)))
  17662. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17663. "Display inline images.
  17664. An inline image is a link which follows either of these
  17665. conventions:
  17666. 1. Its path is a file with an extension matching return value
  17667. from `image-file-name-regexp' and it has no contents.
  17668. 2. Its description consists in a single link of the previous
  17669. type.
  17670. When optional argument INCLUDE-LINKED is non-nil, also links with
  17671. a text description part will be inlined. This can be nice for
  17672. a quick look at those images, but it does not reflect what
  17673. exported files will look like.
  17674. When optional argument REFRESH is non-nil, refresh existing
  17675. images between BEG and END. This will create new image displays
  17676. only if necessary. BEG and END default to the buffer
  17677. boundaries."
  17678. (interactive "P")
  17679. (when (display-graphic-p)
  17680. (unless refresh
  17681. (org-remove-inline-images)
  17682. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17683. (org-with-wide-buffer
  17684. (goto-char (or beg (point-min)))
  17685. (let ((case-fold-search t)
  17686. (file-extension-re (image-file-name-regexp)))
  17687. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17688. (let ((link (save-match-data (org-element-context))))
  17689. ;; Check if we're at an inline image.
  17690. (when (and (equal (org-element-property :type link) "file")
  17691. (or include-linked
  17692. (not (org-element-property :contents-begin link)))
  17693. (let ((parent (org-element-property :parent link)))
  17694. (or (not (eq (org-element-type parent) 'link))
  17695. (not (cdr (org-element-contents parent)))))
  17696. (string-match-p file-extension-re
  17697. (org-element-property :path link)))
  17698. (let ((file (expand-file-name
  17699. (org-link-unescape
  17700. (org-element-property :path link)))))
  17701. (when (file-exists-p file)
  17702. (let ((width
  17703. ;; Apply `org-image-actual-width' specifications.
  17704. (cond
  17705. ((not (image-type-available-p 'imagemagick)) nil)
  17706. ((eq org-image-actual-width t) nil)
  17707. ((listp org-image-actual-width)
  17708. (or
  17709. ;; First try to find a width among
  17710. ;; attributes associated to the paragraph
  17711. ;; containing link.
  17712. (let ((paragraph
  17713. (let ((e link))
  17714. (while (and (setq e (org-element-property
  17715. :parent e))
  17716. (not (eq (org-element-type e)
  17717. 'paragraph))))
  17718. e)))
  17719. (when paragraph
  17720. (save-excursion
  17721. (goto-char (org-element-property :begin paragraph))
  17722. (when
  17723. (re-search-forward
  17724. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17725. (org-element-property
  17726. :post-affiliated paragraph)
  17727. t)
  17728. (string-to-number (match-string 1))))))
  17729. ;; Otherwise, fall-back to provided number.
  17730. (car org-image-actual-width)))
  17731. ((numberp org-image-actual-width)
  17732. org-image-actual-width)))
  17733. (old (get-char-property-and-overlay
  17734. (org-element-property :begin link)
  17735. 'org-image-overlay)))
  17736. (if (and (car-safe old) refresh)
  17737. (image-refresh (overlay-get (cdr old) 'display))
  17738. (let ((image (create-image file
  17739. (and width 'imagemagick)
  17740. nil
  17741. :width width)))
  17742. (when image
  17743. (let* ((link
  17744. ;; If inline image is the description
  17745. ;; of another link, be sure to
  17746. ;; consider the latter as the one to
  17747. ;; apply the overlay on.
  17748. (let ((parent
  17749. (org-element-property :parent link)))
  17750. (if (eq (org-element-type parent) 'link)
  17751. parent
  17752. link)))
  17753. (ov (make-overlay
  17754. (org-element-property :begin link)
  17755. (progn
  17756. (goto-char
  17757. (org-element-property :end link))
  17758. (skip-chars-backward " \t")
  17759. (point)))))
  17760. (overlay-put ov 'display image)
  17761. (overlay-put ov 'face 'default)
  17762. (overlay-put ov 'org-image-overlay t)
  17763. (overlay-put
  17764. ov 'modification-hooks
  17765. (list 'org-display-inline-remove-overlay))
  17766. (push ov org-inline-image-overlays)))))))))))))))
  17767. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17768. "Remove inline-display overlay if a corresponding region is modified."
  17769. (let ((inhibit-modification-hooks t))
  17770. (when (and ov after)
  17771. (delete ov org-inline-image-overlays)
  17772. (delete-overlay ov))))
  17773. (defun org-remove-inline-images ()
  17774. "Remove inline display of images."
  17775. (interactive)
  17776. (mapc #'delete-overlay org-inline-image-overlays)
  17777. (setq org-inline-image-overlays nil))
  17778. ;;;; Key bindings
  17779. ;; Outline functions from `outline-mode-prefix-map'
  17780. ;; that can be remapped in Org:
  17781. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17782. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17783. (define-key org-mode-map [remap outline-forward-same-level]
  17784. 'org-forward-heading-same-level)
  17785. (define-key org-mode-map [remap outline-backward-same-level]
  17786. 'org-backward-heading-same-level)
  17787. (define-key org-mode-map [remap outline-show-branches]
  17788. 'org-kill-note-or-show-branches)
  17789. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17790. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17791. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17792. (define-key org-mode-map [remap outline-next-visible-heading]
  17793. 'org-next-visible-heading)
  17794. (define-key org-mode-map [remap outline-previous-visible-heading]
  17795. 'org-previous-visible-heading)
  17796. (define-key org-mode-map [remap show-children] 'org-show-children)
  17797. ;; Outline functions from `outline-mode-prefix-map' that can not
  17798. ;; be remapped in Org:
  17799. ;; - the column "key binding" shows whether the Outline function is still
  17800. ;; available in Org mode on the same key that it has been bound to in
  17801. ;; Outline mode:
  17802. ;; - "overridden": key used for a different functionality in Org mode
  17803. ;; - else: key still bound to the same Outline function in Org mode
  17804. ;; | Outline function | key binding | Org replacement |
  17805. ;; |------------------------------------+-------------+--------------------------|
  17806. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17807. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17808. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17809. ;; | `show-entry' | overridden | no replacement |
  17810. ;; | `show-branches' | `C-c C-k' | still same function |
  17811. ;; | `show-subtree' | overridden | visibility cycling |
  17812. ;; | `show-all' | overridden | no replacement |
  17813. ;; | `hide-subtree' | overridden | visibility cycling |
  17814. ;; | `hide-body' | overridden | no replacement |
  17815. ;; | `hide-entry' | overridden | visibility cycling |
  17816. ;; | `hide-leaves' | overridden | no replacement |
  17817. ;; | `hide-sublevels' | overridden | no replacement |
  17818. ;; | `hide-other' | overridden | no replacement |
  17819. ;; Make `C-c C-x' a prefix key
  17820. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17821. ;; TAB key with modifiers
  17822. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17823. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17824. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17825. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17826. ;; The following line is necessary under Suse GNU/Linux
  17827. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17828. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17829. (define-key org-mode-map [backtab] 'org-shifttab)
  17830. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17831. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17832. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  17833. ;; Cursor keys with modifiers
  17834. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17835. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17836. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17837. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17838. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17839. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17840. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17841. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17842. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17843. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17844. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17845. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17846. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17847. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17848. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17849. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17850. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17851. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17852. ;; Babel keys
  17853. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17854. (dolist (pair org-babel-key-bindings)
  17855. (define-key org-babel-map (car pair) (cdr pair)))
  17856. ;;; Extra keys for tty access.
  17857. ;; We only set them when really needed because otherwise the
  17858. ;; menus don't show the simple keys
  17859. (when (or org-use-extra-keys (not window-system))
  17860. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17861. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17862. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17863. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17864. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17865. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17866. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17867. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17868. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17869. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17870. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17871. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17872. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17873. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17874. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17875. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17876. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17877. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17878. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17879. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17880. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17881. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17882. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17883. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17884. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17885. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17886. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17887. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17888. ;; All the other keys
  17889. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17890. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17891. (if (boundp 'narrow-map)
  17892. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17893. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17894. (if (boundp 'narrow-map)
  17895. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17896. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17897. (if (boundp 'narrow-map)
  17898. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17899. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17900. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17901. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17902. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17903. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17904. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17905. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17906. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17907. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17908. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17909. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17910. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17911. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17912. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17913. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17914. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17915. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17916. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17917. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17918. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17919. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17920. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17921. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17922. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17923. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17924. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17925. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17926. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17927. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17928. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17929. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17930. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17931. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17932. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17933. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17934. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17935. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17936. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17937. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17938. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17939. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17940. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17941. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17942. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17943. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17944. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17945. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17946. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17947. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17948. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17949. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17950. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17951. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17952. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17953. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17954. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17955. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17956. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17957. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17958. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17959. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17960. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17961. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17962. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17963. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17964. (org-defkey org-mode-map "\C-m" 'org-return)
  17965. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17966. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17967. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17968. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17969. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17970. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17971. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17972. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17973. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17974. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17975. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17976. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17977. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17978. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17979. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17980. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17981. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17982. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17983. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17984. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17985. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17986. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17987. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17988. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17989. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17990. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17991. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17992. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17993. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17994. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17995. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17996. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17997. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17998. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17999. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18000. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18001. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18002. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18003. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18004. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18005. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18006. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18007. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18008. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18009. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18010. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18011. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18012. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18013. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18014. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18015. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18016. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18017. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18018. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18019. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18020. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18021. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18022. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18023. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18024. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18025. (defconst org-speed-commands-default
  18026. '(
  18027. ("Outline Navigation")
  18028. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18029. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18030. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18031. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18032. ("F" . org-next-block)
  18033. ("B" . org-previous-block)
  18034. ("u" . (org-speed-move-safe 'outline-up-heading))
  18035. ("j" . org-goto)
  18036. ("g" . (org-refile t))
  18037. ("Outline Visibility")
  18038. ("c" . org-cycle)
  18039. ("C" . org-shifttab)
  18040. (" " . org-display-outline-path)
  18041. ("s" . org-narrow-to-subtree)
  18042. ("=" . org-columns)
  18043. ("Outline Structure Editing")
  18044. ("U" . org-metaup)
  18045. ("D" . org-metadown)
  18046. ("r" . org-metaright)
  18047. ("l" . org-metaleft)
  18048. ("R" . org-shiftmetaright)
  18049. ("L" . org-shiftmetaleft)
  18050. ("i" . (progn (forward-char 1) (call-interactively
  18051. 'org-insert-heading-respect-content)))
  18052. ("^" . org-sort)
  18053. ("w" . org-refile)
  18054. ("a" . org-archive-subtree-default-with-confirmation)
  18055. ("@" . org-mark-subtree)
  18056. ("#" . org-toggle-comment)
  18057. ("Clock Commands")
  18058. ("I" . org-clock-in)
  18059. ("O" . org-clock-out)
  18060. ("Meta Data Editing")
  18061. ("t" . org-todo)
  18062. ("," . (org-priority))
  18063. ("0" . (org-priority ?\ ))
  18064. ("1" . (org-priority ?A))
  18065. ("2" . (org-priority ?B))
  18066. ("3" . (org-priority ?C))
  18067. (":" . org-set-tags-command)
  18068. ("e" . org-set-effort)
  18069. ("E" . org-inc-effort)
  18070. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18071. (org-entry-put (point) "APPT_WARNTIME" m)))
  18072. ("Agenda Views etc")
  18073. ("v" . org-agenda)
  18074. ("/" . org-sparse-tree)
  18075. ("Misc")
  18076. ("o" . org-open-at-point)
  18077. ("?" . org-speed-command-help)
  18078. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18079. (">" . (org-agenda-remove-restriction-lock))
  18080. )
  18081. "The default speed commands.")
  18082. (defun org-print-speed-command (e)
  18083. (if (> (length (car e)) 1)
  18084. (progn
  18085. (princ "\n")
  18086. (princ (car e))
  18087. (princ "\n")
  18088. (princ (make-string (length (car e)) ?-))
  18089. (princ "\n"))
  18090. (princ (car e))
  18091. (princ " ")
  18092. (if (symbolp (cdr e))
  18093. (princ (symbol-name (cdr e)))
  18094. (prin1 (cdr e)))
  18095. (princ "\n")))
  18096. (defun org-speed-command-help ()
  18097. "Show the available speed commands."
  18098. (interactive)
  18099. (if (not org-use-speed-commands)
  18100. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18101. (with-output-to-temp-buffer "*Help*"
  18102. (princ "User-defined Speed commands\n===========================\n")
  18103. (mapc #'org-print-speed-command org-speed-commands-user)
  18104. (princ "\n")
  18105. (princ "Built-in Speed commands\n=======================\n")
  18106. (mapc #'org-print-speed-command org-speed-commands-default))
  18107. (with-current-buffer "*Help*"
  18108. (setq truncate-lines t))))
  18109. (defun org-speed-move-safe (cmd)
  18110. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18111. If not, return to the original position and throw an error."
  18112. (interactive)
  18113. (let ((pos (point)))
  18114. (call-interactively cmd)
  18115. (unless (and (bolp) (org-at-heading-p))
  18116. (goto-char pos)
  18117. (error "Boundary reached while executing %s" cmd))))
  18118. (defvar org-self-insert-command-undo-counter 0)
  18119. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18120. (defvar org-speed-command nil)
  18121. (defun org-speed-command-activate (keys)
  18122. "Hook for activating single-letter speed commands.
  18123. `org-speed-commands-default' specifies a minimal command set.
  18124. Use `org-speed-commands-user' for further customization."
  18125. (when (or (and (bolp) (looking-at org-outline-regexp))
  18126. (and (functionp org-use-speed-commands)
  18127. (funcall org-use-speed-commands)))
  18128. (cdr (assoc keys (append org-speed-commands-user
  18129. org-speed-commands-default)))))
  18130. (defun org-babel-speed-command-activate (keys)
  18131. "Hook for activating single-letter code block commands."
  18132. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18133. (cdr (assoc keys org-babel-key-bindings))))
  18134. (defcustom org-speed-command-hook
  18135. '(org-speed-command-activate org-babel-speed-command-activate)
  18136. "Hook for activating speed commands at strategic locations.
  18137. Hook functions are called in sequence until a valid handler is
  18138. found.
  18139. Each hook takes a single argument, a user-pressed command key
  18140. which is also a `self-insert-command' from the global map.
  18141. Within the hook, examine the cursor position and the command key
  18142. and return nil or a valid handler as appropriate. Handler could
  18143. be one of an interactive command, a function, or a form.
  18144. Set `org-use-speed-commands' to non-nil value to enable this
  18145. hook. The default setting is `org-speed-command-activate'."
  18146. :group 'org-structure
  18147. :version "24.1"
  18148. :type 'hook)
  18149. (defun org-self-insert-command (N)
  18150. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18151. If the cursor is in a table looking at whitespace, the whitespace is
  18152. overwritten, and the table is not marked as requiring realignment."
  18153. (interactive "p")
  18154. (org-check-before-invisible-edit 'insert)
  18155. (cond
  18156. ((and org-use-speed-commands
  18157. (let ((kv (this-command-keys-vector)))
  18158. (setq org-speed-command
  18159. (run-hook-with-args-until-success
  18160. 'org-speed-command-hook
  18161. (make-string 1 (aref kv (1- (length kv))))))))
  18162. (cond
  18163. ((commandp org-speed-command)
  18164. (setq this-command org-speed-command)
  18165. (call-interactively org-speed-command))
  18166. ((functionp org-speed-command)
  18167. (funcall org-speed-command))
  18168. ((and org-speed-command (listp org-speed-command))
  18169. (eval org-speed-command))
  18170. (t (let (org-use-speed-commands)
  18171. (call-interactively 'org-self-insert-command)))))
  18172. ((and
  18173. (org-at-table-p)
  18174. (progn
  18175. ;; Check if we blank the field, and if that triggers align.
  18176. (and (featurep 'org-table) org-table-auto-blank-field
  18177. (memq last-command
  18178. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18179. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18180. ;; Got extra space, this field does not determine
  18181. ;; column width.
  18182. (let (org-table-may-need-update) (org-table-blank-field))
  18183. ;; No extra space, this field may determine column
  18184. ;; width.
  18185. (org-table-blank-field)))
  18186. t)
  18187. (eq N 1)
  18188. (looking-at "[^|\n]* \\( \\)|"))
  18189. ;; There is room for insertion without re-aligning the table.
  18190. (delete-region (match-beginning 1) (match-end 1))
  18191. (self-insert-command N))
  18192. (t
  18193. (setq org-table-may-need-update t)
  18194. (self-insert-command N)
  18195. (org-fix-tags-on-the-fly)
  18196. (when org-self-insert-cluster-for-undo
  18197. (if (not (eq last-command 'org-self-insert-command))
  18198. (setq org-self-insert-command-undo-counter 1)
  18199. (if (>= org-self-insert-command-undo-counter 20)
  18200. (setq org-self-insert-command-undo-counter 1)
  18201. (and (> org-self-insert-command-undo-counter 0)
  18202. buffer-undo-list (listp buffer-undo-list)
  18203. (not (cadr buffer-undo-list)) ; remove nil entry
  18204. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18205. (setq org-self-insert-command-undo-counter
  18206. (1+ org-self-insert-command-undo-counter))))))))
  18207. (defun org-check-before-invisible-edit (kind)
  18208. "Check is editing if kind KIND would be dangerous with invisible text around.
  18209. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18210. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18211. (when (and org-catch-invisible-edits
  18212. (or (not (boundp 'visible-mode)) (not visible-mode))
  18213. (or (get-char-property (point) 'invisible)
  18214. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18215. ;; OK, we need to take a closer look
  18216. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18217. (invisible-before-point (unless (bobp) (get-char-property
  18218. (1- (point)) 'invisible)))
  18219. (border-and-ok-direction
  18220. (or
  18221. ;; Check if we are acting predictably before invisible text
  18222. (and invisible-at-point (not invisible-before-point)
  18223. (memq kind '(insert delete-backward)))
  18224. ;; Check if we are acting predictably after invisible text
  18225. ;; This works not well, and I have turned it off. It seems
  18226. ;; better to always show and stop after invisible text.
  18227. ;; (and (not invisible-at-point) invisible-before-point
  18228. ;; (memq kind '(insert delete)))
  18229. )))
  18230. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18231. (memq invisible-before-point '(outline org-hide-block t)))
  18232. (when (eq org-catch-invisible-edits 'error)
  18233. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18234. (if (and org-custom-properties-overlays
  18235. (y-or-n-p "Display invisible properties in this buffer? "))
  18236. (org-toggle-custom-properties-visibility)
  18237. ;; Make the area visible
  18238. (save-excursion
  18239. (when invisible-before-point
  18240. (goto-char (previous-single-char-property-change
  18241. (point) 'invisible)))
  18242. (outline-show-subtree))
  18243. (cond
  18244. ((eq org-catch-invisible-edits 'show)
  18245. ;; That's it, we do the edit after showing
  18246. (message
  18247. "Unfolding invisible region around point before editing")
  18248. (sit-for 1))
  18249. ((and (eq org-catch-invisible-edits 'smart)
  18250. border-and-ok-direction)
  18251. (message "Unfolding invisible region around point before editing"))
  18252. (t
  18253. ;; Don't do the edit, make the user repeat it in full visibility
  18254. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18255. (defun org-fix-tags-on-the-fly ()
  18256. "Align tags in headline at point.
  18257. Unlike to `org-set-tags', it ignores region and sorting."
  18258. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18259. (org-at-heading-p))
  18260. (let ((org-ignore-region t)
  18261. (org-tags-sort-function nil))
  18262. (org-set-tags nil t))))
  18263. (defun org-delete-backward-char (N)
  18264. "Like `delete-backward-char', insert whitespace at field end in tables.
  18265. When deleting backwards, in tables this function will insert whitespace in
  18266. front of the next \"|\" separator, to keep the table aligned. The table will
  18267. still be marked for re-alignment if the field did fill the entire column,
  18268. because, in this case the deletion might narrow the column."
  18269. (interactive "p")
  18270. (save-match-data
  18271. (org-check-before-invisible-edit 'delete-backward)
  18272. (if (and (org-at-table-p)
  18273. (eq N 1)
  18274. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18275. (looking-at ".*?|"))
  18276. (let ((pos (point))
  18277. (noalign (looking-at "[^|\n\r]* |"))
  18278. (c org-table-may-need-update))
  18279. (backward-delete-char N)
  18280. (unless overwrite-mode
  18281. (skip-chars-forward "^|")
  18282. (insert " ")
  18283. (goto-char (1- pos)))
  18284. ;; noalign: if there were two spaces at the end, this field
  18285. ;; does not determine the width of the column.
  18286. (when noalign (setq org-table-may-need-update c)))
  18287. (backward-delete-char N)
  18288. (org-fix-tags-on-the-fly))))
  18289. (defun org-delete-char (N)
  18290. "Like `delete-char', but insert whitespace at field end in tables.
  18291. When deleting characters, in tables this function will insert whitespace in
  18292. front of the next \"|\" separator, to keep the table aligned. The table will
  18293. still be marked for re-alignment if the field did fill the entire column,
  18294. because, in this case the deletion might narrow the column."
  18295. (interactive "p")
  18296. (save-match-data
  18297. (org-check-before-invisible-edit 'delete)
  18298. (if (and (org-at-table-p)
  18299. (not (bolp))
  18300. (not (= (char-after) ?|))
  18301. (eq N 1))
  18302. (if (looking-at ".*?|")
  18303. (let ((pos (point))
  18304. (noalign (looking-at "[^|\n\r]* |"))
  18305. (c org-table-may-need-update))
  18306. (replace-match
  18307. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18308. (goto-char pos)
  18309. ;; noalign: if there were two spaces at the end, this field
  18310. ;; does not determine the width of the column.
  18311. (when noalign (setq org-table-may-need-update c)))
  18312. (delete-char N))
  18313. (delete-char N)
  18314. (org-fix-tags-on-the-fly))))
  18315. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18316. (put 'org-self-insert-command 'delete-selection
  18317. (lambda ()
  18318. (not (run-hook-with-args-until-success
  18319. 'self-insert-uses-region-functions))))
  18320. (put 'orgtbl-self-insert-command 'delete-selection
  18321. (lambda ()
  18322. (not (run-hook-with-args-until-success
  18323. 'self-insert-uses-region-functions))))
  18324. (put 'org-delete-char 'delete-selection 'supersede)
  18325. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18326. (put 'org-yank 'delete-selection 'yank)
  18327. ;; Make `flyspell-mode' delay after some commands
  18328. (put 'org-self-insert-command 'flyspell-delayed t)
  18329. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18330. (put 'org-delete-char 'flyspell-delayed t)
  18331. (put 'org-delete-backward-char 'flyspell-delayed t)
  18332. ;; Make pabbrev-mode expand after Org mode commands
  18333. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18334. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18335. (defun org-remap (map &rest commands)
  18336. "In MAP, remap the functions given in COMMANDS.
  18337. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18338. (let (new old)
  18339. (while commands
  18340. (setq old (pop commands) new (pop commands))
  18341. (org-defkey map (vector 'remap old) new))))
  18342. (defun org-transpose-words ()
  18343. "Transpose words for Org.
  18344. This uses the `org-mode-transpose-word-syntax-table' syntax
  18345. table, which interprets characters in `org-emphasis-alist' as
  18346. word constituents."
  18347. (interactive)
  18348. (with-syntax-table org-mode-transpose-word-syntax-table
  18349. (call-interactively 'transpose-words)))
  18350. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18351. (when (eq org-enable-table-editor 'optimized)
  18352. ;; If the user wants maximum table support, we need to hijack
  18353. ;; some standard editing functions
  18354. (org-remap org-mode-map
  18355. 'self-insert-command 'org-self-insert-command
  18356. 'delete-char 'org-delete-char
  18357. 'delete-backward-char 'org-delete-backward-char)
  18358. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18359. (defvar org-ctrl-c-ctrl-c-hook nil
  18360. "Hook for functions attaching themselves to `C-c C-c'.
  18361. This can be used to add additional functionality to the C-c C-c
  18362. key which executes context-dependent commands. This hook is run
  18363. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18364. run after the last test.
  18365. Each function will be called with no arguments. The function
  18366. must check if the context is appropriate for it to act. If yes,
  18367. it should do its thing and then return a non-nil value. If the
  18368. context is wrong, just do nothing and return nil.")
  18369. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18370. "Hook for functions attaching themselves to `C-c C-c'.
  18371. This can be used to add additional functionality to the C-c C-c
  18372. key which executes context-dependent commands. This hook is run
  18373. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18374. before the first test.
  18375. Each function will be called with no arguments. The function
  18376. must check if the context is appropriate for it to act. If yes,
  18377. it should do its thing and then return a non-nil value. If the
  18378. context is wrong, just do nothing and return nil.")
  18379. (defvar org-tab-first-hook nil
  18380. "Hook for functions to attach themselves to TAB.
  18381. See `org-ctrl-c-ctrl-c-hook' for more information.
  18382. This hook runs as the first action when TAB is pressed, even before
  18383. `org-cycle' messes around with the `outline-regexp' to cater for
  18384. inline tasks and plain list item folding.
  18385. If any function in this hook returns t, any other actions that
  18386. would have been caused by TAB (such as table field motion or visibility
  18387. cycling) will not occur.")
  18388. (defvar org-tab-after-check-for-table-hook nil
  18389. "Hook for functions to attach themselves to TAB.
  18390. See `org-ctrl-c-ctrl-c-hook' for more information.
  18391. This hook runs after it has been established that the cursor is not in a
  18392. table, but before checking if the cursor is in a headline or if global cycling
  18393. should be done.
  18394. If any function in this hook returns t, not other actions like visibility
  18395. cycling will be done.")
  18396. (defvar org-tab-after-check-for-cycling-hook nil
  18397. "Hook for functions to attach themselves to TAB.
  18398. See `org-ctrl-c-ctrl-c-hook' for more information.
  18399. This hook runs after it has been established that not table field motion and
  18400. not visibility should be done because of current context. This is probably
  18401. the place where a package like yasnippets can hook in.")
  18402. (defvar org-tab-before-tab-emulation-hook nil
  18403. "Hook for functions to attach themselves to TAB.
  18404. See `org-ctrl-c-ctrl-c-hook' for more information.
  18405. This hook runs after every other options for TAB have been exhausted, but
  18406. before indentation and \t insertion takes place.")
  18407. (defvar org-metaleft-hook nil
  18408. "Hook for functions attaching themselves to `M-left'.
  18409. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18410. (defvar org-metaright-hook nil
  18411. "Hook for functions attaching themselves to `M-right'.
  18412. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18413. (defvar org-metaup-hook nil
  18414. "Hook for functions attaching themselves to `M-up'.
  18415. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18416. (defvar org-metadown-hook nil
  18417. "Hook for functions attaching themselves to `M-down'.
  18418. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18419. (defvar org-shiftmetaleft-hook nil
  18420. "Hook for functions attaching themselves to `M-S-left'.
  18421. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18422. (defvar org-shiftmetaright-hook nil
  18423. "Hook for functions attaching themselves to `M-S-right'.
  18424. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18425. (defvar org-shiftmetaup-hook nil
  18426. "Hook for functions attaching themselves to `M-S-up'.
  18427. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18428. (defvar org-shiftmetadown-hook nil
  18429. "Hook for functions attaching themselves to `M-S-down'.
  18430. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18431. (defvar org-metareturn-hook nil
  18432. "Hook for functions attaching themselves to `M-RET'.
  18433. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18434. (defvar org-shiftup-hook nil
  18435. "Hook for functions attaching themselves to `S-up'.
  18436. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18437. (defvar org-shiftup-final-hook nil
  18438. "Hook for functions attaching themselves to `S-up'.
  18439. This one runs after all other options except shift-select have been excluded.
  18440. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18441. (defvar org-shiftdown-hook nil
  18442. "Hook for functions attaching themselves to `S-down'.
  18443. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18444. (defvar org-shiftdown-final-hook nil
  18445. "Hook for functions attaching themselves to `S-down'.
  18446. This one runs after all other options except shift-select have been excluded.
  18447. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18448. (defvar org-shiftleft-hook nil
  18449. "Hook for functions attaching themselves to `S-left'.
  18450. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18451. (defvar org-shiftleft-final-hook nil
  18452. "Hook for functions attaching themselves to `S-left'.
  18453. This one runs after all other options except shift-select have been excluded.
  18454. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18455. (defvar org-shiftright-hook nil
  18456. "Hook for functions attaching themselves to `S-right'.
  18457. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18458. (defvar org-shiftright-final-hook nil
  18459. "Hook for functions attaching themselves to `S-right'.
  18460. This one runs after all other options except shift-select have been excluded.
  18461. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18462. (defun org-modifier-cursor-error ()
  18463. "Throw an error, a modified cursor command was applied in wrong context."
  18464. (user-error "This command is active in special context like tables, headlines or items"))
  18465. (defun org-shiftselect-error ()
  18466. "Throw an error because Shift-Cursor command was applied in wrong context."
  18467. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18468. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18469. (user-error "This command works only in special context like headlines or timestamps")))
  18470. (defun org-call-for-shift-select (cmd)
  18471. (let ((this-command-keys-shift-translated t))
  18472. (call-interactively cmd)))
  18473. (defun org-shifttab (&optional arg)
  18474. "Global visibility cycling or move to previous table field.
  18475. Call `org-table-previous-field' within a table.
  18476. When ARG is nil, cycle globally through visibility states.
  18477. When ARG is a numeric prefix, show contents of this level."
  18478. (interactive "P")
  18479. (cond
  18480. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18481. ((integerp arg)
  18482. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18483. (message "Content view to level: %d" arg)
  18484. (org-content (prefix-numeric-value arg2))
  18485. (org-cycle-show-empty-lines t)
  18486. (setq org-cycle-global-status 'overview)))
  18487. (t (call-interactively 'org-global-cycle))))
  18488. (defun org-shiftmetaleft ()
  18489. "Promote subtree or delete table column.
  18490. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18491. `org-table-delete-column', depending on context. See the
  18492. individual commands for more information."
  18493. (interactive)
  18494. (cond
  18495. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18496. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18497. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18498. ((if (not (org-region-active-p)) (org-at-item-p)
  18499. (save-excursion (goto-char (region-beginning))
  18500. (org-at-item-p)))
  18501. (call-interactively 'org-outdent-item-tree))
  18502. (t (org-modifier-cursor-error))))
  18503. (defun org-shiftmetaright ()
  18504. "Demote subtree or insert table column.
  18505. Calls `org-demote-subtree', `org-indent-item-tree', or
  18506. `org-table-insert-column', depending on context. See the
  18507. individual commands for more information."
  18508. (interactive)
  18509. (cond
  18510. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18511. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18512. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18513. ((if (not (org-region-active-p)) (org-at-item-p)
  18514. (save-excursion (goto-char (region-beginning))
  18515. (org-at-item-p)))
  18516. (call-interactively 'org-indent-item-tree))
  18517. (t (org-modifier-cursor-error))))
  18518. (defun org-shiftmetaup (&optional _arg)
  18519. "Drag the line at point up.
  18520. In a table, kill the current row.
  18521. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18522. but also adjust the previous clocked item in the clock history.
  18523. Everywhere else, drag the line at point up."
  18524. (interactive "P")
  18525. (cond
  18526. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18527. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18528. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18529. (call-interactively 'org-timestamp-up)))
  18530. (t (call-interactively 'org-drag-line-backward))))
  18531. (defun org-shiftmetadown (&optional _arg)
  18532. "Drag the line at point down.
  18533. In a table, insert an empty row at the current line.
  18534. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18535. but also adjust the previous clocked item in the clock history.
  18536. Everywhere else, drag the line at point down."
  18537. (interactive "P")
  18538. (cond
  18539. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18540. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18541. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18542. (call-interactively 'org-timestamp-down)))
  18543. (t (call-interactively 'org-drag-line-forward))))
  18544. (defsubst org-hidden-tree-error ()
  18545. (user-error
  18546. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18547. (defun org-metaleft (&optional _arg)
  18548. "Promote heading, list item at point or move table column left.
  18549. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18550. depending on context. With no specific context, calls the Emacs
  18551. default `backward-word'. See the individual commands for more
  18552. information.
  18553. This function runs the hook `org-metaleft-hook' as a first step,
  18554. and returns at first non-nil value."
  18555. (interactive "P")
  18556. (cond
  18557. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18558. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18559. ((org-with-limited-levels
  18560. (or (org-at-heading-p)
  18561. (and (org-region-active-p)
  18562. (save-excursion
  18563. (goto-char (region-beginning))
  18564. (org-at-heading-p)))))
  18565. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18566. (call-interactively 'org-do-promote))
  18567. ;; At an inline task.
  18568. ((org-at-heading-p)
  18569. (call-interactively 'org-inlinetask-promote))
  18570. ((or (org-at-item-p)
  18571. (and (org-region-active-p)
  18572. (save-excursion
  18573. (goto-char (region-beginning))
  18574. (org-at-item-p))))
  18575. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18576. (call-interactively 'org-outdent-item))
  18577. (t (call-interactively 'backward-word))))
  18578. (defun org-metaright (&optional _arg)
  18579. "Demote heading, list item at point or move table column right.
  18580. In front of a drawer or a block keyword, indent it correctly.
  18581. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18582. `org-indent-drawer' or `org-indent-block' depending on context.
  18583. With no specific context, calls the Emacs default `forward-word'.
  18584. See the individual commands for more information.
  18585. This function runs the hook `org-metaright-hook' as a first step,
  18586. and returns at first non-nil value."
  18587. (interactive "P")
  18588. (cond
  18589. ((run-hook-with-args-until-success 'org-metaright-hook))
  18590. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18591. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18592. ((org-at-block-p) (call-interactively 'org-indent-block))
  18593. ((org-with-limited-levels
  18594. (or (org-at-heading-p)
  18595. (and (org-region-active-p)
  18596. (save-excursion
  18597. (goto-char (region-beginning))
  18598. (org-at-heading-p)))))
  18599. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18600. (call-interactively 'org-do-demote))
  18601. ;; At an inline task.
  18602. ((org-at-heading-p)
  18603. (call-interactively 'org-inlinetask-demote))
  18604. ((or (org-at-item-p)
  18605. (and (org-region-active-p)
  18606. (save-excursion
  18607. (goto-char (region-beginning))
  18608. (org-at-item-p))))
  18609. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18610. (call-interactively 'org-indent-item))
  18611. (t (call-interactively 'forward-word))))
  18612. (defun org-check-for-hidden (what)
  18613. "Check if there are hidden headlines/items in the current visual line.
  18614. WHAT can be either `headlines' or `items'. If the current line is
  18615. an outline or item heading and it has a folded subtree below it,
  18616. this function returns t, nil otherwise."
  18617. (let ((re (cond
  18618. ((eq what 'headlines) org-outline-regexp-bol)
  18619. ((eq what 'items) (org-item-beginning-re))
  18620. (t (error "This should not happen"))))
  18621. beg end)
  18622. (save-excursion
  18623. (catch 'exit
  18624. (unless (org-region-active-p)
  18625. (setq beg (point-at-bol))
  18626. (beginning-of-line 2)
  18627. (while (and (not (eobp)) ;; this is like `next-line'
  18628. (get-char-property (1- (point)) 'invisible))
  18629. (beginning-of-line 2))
  18630. (setq end (point))
  18631. (goto-char beg)
  18632. (goto-char (point-at-eol))
  18633. (setq end (max end (point)))
  18634. (while (re-search-forward re end t)
  18635. (when (get-char-property (match-beginning 0) 'invisible)
  18636. (throw 'exit t))))
  18637. nil))))
  18638. (defun org-metaup (&optional _arg)
  18639. "Move subtree up or move table row up.
  18640. Calls `org-move-subtree-up' or `org-table-move-row' or
  18641. `org-move-item-up', depending on context. See the individual commands
  18642. for more information."
  18643. (interactive "P")
  18644. (cond
  18645. ((run-hook-with-args-until-success 'org-metaup-hook))
  18646. ((org-region-active-p)
  18647. (let* ((a (min (region-beginning) (region-end)))
  18648. (b (1- (max (region-beginning) (region-end))))
  18649. (c (save-excursion (goto-char a)
  18650. (move-beginning-of-line 0)))
  18651. (d (save-excursion (goto-char a)
  18652. (move-end-of-line 0) (point))))
  18653. (transpose-regions a b c d)
  18654. (goto-char c)))
  18655. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18656. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18657. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18658. (t (org-drag-element-backward))))
  18659. (defun org-metadown (&optional _arg)
  18660. "Move subtree down or move table row down.
  18661. Calls `org-move-subtree-down' or `org-table-move-row' or
  18662. `org-move-item-down', depending on context. See the individual
  18663. commands for more information."
  18664. (interactive "P")
  18665. (cond
  18666. ((run-hook-with-args-until-success 'org-metadown-hook))
  18667. ((org-region-active-p)
  18668. (let* ((a (min (region-beginning) (region-end)))
  18669. (b (max (region-beginning) (region-end)))
  18670. (c (save-excursion (goto-char b)
  18671. (move-beginning-of-line 1)))
  18672. (d (save-excursion (goto-char b)
  18673. (move-end-of-line 1) (1+ (point)))))
  18674. (transpose-regions a b c d)
  18675. (goto-char d)))
  18676. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18677. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18678. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18679. (t (org-drag-element-forward))))
  18680. (defun org-shiftup (&optional arg)
  18681. "Increase item in timestamp or increase priority of current headline.
  18682. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18683. depending on context. See the individual commands for more information."
  18684. (interactive "P")
  18685. (cond
  18686. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18687. ((and org-support-shift-select (org-region-active-p))
  18688. (org-call-for-shift-select 'previous-line))
  18689. ((org-at-timestamp-p t)
  18690. (call-interactively (if org-edit-timestamp-down-means-later
  18691. 'org-timestamp-down 'org-timestamp-up)))
  18692. ((and (not (eq org-support-shift-select 'always))
  18693. org-enable-priority-commands
  18694. (org-at-heading-p))
  18695. (call-interactively 'org-priority-up))
  18696. ((and (not org-support-shift-select) (org-at-item-p))
  18697. (call-interactively 'org-previous-item))
  18698. ((org-clocktable-try-shift 'up arg))
  18699. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18700. (org-support-shift-select
  18701. (org-call-for-shift-select 'previous-line))
  18702. (t (org-shiftselect-error))))
  18703. (defun org-shiftdown (&optional arg)
  18704. "Decrease item in timestamp or decrease priority of current headline.
  18705. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18706. depending on context. See the individual commands for more information."
  18707. (interactive "P")
  18708. (cond
  18709. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18710. ((and org-support-shift-select (org-region-active-p))
  18711. (org-call-for-shift-select 'next-line))
  18712. ((org-at-timestamp-p t)
  18713. (call-interactively (if org-edit-timestamp-down-means-later
  18714. 'org-timestamp-up 'org-timestamp-down)))
  18715. ((and (not (eq org-support-shift-select 'always))
  18716. org-enable-priority-commands
  18717. (org-at-heading-p))
  18718. (call-interactively 'org-priority-down))
  18719. ((and (not org-support-shift-select) (org-at-item-p))
  18720. (call-interactively 'org-next-item))
  18721. ((org-clocktable-try-shift 'down arg))
  18722. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18723. (org-support-shift-select
  18724. (org-call-for-shift-select 'next-line))
  18725. (t (org-shiftselect-error))))
  18726. (defun org-shiftright (&optional arg)
  18727. "Cycle the thing at point or in the current line, depending on context.
  18728. Depending on context, this does one of the following:
  18729. - switch a timestamp at point one day into the future
  18730. - on a headline, switch to the next TODO keyword.
  18731. - on an item, switch entire list to the next bullet type
  18732. - on a property line, switch to the next allowed value
  18733. - on a clocktable definition line, move time block into the future"
  18734. (interactive "P")
  18735. (cond
  18736. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18737. ((and org-support-shift-select (org-region-active-p))
  18738. (org-call-for-shift-select 'forward-char))
  18739. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  18740. ((and (not (eq org-support-shift-select 'always))
  18741. (org-at-heading-p))
  18742. (let ((org-inhibit-logging
  18743. (not org-treat-S-cursor-todo-selection-as-state-change))
  18744. (org-inhibit-blocking
  18745. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18746. (org-call-with-arg 'org-todo 'right)))
  18747. ((or (and org-support-shift-select
  18748. (not (eq org-support-shift-select 'always))
  18749. (org-at-item-bullet-p))
  18750. (and (not org-support-shift-select) (org-at-item-p)))
  18751. (org-call-with-arg 'org-cycle-list-bullet nil))
  18752. ((and (not (eq org-support-shift-select 'always))
  18753. (org-at-property-p))
  18754. (call-interactively 'org-property-next-allowed-value))
  18755. ((org-clocktable-try-shift 'right arg))
  18756. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18757. (org-support-shift-select
  18758. (org-call-for-shift-select 'forward-char))
  18759. (t (org-shiftselect-error))))
  18760. (defun org-shiftleft (&optional arg)
  18761. "Cycle the thing at point or in the current line, depending on context.
  18762. Depending on context, this does one of the following:
  18763. - switch a timestamp at point one day into the past
  18764. - on a headline, switch to the previous TODO keyword.
  18765. - on an item, switch entire list to the previous bullet type
  18766. - on a property line, switch to the previous allowed value
  18767. - on a clocktable definition line, move time block into the past"
  18768. (interactive "P")
  18769. (cond
  18770. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18771. ((and org-support-shift-select (org-region-active-p))
  18772. (org-call-for-shift-select 'backward-char))
  18773. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  18774. ((and (not (eq org-support-shift-select 'always))
  18775. (org-at-heading-p))
  18776. (let ((org-inhibit-logging
  18777. (not org-treat-S-cursor-todo-selection-as-state-change))
  18778. (org-inhibit-blocking
  18779. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18780. (org-call-with-arg 'org-todo 'left)))
  18781. ((or (and org-support-shift-select
  18782. (not (eq org-support-shift-select 'always))
  18783. (org-at-item-bullet-p))
  18784. (and (not org-support-shift-select) (org-at-item-p)))
  18785. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18786. ((and (not (eq org-support-shift-select 'always))
  18787. (org-at-property-p))
  18788. (call-interactively 'org-property-previous-allowed-value))
  18789. ((org-clocktable-try-shift 'left arg))
  18790. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18791. (org-support-shift-select
  18792. (org-call-for-shift-select 'backward-char))
  18793. (t (org-shiftselect-error))))
  18794. (defun org-shiftcontrolright ()
  18795. "Switch to next TODO set."
  18796. (interactive)
  18797. (cond
  18798. ((and org-support-shift-select (org-region-active-p))
  18799. (org-call-for-shift-select 'forward-word))
  18800. ((and (not (eq org-support-shift-select 'always))
  18801. (org-at-heading-p))
  18802. (org-call-with-arg 'org-todo 'nextset))
  18803. (org-support-shift-select
  18804. (org-call-for-shift-select 'forward-word))
  18805. (t (org-shiftselect-error))))
  18806. (defun org-shiftcontrolleft ()
  18807. "Switch to previous TODO set."
  18808. (interactive)
  18809. (cond
  18810. ((and org-support-shift-select (org-region-active-p))
  18811. (org-call-for-shift-select 'backward-word))
  18812. ((and (not (eq org-support-shift-select 'always))
  18813. (org-at-heading-p))
  18814. (org-call-with-arg 'org-todo 'previousset))
  18815. (org-support-shift-select
  18816. (org-call-for-shift-select 'backward-word))
  18817. (t (org-shiftselect-error))))
  18818. (defun org-shiftcontrolup (&optional n)
  18819. "Change timestamps synchronously up in CLOCK log lines.
  18820. Optional argument N tells to change by that many units."
  18821. (interactive "P")
  18822. (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
  18823. (let (org-support-shift-select)
  18824. (org-clock-timestamps-up n))
  18825. (user-error "Not at a clock log")))
  18826. (defun org-shiftcontroldown (&optional n)
  18827. "Change timestamps synchronously down in CLOCK log lines.
  18828. Optional argument N tells to change by that many units."
  18829. (interactive "P")
  18830. (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
  18831. (let (org-support-shift-select)
  18832. (org-clock-timestamps-down n))
  18833. (user-error "Not at a clock log")))
  18834. (defun org-increase-number-at-point (&optional inc)
  18835. "Increment the number at point.
  18836. With an optional prefix numeric argument INC, increment using
  18837. this numeric value."
  18838. (interactive "p")
  18839. (if (not (number-at-point))
  18840. (user-error "Not on a number")
  18841. (unless inc (setq inc 1))
  18842. (let ((pos (point))
  18843. (beg (skip-chars-backward "-+^/*0-9eE."))
  18844. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18845. (setq nap (buffer-substring-no-properties
  18846. (+ pos beg) (+ pos beg end)))
  18847. (delete-region (+ pos beg) (+ pos beg end))
  18848. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18849. (when (org-at-table-p)
  18850. (org-table-align)
  18851. (org-table-end-of-field 1))))
  18852. (defun org-decrease-number-at-point (&optional inc)
  18853. "Decrement the number at point.
  18854. With an optional prefix numeric argument INC, decrement using
  18855. this numeric value."
  18856. (interactive "p")
  18857. (org-increase-number-at-point (- (or inc 1))))
  18858. (defun org-ctrl-c-ret ()
  18859. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18860. (interactive)
  18861. (cond
  18862. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18863. (t (call-interactively 'org-insert-heading))))
  18864. (defun org-find-visible ()
  18865. (let ((s (point)))
  18866. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18867. (get-char-property s 'invisible)))
  18868. s))
  18869. (defun org-find-invisible ()
  18870. (let ((s (point)))
  18871. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18872. (not (get-char-property s 'invisible))))
  18873. s))
  18874. (defun org-copy-visible (beg end)
  18875. "Copy the visible parts of the region."
  18876. (interactive "r")
  18877. (let (snippets s)
  18878. (save-excursion
  18879. (save-restriction
  18880. (narrow-to-region beg end)
  18881. (setq s (goto-char (point-min)))
  18882. (while (not (= (point) (point-max)))
  18883. (goto-char (org-find-invisible))
  18884. (push (buffer-substring s (point)) snippets)
  18885. (setq s (goto-char (org-find-visible))))))
  18886. (kill-new (apply 'concat (nreverse snippets)))))
  18887. (defun org-copy-special ()
  18888. "Copy region in table or copy current subtree.
  18889. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18890. context. See the individual commands for more information."
  18891. (interactive)
  18892. (call-interactively
  18893. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18894. (defun org-cut-special ()
  18895. "Cut region in table or cut current subtree.
  18896. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18897. context. See the individual commands for more information."
  18898. (interactive)
  18899. (call-interactively
  18900. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18901. (defun org-paste-special (arg)
  18902. "Paste rectangular region into table, or past subtree relative to level.
  18903. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18904. See the individual commands for more information."
  18905. (interactive "P")
  18906. (if (org-at-table-p)
  18907. (org-table-paste-rectangle)
  18908. (org-paste-subtree arg)))
  18909. (defun org-edit-special (&optional arg)
  18910. "Call a special editor for the element at point.
  18911. When at a table, call the formula editor with `org-table-edit-formulas'.
  18912. When in a source code block, call `org-edit-src-code'.
  18913. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18914. When in an export block, call `org-edit-export-block'.
  18915. When in a LaTeX environment, call `org-edit-latex-environment'.
  18916. When at an #+INCLUDE keyword, visit the included file.
  18917. When at a footnote reference, call `org-edit-footnote-reference'
  18918. On a link, call `ffap' to visit the link at point.
  18919. Otherwise, return a user error."
  18920. (interactive "P")
  18921. (let ((element (org-element-at-point)))
  18922. (barf-if-buffer-read-only)
  18923. (pcase (org-element-type element)
  18924. (`src-block
  18925. (if (not arg) (org-edit-src-code)
  18926. (let* ((info (org-babel-get-src-block-info))
  18927. (lang (nth 0 info))
  18928. (params (nth 2 info))
  18929. (session (cdr (assq :session params))))
  18930. (if (not session) (org-edit-src-code)
  18931. ;; At a src-block with a session and function called with
  18932. ;; an ARG: switch to the buffer related to the inferior
  18933. ;; process.
  18934. (switch-to-buffer
  18935. (funcall (intern (concat "org-babel-prep-session:" lang))
  18936. session params))))))
  18937. (`keyword
  18938. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18939. (org-open-link-from-string
  18940. (format "[[%s]]"
  18941. (expand-file-name
  18942. (let ((value (org-element-property :value element)))
  18943. (cond ((not (org-string-nw-p value))
  18944. (user-error "No file to edit"))
  18945. ((string-match "\\`\"\\(.*?\\)\"" value)
  18946. (match-string 1 value))
  18947. ((string-match "\\`[^ \t\"]\\S-*" value)
  18948. (match-string 0 value))
  18949. (t (user-error "No valid file specified")))))))
  18950. (user-error "No special environment to edit here")))
  18951. (`table
  18952. (if (eq (org-element-property :type element) 'table.el)
  18953. (org-edit-table.el)
  18954. (call-interactively 'org-table-edit-formulas)))
  18955. ;; Only Org tables contain `table-row' type elements.
  18956. (`table-row (call-interactively 'org-table-edit-formulas))
  18957. (`example-block (org-edit-src-code))
  18958. (`export-block (org-edit-export-block))
  18959. (`fixed-width (org-edit-fixed-width-region))
  18960. (`latex-environment (org-edit-latex-environment))
  18961. (_
  18962. ;; No notable element at point. Though, we may be at a link or
  18963. ;; a footnote reference, which are objects. Thus, scan deeper.
  18964. (let ((context (org-element-context element)))
  18965. (pcase (org-element-type context)
  18966. (`footnote-reference (org-edit-footnote-reference))
  18967. (`inline-src-block (org-edit-inline-src-code))
  18968. (`link (call-interactively #'ffap))
  18969. (_ (user-error "No special environment to edit here"))))))))
  18970. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18971. (defun org-ctrl-c-ctrl-c (&optional arg)
  18972. "Set tags in headline, or update according to changed information at point.
  18973. This command does many different things, depending on context:
  18974. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18975. this is what we do.
  18976. - If the cursor is on a statistics cookie, update it.
  18977. - If the cursor is in a headline, prompt for tags and insert them
  18978. into the current line, aligned to `org-tags-column'. When called
  18979. with prefix arg, realign all tags in the current buffer.
  18980. - If the cursor is in one of the special #+KEYWORD lines, this
  18981. triggers scanning the buffer for these lines and updating the
  18982. information.
  18983. - If the cursor is inside a table, realign the table. This command
  18984. works even if the automatic table editor has been turned off.
  18985. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18986. the entire table.
  18987. - If the cursor is at a footnote reference or definition, jump to
  18988. the corresponding definition or references, respectively.
  18989. - If the cursor is a the beginning of a dynamic block, update it.
  18990. - If the current buffer is a capture buffer, close note and file it.
  18991. - If the cursor is on a <<<target>>>, update radio targets and
  18992. corresponding links in this buffer.
  18993. - If the cursor is on a numbered item in a plain list, renumber the
  18994. ordered list.
  18995. - If the cursor is on a checkbox, toggle it.
  18996. - If the cursor is on a code block, evaluate it. The variable
  18997. `org-confirm-babel-evaluate' can be used to control prompting
  18998. before code block evaluation, by default every code block
  18999. evaluation requires confirmation. Code block evaluation can be
  19000. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19001. (interactive "P")
  19002. (cond
  19003. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19004. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19005. (org-remove-occur-highlights)
  19006. (message "Temporary highlights/overlays removed from current buffer"))
  19007. ((and (local-variable-p 'org-finish-function)
  19008. (fboundp org-finish-function))
  19009. (funcall org-finish-function))
  19010. ((org-babel-hash-at-point))
  19011. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19012. (t
  19013. (let* ((context
  19014. (org-element-lineage
  19015. (org-element-context)
  19016. ;; Limit to supported contexts.
  19017. '(babel-call clock dynamic-block footnote-definition
  19018. footnote-reference inline-babel-call inline-src-block
  19019. inlinetask item keyword node-property paragraph
  19020. plain-list property-drawer radio-target src-block
  19021. statistics-cookie table table-cell table-row
  19022. timestamp)
  19023. t))
  19024. (type (org-element-type context)))
  19025. ;; For convenience: at the first line of a paragraph on the same
  19026. ;; line as an item, apply function on that item instead.
  19027. (when (eq type 'paragraph)
  19028. (let ((parent (org-element-property :parent context)))
  19029. (when (and (eq (org-element-type parent) 'item)
  19030. (= (line-beginning-position)
  19031. (org-element-property :begin parent)))
  19032. (setq context parent)
  19033. (setq type 'item))))
  19034. ;; Act according to type of element or object at point.
  19035. ;;
  19036. ;; Do nothing on a blank line, except if it is contained in
  19037. ;; a src block. Hence, we first check if point is in such
  19038. ;; a block and then if it is at a blank line.
  19039. (pcase type
  19040. ((or `inline-src-block `src-block)
  19041. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19042. (org-babel-eval-wipe-error-buffer)
  19043. (org-babel-execute-src-block
  19044. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19045. ((guard (org-match-line "[ \t]*$"))
  19046. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19047. (user-error
  19048. (substitute-command-keys
  19049. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19050. ((or `babel-call `inline-babel-call)
  19051. (let ((info (org-babel-lob-get-info context)))
  19052. (when info (org-babel-execute-src-block nil info))))
  19053. (`clock (org-clock-update-time-maybe))
  19054. (`dynamic-block
  19055. (save-excursion
  19056. (goto-char (org-element-property :post-affiliated context))
  19057. (org-update-dblock)))
  19058. (`footnote-definition
  19059. (goto-char (org-element-property :post-affiliated context))
  19060. (call-interactively 'org-footnote-action))
  19061. (`footnote-reference (call-interactively #'org-footnote-action))
  19062. ((or `headline `inlinetask)
  19063. (save-excursion (goto-char (org-element-property :begin context))
  19064. (call-interactively #'org-set-tags)))
  19065. (`item
  19066. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19067. ;; unconditionally, whereas `C-u' will toggle its presence.
  19068. ;; Without a universal argument, if the item has a checkbox,
  19069. ;; toggle it. Otherwise repair the list.
  19070. (let* ((box (org-element-property :checkbox context))
  19071. (struct (org-element-property :structure context))
  19072. (old-struct (copy-tree struct))
  19073. (parents (org-list-parents-alist struct))
  19074. (prevs (org-list-prevs-alist struct))
  19075. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19076. (org-list-set-checkbox
  19077. (org-element-property :begin context) struct
  19078. (cond ((equal arg '(16)) "[-]")
  19079. ((and (not box) (equal arg '(4))) "[ ]")
  19080. ((or (not box) (equal arg '(4))) nil)
  19081. ((eq box 'on) "[ ]")
  19082. (t "[X]")))
  19083. ;; Mimic `org-list-write-struct' but with grabbing a return
  19084. ;; value from `org-list-struct-fix-box'.
  19085. (org-list-struct-fix-ind struct parents 2)
  19086. (org-list-struct-fix-item-end struct)
  19087. (org-list-struct-fix-bul struct prevs)
  19088. (org-list-struct-fix-ind struct parents)
  19089. (let ((block-item
  19090. (org-list-struct-fix-box struct parents prevs orderedp)))
  19091. (if (and box (equal struct old-struct))
  19092. (if (equal arg '(16))
  19093. (message "Checkboxes already reset")
  19094. (user-error "Cannot toggle this checkbox: %s"
  19095. (if (eq box 'on)
  19096. "all subitems checked"
  19097. "unchecked subitems")))
  19098. (org-list-struct-apply-struct struct old-struct)
  19099. (org-update-checkbox-count-maybe))
  19100. (when block-item
  19101. (message "Checkboxes were removed due to empty box at line %d"
  19102. (org-current-line block-item))))))
  19103. (`keyword
  19104. (let ((org-inhibit-startup-visibility-stuff t)
  19105. (org-startup-align-all-tables nil))
  19106. (when (boundp 'org-table-coordinate-overlays)
  19107. (mapc #'delete-overlay org-table-coordinate-overlays)
  19108. (setq org-table-coordinate-overlays nil))
  19109. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19110. (message "Local setup has been refreshed"))
  19111. (`plain-list
  19112. ;; At a plain list, with a double C-u argument, set
  19113. ;; checkboxes of each item to "[-]", whereas a single one
  19114. ;; will toggle their presence according to the state of the
  19115. ;; first item in the list. Without an argument, repair the
  19116. ;; list.
  19117. (let* ((begin (org-element-property :contents-begin context))
  19118. (beginm (move-marker (make-marker) begin))
  19119. (struct (org-element-property :structure context))
  19120. (old-struct (copy-tree struct))
  19121. (first-box (save-excursion
  19122. (goto-char begin)
  19123. (looking-at org-list-full-item-re)
  19124. (match-string-no-properties 3)))
  19125. (new-box (cond ((equal arg '(16)) "[-]")
  19126. ((equal arg '(4)) (unless first-box "[ ]"))
  19127. ((equal first-box "[X]") "[ ]")
  19128. (t "[X]"))))
  19129. (cond
  19130. (arg
  19131. (dolist (pos
  19132. (org-list-get-all-items
  19133. begin struct (org-list-prevs-alist struct)))
  19134. (org-list-set-checkbox pos struct new-box)))
  19135. ((and first-box (eq (point) begin))
  19136. ;; For convenience, when point is at bol on the first
  19137. ;; item of the list and no argument is provided, simply
  19138. ;; toggle checkbox of that item, if any.
  19139. (org-list-set-checkbox begin struct new-box)))
  19140. (org-list-write-struct
  19141. struct (org-list-parents-alist struct) old-struct)
  19142. (org-update-checkbox-count-maybe)
  19143. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19144. ((or `property-drawer `node-property)
  19145. (call-interactively #'org-property-action))
  19146. (`radio-target
  19147. (call-interactively #'org-update-radio-target-regexp))
  19148. (`statistics-cookie
  19149. (call-interactively #'org-update-statistics-cookies))
  19150. ((or `table `table-cell `table-row)
  19151. ;; At a table, recalculate every field and align it. Also
  19152. ;; send the table if necessary. If the table has
  19153. ;; a `table.el' type, just give up. At a table row or cell,
  19154. ;; maybe recalculate line but always align table.
  19155. (if (eq (org-element-property :type context) 'table.el)
  19156. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19157. Use `\\[org-edit-special]' to edit table.el tables"))
  19158. (let ((org-enable-table-editor t))
  19159. (if (or (eq type 'table)
  19160. ;; Check if point is at a TBLFM line.
  19161. (and (eq type 'table-row)
  19162. (= (point) (org-element-property :end context))))
  19163. (save-excursion
  19164. (if (org-at-TBLFM-p)
  19165. (progn (require 'org-table)
  19166. (org-table-calc-current-TBLFM))
  19167. (goto-char (org-element-property :contents-begin context))
  19168. (org-call-with-arg 'org-table-recalculate (or arg t))
  19169. (orgtbl-send-table 'maybe)))
  19170. (org-table-maybe-eval-formula)
  19171. (cond (arg (call-interactively #'org-table-recalculate))
  19172. ((org-table-maybe-recalculate-line))
  19173. (t (org-table-align)))))))
  19174. (`timestamp (org-timestamp-change 0 'day))
  19175. ((and `nil (guard (org-at-heading-p)))
  19176. ;; When point is on an unsupported object type, we can miss
  19177. ;; the fact that it also is at a heading. Handle it here.
  19178. (call-interactively #'org-set-tags))
  19179. ((guard
  19180. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19181. (_
  19182. (user-error
  19183. (substitute-command-keys
  19184. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19185. (defun org-mode-restart ()
  19186. (interactive)
  19187. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19188. (funcall major-mode)
  19189. (hack-local-variables)
  19190. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19191. (org-indent-mode -1)))
  19192. (message "%s restarted" major-mode))
  19193. (defun org-kill-note-or-show-branches ()
  19194. "Abort storing current note, or call `outline-show-branches'."
  19195. (interactive)
  19196. (if (not org-finish-function)
  19197. (progn
  19198. (outline-hide-subtree)
  19199. (call-interactively 'outline-show-branches))
  19200. (let ((org-note-abort t))
  19201. (funcall org-finish-function))))
  19202. (defun org-delete-indentation (&optional arg)
  19203. "Join current line to previous and fix whitespace at join.
  19204. If previous line is a headline add to headline title. Otherwise
  19205. the function calls `delete-indentation'.
  19206. With a non-nil optional argument, join it to the following one."
  19207. (interactive "*P")
  19208. (if (save-excursion
  19209. (beginning-of-line (if arg 1 0))
  19210. (let ((case-fold-search nil))
  19211. (looking-at org-complex-heading-regexp)))
  19212. ;; At headline.
  19213. (let ((tags-column (when (match-beginning 5)
  19214. (save-excursion (goto-char (match-beginning 5))
  19215. (current-column))))
  19216. (string (concat " " (progn (when arg (forward-line 1))
  19217. (org-trim (delete-and-extract-region
  19218. (line-beginning-position)
  19219. (line-end-position)))))))
  19220. (unless (bobp) (delete-region (point) (1- (point))))
  19221. (goto-char (or (match-end 4)
  19222. (match-beginning 5)
  19223. (match-end 0)))
  19224. (skip-chars-backward " \t")
  19225. (save-excursion (insert string))
  19226. ;; Adjust alignment of tags.
  19227. (cond
  19228. ((not tags-column)) ;no tags
  19229. (org-auto-align-tags (org-set-tags nil t))
  19230. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19231. (delete-indentation arg)))
  19232. (defun org-open-line (n)
  19233. "Insert a new row in tables, call `open-line' elsewhere.
  19234. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19235. As a special case, when a document starts with a table, allow to
  19236. call `open-line' on the very first character."
  19237. (interactive "*p")
  19238. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19239. (org-table-insert-row)
  19240. (open-line n)))
  19241. (defun org-return (&optional indent)
  19242. "Goto next table row or insert a newline.
  19243. Calls `org-table-next-row' or `newline', depending on context.
  19244. When optional INDENT argument is non-nil, call
  19245. `newline-and-indent' instead of `newline'.
  19246. When `org-return-follows-link' is non-nil and point is on
  19247. a timestamp or a link, call `org-open-at-point'. However, it
  19248. will not happen if point is in a table or on a \"dead\"
  19249. object (e.g., within a comment). In these case, you need to use
  19250. `org-open-at-point' directly."
  19251. (interactive)
  19252. (let ((context (if org-return-follows-link (org-element-context)
  19253. (org-element-at-point))))
  19254. (cond
  19255. ;; In a table, call `org-table-next-row'.
  19256. ((or (and (eq (org-element-type context) 'table)
  19257. (>= (point) (org-element-property :contents-begin context))
  19258. (< (point) (org-element-property :contents-end context)))
  19259. (org-element-lineage context '(table-row table-cell) t))
  19260. (org-table-justify-field-maybe)
  19261. (call-interactively #'org-table-next-row))
  19262. ;; On a link or a timestamp, call `org-open-at-point' if
  19263. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19264. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19265. ((and org-return-follows-link
  19266. (or (org-in-regexp org-ts-regexp-both nil t)
  19267. (org-in-regexp org-tsr-regexp-both nil t)
  19268. (org-in-regexp org-any-link-re nil t)))
  19269. (call-interactively #'org-open-at-point))
  19270. ;; Insert newline in heading, but preserve tags.
  19271. ((and (not (bolp))
  19272. (save-excursion (beginning-of-line)
  19273. (let ((case-fold-search nil))
  19274. (looking-at org-complex-heading-regexp))))
  19275. ;; At headline. Split line. However, if point is on keyword,
  19276. ;; priority cookie or tags, do not break any of them: add
  19277. ;; a newline after the headline instead.
  19278. (let ((tags-column (and (match-beginning 5)
  19279. (save-excursion (goto-char (match-beginning 5))
  19280. (current-column))))
  19281. (string
  19282. (when (and (match-end 4) (org-point-in-group (point) 4))
  19283. (delete-and-extract-region (point) (match-end 4)))))
  19284. ;; Adjust tag alignment.
  19285. (cond
  19286. ((not (and tags-column string)))
  19287. (org-auto-align-tags (org-set-tags nil t))
  19288. (t (org--align-tags-here tags-column))) ;preserve tags column
  19289. (end-of-line)
  19290. (org-show-entry)
  19291. (if indent (newline-and-indent) (newline))
  19292. (when string (save-excursion (insert (org-trim string))))))
  19293. ;; In a list, make sure indenting keeps trailing text within.
  19294. ((and indent
  19295. (not (eolp))
  19296. (org-element-lineage context '(item)))
  19297. (let ((trailing-data
  19298. (delete-and-extract-region (point) (line-end-position))))
  19299. (newline-and-indent)
  19300. (save-excursion (insert trailing-data))))
  19301. (t (if indent (newline-and-indent) (newline))))))
  19302. (defun org-return-indent ()
  19303. "Goto next table row or insert a newline and indent.
  19304. Calls `org-table-next-row' or `newline-and-indent', depending on
  19305. context. See the individual commands for more information."
  19306. (interactive)
  19307. (org-return t))
  19308. (defun org-ctrl-c-star ()
  19309. "Compute table, or change heading status of lines.
  19310. Calls `org-table-recalculate' or `org-toggle-heading',
  19311. depending on context."
  19312. (interactive)
  19313. (cond
  19314. ((org-at-table-p)
  19315. (call-interactively 'org-table-recalculate))
  19316. (t
  19317. ;; Convert all lines in region to list items
  19318. (call-interactively 'org-toggle-heading))))
  19319. (defun org-ctrl-c-minus ()
  19320. "Insert separator line in table or modify bullet status of line.
  19321. Also turns a plain line or a region of lines into list items.
  19322. Calls `org-table-insert-hline', `org-toggle-item', or
  19323. `org-cycle-list-bullet', depending on context."
  19324. (interactive)
  19325. (cond
  19326. ((org-at-table-p)
  19327. (call-interactively 'org-table-insert-hline))
  19328. ((org-region-active-p)
  19329. (call-interactively 'org-toggle-item))
  19330. ((org-in-item-p)
  19331. (call-interactively 'org-cycle-list-bullet))
  19332. (t
  19333. (call-interactively 'org-toggle-item))))
  19334. (defun org-toggle-heading (&optional nstars)
  19335. "Convert headings to normal text, or items or text to headings.
  19336. If there is no active region, only convert the current line.
  19337. With a `\\[universal-argument]' prefix, convert the whole list at
  19338. point into heading.
  19339. In a region:
  19340. - If the first non blank line is a headline, remove the stars
  19341. from all headlines in the region.
  19342. - If it is a normal line, turn each and every normal line (i.e.,
  19343. not an heading or an item) in the region into headings. If you
  19344. want to convert only the first line of this region, use one
  19345. universal prefix argument.
  19346. - If it is a plain list item, turn all plain list items into headings.
  19347. When converting a line into a heading, the number of stars is chosen
  19348. such that the lines become children of the current entry. However,
  19349. when a numeric prefix argument is given, its value determines the
  19350. number of stars to add."
  19351. (interactive "P")
  19352. (let ((skip-blanks
  19353. (function
  19354. ;; Return beginning of first non-blank line, starting from
  19355. ;; line at POS.
  19356. (lambda (pos)
  19357. (save-excursion
  19358. (goto-char pos)
  19359. (while (org-at-comment-p) (forward-line))
  19360. (skip-chars-forward " \r\t\n")
  19361. (point-at-bol)))))
  19362. beg end toggled)
  19363. ;; Determine boundaries of changes. If a universal prefix has
  19364. ;; been given, put the list in a region. If region ends at a bol,
  19365. ;; do not consider the last line to be in the region.
  19366. (when (and current-prefix-arg (org-at-item-p))
  19367. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19368. (org-mark-element))
  19369. (if (org-region-active-p)
  19370. (setq beg (funcall skip-blanks (region-beginning))
  19371. end (copy-marker (save-excursion
  19372. (goto-char (region-end))
  19373. (if (bolp) (point) (point-at-eol)))))
  19374. (setq beg (funcall skip-blanks (point-at-bol))
  19375. end (copy-marker (point-at-eol))))
  19376. ;; Ensure inline tasks don't count as headings.
  19377. (org-with-limited-levels
  19378. (save-excursion
  19379. (goto-char beg)
  19380. (cond
  19381. ;; Case 1. Started at an heading: de-star headings.
  19382. ((org-at-heading-p)
  19383. (while (< (point) end)
  19384. (when (org-at-heading-p t)
  19385. (looking-at org-outline-regexp) (replace-match "")
  19386. (setq toggled t))
  19387. (forward-line)))
  19388. ;; Case 2. Started at an item: change items into headlines.
  19389. ;; One star will be added by `org-list-to-subtree'.
  19390. ((org-at-item-p)
  19391. (while (< (point) end)
  19392. (when (org-at-item-p)
  19393. ;; Pay attention to cases when region ends before list.
  19394. (let* ((struct (org-list-struct))
  19395. (list-end
  19396. (min (org-list-get-bottom-point struct) (1+ end))))
  19397. (save-restriction
  19398. (narrow-to-region (point) list-end)
  19399. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19400. (setq toggled t))
  19401. (forward-line)))
  19402. ;; Case 3. Started at normal text: make every line an heading,
  19403. ;; skipping headlines and items.
  19404. (t (let* ((stars
  19405. (make-string
  19406. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19407. (add-stars
  19408. (cond (nstars "") ; stars from prefix only
  19409. ((equal stars "") "*") ; before first heading
  19410. (org-odd-levels-only "**") ; inside heading, odd
  19411. (t "*"))) ; inside heading, oddeven
  19412. (rpl (concat stars add-stars " "))
  19413. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19414. (while (< (point) (if (equal nstars '(4)) lend end))
  19415. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19416. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19417. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19418. (forward-line)))))))
  19419. (unless toggled (message "Cannot toggle heading from here"))))
  19420. (defun org-meta-return (&optional arg)
  19421. "Insert a new heading or wrap a region in a table.
  19422. Calls `org-insert-heading', `org-insert-item' or
  19423. `org-table-wrap-region', depending on context. When called with
  19424. an argument, unconditionally call `org-insert-heading'."
  19425. (interactive "P")
  19426. (org-check-before-invisible-edit 'insert)
  19427. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19428. (call-interactively (cond (arg #'org-insert-heading)
  19429. ((org-at-table-p) #'org-table-wrap-region)
  19430. ((org-in-item-p) #'org-insert-item)
  19431. (t #'org-insert-heading)))))
  19432. ;;; Menu entries
  19433. (defsubst org-in-subtree-not-table-p ()
  19434. "Are we in a subtree and not in a table?"
  19435. (and (not (org-before-first-heading-p))
  19436. (not (org-at-table-p))))
  19437. ;; Define the Org mode menus
  19438. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19439. '("Tbl"
  19440. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19441. ["Next Field" org-cycle (org-at-table-p)]
  19442. ["Previous Field" org-shifttab (org-at-table-p)]
  19443. ["Next Row" org-return (org-at-table-p)]
  19444. "--"
  19445. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19446. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19447. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19448. "--"
  19449. ("Column"
  19450. ["Move Column Left" org-metaleft (org-at-table-p)]
  19451. ["Move Column Right" org-metaright (org-at-table-p)]
  19452. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19453. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19454. ("Row"
  19455. ["Move Row Up" org-metaup (org-at-table-p)]
  19456. ["Move Row Down" org-metadown (org-at-table-p)]
  19457. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19458. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19459. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19460. "--"
  19461. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19462. ("Rectangle"
  19463. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19464. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19465. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19466. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19467. "--"
  19468. ("Calculate"
  19469. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19470. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19471. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19472. "--"
  19473. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19474. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19475. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19476. "--"
  19477. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19478. "--"
  19479. ["Sum Column/Rectangle" org-table-sum
  19480. (or (org-at-table-p) (org-region-active-p))]
  19481. ["Which Column?" org-table-current-column (org-at-table-p)])
  19482. ["Debug Formulas"
  19483. org-table-toggle-formula-debugger
  19484. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19485. ["Show Col/Row Numbers"
  19486. org-table-toggle-coordinate-overlays
  19487. :style toggle
  19488. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19489. "--"
  19490. ["Create" org-table-create (and (not (org-at-table-p))
  19491. org-enable-table-editor)]
  19492. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19493. ["Import from File" org-table-import (not (org-at-table-p))]
  19494. ["Export to File" org-table-export (org-at-table-p)]
  19495. "--"
  19496. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19497. "--"
  19498. ("Plot"
  19499. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19500. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19501. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19502. '("Org"
  19503. ("Show/Hide"
  19504. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19505. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19506. ["Sparse Tree..." org-sparse-tree t]
  19507. ["Reveal Context" org-reveal t]
  19508. ["Show All" outline-show-all t]
  19509. "--"
  19510. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19511. "--"
  19512. ["New Heading" org-insert-heading t]
  19513. ("Navigate Headings"
  19514. ["Up" outline-up-heading t]
  19515. ["Next" outline-next-visible-heading t]
  19516. ["Previous" outline-previous-visible-heading t]
  19517. ["Next Same Level" outline-forward-same-level t]
  19518. ["Previous Same Level" outline-backward-same-level t]
  19519. "--"
  19520. ["Jump" org-goto t])
  19521. ("Edit Structure"
  19522. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19523. "--"
  19524. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19525. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19526. "--"
  19527. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19528. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19529. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19530. "--"
  19531. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19532. "--"
  19533. ["Copy visible text" org-copy-visible t]
  19534. "--"
  19535. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19536. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19537. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19538. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19539. "--"
  19540. ["Sort Region/Children" org-sort t]
  19541. "--"
  19542. ["Convert to odd levels" org-convert-to-odd-levels t]
  19543. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19544. ("Editing"
  19545. ["Emphasis..." org-emphasize t]
  19546. ["Edit Source Example" org-edit-special t]
  19547. "--"
  19548. ["Footnote new/jump" org-footnote-action t]
  19549. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19550. ("Archive"
  19551. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19552. "--"
  19553. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19554. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19555. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19556. )
  19557. "--"
  19558. ("Hyperlinks"
  19559. ["Store Link (Global)" org-store-link t]
  19560. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19561. ["Insert Link" org-insert-link t]
  19562. ["Follow Link" org-open-at-point t]
  19563. "--"
  19564. ["Next link" org-next-link t]
  19565. ["Previous link" org-previous-link t]
  19566. "--"
  19567. ["Descriptive Links"
  19568. org-toggle-link-display
  19569. :style radio
  19570. :selected org-descriptive-links
  19571. ]
  19572. ["Literal Links"
  19573. org-toggle-link-display
  19574. :style radio
  19575. :selected (not org-descriptive-links)])
  19576. "--"
  19577. ("TODO Lists"
  19578. ["TODO/DONE/-" org-todo t]
  19579. ("Select keyword"
  19580. ["Next keyword" org-shiftright (org-at-heading-p)]
  19581. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19582. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19583. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19584. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19585. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19586. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19587. "--"
  19588. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19589. :selected org-enforce-todo-dependencies :style toggle :active t]
  19590. "Settings for tree at point"
  19591. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19592. :selected (org-entry-get nil "ORDERED")
  19593. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19594. ["Do Children parallel" org-toggle-ordered-property :style radio
  19595. :selected (not (org-entry-get nil "ORDERED"))
  19596. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19597. "--"
  19598. ["Set Priority" org-priority t]
  19599. ["Priority Up" org-shiftup t]
  19600. ["Priority Down" org-shiftdown t]
  19601. "--"
  19602. ["Get news from all feeds" org-feed-update-all t]
  19603. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19604. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19605. ("TAGS and Properties"
  19606. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19607. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19608. "--"
  19609. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19610. ["Column view of properties" org-columns t]
  19611. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19612. ("Dates and Scheduling"
  19613. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19614. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19615. ("Change Date"
  19616. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19617. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19618. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19619. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19620. ["Compute Time Range" org-evaluate-time-range t]
  19621. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19622. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19623. "--"
  19624. ["Custom time format" org-toggle-time-stamp-overlays
  19625. :style radio :selected org-display-custom-times]
  19626. "--"
  19627. ["Goto Calendar" org-goto-calendar t]
  19628. ["Date from Calendar" org-date-from-calendar t]
  19629. "--"
  19630. ["Start/Restart Timer" org-timer-start t]
  19631. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19632. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19633. ["Insert Timer String" org-timer t]
  19634. ["Insert Timer Item" org-timer-item t])
  19635. ("Logging work"
  19636. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19637. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19638. ["Clock out" org-clock-out t]
  19639. ["Clock cancel" org-clock-cancel t]
  19640. "--"
  19641. ["Mark as default task" org-clock-mark-default-task t]
  19642. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19643. ["Goto running clock" org-clock-goto t]
  19644. "--"
  19645. ["Display times" org-clock-display t]
  19646. ["Create clock table" org-clock-report t]
  19647. "--"
  19648. ["Record DONE time"
  19649. (progn (setq org-log-done (not org-log-done))
  19650. (message "Switching to %s will %s record a timestamp"
  19651. (car org-done-keywords)
  19652. (if org-log-done "automatically" "not")))
  19653. :style toggle :selected org-log-done])
  19654. "--"
  19655. ["Agenda Command..." org-agenda t]
  19656. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19657. ("File List for Agenda")
  19658. ("Special views current file"
  19659. ["TODO Tree" org-show-todo-tree t]
  19660. ["Check Deadlines" org-check-deadlines t]
  19661. ["Tags/Property tree" org-match-sparse-tree t])
  19662. "--"
  19663. ["Export/Publish..." org-export-dispatch t]
  19664. ("LaTeX"
  19665. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19666. :selected org-cdlatex-mode]
  19667. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19668. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19669. ["Modify math symbol" org-cdlatex-math-modify
  19670. (org-inside-LaTeX-fragment-p)]
  19671. ["Insert citation" org-reftex-citation t])
  19672. "--"
  19673. ("MobileOrg"
  19674. ["Push Files and Views" org-mobile-push t]
  19675. ["Get Captured and Flagged" org-mobile-pull t]
  19676. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19677. "--"
  19678. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19679. "--"
  19680. ("Documentation"
  19681. ["Show Version" org-version t]
  19682. ["Info Documentation" org-info t])
  19683. ("Customize"
  19684. ["Browse Org Group" org-customize t]
  19685. "--"
  19686. ["Expand This Menu" org-create-customize-menu
  19687. (fboundp 'customize-menu-create)])
  19688. ["Send bug report" org-submit-bug-report t]
  19689. "--"
  19690. ("Refresh/Reload"
  19691. ["Refresh setup current buffer" org-mode-restart t]
  19692. ["Reload Org (after update)" org-reload t]
  19693. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19694. ))
  19695. (defun org-info (&optional node)
  19696. "Read documentation for Org in the info system.
  19697. With optional NODE, go directly to that node."
  19698. (interactive)
  19699. (info (format "(org)%s" (or node ""))))
  19700. ;;;###autoload
  19701. (defun org-submit-bug-report ()
  19702. "Submit a bug report on Org via mail.
  19703. Don't hesitate to report any problems or inaccurate documentation.
  19704. If you don't have setup sending mail from (X)Emacs, please copy the
  19705. output buffer into your mail program, as it gives us important
  19706. information about your Org version and configuration."
  19707. (interactive)
  19708. (require 'reporter)
  19709. (defvar reporter-prompt-for-summary-p)
  19710. (org-load-modules-maybe)
  19711. (org-require-autoloaded-modules)
  19712. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19713. (reporter-submit-bug-report
  19714. "emacs-orgmode@gnu.org"
  19715. (org-version nil 'full)
  19716. (let (list)
  19717. (save-window-excursion
  19718. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19719. (delete-other-windows)
  19720. (erase-buffer)
  19721. (insert "You are about to submit a bug report to the Org mailing list.
  19722. We would like to add your full Org and Outline configuration to the
  19723. bug report. This greatly simplifies the work of the maintainer and
  19724. other experts on the mailing list.
  19725. HOWEVER, some variables you have customized may contain private
  19726. information. The names of customers, colleagues, or friends, might
  19727. appear in the form of file names, tags, todo states, or search strings.
  19728. If you answer yes to the prompt, you might want to check and remove
  19729. such private information before sending the email.")
  19730. (add-text-properties (point-min) (point-max) '(face org-warning))
  19731. (when (yes-or-no-p "Include your Org configuration ")
  19732. (mapatoms
  19733. (lambda (v)
  19734. (and (boundp v)
  19735. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19736. (or (and (symbol-value v)
  19737. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19738. (and
  19739. (get v 'custom-type) (get v 'standard-value)
  19740. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19741. (push v list)))))
  19742. (kill-buffer (get-buffer "*Warn about privacy*"))
  19743. list))
  19744. nil nil
  19745. "Remember to cover the basics, that is, what you expected to happen and
  19746. what in fact did happen. You don't know how to make a good report? See
  19747. http://orgmode.org/manual/Feedback.html#Feedback
  19748. Your bug report will be posted to the Org mailing list.
  19749. ------------------------------------------------------------------------")
  19750. (save-excursion
  19751. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19752. (replace-match "\\1Bug: \\3 [\\2]")))))
  19753. (defun org-install-agenda-files-menu ()
  19754. (let ((bl (buffer-list)))
  19755. (save-excursion
  19756. (while bl
  19757. (set-buffer (pop bl))
  19758. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19759. (when (derived-mode-p 'org-mode)
  19760. (easy-menu-change
  19761. '("Org") "File List for Agenda"
  19762. (append
  19763. (list
  19764. ["Edit File List" (org-edit-agenda-file-list) t]
  19765. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19766. ["Remove Current File from List" org-remove-file t]
  19767. ["Cycle through agenda files" org-cycle-agenda-files t]
  19768. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19769. "--")
  19770. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19771. ;;;; Documentation
  19772. (defun org-require-autoloaded-modules ()
  19773. (interactive)
  19774. (mapc #'require
  19775. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19776. org-table org-timer)))
  19777. ;;;###autoload
  19778. (defun org-reload (&optional uncompiled)
  19779. "Reload all org lisp files.
  19780. With prefix arg UNCOMPILED, load the uncompiled versions."
  19781. (interactive "P")
  19782. (require 'loadhist)
  19783. (let* ((org-dir (org-find-library-dir "org"))
  19784. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19785. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19786. (remove-re (format "\\`%s\\'"
  19787. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19788. (feats (delete-dups
  19789. (mapcar 'file-name-sans-extension
  19790. (mapcar 'file-name-nondirectory
  19791. (delq nil
  19792. (mapcar 'feature-file
  19793. features))))))
  19794. (lfeat (append
  19795. (sort
  19796. (setq feats
  19797. (delq nil (mapcar
  19798. (lambda (f)
  19799. (if (and (string-match feature-re f)
  19800. (not (string-match remove-re f)))
  19801. f nil))
  19802. feats)))
  19803. 'string-lessp)
  19804. (list "org-version" "org")))
  19805. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19806. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19807. load-uncore load-misses)
  19808. (setq load-misses
  19809. (delq 't
  19810. (mapcar (lambda (f)
  19811. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19812. (and (string= org-dir contrib-dir)
  19813. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19814. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19815. (add-to-list 'load-uncore f 'append)
  19816. 't)
  19817. f))
  19818. lfeat)))
  19819. (when load-uncore
  19820. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19821. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19822. (if load-misses
  19823. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19824. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19825. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19826. ;;;###autoload
  19827. (defun org-customize ()
  19828. "Call the customize function with org as argument."
  19829. (interactive)
  19830. (org-load-modules-maybe)
  19831. (org-require-autoloaded-modules)
  19832. (customize-browse 'org))
  19833. (defun org-create-customize-menu ()
  19834. "Create a full customization menu for Org mode, insert it into the menu."
  19835. (interactive)
  19836. (org-load-modules-maybe)
  19837. (org-require-autoloaded-modules)
  19838. (if (fboundp 'customize-menu-create)
  19839. (progn
  19840. (easy-menu-change
  19841. '("Org") "Customize"
  19842. `(["Browse Org group" org-customize t]
  19843. "--"
  19844. ,(customize-menu-create 'org)
  19845. ["Set" Custom-set t]
  19846. ["Save" Custom-save t]
  19847. ["Reset to Current" Custom-reset-current t]
  19848. ["Reset to Saved" Custom-reset-saved t]
  19849. ["Reset to Standard Settings" Custom-reset-standard t]))
  19850. (message "\"Org\"-menu now contains full customization menu"))
  19851. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19852. ;;;; Miscellaneous stuff
  19853. ;;; Generally useful functions
  19854. (defun org-get-at-eol (property n)
  19855. "Get text property PROPERTY at the end of line less N characters."
  19856. (get-text-property (- (point-at-eol) n) property))
  19857. (defun org-find-text-property-in-string (prop s)
  19858. "Return the first non-nil value of property PROP in string S."
  19859. (or (get-text-property 0 prop s)
  19860. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19861. prop s)))
  19862. (defun org-display-warning (message)
  19863. "Display the given MESSAGE as a warning."
  19864. (display-warning 'org message :warning))
  19865. (defun org-eval (form)
  19866. "Eval FORM and return result."
  19867. (condition-case error
  19868. (eval form)
  19869. (error (format "%%![Error: %s]" error))))
  19870. (defun org-in-clocktable-p ()
  19871. "Check if the cursor is in a clocktable."
  19872. (let ((pos (point)) start)
  19873. (save-excursion
  19874. (end-of-line 1)
  19875. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19876. (setq start (match-beginning 0))
  19877. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19878. (>= (match-end 0) pos)
  19879. start))))
  19880. (defun org-in-verbatim-emphasis ()
  19881. (save-match-data
  19882. (and (org-in-regexp org-verbatim-re 2)
  19883. (>= (point) (match-beginning 3))
  19884. (<= (point) (match-end 4)))))
  19885. (defun org-overlay-display (ovl text &optional face evap)
  19886. "Make overlay OVL display TEXT with face FACE."
  19887. (overlay-put ovl 'display text)
  19888. (if face (overlay-put ovl 'face face))
  19889. (if evap (overlay-put ovl 'evaporate t)))
  19890. (defun org-overlay-before-string (ovl text &optional face evap)
  19891. "Make overlay OVL display TEXT with face FACE."
  19892. (if face (org-add-props text nil 'face face))
  19893. (overlay-put ovl 'before-string text)
  19894. (if evap (overlay-put ovl 'evaporate t)))
  19895. (defun org-find-overlays (prop &optional pos delete)
  19896. "Find all overlays specifying PROP at POS or point.
  19897. If DELETE is non-nil, delete all those overlays."
  19898. (let (found)
  19899. (dolist (ov (overlays-at (or pos (point))) found)
  19900. (cond ((not (overlay-get ov prop)))
  19901. (delete (delete-overlay ov))
  19902. (t (push ov found))))))
  19903. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19904. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19905. (if (and marker (marker-buffer marker)
  19906. (buffer-live-p (marker-buffer marker)))
  19907. (progn
  19908. (pop-to-buffer-same-window (marker-buffer marker))
  19909. (when (or (> marker (point-max)) (< marker (point-min)))
  19910. (widen))
  19911. (goto-char marker)
  19912. (org-show-context 'org-goto))
  19913. (if bookmark
  19914. (bookmark-jump bookmark)
  19915. (error "Cannot find location"))))
  19916. (defun org-quote-csv-field (s)
  19917. "Quote field for inclusion in CSV material."
  19918. (if (string-match "[\",]" s)
  19919. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19920. s))
  19921. (defun org-force-self-insert (N)
  19922. "Needed to enforce self-insert under remapping."
  19923. (interactive "p")
  19924. (self-insert-command N))
  19925. (defun org-string-width (s)
  19926. "Compute width of string, ignoring invisible characters.
  19927. This ignores character with invisibility property `org-link', and also
  19928. characters with property `org-cwidth', because these will become invisible
  19929. upon the next fontification round."
  19930. (let (b l)
  19931. (when (or (eq t buffer-invisibility-spec)
  19932. (assq 'org-link buffer-invisibility-spec))
  19933. (while (setq b (text-property-any 0 (length s)
  19934. 'invisible 'org-link s))
  19935. (setq s (concat (substring s 0 b)
  19936. (substring s (or (next-single-property-change
  19937. b 'invisible s)
  19938. (length s)))))))
  19939. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  19940. (setq s (concat (substring s 0 b)
  19941. (substring s (or (next-single-property-change
  19942. b 'org-cwidth s)
  19943. (length s))))))
  19944. (setq l (string-width s) b -1)
  19945. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  19946. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  19947. l))
  19948. (defun org-shorten-string (s maxlength)
  19949. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19950. If the string is shorter or has length MAXLENGTH, just return the
  19951. original string. If it is longer, the functions finds a space in the
  19952. string, breaks this string off at that locations and adds three dots
  19953. as ellipsis. Including the ellipsis, the string will not be longer
  19954. than MAXLENGTH. If finding a good breaking point in the string does
  19955. not work, the string is just chopped off in the middle of a word
  19956. if necessary."
  19957. (if (<= (length s) maxlength)
  19958. s
  19959. (let* ((n (max (- maxlength 4) 1))
  19960. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19961. (if (string-match re s)
  19962. (concat (match-string 1 s) "...")
  19963. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19964. (defun org-get-indentation (&optional line)
  19965. "Get the indentation of the current line, interpreting tabs.
  19966. When LINE is given, assume it represents a line and compute its indentation."
  19967. (if line
  19968. (when (string-match "^ *" (org-remove-tabs line))
  19969. (match-end 0))
  19970. (save-excursion
  19971. (beginning-of-line 1)
  19972. (skip-chars-forward " \t")
  19973. (current-column))))
  19974. (defun org-get-string-indentation (s)
  19975. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19976. (let ((n -1) (i 0) (w tab-width) c)
  19977. (catch 'exit
  19978. (while (< (setq n (1+ n)) (length s))
  19979. (setq c (aref s n))
  19980. (cond ((= c ?\ ) (setq i (1+ i)))
  19981. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19982. (t (throw 'exit t)))))
  19983. i))
  19984. (defun org-remove-tabs (s &optional width)
  19985. "Replace tabulators in S with spaces.
  19986. Assumes that s is a single line, starting in column 0."
  19987. (setq width (or width tab-width))
  19988. (while (string-match "\t" s)
  19989. (setq s (replace-match
  19990. (make-string
  19991. (- (* width (/ (+ (match-beginning 0) width) width))
  19992. (match-beginning 0)) ?\ )
  19993. t t s)))
  19994. s)
  19995. (defun org-fix-indentation (line ind)
  19996. "Fix indentation in LINE.
  19997. IND is a cons cell with target and minimum indentation.
  19998. If the current indentation in LINE is smaller than the minimum,
  19999. leave it alone. If it is larger than ind, set it to the target."
  20000. (let* ((l (org-remove-tabs line))
  20001. (i (org-get-indentation l))
  20002. (i1 (car ind)) (i2 (cdr ind)))
  20003. (when (>= i i2) (setq l (substring line i2)))
  20004. (if (> i1 0)
  20005. (concat (make-string i1 ?\ ) l)
  20006. l)))
  20007. (defun org-remove-indentation (code &optional n)
  20008. "Remove maximum common indentation in string CODE and return it.
  20009. N may optionally be the number of columns to remove. Return CODE
  20010. as-is if removal failed."
  20011. (with-temp-buffer
  20012. (insert code)
  20013. (if (org-do-remove-indentation n) (buffer-string) code)))
  20014. (defun org-do-remove-indentation (&optional n)
  20015. "Remove the maximum common indentation from the buffer.
  20016. When optional argument N is a positive integer, remove exactly
  20017. that much characters from indentation, if possible. Return nil
  20018. if it fails."
  20019. (catch :exit
  20020. (goto-char (point-min))
  20021. ;; Find maximum common indentation, if not specified.
  20022. (let ((n (or n
  20023. (let ((min-ind (point-max)))
  20024. (save-excursion
  20025. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20026. (let ((ind (1- (current-column))))
  20027. (if (zerop ind) (throw :exit nil)
  20028. (setq min-ind (min min-ind ind))))))
  20029. min-ind))))
  20030. (if (zerop n) (throw :exit nil)
  20031. ;; Remove exactly N indentation, but give up if not possible.
  20032. (while (not (eobp))
  20033. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20034. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20035. ((< ind n) (throw :exit nil))
  20036. (t (indent-line-to (- ind n))))
  20037. (forward-line)))
  20038. ;; Signal success.
  20039. t))))
  20040. (defun org-fill-template (template alist)
  20041. "Find each %key of ALIST in TEMPLATE and replace it."
  20042. (let ((case-fold-search nil))
  20043. (dolist (entry (sort (copy-sequence alist)
  20044. (lambda (a b) (< (length (car a)) (length (car b))))))
  20045. (setq template
  20046. (replace-regexp-in-string
  20047. (concat "%" (regexp-quote (car entry)))
  20048. (or (cdr entry) "") template t t)))
  20049. template))
  20050. (defun org-base-buffer (buffer)
  20051. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20052. (if (not buffer)
  20053. buffer
  20054. (or (buffer-base-buffer buffer)
  20055. buffer)))
  20056. (defun org-wrap (string &optional width lines)
  20057. "Wrap string to either a number of lines, or a width in characters.
  20058. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20059. that costs. If there is a word longer than WIDTH, the text is actually
  20060. wrapped to the length of that word.
  20061. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20062. many lines, whatever width that takes.
  20063. The return value is a list of lines, without newlines at the end."
  20064. (let* ((words (org-split-string string "[ \t\n]+"))
  20065. (maxword (apply 'max (mapcar 'org-string-width words)))
  20066. w ll)
  20067. (cond (width
  20068. (org-do-wrap words (max maxword width)))
  20069. (lines
  20070. (setq w maxword)
  20071. (setq ll (org-do-wrap words maxword))
  20072. (if (<= (length ll) lines)
  20073. ll
  20074. (setq ll words)
  20075. (while (> (length ll) lines)
  20076. (setq w (1+ w))
  20077. (setq ll (org-do-wrap words w)))
  20078. ll))
  20079. (t (error "Cannot wrap this")))))
  20080. (defun org-do-wrap (words width)
  20081. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20082. (let (lines line)
  20083. (while words
  20084. (setq line (pop words))
  20085. (while (and words (< (+ (length line) (length (car words))) width))
  20086. (setq line (concat line " " (pop words))))
  20087. (setq lines (push line lines)))
  20088. (nreverse lines)))
  20089. (defun org-split-string (string &optional separators)
  20090. "Splits STRING into substrings at SEPARATORS.
  20091. SEPARATORS is a regular expression.
  20092. No empty strings are returned if there are matches at the beginning
  20093. and end of string."
  20094. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20095. (let ((start 0) notfirst list)
  20096. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20097. (if (and notfirst
  20098. (= start (match-beginning 0))
  20099. (< start (length string)))
  20100. (1+ start) start))
  20101. (< (match-beginning 0) (length string)))
  20102. (setq notfirst t)
  20103. (or (eq (match-beginning 0) 0)
  20104. (and (eq (match-beginning 0) (match-end 0))
  20105. (eq (match-beginning 0) start))
  20106. (push (substring string start (match-beginning 0)) list))
  20107. (setq start (match-end 0)))
  20108. (or (eq start (length string))
  20109. (push (substring string start) list))
  20110. (nreverse list)))
  20111. (defun org-quote-vert (s)
  20112. "Replace \"|\" with \"\\vert\"."
  20113. (while (string-match "|" s)
  20114. (setq s (replace-match "\\vert" t t s)))
  20115. s)
  20116. (defun org-uuidgen-p (s)
  20117. "Is S an ID created by UUIDGEN?"
  20118. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20119. (defun org-in-src-block-p (&optional inside)
  20120. "Whether point is in a code source block.
  20121. When INSIDE is non-nil, don't consider we are within a src block
  20122. when point is at #+BEGIN_SRC or #+END_SRC."
  20123. (let ((case-fold-search t))
  20124. (or (and (eq (get-char-property (point) 'src-block) t))
  20125. (and (not inside)
  20126. (save-match-data
  20127. (save-excursion
  20128. (beginning-of-line)
  20129. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20130. (defun org-context ()
  20131. "Return a list of contexts of the current cursor position.
  20132. If several contexts apply, all are returned.
  20133. Each context entry is a list with a symbol naming the context, and
  20134. two positions indicating start and end of the context. Possible
  20135. contexts are:
  20136. :headline anywhere in a headline
  20137. :headline-stars on the leading stars in a headline
  20138. :todo-keyword on a TODO keyword (including DONE) in a headline
  20139. :tags on the TAGS in a headline
  20140. :priority on the priority cookie in a headline
  20141. :item on the first line of a plain list item
  20142. :item-bullet on the bullet/number of a plain list item
  20143. :checkbox on the checkbox in a plain list item
  20144. :table in an Org table
  20145. :table-special on a special filed in a table
  20146. :table-table in a table.el table
  20147. :clocktable in a clocktable
  20148. :src-block in a source block
  20149. :link on a hyperlink
  20150. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20151. :target on a <<target>>
  20152. :radio-target on a <<<radio-target>>>
  20153. :latex-fragment on a LaTeX fragment
  20154. :latex-preview on a LaTeX fragment with overlaid preview image
  20155. This function expects the position to be visible because it uses font-lock
  20156. faces as a help to recognize the following contexts: :table-special, :link,
  20157. and :keyword."
  20158. (let* ((f (get-text-property (point) 'face))
  20159. (faces (if (listp f) f (list f)))
  20160. (case-fold-search t)
  20161. (p (point)) clist o)
  20162. ;; First the large context
  20163. (cond
  20164. ((org-at-heading-p t)
  20165. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20166. (when (progn
  20167. (beginning-of-line 1)
  20168. (looking-at org-todo-line-tags-regexp))
  20169. (push (org-point-in-group p 1 :headline-stars) clist)
  20170. (push (org-point-in-group p 2 :todo-keyword) clist)
  20171. (push (org-point-in-group p 4 :tags) clist))
  20172. (goto-char p)
  20173. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20174. (when (looking-at "\\[#[A-Z0-9]\\]")
  20175. (push (org-point-in-group p 0 :priority) clist)))
  20176. ((org-at-item-p)
  20177. (push (org-point-in-group p 2 :item-bullet) clist)
  20178. (push (list :item (point-at-bol)
  20179. (save-excursion (org-end-of-item) (point)))
  20180. clist)
  20181. (and (org-at-item-checkbox-p)
  20182. (push (org-point-in-group p 0 :checkbox) clist)))
  20183. ((org-at-table-p)
  20184. (push (list :table (org-table-begin) (org-table-end)) clist)
  20185. (when (memq 'org-formula faces)
  20186. (push (list :table-special
  20187. (previous-single-property-change p 'face)
  20188. (next-single-property-change p 'face)) clist)))
  20189. ((org-at-table-p 'any)
  20190. (push (list :table-table) clist)))
  20191. (goto-char p)
  20192. (let ((case-fold-search t))
  20193. ;; New the "medium" contexts: clocktables, source blocks
  20194. (cond ((org-in-clocktable-p)
  20195. (push (list :clocktable
  20196. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20197. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20198. (match-beginning 1))
  20199. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20200. (match-end 0))) clist))
  20201. ((org-in-src-block-p)
  20202. (push (list :src-block
  20203. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20204. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20205. (match-beginning 1))
  20206. (and (search-forward "#+END_SRC" nil t)
  20207. (match-beginning 0))) clist))))
  20208. (goto-char p)
  20209. ;; Now the small context
  20210. (cond
  20211. ((org-at-timestamp-p)
  20212. (push (org-point-in-group p 0 :timestamp) clist))
  20213. ((memq 'org-link faces)
  20214. (push (list :link
  20215. (previous-single-property-change p 'face)
  20216. (next-single-property-change p 'face)) clist))
  20217. ((memq 'org-special-keyword faces)
  20218. (push (list :keyword
  20219. (previous-single-property-change p 'face)
  20220. (next-single-property-change p 'face)) clist))
  20221. ((org-at-target-p)
  20222. (push (org-point-in-group p 0 :target) clist)
  20223. (goto-char (1- (match-beginning 0)))
  20224. (when (looking-at org-radio-target-regexp)
  20225. (push (org-point-in-group p 0 :radio-target) clist))
  20226. (goto-char p))
  20227. ((setq o (cl-some
  20228. (lambda (o)
  20229. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20230. o))
  20231. (overlays-at (point))))
  20232. (push (list :latex-fragment
  20233. (overlay-start o) (overlay-end o)) clist)
  20234. (push (list :latex-preview
  20235. (overlay-start o) (overlay-end o)) clist))
  20236. ((org-inside-LaTeX-fragment-p)
  20237. ;; FIXME: positions wrong.
  20238. (push (list :latex-fragment (point) (point)) clist)))
  20239. (setq clist (nreverse (delq nil clist)))
  20240. clist))
  20241. (defun org-in-regexp (regexp &optional nlines visually)
  20242. "Check if point is inside a match of REGEXP.
  20243. Normally only the current line is checked, but you can include
  20244. NLINES extra lines around point into the search. If VISUALLY is
  20245. set, require that the cursor is not after the match but really
  20246. on, so that the block visually is on the match.
  20247. Return nil or a cons cell (BEG . END) where BEG and END are,
  20248. respectively, the positions at the beginning and the end of the
  20249. match."
  20250. (catch :exit
  20251. (let ((pos (point))
  20252. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20253. (save-excursion
  20254. (beginning-of-line (- 1 (or nlines 0)))
  20255. (while (and (re-search-forward regexp eol t)
  20256. (<= (match-beginning 0) pos))
  20257. (let ((end (match-end 0)))
  20258. (when (or (> end pos) (and (= end pos) (not visually)))
  20259. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20260. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20261. "Non-nil when point is between matches of START-RE and END-RE.
  20262. Also return a non-nil value when point is on one of the matches.
  20263. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20264. buffer positions. Default values are the positions of headlines
  20265. surrounding the point.
  20266. The functions returns a cons cell whose car (resp. cdr) is the
  20267. position before START-RE (resp. after END-RE)."
  20268. (save-match-data
  20269. (let ((pos (point))
  20270. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20271. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20272. beg end)
  20273. (save-excursion
  20274. ;; Point is on a block when on START-RE or if START-RE can be
  20275. ;; found before it...
  20276. (and (or (org-in-regexp start-re)
  20277. (re-search-backward start-re limit-up t))
  20278. (setq beg (match-beginning 0))
  20279. ;; ... and END-RE after it...
  20280. (goto-char (match-end 0))
  20281. (re-search-forward end-re limit-down t)
  20282. (> (setq end (match-end 0)) pos)
  20283. ;; ... without another START-RE in-between.
  20284. (goto-char (match-beginning 0))
  20285. (not (re-search-backward start-re (1+ beg) t))
  20286. ;; Return value.
  20287. (cons beg end))))))
  20288. (defun org-in-block-p (names)
  20289. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20290. NAMES is a list of strings containing names of blocks.
  20291. Return first block name matched, or nil. Beware that in case of
  20292. nested blocks, the returned name may not belong to the closest
  20293. block from point."
  20294. (save-match-data
  20295. (catch 'exit
  20296. (let ((case-fold-search t)
  20297. (lim-up (save-excursion (outline-previous-heading)))
  20298. (lim-down (save-excursion (outline-next-heading))))
  20299. (dolist (name names)
  20300. (let ((n (regexp-quote name)))
  20301. (when (org-between-regexps-p
  20302. (concat "^[ \t]*#\\+begin_" n)
  20303. (concat "^[ \t]*#\\+end_" n)
  20304. lim-up lim-down)
  20305. (throw 'exit n)))))
  20306. nil)))
  20307. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20308. "Call `multi-occur' with buffers for all agenda files."
  20309. (interactive "sOrg-files matching: ")
  20310. (let* ((files (org-agenda-files))
  20311. (tnames (mapcar #'file-truename files))
  20312. (extra org-agenda-text-search-extra-files))
  20313. (when (eq (car extra) 'agenda-archives)
  20314. (setq extra (cdr extra))
  20315. (setq files (org-add-archive-files files)))
  20316. (dolist (f extra)
  20317. (unless (member (file-truename f) tnames)
  20318. (unless (member f files) (setq files (append files (list f))))
  20319. (setq tnames (append tnames (list (file-truename f))))))
  20320. (multi-occur
  20321. (mapcar (lambda (x)
  20322. (with-current-buffer
  20323. ;; FIXME: Why not just (find-file-noselect x)?
  20324. ;; Is it to avoid the "revert buffer" prompt?
  20325. (or (get-file-buffer x) (find-file-noselect x))
  20326. (widen)
  20327. (current-buffer)))
  20328. files)
  20329. regexp)))
  20330. (add-hook 'occur-mode-find-occurrence-hook
  20331. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20332. (defun org-occur-link-in-agenda-files ()
  20333. "Create a link and search for it in the agendas.
  20334. The link is not stored in `org-stored-links', it is just created
  20335. for the search purpose."
  20336. (interactive)
  20337. (let ((link (condition-case nil
  20338. (org-store-link nil)
  20339. (error "Unable to create a link to here"))))
  20340. (org-occur-in-agenda-files (regexp-quote link))))
  20341. (defun org-reverse-string (string)
  20342. "Return the reverse of STRING."
  20343. (apply 'string (reverse (string-to-list string))))
  20344. ;; defsubst org-uniquify must be defined before first use
  20345. (defun org-uniquify-alist (alist)
  20346. "Merge elements of ALIST with the same key.
  20347. For example, in this alist:
  20348. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20349. => \\='((a 1 3) (b 2))
  20350. merge (a 1) and (a 3) into (a 1 3).
  20351. The function returns the new ALIST."
  20352. (let (rtn)
  20353. (dolist (e alist rtn)
  20354. (let (n)
  20355. (if (not (assoc (car e) rtn))
  20356. (push e rtn)
  20357. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20358. (setq rtn (assq-delete-all (car e) rtn))
  20359. (push n rtn))))))
  20360. (defun org-delete-all (elts list)
  20361. "Remove all elements in ELTS from LIST.
  20362. Comparison is done with `equal'. It is a destructive operation
  20363. that may remove elements by altering the list structure."
  20364. (while elts
  20365. (setq list (delete (pop elts) list)))
  20366. list)
  20367. (defun org-back-over-empty-lines ()
  20368. "Move backwards over whitespace, to the beginning of the first empty line.
  20369. Returns the number of empty lines passed."
  20370. (let ((pos (point)))
  20371. (if (cdr (assq 'heading org-blank-before-new-entry))
  20372. (skip-chars-backward " \t\n\r")
  20373. (unless (eobp)
  20374. (forward-line -1)))
  20375. (beginning-of-line 2)
  20376. (goto-char (min (point) pos))
  20377. (count-lines (point) pos)))
  20378. (defun org-skip-whitespace ()
  20379. (skip-chars-forward " \t\n\r"))
  20380. (defun org-point-in-group (point group &optional context)
  20381. "Check if POINT is in match-group GROUP.
  20382. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20383. match. If the match group does not exist or point is not inside it,
  20384. return nil."
  20385. (and (match-beginning group)
  20386. (>= point (match-beginning group))
  20387. (<= point (match-end group))
  20388. (if context
  20389. (list context (match-beginning group) (match-end group))
  20390. t)))
  20391. (defun org-switch-to-buffer-other-window (&rest args)
  20392. "Switch to buffer in a second window on the current frame.
  20393. In particular, do not allow pop-up frames.
  20394. Returns the newly created buffer."
  20395. (org-no-popups
  20396. (apply 'switch-to-buffer-other-window args)))
  20397. (defun org-combine-plists (&rest plists)
  20398. "Create a single property list from all plists in PLISTS.
  20399. The process starts by copying the first list, and then setting properties
  20400. from the other lists. Settings in the last list are the most significant
  20401. ones and overrule settings in the other lists."
  20402. (let ((rtn (copy-sequence (pop plists)))
  20403. p v ls)
  20404. (while plists
  20405. (setq ls (pop plists))
  20406. (while ls
  20407. (setq p (pop ls) v (pop ls))
  20408. (setq rtn (plist-put rtn p v))))
  20409. rtn))
  20410. (defun org-replace-escapes (string table)
  20411. "Replace %-escapes in STRING with values in TABLE.
  20412. TABLE is an association list with keys like \"%a\" and string values.
  20413. The sequences in STRING may contain normal field width and padding information,
  20414. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20415. so values can contain further %-escapes if they are define later in TABLE."
  20416. (let ((tbl (copy-alist table))
  20417. (case-fold-search nil)
  20418. (pchg 0)
  20419. re rpl)
  20420. (dolist (e tbl)
  20421. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20422. (when (and (cdr e) (string-match re (cdr e)))
  20423. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20424. (safe "SREF"))
  20425. (add-text-properties 0 3 (list 'sref sref) safe)
  20426. (setcdr e (replace-match safe t t (cdr e)))))
  20427. (while (string-match re string)
  20428. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20429. (cdr e)))
  20430. (setq string (replace-match rpl t t string))))
  20431. (while (setq pchg (next-property-change pchg string))
  20432. (let ((sref (get-text-property pchg 'sref string)))
  20433. (when (and sref (string-match "SREF" string pchg))
  20434. (setq string (replace-match sref t t string)))))
  20435. string))
  20436. (defun org-find-base-buffer-visiting (file)
  20437. "Like `find-buffer-visiting' but always return the base buffer and
  20438. not an indirect buffer."
  20439. (let ((buf (or (get-file-buffer file)
  20440. (find-buffer-visiting file))))
  20441. (if buf
  20442. (or (buffer-base-buffer buf) buf)
  20443. nil)))
  20444. ;;; TODO: Only called once, from ox-odt which should probably use
  20445. ;;; org-export-inline-image-p or something.
  20446. (defun org-file-image-p (file)
  20447. "Return non-nil if FILE is an image."
  20448. (save-match-data
  20449. (string-match (image-file-name-regexp) file)))
  20450. (defun org-get-cursor-date (&optional with-time)
  20451. "Return the date at cursor in as a time.
  20452. This works in the calendar and in the agenda, anywhere else it just
  20453. returns the current time.
  20454. If WITH-TIME is non-nil, returns the time of the event at point (in
  20455. the agenda) or the current time of the day."
  20456. (let (date day defd tp hod mod)
  20457. (when with-time
  20458. (setq tp (get-text-property (point) 'time))
  20459. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20460. (setq hod (string-to-number (match-string 1 tp))
  20461. mod (string-to-number (match-string 2 tp))))
  20462. (or tp (let ((now (decode-time)))
  20463. (setq hod (nth 2 now)
  20464. mod (nth 1 now)))))
  20465. (cond
  20466. ((eq major-mode 'calendar-mode)
  20467. (setq date (calendar-cursor-to-date)
  20468. defd (encode-time 0 (or mod 0) (or hod 0)
  20469. (nth 1 date) (nth 0 date) (nth 2 date))))
  20470. ((eq major-mode 'org-agenda-mode)
  20471. (setq day (get-text-property (point) 'day))
  20472. (when day
  20473. (setq date (calendar-gregorian-from-absolute day)
  20474. defd (encode-time 0 (or mod 0) (or hod 0)
  20475. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20476. (or defd (current-time))))
  20477. (defun org-mark-subtree (&optional up)
  20478. "Mark the current subtree.
  20479. This puts point at the start of the current subtree, and mark at
  20480. the end. If a numeric prefix UP is given, move up into the
  20481. hierarchy of headlines by UP levels before marking the subtree."
  20482. (interactive "P")
  20483. (org-with-limited-levels
  20484. (cond ((org-at-heading-p) (beginning-of-line))
  20485. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20486. (t (outline-previous-visible-heading 1))))
  20487. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20488. (if (called-interactively-p 'any)
  20489. (call-interactively 'org-mark-element)
  20490. (org-mark-element)))
  20491. (defun org-file-newer-than-p (file time)
  20492. "Non-nil if FILE is newer than TIME.
  20493. FILE is a filename, as a string, TIME is a list of integers, as
  20494. returned by, e.g., `current-time'."
  20495. (and (file-exists-p file)
  20496. ;; Only compare times up to whole seconds as some file-systems
  20497. ;; (e.g. HFS+) do not retain any finer granularity. As
  20498. ;; a consequence, make sure we return non-nil when the two
  20499. ;; times are equal.
  20500. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20501. (cl-subseq time 0 2)))))
  20502. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20503. "Compile a SOURCE file using PROCESS.
  20504. PROCESS is either a function or a list of shell commands, as
  20505. strings. EXT is a file extension, without the leading dot, as
  20506. a string. It is used to check if the process actually succeeded.
  20507. PROCESS must create a file with the same base name and directory
  20508. as SOURCE, but ending with EXT. The function then returns its
  20509. filename. Otherwise, it raises an error. The error message can
  20510. then be refined by providing string ERR-MSG, which is appended to
  20511. the standard message.
  20512. If PROCESS is a function, it is called with a single argument:
  20513. the SOURCE file.
  20514. If it is a list of commands, each of them is called using
  20515. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20516. %O are replaced with, respectively, SOURCE base name, name, full
  20517. name, directory and absolute output file name. It is possible,
  20518. however, to use more place-holders by specifying them in optional
  20519. argument SPEC, as an alist following the pattern
  20520. (CHARACTER . REPLACEMENT-STRING).
  20521. When PROCESS is a list of commands, optional argument LOG-BUF can
  20522. be set to a buffer or a buffer name. `shell-command' then uses
  20523. it for output."
  20524. (let* ((base-name (file-name-base source))
  20525. (full-name (file-truename source))
  20526. (out-dir (or (file-name-directory source) "./"))
  20527. (output (expand-file-name (concat base-name "." ext) out-dir))
  20528. (time (current-time))
  20529. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20530. (save-window-excursion
  20531. (pcase process
  20532. ((pred functionp) (funcall process (shell-quote-argument source)))
  20533. ((pred consp)
  20534. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20535. (spec (append spec
  20536. `((?b . ,(shell-quote-argument base-name))
  20537. (?f . ,(shell-quote-argument source))
  20538. (?F . ,(shell-quote-argument full-name))
  20539. (?o . ,(shell-quote-argument out-dir))
  20540. (?O . ,(shell-quote-argument output))))))
  20541. (dolist (command process)
  20542. (shell-command (format-spec command spec) log-buf))
  20543. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20544. (_ (error "No valid command to process %S%s" source err-msg))))
  20545. ;; Check for process failure. Output file is expected to be
  20546. ;; located in the same directory as SOURCE.
  20547. (unless (org-file-newer-than-p output time)
  20548. (error (format "File %S wasn't produced%s" output err-msg)))
  20549. output))
  20550. ;;; Indentation
  20551. (defun org--get-expected-indentation (element contentsp)
  20552. "Expected indentation column for current line, according to ELEMENT.
  20553. ELEMENT is an element containing point. CONTENTSP is non-nil
  20554. when indentation is to be computed according to contents of
  20555. ELEMENT."
  20556. (let ((type (org-element-type element))
  20557. (start (org-element-property :begin element))
  20558. (post-affiliated (org-element-property :post-affiliated element)))
  20559. (org-with-wide-buffer
  20560. (cond
  20561. (contentsp
  20562. (cl-case type
  20563. ((diary-sexp footnote-definition) 0)
  20564. ((headline inlinetask nil)
  20565. (if (not org-adapt-indentation) 0
  20566. (let ((level (org-current-level)))
  20567. (if level (1+ level) 0))))
  20568. ((item plain-list) (org-list-item-body-column post-affiliated))
  20569. (t
  20570. (goto-char start)
  20571. (org-get-indentation))))
  20572. ((memq type '(headline inlinetask nil))
  20573. (if (org-match-line "[ \t]*$")
  20574. (org--get-expected-indentation element t)
  20575. 0))
  20576. ((memq type '(diary-sexp footnote-definition)) 0)
  20577. ;; First paragraph of a footnote definition or an item.
  20578. ;; Indent like parent.
  20579. ((< (line-beginning-position) start)
  20580. (org--get-expected-indentation
  20581. (org-element-property :parent element) t))
  20582. ;; At first line: indent according to previous sibling, if any,
  20583. ;; ignoring footnote definitions and inline tasks, or parent's
  20584. ;; contents.
  20585. ((= (line-beginning-position) start)
  20586. (catch 'exit
  20587. (while t
  20588. (if (= (point-min) start) (throw 'exit 0)
  20589. (goto-char (1- start))
  20590. (let* ((previous (org-element-at-point))
  20591. (parent previous))
  20592. (while (and parent (<= (org-element-property :end parent) start))
  20593. (setq previous parent
  20594. parent (org-element-property :parent parent)))
  20595. (cond
  20596. ((not previous) (throw 'exit 0))
  20597. ((> (org-element-property :end previous) start)
  20598. (throw 'exit (org--get-expected-indentation previous t)))
  20599. ((memq (org-element-type previous)
  20600. '(footnote-definition inlinetask))
  20601. (setq start (org-element-property :begin previous)))
  20602. (t (goto-char (org-element-property :begin previous))
  20603. (throw 'exit
  20604. (if (bolp) (org-get-indentation)
  20605. ;; At first paragraph in an item or
  20606. ;; a footnote definition.
  20607. (org--get-expected-indentation
  20608. (org-element-property :parent previous) t))))))))))
  20609. ;; Otherwise, move to the first non-blank line above.
  20610. (t
  20611. (beginning-of-line)
  20612. (let ((pos (point)))
  20613. (skip-chars-backward " \r\t\n")
  20614. (cond
  20615. ;; Two blank lines end a footnote definition or a plain
  20616. ;; list. When we indent an empty line after them, the
  20617. ;; containing list or footnote definition is over, so it
  20618. ;; qualifies as a previous sibling. Therefore, we indent
  20619. ;; like its first line.
  20620. ((and (memq type '(footnote-definition plain-list))
  20621. (> (count-lines (point) pos) 2))
  20622. (goto-char start)
  20623. (org-get-indentation))
  20624. ;; Line above is the first one of a paragraph at the
  20625. ;; beginning of an item or a footnote definition. Indent
  20626. ;; like parent.
  20627. ((< (line-beginning-position) start)
  20628. (org--get-expected-indentation
  20629. (org-element-property :parent element) t))
  20630. ;; Line above is the beginning of an element, i.e., point
  20631. ;; was originally on the blank lines between element's start
  20632. ;; and contents.
  20633. ((= (line-beginning-position) post-affiliated)
  20634. (org--get-expected-indentation element t))
  20635. ;; POS is after contents in a greater element. Indent like
  20636. ;; the beginning of the element.
  20637. ;;
  20638. ;; As a special case, if point is at the end of a footnote
  20639. ;; definition or an item, indent like the very last element
  20640. ;; within. If that last element is an item, indent like its
  20641. ;; contents.
  20642. ((and (not (eq type 'paragraph))
  20643. (let ((cend (org-element-property :contents-end element)))
  20644. (and cend (<= cend pos))))
  20645. (if (memq type '(footnote-definition item plain-list))
  20646. (let ((last (org-element-at-point)))
  20647. (org--get-expected-indentation
  20648. last (eq (org-element-type last) 'item)))
  20649. (goto-char start)
  20650. (org-get-indentation)))
  20651. ;; In any other case, indent like the current line.
  20652. (t (org-get-indentation)))))))))
  20653. (defun org--align-node-property ()
  20654. "Align node property at point.
  20655. Alignment is done according to `org-property-format', which see."
  20656. (when (save-excursion
  20657. (beginning-of-line)
  20658. (looking-at org-property-re))
  20659. (replace-match
  20660. (concat (match-string 4)
  20661. (org-trim
  20662. (format org-property-format (match-string 1) (match-string 3))))
  20663. t t)))
  20664. (defun org-indent-line ()
  20665. "Indent line depending on context.
  20666. Indentation is done according to the following rules:
  20667. - Footnote definitions, diary sexps, headlines and inline tasks
  20668. have to start at column 0.
  20669. - On the very first line of an element, consider, in order, the
  20670. next rules until one matches:
  20671. 1. If there's a sibling element before, ignoring footnote
  20672. definitions and inline tasks, indent like its first line.
  20673. 2. If element has a parent, indent like its contents. More
  20674. precisely, if parent is an item, indent after the
  20675. description part, if any, or the bullet (see
  20676. `org-list-description-max-indent'). Else, indent like
  20677. parent's first line.
  20678. 3. Otherwise, indent relatively to current level, if
  20679. `org-adapt-indentation' is non-nil, or to left margin.
  20680. - On a blank line at the end of an element, indent according to
  20681. the type of the element. More precisely
  20682. 1. If element is a plain list, an item, or a footnote
  20683. definition, indent like the very last element within.
  20684. 2. If element is a paragraph, indent like its last non blank
  20685. line.
  20686. 3. Otherwise, indent like its very first line.
  20687. - In the code part of a source block, use language major mode
  20688. to indent current line if `org-src-tab-acts-natively' is
  20689. non-nil. If it is nil, do nothing.
  20690. - Otherwise, indent like the first non-blank line above.
  20691. The function doesn't indent an item as it could break the whole
  20692. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20693. `\\[org-shiftmetaright]'.
  20694. Also align node properties according to `org-property-format'."
  20695. (interactive)
  20696. (cond
  20697. (orgstruct-is-++
  20698. (let ((indent-line-function
  20699. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20700. (indent-according-to-mode)))
  20701. ((org-at-heading-p) 'noindent)
  20702. (t
  20703. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20704. (type (org-element-type element)))
  20705. (cond ((and (memq type '(plain-list item))
  20706. (= (line-beginning-position)
  20707. (org-element-property :post-affiliated element)))
  20708. 'noindent)
  20709. ((and (eq type 'latex-environment)
  20710. (>= (point) (org-element-property :post-affiliated element))
  20711. (< (point) (org-with-wide-buffer
  20712. (goto-char (org-element-property :end element))
  20713. (skip-chars-backward " \r\t\n")
  20714. (line-beginning-position 2))))
  20715. 'noindent)
  20716. ((and (eq type 'src-block)
  20717. org-src-tab-acts-natively
  20718. (> (line-beginning-position)
  20719. (org-element-property :post-affiliated element))
  20720. (< (line-beginning-position)
  20721. (org-with-wide-buffer
  20722. (goto-char (org-element-property :end element))
  20723. (skip-chars-backward " \r\t\n")
  20724. (line-beginning-position))))
  20725. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20726. (t
  20727. (let ((column (org--get-expected-indentation element nil)))
  20728. ;; Preserve current column.
  20729. (if (<= (current-column) (current-indentation))
  20730. (indent-line-to column)
  20731. (save-excursion (indent-line-to column))))
  20732. ;; Align node property. Also preserve current column.
  20733. (when (eq type 'node-property)
  20734. (let ((column (current-column)))
  20735. (org--align-node-property)
  20736. (org-move-to-column column)))))))))
  20737. (defun org-indent-region (start end)
  20738. "Indent each non-blank line in the region.
  20739. Called from a program, START and END specify the region to
  20740. indent. The function will not indent contents of example blocks,
  20741. verse blocks and export blocks as leading white spaces are
  20742. assumed to be significant there."
  20743. (interactive "r")
  20744. (save-excursion
  20745. (goto-char start)
  20746. (skip-chars-forward " \r\t\n")
  20747. (unless (eobp) (beginning-of-line))
  20748. (let ((indent-to
  20749. (lambda (ind pos)
  20750. ;; Set IND as indentation for all lines between point and
  20751. ;; POS. Blank lines are ignored. Leave point after POS
  20752. ;; once done.
  20753. (let ((limit (copy-marker pos)))
  20754. (while (< (point) limit)
  20755. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20756. (forward-line))
  20757. (set-marker limit nil))))
  20758. (end (copy-marker end)))
  20759. (while (< (point) end)
  20760. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20761. (let* ((element (org-element-at-point))
  20762. (type (org-element-type element))
  20763. (element-end (copy-marker (org-element-property :end element)))
  20764. (ind (org--get-expected-indentation element nil)))
  20765. (cond
  20766. ;; Element indented as a single block. Example blocks
  20767. ;; preserving indentation are a special case since the
  20768. ;; "contents" must not be indented whereas the block
  20769. ;; boundaries can.
  20770. ((or (memq type '(export-block latex-environment))
  20771. (and (eq type 'example-block)
  20772. (not
  20773. (or org-src-preserve-indentation
  20774. (org-element-property :preserve-indent element)))))
  20775. (let ((offset (- ind (org-get-indentation))))
  20776. (unless (zerop offset)
  20777. (indent-rigidly (org-element-property :begin element)
  20778. (org-element-property :end element)
  20779. offset)))
  20780. (goto-char element-end))
  20781. ;; Elements indented line wise. Be sure to exclude
  20782. ;; example blocks (preserving indentation) and source
  20783. ;; blocks from this category as they are treated
  20784. ;; specially later.
  20785. ((or (memq type '(paragraph table table-row))
  20786. (not (or (org-element-property :contents-begin element)
  20787. (memq type '(example-block src-block)))))
  20788. (when (eq type 'node-property)
  20789. (org--align-node-property)
  20790. (beginning-of-line))
  20791. (funcall indent-to ind (min element-end end)))
  20792. ;; Elements consisting of three parts: before the
  20793. ;; contents, the contents, and after the contents. The
  20794. ;; contents are treated specially, according to the
  20795. ;; element type, or not indented at all. Other parts are
  20796. ;; indented as a single block.
  20797. (t
  20798. (let* ((post (copy-marker
  20799. (org-element-property :post-affiliated element)))
  20800. (cbeg
  20801. (copy-marker
  20802. (cond
  20803. ((not (org-element-property :contents-begin element))
  20804. ;; Fake contents for source blocks.
  20805. (org-with-wide-buffer
  20806. (goto-char post)
  20807. (line-beginning-position 2)))
  20808. ((memq type '(footnote-definition item plain-list))
  20809. ;; Contents in these elements could start on
  20810. ;; the same line as the beginning of the
  20811. ;; element. Make sure we start indenting
  20812. ;; from the second line.
  20813. (org-with-wide-buffer
  20814. (goto-char post)
  20815. (end-of-line)
  20816. (skip-chars-forward " \r\t\n")
  20817. (if (eobp) (point) (line-beginning-position))))
  20818. (t (org-element-property :contents-begin element)))))
  20819. (cend (copy-marker
  20820. (or (org-element-property :contents-end element)
  20821. ;; Fake contents for source blocks.
  20822. (org-with-wide-buffer
  20823. (goto-char element-end)
  20824. (skip-chars-backward " \r\t\n")
  20825. (line-beginning-position)))
  20826. t)))
  20827. ;; Do not change items indentation individually as it
  20828. ;; might break the list as a whole. On the other
  20829. ;; hand, when at a plain list, indent it as a whole.
  20830. (cond ((eq type 'plain-list)
  20831. (let ((offset (- ind (org-get-indentation))))
  20832. (unless (zerop offset)
  20833. (indent-rigidly (org-element-property :begin element)
  20834. (org-element-property :end element)
  20835. offset))
  20836. (goto-char cbeg)))
  20837. ((eq type 'item) (goto-char cbeg))
  20838. (t (funcall indent-to ind (min cbeg end))))
  20839. (when (< (point) end)
  20840. (cl-case type
  20841. ((example-block verse-block))
  20842. (src-block
  20843. ;; In a source block, indent source code
  20844. ;; according to language major mode, but only if
  20845. ;; `org-src-tab-acts-natively' is non-nil.
  20846. (when (and (< (point) end) org-src-tab-acts-natively)
  20847. (ignore-errors
  20848. (org-babel-do-in-edit-buffer
  20849. (indent-region (point-min) (point-max))))))
  20850. (t (org-indent-region (point) (min cend end))))
  20851. (goto-char (min cend end))
  20852. (when (< (point) end)
  20853. (funcall indent-to ind (min element-end end))))
  20854. (set-marker post nil)
  20855. (set-marker cbeg nil)
  20856. (set-marker cend nil))))
  20857. (set-marker element-end nil))))
  20858. (set-marker end nil))))
  20859. (defun org-indent-drawer ()
  20860. "Indent the drawer at point."
  20861. (interactive)
  20862. (unless (save-excursion
  20863. (beginning-of-line)
  20864. (looking-at-p org-drawer-regexp))
  20865. (user-error "Not at a drawer"))
  20866. (let ((element (org-element-at-point)))
  20867. (unless (memq (org-element-type element) '(drawer property-drawer))
  20868. (user-error "Not at a drawer"))
  20869. (org-with-wide-buffer
  20870. (org-indent-region (org-element-property :begin element)
  20871. (org-element-property :end element))))
  20872. (message "Drawer at point indented"))
  20873. (defun org-indent-block ()
  20874. "Indent the block at point."
  20875. (interactive)
  20876. (unless (save-excursion
  20877. (beginning-of-line)
  20878. (let ((case-fold-search t))
  20879. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20880. (user-error "Not at a block"))
  20881. (let ((element (org-element-at-point)))
  20882. (unless (memq (org-element-type element)
  20883. '(comment-block center-block dynamic-block example-block
  20884. export-block quote-block special-block
  20885. src-block verse-block))
  20886. (user-error "Not at a block"))
  20887. (org-with-wide-buffer
  20888. (org-indent-region (org-element-property :begin element)
  20889. (org-element-property :end element))))
  20890. (message "Block at point indented"))
  20891. ;;; Filling
  20892. ;; We use our own fill-paragraph and auto-fill functions.
  20893. ;; `org-fill-paragraph' relies on adaptive filling and context
  20894. ;; checking. Appropriate `fill-prefix' is computed with
  20895. ;; `org-adaptive-fill-function'.
  20896. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20897. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20898. ;; `org-adaptive-fill-function' value. Internally,
  20899. ;; `org-comment-line-break-function' breaks the line.
  20900. ;; `org-setup-filling' installs filling and auto-filling related
  20901. ;; variables during `org-mode' initialization.
  20902. (defvar org-element-paragraph-separate) ; org-element.el
  20903. (defun org-setup-filling ()
  20904. (require 'org-element)
  20905. ;; Prevent auto-fill from inserting unwanted new items.
  20906. (when (boundp 'fill-nobreak-predicate)
  20907. (setq-local
  20908. fill-nobreak-predicate
  20909. (org-uniquify
  20910. (append fill-nobreak-predicate
  20911. '(org-fill-line-break-nobreak-p
  20912. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20913. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20914. (setq-local paragraph-start paragraph-ending)
  20915. (setq-local paragraph-separate paragraph-ending))
  20916. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20917. (setq-local auto-fill-inhibit-regexp nil)
  20918. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20919. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20920. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20921. (defun org-fill-line-break-nobreak-p ()
  20922. "Non-nil when a new line at point would create an Org line break."
  20923. (save-excursion
  20924. (skip-chars-backward "[ \t]")
  20925. (skip-chars-backward "\\\\")
  20926. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20927. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20928. "Non-nil when a new line at point would split a timestamp."
  20929. (and (org-at-timestamp-p t)
  20930. (not (looking-at org-ts-regexp-both))))
  20931. (declare-function message-in-body-p "message" ())
  20932. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20933. (defun org-adaptive-fill-function ()
  20934. "Compute a fill prefix for the current line.
  20935. Return fill prefix, as a string, or nil if current line isn't
  20936. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20937. matches in paragraphs or comments, use it."
  20938. (catch 'exit
  20939. (when (derived-mode-p 'message-mode)
  20940. (save-excursion
  20941. (beginning-of-line)
  20942. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20943. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20944. ((looking-at message-cite-prefix-regexp)
  20945. (throw 'exit (match-string-no-properties 0)))
  20946. ((looking-at org-outline-regexp)
  20947. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20948. (org-with-wide-buffer
  20949. (unless (org-at-heading-p)
  20950. (let* ((p (line-beginning-position))
  20951. (element (save-excursion
  20952. (beginning-of-line)
  20953. (org-element-at-point)))
  20954. (type (org-element-type element))
  20955. (post-affiliated (org-element-property :post-affiliated element)))
  20956. (unless (< p post-affiliated)
  20957. (cl-case type
  20958. (comment
  20959. (save-excursion
  20960. (beginning-of-line)
  20961. (looking-at "[ \t]*")
  20962. (concat (match-string 0) "# ")))
  20963. (footnote-definition "")
  20964. ((item plain-list)
  20965. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20966. (paragraph
  20967. ;; Fill prefix is usually the same as the current line,
  20968. ;; unless the paragraph is at the beginning of an item.
  20969. (let ((parent (org-element-property :parent element)))
  20970. (save-excursion
  20971. (beginning-of-line)
  20972. (cond ((eq (org-element-type parent) 'item)
  20973. (make-string (org-list-item-body-column
  20974. (org-element-property :begin parent))
  20975. ?\s))
  20976. ((and adaptive-fill-regexp
  20977. ;; Locally disable
  20978. ;; `adaptive-fill-function' to let
  20979. ;; `fill-context-prefix' handle
  20980. ;; `adaptive-fill-regexp' variable.
  20981. (let (adaptive-fill-function)
  20982. (fill-context-prefix
  20983. post-affiliated
  20984. (org-element-property :end element)))))
  20985. ((looking-at "[ \t]+") (match-string 0))
  20986. (t "")))))
  20987. (comment-block
  20988. ;; Only fill contents if P is within block boundaries.
  20989. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20990. (forward-line)
  20991. (point)))
  20992. (cend (save-excursion
  20993. (goto-char (org-element-property :end element))
  20994. (skip-chars-backward " \r\t\n")
  20995. (line-beginning-position))))
  20996. (when (and (>= p cbeg) (< p cend))
  20997. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20998. (match-string 0)
  20999. "")))))))))))
  21000. (declare-function message-goto-body "message" ())
  21001. (defvar message-cite-prefix-regexp) ; From message.el
  21002. (defun org-fill-paragraph (&optional justify)
  21003. "Fill element at point, when applicable.
  21004. This function only applies to comment blocks, comments, example
  21005. blocks and paragraphs. Also, as a special case, re-align table
  21006. when point is at one.
  21007. If JUSTIFY is non-nil (interactively, with prefix argument),
  21008. justify as well. If `sentence-end-double-space' is non-nil, then
  21009. period followed by one space does not end a sentence, so don't
  21010. break a line there. The variable `fill-column' controls the
  21011. width for filling.
  21012. For convenience, when point is at a plain list, an item or
  21013. a footnote definition, try to fill the first paragraph within."
  21014. (interactive)
  21015. (if (and (derived-mode-p 'message-mode)
  21016. (or (not (message-in-body-p))
  21017. (save-excursion (move-beginning-of-line 1)
  21018. (looking-at message-cite-prefix-regexp))))
  21019. ;; First ensure filling is correct in message-mode.
  21020. (let ((fill-paragraph-function
  21021. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21022. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21023. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21024. (paragraph-separate
  21025. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21026. (fill-paragraph nil))
  21027. (with-syntax-table org-mode-transpose-word-syntax-table
  21028. ;; Move to end of line in order to get the first paragraph
  21029. ;; within a plain list or a footnote definition.
  21030. (let ((element (save-excursion
  21031. (end-of-line)
  21032. (or (ignore-errors (org-element-at-point))
  21033. (user-error "An element cannot be parsed line %d"
  21034. (line-number-at-pos (point)))))))
  21035. ;; First check if point is in a blank line at the beginning of
  21036. ;; the buffer. In that case, ignore filling.
  21037. (cl-case (org-element-type element)
  21038. ;; Use major mode filling function is src blocks.
  21039. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21040. ;; Align Org tables, leave table.el tables as-is.
  21041. (table-row (org-table-align) t)
  21042. (table
  21043. (when (eq (org-element-property :type element) 'org)
  21044. (save-excursion
  21045. (goto-char (org-element-property :post-affiliated element))
  21046. (org-table-align)))
  21047. t)
  21048. (paragraph
  21049. ;; Paragraphs may contain `line-break' type objects.
  21050. (let ((beg (max (point-min)
  21051. (org-element-property :contents-begin element)))
  21052. (end (min (point-max)
  21053. (org-element-property :contents-end element))))
  21054. ;; Do nothing if point is at an affiliated keyword.
  21055. (if (< (line-end-position) beg) t
  21056. (when (derived-mode-p 'message-mode)
  21057. ;; In `message-mode', do not fill following citation
  21058. ;; in current paragraph nor text before message body.
  21059. (let ((body-start (save-excursion (message-goto-body))))
  21060. (when body-start (setq beg (max body-start beg))))
  21061. (when (save-excursion
  21062. (re-search-forward
  21063. (concat "^" message-cite-prefix-regexp) end t))
  21064. (setq end (match-beginning 0))))
  21065. ;; Fill paragraph, taking line breaks into account.
  21066. (save-excursion
  21067. (goto-char beg)
  21068. (let ((cuts (list beg)))
  21069. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21070. (when (eq 'line-break
  21071. (org-element-type
  21072. (save-excursion (backward-char)
  21073. (org-element-context))))
  21074. (push (point) cuts)))
  21075. (dolist (c (delq end cuts))
  21076. (fill-region-as-paragraph c end justify)
  21077. (setq end c))))
  21078. t)))
  21079. ;; Contents of `comment-block' type elements should be
  21080. ;; filled as plain text, but only if point is within block
  21081. ;; markers.
  21082. (comment-block
  21083. (let* ((case-fold-search t)
  21084. (beg (save-excursion
  21085. (goto-char (org-element-property :begin element))
  21086. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21087. (forward-line)
  21088. (point)))
  21089. (end (save-excursion
  21090. (goto-char (org-element-property :end element))
  21091. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21092. (line-beginning-position))))
  21093. (if (or (< (point) beg) (> (point) end)) t
  21094. (fill-region-as-paragraph
  21095. (save-excursion (end-of-line)
  21096. (re-search-backward "^[ \t]*$" beg 'move)
  21097. (line-beginning-position))
  21098. (save-excursion (beginning-of-line)
  21099. (re-search-forward "^[ \t]*$" end 'move)
  21100. (line-beginning-position))
  21101. justify))))
  21102. ;; Fill comments.
  21103. (comment
  21104. (let ((begin (org-element-property :post-affiliated element))
  21105. (end (org-element-property :end element)))
  21106. (when (and (>= (point) begin) (<= (point) end))
  21107. (let ((begin (save-excursion
  21108. (end-of-line)
  21109. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21110. (progn (forward-line) (point))
  21111. begin)))
  21112. (end (save-excursion
  21113. (end-of-line)
  21114. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21115. (1- (line-beginning-position))
  21116. (skip-chars-backward " \r\t\n")
  21117. (line-end-position)))))
  21118. ;; Do not fill comments when at a blank line.
  21119. (when (> end begin)
  21120. (let ((fill-prefix
  21121. (save-excursion
  21122. (beginning-of-line)
  21123. (looking-at "[ \t]*#")
  21124. (let ((comment-prefix (match-string 0)))
  21125. (goto-char (match-end 0))
  21126. (if (looking-at adaptive-fill-regexp)
  21127. (concat comment-prefix (match-string 0))
  21128. (concat comment-prefix " "))))))
  21129. (save-excursion
  21130. (fill-region-as-paragraph begin end justify))))))
  21131. t))
  21132. ;; Ignore every other element.
  21133. (otherwise t))))))
  21134. (defun org-auto-fill-function ()
  21135. "Auto-fill function."
  21136. ;; Check if auto-filling is meaningful.
  21137. (let ((fc (current-fill-column)))
  21138. (when (and fc (> (current-column) fc))
  21139. (let* ((fill-prefix (org-adaptive-fill-function))
  21140. ;; Enforce empty fill prefix, if required. Otherwise, it
  21141. ;; will be computed again.
  21142. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21143. (when fill-prefix (do-auto-fill))))))
  21144. (defun org-comment-line-break-function (&optional soft)
  21145. "Break line at point and indent, continuing comment if within one.
  21146. The inserted newline is marked hard if variable
  21147. `use-hard-newlines' is true, unless optional argument SOFT is
  21148. non-nil."
  21149. (if soft (insert-and-inherit ?\n) (newline 1))
  21150. (save-excursion (forward-char -1) (delete-horizontal-space))
  21151. (delete-horizontal-space)
  21152. (indent-to-left-margin)
  21153. (insert-before-markers-and-inherit fill-prefix))
  21154. ;;; Fixed Width Areas
  21155. (defun org-toggle-fixed-width ()
  21156. "Toggle fixed-width markup.
  21157. Add or remove fixed-width markup on current line, whenever it
  21158. makes sense. Return an error otherwise.
  21159. If a region is active and if it contains only fixed-width areas
  21160. or blank lines, remove all fixed-width markup in it. If the
  21161. region contains anything else, convert all non-fixed-width lines
  21162. to fixed-width ones.
  21163. Blank lines at the end of the region are ignored unless the
  21164. region only contains such lines."
  21165. (interactive)
  21166. (if (not (org-region-active-p))
  21167. ;; No region:
  21168. ;;
  21169. ;; Remove fixed width marker only in a fixed-with element.
  21170. ;;
  21171. ;; Add fixed width maker in paragraphs, in blank lines after
  21172. ;; elements or at the beginning of a headline or an inlinetask,
  21173. ;; and before any one-line elements (e.g., a clock).
  21174. (progn
  21175. (beginning-of-line)
  21176. (let* ((element (org-element-at-point))
  21177. (type (org-element-type element)))
  21178. (cond
  21179. ((and (eq type 'fixed-width)
  21180. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21181. (replace-match
  21182. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21183. ((and (memq type '(babel-call clock comment diary-sexp headline
  21184. horizontal-rule keyword paragraph
  21185. planning))
  21186. (<= (org-element-property :post-affiliated element) (point)))
  21187. (skip-chars-forward " \t")
  21188. (insert ": "))
  21189. ((and (looking-at-p "[ \t]*$")
  21190. (or (eq type 'inlinetask)
  21191. (save-excursion
  21192. (skip-chars-forward " \r\t\n")
  21193. (<= (org-element-property :end element) (point)))))
  21194. (delete-region (point) (line-end-position))
  21195. (org-indent-line)
  21196. (insert ": "))
  21197. (t (user-error "Cannot insert a fixed-width line here")))))
  21198. ;; Region active.
  21199. (let* ((begin (save-excursion
  21200. (goto-char (region-beginning))
  21201. (line-beginning-position)))
  21202. (end (copy-marker
  21203. (save-excursion
  21204. (goto-char (region-end))
  21205. (unless (eolp) (beginning-of-line))
  21206. (if (save-excursion (re-search-backward "\\S-" begin t))
  21207. (progn (skip-chars-backward " \r\t\n") (point))
  21208. (point)))))
  21209. (all-fixed-width-p
  21210. (catch 'not-all-p
  21211. (save-excursion
  21212. (goto-char begin)
  21213. (skip-chars-forward " \r\t\n")
  21214. (when (eobp) (throw 'not-all-p nil))
  21215. (while (< (point) end)
  21216. (let ((element (org-element-at-point)))
  21217. (if (eq (org-element-type element) 'fixed-width)
  21218. (goto-char (org-element-property :end element))
  21219. (throw 'not-all-p nil))))
  21220. t))))
  21221. (if all-fixed-width-p
  21222. (save-excursion
  21223. (goto-char begin)
  21224. (while (< (point) end)
  21225. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21226. (replace-match
  21227. "" nil nil nil
  21228. (if (= (line-end-position) (match-end 0)) 0 1)))
  21229. (forward-line)))
  21230. (let ((min-ind (point-max)))
  21231. ;; Find minimum indentation across all lines.
  21232. (save-excursion
  21233. (goto-char begin)
  21234. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21235. (setq min-ind 0)
  21236. (catch 'zerop
  21237. (while (< (point) end)
  21238. (unless (looking-at-p "[ \t]*$")
  21239. (let ((ind (org-get-indentation)))
  21240. (setq min-ind (min min-ind ind))
  21241. (when (zerop ind) (throw 'zerop t))))
  21242. (forward-line)))))
  21243. ;; Loop over all lines and add fixed-width markup everywhere
  21244. ;; but in fixed-width lines.
  21245. (save-excursion
  21246. (goto-char begin)
  21247. (while (< (point) end)
  21248. (cond
  21249. ((org-at-heading-p)
  21250. (insert ": ")
  21251. (forward-line)
  21252. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21253. (insert ":")
  21254. (forward-line)))
  21255. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21256. (let* ((element (org-element-at-point))
  21257. (element-end (org-element-property :end element)))
  21258. (if (eq (org-element-type element) 'fixed-width)
  21259. (progn (goto-char element-end)
  21260. (skip-chars-backward " \r\t\n")
  21261. (forward-line))
  21262. (let ((limit (min end element-end)))
  21263. (while (< (point) limit)
  21264. (org-move-to-column min-ind t)
  21265. (insert ": ")
  21266. (forward-line))))))
  21267. (t
  21268. (org-move-to-column min-ind t)
  21269. (insert ": ")
  21270. (forward-line)))))))
  21271. (set-marker end nil))))
  21272. ;;; Comments
  21273. ;; Org comments syntax is quite complex. It requires the entire line
  21274. ;; to be just a comment. Also, even with the right syntax at the
  21275. ;; beginning of line, some some elements (i.e. verse-block or
  21276. ;; example-block) don't accept comments. Usual Emacs comment commands
  21277. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21278. ;; Org still relies on `comment-dwim', but cannot trust
  21279. ;; `comment-only-p'. So, `comment-region-function' and
  21280. ;; `uncomment-region-function' both point
  21281. ;; to`org-comment-or-uncomment-region'. Eventually,
  21282. ;; `org-insert-comment' takes care of insertion of comments at the
  21283. ;; beginning of line.
  21284. ;; `org-setup-comments-handling' install comments related variables
  21285. ;; during `org-mode' initialization.
  21286. (defun org-setup-comments-handling ()
  21287. (interactive)
  21288. (setq-local comment-use-syntax nil)
  21289. (setq-local comment-start "# ")
  21290. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21291. (setq-local comment-insert-comment-function 'org-insert-comment)
  21292. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21293. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21294. (defun org-insert-comment ()
  21295. "Insert an empty comment above current line.
  21296. If the line is empty, insert comment at its beginning. When
  21297. point is within a source block, comment according to the related
  21298. major mode."
  21299. (if (let ((element (org-element-at-point)))
  21300. (and (eq (org-element-type element) 'src-block)
  21301. (< (save-excursion
  21302. (goto-char (org-element-property :post-affiliated element))
  21303. (line-end-position))
  21304. (point))
  21305. (> (save-excursion
  21306. (goto-char (org-element-property :end element))
  21307. (skip-chars-backward " \r\t\n")
  21308. (line-beginning-position))
  21309. (point))))
  21310. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21311. (beginning-of-line)
  21312. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21313. (open-line 1))
  21314. (org-indent-line)
  21315. (insert "# ")))
  21316. (defvar comment-empty-lines) ; From newcomment.el.
  21317. (defun org-comment-or-uncomment-region (beg end &rest _)
  21318. "Comment or uncomment each non-blank line in the region.
  21319. Uncomment each non-blank line between BEG and END if it only
  21320. contains commented lines. Otherwise, comment them. If region is
  21321. strictly within a source block, use appropriate comment syntax."
  21322. (if (let ((element (org-element-at-point)))
  21323. (and (eq (org-element-type element) 'src-block)
  21324. (< (save-excursion
  21325. (goto-char (org-element-property :post-affiliated element))
  21326. (line-end-position))
  21327. beg)
  21328. (>= (save-excursion
  21329. (goto-char (org-element-property :end element))
  21330. (skip-chars-backward " \r\t\n")
  21331. (line-beginning-position))
  21332. end)))
  21333. ;; Translate region boundaries for the Org buffer to the source
  21334. ;; buffer.
  21335. (let ((offset (- end beg)))
  21336. (save-excursion
  21337. (goto-char beg)
  21338. (org-babel-do-in-edit-buffer
  21339. (comment-or-uncomment-region (point) (+ offset (point))))))
  21340. (save-restriction
  21341. ;; Restrict region
  21342. (narrow-to-region (save-excursion (goto-char beg)
  21343. (skip-chars-forward " \r\t\n" end)
  21344. (line-beginning-position))
  21345. (save-excursion (goto-char end)
  21346. (skip-chars-backward " \r\t\n" beg)
  21347. (line-end-position)))
  21348. (let ((uncommentp
  21349. ;; UNCOMMENTP is non-nil when every non blank line between
  21350. ;; BEG and END is a comment.
  21351. (save-excursion
  21352. (goto-char (point-min))
  21353. (while (and (not (eobp))
  21354. (let ((element (org-element-at-point)))
  21355. (and (eq (org-element-type element) 'comment)
  21356. (goto-char (min (point-max)
  21357. (org-element-property
  21358. :end element)))))))
  21359. (eobp))))
  21360. (if uncommentp
  21361. ;; Only blank lines and comments in region: uncomment it.
  21362. (save-excursion
  21363. (goto-char (point-min))
  21364. (while (not (eobp))
  21365. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21366. (replace-match "" nil nil nil 1))
  21367. (forward-line)))
  21368. ;; Comment each line in region.
  21369. (let ((min-indent (point-max)))
  21370. ;; First find the minimum indentation across all lines.
  21371. (save-excursion
  21372. (goto-char (point-min))
  21373. (while (and (not (eobp)) (not (zerop min-indent)))
  21374. (unless (looking-at "[ \t]*$")
  21375. (setq min-indent (min min-indent (current-indentation))))
  21376. (forward-line)))
  21377. ;; Then loop over all lines.
  21378. (save-excursion
  21379. (goto-char (point-min))
  21380. (while (not (eobp))
  21381. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21382. ;; Don't get fooled by invisible text (e.g. link path)
  21383. ;; when moving to column MIN-INDENT.
  21384. (let ((buffer-invisibility-spec nil))
  21385. (org-move-to-column min-indent t))
  21386. (insert comment-start))
  21387. (forward-line)))))))))
  21388. (defun org-comment-dwim (_arg)
  21389. "Call `comment-dwim' within a source edit buffer if needed."
  21390. (interactive "*P")
  21391. (if (org-in-src-block-p)
  21392. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21393. (call-interactively 'comment-dwim)))
  21394. ;;; Timestamps API
  21395. ;; This section contains tools to operate on timestamp objects, as
  21396. ;; returned by, e.g. `org-element-context'.
  21397. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21398. "Encode TIMESTAMP object into Emacs internal time.
  21399. Use end of date range or time range when END is non-nil."
  21400. (apply #'encode-time
  21401. (cons 0
  21402. (mapcar
  21403. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21404. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21405. '(:minute-start :hour-start :day-start :month-start
  21406. :year-start))))))
  21407. (defun org-timestamp-has-time-p (timestamp)
  21408. "Non-nil when TIMESTAMP has a time specified."
  21409. (org-element-property :hour-start timestamp))
  21410. (defun org-timestamp-format (timestamp format &optional end utc)
  21411. "Format a TIMESTAMP object into a string.
  21412. FORMAT is a format specifier to be passed to
  21413. `format-time-string'.
  21414. When optional argument END is non-nil, use end of date-range or
  21415. time-range, if possible.
  21416. When optional argument UTC is non-nil, time will be expressed as
  21417. Universal Time."
  21418. (format-time-string
  21419. format (org-timestamp--to-internal-time timestamp end)
  21420. (and utc t)))
  21421. (defun org-timestamp-split-range (timestamp &optional end)
  21422. "Extract a TIMESTAMP object from a date or time range.
  21423. END, when non-nil, means extract the end of the range.
  21424. Otherwise, extract its start.
  21425. Return a new timestamp object."
  21426. (let ((type (org-element-property :type timestamp)))
  21427. (if (memq type '(active inactive diary)) timestamp
  21428. (let ((split-ts (org-element-copy timestamp)))
  21429. ;; Set new type.
  21430. (org-element-put-property
  21431. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21432. ;; Copy start properties over end properties if END is
  21433. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21434. (let ((p-alist '((:minute-start . :minute-end)
  21435. (:hour-start . :hour-end)
  21436. (:day-start . :day-end)
  21437. (:month-start . :month-end)
  21438. (:year-start . :year-end))))
  21439. (dolist (p-cell p-alist)
  21440. (org-element-put-property
  21441. split-ts
  21442. (funcall (if end #'car #'cdr) p-cell)
  21443. (org-element-property
  21444. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21445. ;; Eventually refresh `:raw-value'.
  21446. (org-element-put-property split-ts :raw-value nil)
  21447. (org-element-put-property
  21448. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21449. (defun org-timestamp-translate (timestamp &optional boundary)
  21450. "Translate TIMESTAMP object to custom format.
  21451. Format string is defined in `org-time-stamp-custom-formats',
  21452. which see.
  21453. When optional argument BOUNDARY is non-nil, it is either the
  21454. symbol `start' or `end'. In this case, only translate the
  21455. starting or ending part of TIMESTAMP if it is a date or time
  21456. range. Otherwise, translate both parts.
  21457. Return timestamp as-is if `org-display-custom-times' is nil or if
  21458. it has a `diary' type."
  21459. (let ((type (org-element-property :type timestamp)))
  21460. (if (or (not org-display-custom-times) (eq type 'diary))
  21461. (org-element-interpret-data timestamp)
  21462. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21463. org-time-stamp-custom-formats)))
  21464. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21465. (concat (org-timestamp-format timestamp fmt)
  21466. "--"
  21467. (org-timestamp-format timestamp fmt t))
  21468. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21469. ;;; Other stuff.
  21470. (defvar reftex-docstruct-symbol)
  21471. (defvar org--rds)
  21472. (defun org-reftex-citation ()
  21473. "Use reftex-citation to insert a citation into the buffer.
  21474. This looks for a line like
  21475. #+BIBLIOGRAPHY: foo plain option:-d
  21476. and derives from it that foo.bib is the bibliography file relevant
  21477. for this document. It then installs the necessary environment for RefTeX
  21478. to work in this buffer and calls `reftex-citation' to insert a citation
  21479. into the buffer.
  21480. Export of such citations to both LaTeX and HTML is handled by the contributed
  21481. package ox-bibtex by Taru Karttunen."
  21482. (interactive)
  21483. (let ((reftex-docstruct-symbol 'org--rds)
  21484. org--rds bib)
  21485. (org-with-wide-buffer
  21486. (let ((case-fold-search t)
  21487. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21488. (if (not (save-excursion
  21489. (or (re-search-forward re nil t)
  21490. (re-search-backward re nil t))))
  21491. (user-error "No bibliography defined in file")
  21492. (setq bib (concat (match-string 1) ".bib")
  21493. org--rds (list (list 'bib bib))))))
  21494. (call-interactively 'reftex-citation)))
  21495. ;;;; Functions extending outline functionality
  21496. (defun org-beginning-of-line (&optional n)
  21497. "Go to the beginning of the current visible line.
  21498. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21499. tags on the first attempt, and only move to after the tags when
  21500. the cursor is already beyond the end of the headline.
  21501. With argument N not nil or 1, move forward N - 1 lines first."
  21502. (interactive "^p")
  21503. (let ((origin (point))
  21504. (special (pcase org-special-ctrl-a/e
  21505. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21506. deactivate-mark)
  21507. ;; First move to a visible line.
  21508. (if (bound-and-true-p visual-line-mode)
  21509. (beginning-of-visual-line n)
  21510. (move-beginning-of-line n)
  21511. ;; `move-beginning-of-line' may leave point after invisible
  21512. ;; characters if line starts with such of these (e.g., with
  21513. ;; a link at column 0). Really move to the beginning of the
  21514. ;; current visible line.
  21515. (beginning-of-line))
  21516. (cond
  21517. ;; No special behavior. Point is already at the beginning of
  21518. ;; a line, logical or visual.
  21519. ((not special))
  21520. ;; `beginning-of-visual-line' left point before logical beginning
  21521. ;; of line: point is at the beginning of a visual line. Bail
  21522. ;; out.
  21523. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21524. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21525. ;; At a headline, special position is before the title, but
  21526. ;; after any TODO keyword or priority cookie.
  21527. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21528. (line-end-position)))
  21529. (bol (point)))
  21530. (if (eq special 'reversed)
  21531. (when (and (= origin bol) (eq last-command this-command))
  21532. (goto-char refpos))
  21533. (when (or (> origin refpos) (= origin bol))
  21534. (goto-char refpos)))))
  21535. ((and (looking-at org-list-full-item-re)
  21536. (memq (org-element-type (save-match-data (org-element-at-point)))
  21537. '(item plain-list)))
  21538. ;; Set special position at first white space character after
  21539. ;; bullet, and check-box, if any.
  21540. (let ((after-bullet
  21541. (let ((box (match-end 3)))
  21542. (cond ((not box) (match-end 1))
  21543. ((eq (char-after box) ?\s) (1+ box))
  21544. (t box)))))
  21545. (if (eq special 'reversed)
  21546. (when (and (= (point) origin) (eq last-command this-command))
  21547. (goto-char after-bullet))
  21548. (when (or (> origin after-bullet) (= (point) origin))
  21549. (goto-char after-bullet)))))
  21550. ;; No special context. Point is already at beginning of line.
  21551. (t nil))))
  21552. (defun org-end-of-line (&optional n)
  21553. "Go to the end of the line, but before ellipsis, if any.
  21554. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21555. tags on the first attempt, and only move to after the tags when
  21556. the cursor is already beyond the end of the headline.
  21557. With argument N not nil or 1, move forward N - 1 lines first."
  21558. (interactive "^p")
  21559. (let ((origin (point))
  21560. (special (pcase org-special-ctrl-a/e
  21561. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21562. deactivate-mark)
  21563. ;; First move to a visible line.
  21564. (if (bound-and-true-p visual-line-mode)
  21565. (beginning-of-visual-line n)
  21566. (move-beginning-of-line n))
  21567. (cond
  21568. ;; At a headline, with tags.
  21569. ((and special
  21570. (save-excursion
  21571. (beginning-of-line)
  21572. (let ((case-fold-search nil))
  21573. (looking-at org-complex-heading-regexp)))
  21574. (match-end 5))
  21575. (let ((tags (save-excursion
  21576. (goto-char (match-beginning 5))
  21577. (skip-chars-backward " \t")
  21578. (point)))
  21579. (visual-end (and (bound-and-true-p visual-line-mode)
  21580. (save-excursion
  21581. (end-of-visual-line)
  21582. (point)))))
  21583. ;; If `end-of-visual-line' brings us before end of line or
  21584. ;; even tags, i.e., the headline spans over multiple visual
  21585. ;; lines, move there.
  21586. (cond ((and visual-end
  21587. (< visual-end tags)
  21588. (<= origin visual-end))
  21589. (goto-char visual-end))
  21590. ((eq special 'reversed)
  21591. (if (and (= origin (line-end-position))
  21592. (eq this-command last-command))
  21593. (goto-char tags)
  21594. (end-of-line)))
  21595. (t
  21596. (if (or (< origin tags) (= origin (line-end-position)))
  21597. (goto-char tags)
  21598. (end-of-line))))))
  21599. ((bound-and-true-p visual-line-mode)
  21600. (let ((bol (line-beginning-position)))
  21601. (end-of-visual-line)
  21602. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21603. ;; end of a line, backtrack and use `end-of-line' instead.
  21604. (when (/= bol (line-beginning-position))
  21605. (goto-char bol)
  21606. (end-of-line))))
  21607. (t (end-of-line)))))
  21608. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21609. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21610. (defun org-backward-sentence (&optional _arg)
  21611. "Go to beginning of sentence, or beginning of table field.
  21612. This will call `backward-sentence' or `org-table-beginning-of-field',
  21613. depending on context."
  21614. (interactive)
  21615. (let* ((element (org-element-at-point))
  21616. (contents-begin (org-element-property :contents-begin element))
  21617. (table (org-element-lineage element '(table) t)))
  21618. (if (and table
  21619. (> (point) contents-begin)
  21620. (<= (point) (org-element-property :contents-end table)))
  21621. (call-interactively #'org-table-beginning-of-field)
  21622. (save-restriction
  21623. (when (and contents-begin
  21624. (< (point-min) contents-begin)
  21625. (> (point) contents-begin))
  21626. (narrow-to-region contents-begin
  21627. (org-element-property :contents-end element)))
  21628. (call-interactively #'backward-sentence)))))
  21629. (defun org-forward-sentence (&optional _arg)
  21630. "Go to end of sentence, or end of table field.
  21631. This will call `forward-sentence' or `org-table-end-of-field',
  21632. depending on context."
  21633. (interactive)
  21634. (let* ((element (org-element-at-point))
  21635. (contents-end (org-element-property :contents-end element))
  21636. (table (org-element-lineage element '(table) t)))
  21637. (if (and table
  21638. (>= (point) (org-element-property :contents-begin table))
  21639. (< (point) contents-end))
  21640. (call-interactively #'org-table-end-of-field)
  21641. (save-restriction
  21642. (when (and contents-end
  21643. (> (point-max) contents-end)
  21644. ;; Skip blank lines between elements.
  21645. (< (org-element-property :end element)
  21646. (save-excursion (goto-char contents-end)
  21647. (skip-chars-forward " \r\t\n"))))
  21648. (narrow-to-region (org-element-property :contents-begin element)
  21649. contents-end))
  21650. (call-interactively #'forward-sentence)))))
  21651. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21652. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21653. (defun org-kill-line (&optional _arg)
  21654. "Kill line, to tags or end of line."
  21655. (interactive)
  21656. (cond
  21657. ((or (not org-special-ctrl-k)
  21658. (bolp)
  21659. (not (org-at-heading-p)))
  21660. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21661. org-ctrl-k-protect-subtree
  21662. (or (eq org-ctrl-k-protect-subtree 'error)
  21663. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21664. (user-error "C-k aborted as it would kill a hidden subtree"))
  21665. (call-interactively
  21666. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21667. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21668. (kill-region (point) (match-beginning 1))
  21669. (org-set-tags nil t))
  21670. (t (kill-region (point) (point-at-eol)))))
  21671. (define-key org-mode-map "\C-k" 'org-kill-line)
  21672. (defun org-yank (&optional arg)
  21673. "Yank. If the kill is a subtree, treat it specially.
  21674. This command will look at the current kill and check if is a single
  21675. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21676. cursor is at the beginning of a line or after the stars of a currently
  21677. empty headline, then the yank is handled specially. How exactly depends
  21678. on the value of the following variables.
  21679. `org-yank-folded-subtrees'
  21680. By default, this variable is non-nil, which results in
  21681. subtree(s) being folded after insertion, except if doing so
  21682. would swallow text after the yanked text.
  21683. `org-yank-adjusted-subtrees'
  21684. When non-nil (the default value is nil), the subtree will be
  21685. promoted or demoted in order to fit into the local outline tree
  21686. structure, which means that the level will be adjusted so that it
  21687. becomes the smaller one of the two *visible* surrounding headings.
  21688. Any prefix to this command will cause `yank' to be called directly with
  21689. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21690. will just
  21691. plainly yank the text as it is.
  21692. \[1] The test checks if the first non-white line is a heading
  21693. and if there are no other headings with fewer stars."
  21694. (interactive "P")
  21695. (org-yank-generic 'yank arg))
  21696. (defun org-yank-generic (command arg)
  21697. "Perform some yank-like command.
  21698. This function implements the behavior described in the `org-yank'
  21699. documentation. However, it has been generalized to work for any
  21700. interactive command with similar behavior."
  21701. ;; pretend to be command COMMAND
  21702. (setq this-command command)
  21703. (if arg
  21704. (call-interactively command)
  21705. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21706. (and (org-kill-is-subtree-p)
  21707. (or (bolp)
  21708. (and (looking-at "[ \t]*$")
  21709. (string-match
  21710. "\\`\\*+\\'"
  21711. (buffer-substring (point-at-bol) (point)))))))
  21712. swallowp)
  21713. (cond
  21714. ((and subtreep org-yank-folded-subtrees)
  21715. (let ((beg (point))
  21716. end)
  21717. (if (and subtreep org-yank-adjusted-subtrees)
  21718. (org-paste-subtree nil nil 'for-yank)
  21719. (call-interactively command))
  21720. (setq end (point))
  21721. (goto-char beg)
  21722. (when (and (bolp) subtreep
  21723. (not (setq swallowp
  21724. (org-yank-folding-would-swallow-text beg end))))
  21725. (org-with-limited-levels
  21726. (or (looking-at org-outline-regexp)
  21727. (re-search-forward org-outline-regexp-bol end t))
  21728. (while (and (< (point) end) (looking-at org-outline-regexp))
  21729. (outline-hide-subtree)
  21730. (org-cycle-show-empty-lines 'folded)
  21731. (condition-case nil
  21732. (outline-forward-same-level 1)
  21733. (error (goto-char end))))))
  21734. (when swallowp
  21735. (message
  21736. "Inserted text not folded because that would swallow text"))
  21737. (goto-char end)
  21738. (skip-chars-forward " \t\n\r")
  21739. (beginning-of-line 1)
  21740. (push-mark beg 'nomsg)))
  21741. ((and subtreep org-yank-adjusted-subtrees)
  21742. (let ((beg (point-at-bol)))
  21743. (org-paste-subtree nil nil 'for-yank)
  21744. (push-mark beg 'nomsg)))
  21745. (t
  21746. (call-interactively command))))))
  21747. (defun org-yank-folding-would-swallow-text (beg end)
  21748. "Would hide-subtree at BEG swallow any text after END?"
  21749. (let (level)
  21750. (org-with-limited-levels
  21751. (save-excursion
  21752. (goto-char beg)
  21753. (when (or (looking-at org-outline-regexp)
  21754. (re-search-forward org-outline-regexp-bol end t))
  21755. (setq level (org-outline-level)))
  21756. (goto-char end)
  21757. (skip-chars-forward " \t\r\n\v\f")
  21758. (not (or (eobp)
  21759. (and (bolp) (looking-at-p org-outline-regexp)
  21760. (<= (org-outline-level) level))))))))
  21761. (define-key org-mode-map "\C-y" 'org-yank)
  21762. (defun org-truely-invisible-p ()
  21763. "Check if point is at a character currently not visible.
  21764. This version does not only check the character property, but also
  21765. `visible-mode'."
  21766. ;; Early versions of noutline don't have `outline-invisible-p'.
  21767. (unless (bound-and-true-p visible-mode)
  21768. (outline-invisible-p)))
  21769. (defun org-invisible-p2 ()
  21770. "Check if point is at a character currently not visible."
  21771. (save-excursion
  21772. (when (and (eolp) (not (bobp))) (backward-char 1))
  21773. ;; Early versions of noutline don't have `outline-invisible-p'.
  21774. (outline-invisible-p)))
  21775. (defun org-back-to-heading (&optional invisible-ok)
  21776. "Call `outline-back-to-heading', but provide a better error message."
  21777. (condition-case nil
  21778. (outline-back-to-heading invisible-ok)
  21779. (error (error "Before first headline at position %d in buffer %s"
  21780. (point) (current-buffer)))))
  21781. (defun org-before-first-heading-p ()
  21782. "Before first heading?"
  21783. (save-excursion
  21784. (end-of-line)
  21785. (null (re-search-backward org-outline-regexp-bol nil t))))
  21786. (defun org-at-heading-p (&optional ignored)
  21787. (outline-on-heading-p t))
  21788. (defun org-in-commented-heading-p (&optional no-inheritance)
  21789. "Non-nil if point is under a commented heading.
  21790. This function also checks ancestors of the current headline,
  21791. unless optional argument NO-INHERITANCE is non-nil."
  21792. (cond
  21793. ((org-before-first-heading-p) nil)
  21794. ((let ((headline (nth 4 (org-heading-components))))
  21795. (and headline
  21796. (let ((case-fold-search nil))
  21797. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21798. headline)))))
  21799. (no-inheritance nil)
  21800. (t
  21801. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21802. (defun org-at-comment-p nil
  21803. "Is cursor in a commented line?"
  21804. (save-excursion
  21805. (save-match-data
  21806. (beginning-of-line)
  21807. (looking-at "^[ \t]*# "))))
  21808. (defun org-at-drawer-p nil
  21809. "Is cursor at a drawer keyword?"
  21810. (save-excursion
  21811. (move-beginning-of-line 1)
  21812. (looking-at org-drawer-regexp)))
  21813. (defun org-at-block-p nil
  21814. "Is cursor at a block keyword?"
  21815. (save-excursion
  21816. (move-beginning-of-line 1)
  21817. (looking-at org-block-regexp)))
  21818. (defun org-point-at-end-of-empty-headline ()
  21819. "If point is at the end of an empty headline, return t, else nil.
  21820. If the heading only contains a TODO keyword, it is still still considered
  21821. empty."
  21822. (let ((case-fold-search nil))
  21823. (and (looking-at "[ \t]*$")
  21824. org-todo-line-regexp
  21825. (save-excursion
  21826. (beginning-of-line)
  21827. (looking-at org-todo-line-regexp)
  21828. (string= (match-string 3) "")))))
  21829. (defun org-at-heading-or-item-p ()
  21830. (or (org-at-heading-p) (org-at-item-p)))
  21831. (defun org-at-target-p ()
  21832. (or (org-in-regexp org-radio-target-regexp)
  21833. (org-in-regexp org-target-regexp)))
  21834. ;; Compatibility alias with Org versions < 7.8.03
  21835. (defalias 'org-on-target-p 'org-at-target-p)
  21836. (defun org-up-heading-all (arg)
  21837. "Move to the heading line of which the present line is a subheading.
  21838. This function considers both visible and invisible heading lines.
  21839. With argument, move up ARG levels."
  21840. (outline-up-heading arg t))
  21841. (defun org-up-heading-safe ()
  21842. "Move to the heading line of which the present line is a subheading.
  21843. This version will not throw an error. It will return the level of the
  21844. headline found, or nil if no higher level is found.
  21845. Also, this function will be a lot faster than `outline-up-heading',
  21846. because it relies on stars being the outline starters. This can really
  21847. make a significant difference in outlines with very many siblings."
  21848. (when (ignore-errors (org-back-to-heading t))
  21849. (let ((level-up (1- (funcall outline-level))))
  21850. (and (> level-up 0)
  21851. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21852. (funcall outline-level)))))
  21853. (defun org-first-sibling-p ()
  21854. "Is this heading the first child of its parents?"
  21855. (interactive)
  21856. (let ((re org-outline-regexp-bol)
  21857. level l)
  21858. (unless (org-at-heading-p t)
  21859. (user-error "Not at a heading"))
  21860. (setq level (funcall outline-level))
  21861. (save-excursion
  21862. (if (not (re-search-backward re nil t))
  21863. t
  21864. (setq l (funcall outline-level))
  21865. (< l level)))))
  21866. (defun org-goto-sibling (&optional previous)
  21867. "Goto the next sibling, even if it is invisible.
  21868. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21869. when a sibling was found. When none is found, return nil and don't
  21870. move point."
  21871. (let ((fun (if previous 're-search-backward 're-search-forward))
  21872. (pos (point))
  21873. (re org-outline-regexp-bol)
  21874. level l)
  21875. (when (ignore-errors (org-back-to-heading t))
  21876. (setq level (funcall outline-level))
  21877. (catch 'exit
  21878. (or previous (forward-char 1))
  21879. (while (funcall fun re nil t)
  21880. (setq l (funcall outline-level))
  21881. (when (< l level) (goto-char pos) (throw 'exit nil))
  21882. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21883. (goto-char pos)
  21884. nil))))
  21885. (defun org-show-siblings ()
  21886. "Show all siblings of the current headline."
  21887. (save-excursion
  21888. (while (org-goto-sibling) (org-flag-heading nil)))
  21889. (save-excursion
  21890. (while (org-goto-sibling 'previous)
  21891. (org-flag-heading nil))))
  21892. (defun org-goto-first-child ()
  21893. "Goto the first child, even if it is invisible.
  21894. Return t when a child was found. Otherwise don't move point and
  21895. return nil."
  21896. (let (level (pos (point)) (re org-outline-regexp-bol))
  21897. (when (ignore-errors (org-back-to-heading t))
  21898. (setq level (outline-level))
  21899. (forward-char 1)
  21900. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21901. (progn (goto-char (match-beginning 0)) t)
  21902. (goto-char pos) nil))))
  21903. (defun org-show-hidden-entry ()
  21904. "Show an entry where even the heading is hidden."
  21905. (save-excursion
  21906. (org-show-entry)))
  21907. (defun org-flag-heading (flag &optional entry)
  21908. "Flag the current heading. FLAG non-nil means make invisible.
  21909. When ENTRY is non-nil, show the entire entry."
  21910. (save-excursion
  21911. (org-back-to-heading t)
  21912. ;; Check if we should show the entire entry
  21913. (if entry
  21914. (progn
  21915. (org-show-entry)
  21916. (save-excursion
  21917. (and (outline-next-heading)
  21918. (org-flag-heading nil))))
  21919. (outline-flag-region (max (point-min) (1- (point)))
  21920. (save-excursion (outline-end-of-heading) (point))
  21921. flag))))
  21922. (defun org-get-next-sibling ()
  21923. "Move to next heading of the same level, and return point.
  21924. If there is no such heading, return nil.
  21925. This is like outline-next-sibling, but invisible headings are ok."
  21926. (let ((level (funcall outline-level)))
  21927. (outline-next-heading)
  21928. (while (and (not (eobp)) (> (funcall outline-level) level))
  21929. (outline-next-heading))
  21930. (unless (or (eobp) (< (funcall outline-level) level))
  21931. (point))))
  21932. (defun org-get-last-sibling ()
  21933. "Move to previous heading of the same level, and return point.
  21934. If there is no such heading, return nil."
  21935. (let ((opoint (point))
  21936. (level (funcall outline-level)))
  21937. (outline-previous-heading)
  21938. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21939. (while (and (> (funcall outline-level) level)
  21940. (not (bobp)))
  21941. (outline-previous-heading))
  21942. (unless (< (funcall outline-level) level)
  21943. (point)))))
  21944. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21945. "Goto to the end of a subtree."
  21946. ;; This contains an exact copy of the original function, but it uses
  21947. ;; `org-back-to-heading', to make it work also in invisible
  21948. ;; trees. And is uses an invisible-ok argument.
  21949. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21950. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21951. ;; with many children and grandchildren etc, this can be much faster
  21952. ;; than the outline version.
  21953. (org-back-to-heading invisible-ok)
  21954. (let ((first t)
  21955. (level (funcall outline-level)))
  21956. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21957. ;; A true heading (not a plain list item), in Org
  21958. ;; This means we can easily find the end by looking
  21959. ;; only for the right number of stars. Using a regexp to do
  21960. ;; this is so much faster than using a Lisp loop.
  21961. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21962. (forward-char 1)
  21963. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21964. ;; something else, do it the slow way
  21965. (while (and (not (eobp))
  21966. (or first (> (funcall outline-level) level)))
  21967. (setq first nil)
  21968. (outline-next-heading)))
  21969. (unless to-heading
  21970. (when (memq (preceding-char) '(?\n ?\^M))
  21971. ;; Go to end of line before heading
  21972. (forward-char -1)
  21973. (when (memq (preceding-char) '(?\n ?\^M))
  21974. ;; leave blank line before heading
  21975. (forward-char -1)))))
  21976. (point))
  21977. (defun org-end-of-meta-data (&optional full)
  21978. "Skip planning line and properties drawer in current entry.
  21979. When optional argument FULL is non-nil, also skip empty lines,
  21980. clocking lines and regular drawers at the beginning of the
  21981. entry."
  21982. (org-back-to-heading t)
  21983. (forward-line)
  21984. (when (looking-at-p org-planning-line-re) (forward-line))
  21985. (when (looking-at org-property-drawer-re)
  21986. (goto-char (match-end 0))
  21987. (forward-line))
  21988. (when (and full (not (org-at-heading-p)))
  21989. (catch 'exit
  21990. (let ((end (save-excursion (outline-next-heading) (point)))
  21991. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21992. (while (not (eobp))
  21993. (cond ((looking-at-p org-drawer-regexp)
  21994. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21995. (forward-line)
  21996. (throw 'exit t)))
  21997. ((looking-at-p re) (forward-line))
  21998. (t (throw 'exit t))))))))
  21999. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22000. "Move forward to the ARG'th subheading at same level as this one.
  22001. Stop at the first and last subheadings of a superior heading.
  22002. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22003. non-nil it will also look at invisible ones."
  22004. (interactive "p")
  22005. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22006. (if (and arg (< arg 0))
  22007. (goto-char (point-min))
  22008. (outline-next-heading))
  22009. (org-at-heading-p)
  22010. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22011. (f (if (and arg (< arg 0))
  22012. 're-search-backward
  22013. 're-search-forward))
  22014. (count (if arg (abs arg) 1))
  22015. (result (point)))
  22016. (while (and (prog1 (> count 0)
  22017. (forward-char (if (and arg (< arg 0)) -1 1)))
  22018. (funcall f org-outline-regexp-bol nil 'move))
  22019. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22020. (cond ((< l level) (setq count 0))
  22021. ((and (= l level)
  22022. (or invisible-ok
  22023. (progn
  22024. (goto-char (line-beginning-position))
  22025. (not (outline-invisible-p)))))
  22026. (setq count (1- count))
  22027. (when (eq l level)
  22028. (setq result (point)))))))
  22029. (goto-char result))
  22030. (beginning-of-line 1)))
  22031. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22032. "Move backward to the ARG'th subheading at same level as this one.
  22033. Stop at the first and last subheadings of a superior heading."
  22034. (interactive "p")
  22035. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22036. (defun org-next-visible-heading (arg)
  22037. "Move to the next visible heading.
  22038. This function wraps `outline-next-visible-heading' with
  22039. `org-with-limited-levels' in order to skip over inline tasks and
  22040. respect customization of `org-odd-levels-only'."
  22041. (interactive "p")
  22042. (org-with-limited-levels
  22043. (outline-next-visible-heading arg)))
  22044. (defun org-previous-visible-heading (arg)
  22045. "Move to the previous visible heading.
  22046. This function wraps `outline-previous-visible-heading' with
  22047. `org-with-limited-levels' in order to skip over inline tasks and
  22048. respect customization of `org-odd-levels-only'."
  22049. (interactive "p")
  22050. (org-with-limited-levels
  22051. (outline-previous-visible-heading arg)))
  22052. (defun org-next-block (arg &optional backward block-regexp)
  22053. "Jump to the next block.
  22054. With a prefix argument ARG, jump forward ARG many blocks.
  22055. When BACKWARD is non-nil, jump to the previous block.
  22056. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22057. Match data is set according to this regexp when the function
  22058. returns.
  22059. Return point at beginning of the opening line of found block.
  22060. Throw an error if no block is found."
  22061. (interactive "p")
  22062. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22063. (case-fold-search t)
  22064. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22065. (count (or arg 1))
  22066. (origin (point))
  22067. last-element)
  22068. (if backward (beginning-of-line) (end-of-line))
  22069. (while (and (> count 0) (funcall search-fn re nil t))
  22070. (let ((element (save-excursion
  22071. (goto-char (match-beginning 0))
  22072. (save-match-data (org-element-at-point)))))
  22073. (when (and (memq (org-element-type element)
  22074. '(center-block comment-block dynamic-block
  22075. example-block export-block quote-block
  22076. special-block src-block verse-block))
  22077. (<= (match-beginning 0)
  22078. (org-element-property :post-affiliated element)))
  22079. (setq last-element element)
  22080. (cl-decf count))))
  22081. (if (= count 0)
  22082. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22083. (save-match-data (org-show-context)))
  22084. (goto-char origin)
  22085. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22086. (defun org-previous-block (arg &optional block-regexp)
  22087. "Jump to the previous block.
  22088. With a prefix argument ARG, jump backward ARG many source blocks.
  22089. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22090. (interactive "p")
  22091. (org-next-block arg t block-regexp))
  22092. (defun org-forward-paragraph ()
  22093. "Move forward to beginning of next paragraph or equivalent.
  22094. The function moves point to the beginning of the next visible
  22095. structural element, which can be a paragraph, a table, a list
  22096. item, etc. It also provides some special moves for convenience:
  22097. - On an affiliated keyword, jump to the beginning of the
  22098. relative element.
  22099. - On an item or a footnote definition, move to the second
  22100. element inside, if any.
  22101. - On a table or a property drawer, jump after it.
  22102. - On a verse or source block, stop after blank lines."
  22103. (interactive)
  22104. (when (eobp) (user-error "Cannot move further down"))
  22105. (let* ((deactivate-mark nil)
  22106. (element (org-element-at-point))
  22107. (type (org-element-type element))
  22108. (post-affiliated (org-element-property :post-affiliated element))
  22109. (contents-begin (org-element-property :contents-begin element))
  22110. (contents-end (org-element-property :contents-end element))
  22111. (end (let ((end (org-element-property :end element)) (parent element))
  22112. (while (and (setq parent (org-element-property :parent parent))
  22113. (= (org-element-property :contents-end parent) end))
  22114. (setq end (org-element-property :end parent)))
  22115. end)))
  22116. (cond ((not element)
  22117. (skip-chars-forward " \r\t\n")
  22118. (or (eobp) (beginning-of-line)))
  22119. ;; On affiliated keywords, move to element's beginning.
  22120. ((< (point) post-affiliated)
  22121. (goto-char post-affiliated))
  22122. ;; At a table row, move to the end of the table. Similarly,
  22123. ;; at a node property, move to the end of the property
  22124. ;; drawer.
  22125. ((memq type '(node-property table-row))
  22126. (goto-char (org-element-property
  22127. :end (org-element-property :parent element))))
  22128. ((memq type '(property-drawer table)) (goto-char end))
  22129. ;; Consider blank lines as separators in verse and source
  22130. ;; blocks to ease editing.
  22131. ((memq type '(src-block verse-block))
  22132. (when (eq type 'src-block)
  22133. (setq contents-end
  22134. (save-excursion (goto-char end)
  22135. (skip-chars-backward " \r\t\n")
  22136. (line-beginning-position))))
  22137. (beginning-of-line)
  22138. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22139. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22140. (goto-char end)
  22141. (skip-chars-forward " \r\t\n")
  22142. (if (= (point) contents-end) (goto-char end)
  22143. (beginning-of-line))))
  22144. ;; With no contents, just skip element.
  22145. ((not contents-begin) (goto-char end))
  22146. ;; If contents are invisible, skip the element altogether.
  22147. ((outline-invisible-p (line-end-position))
  22148. (cl-case type
  22149. (headline
  22150. (org-with-limited-levels (outline-next-visible-heading 1)))
  22151. ;; At a plain list, make sure we move to the next item
  22152. ;; instead of skipping the whole list.
  22153. (plain-list (forward-char)
  22154. (org-forward-paragraph))
  22155. (otherwise (goto-char end))))
  22156. ((>= (point) contents-end) (goto-char end))
  22157. ((>= (point) contents-begin)
  22158. ;; This can only happen on paragraphs and plain lists.
  22159. (cl-case type
  22160. (paragraph (goto-char end))
  22161. ;; At a plain list, try to move to second element in
  22162. ;; first item, if possible.
  22163. (plain-list (end-of-line)
  22164. (org-forward-paragraph))))
  22165. ;; When contents start on the middle of a line (e.g. in
  22166. ;; items and footnote definitions), try to reach first
  22167. ;; element starting after current line.
  22168. ((> (line-end-position) contents-begin)
  22169. (end-of-line)
  22170. (org-forward-paragraph))
  22171. (t (goto-char contents-begin)))))
  22172. (defun org-backward-paragraph ()
  22173. "Move backward to start of previous paragraph or equivalent.
  22174. The function moves point to the beginning of the current
  22175. structural element, which can be a paragraph, a table, a list
  22176. item, etc., or to the beginning of the previous visible one if
  22177. point is already there. It also provides some special moves for
  22178. convenience:
  22179. - On an affiliated keyword, jump to the first one.
  22180. - On a table or a property drawer, move to its beginning.
  22181. - On a verse or source block, stop before blank lines."
  22182. (interactive)
  22183. (when (bobp) (user-error "Cannot move further up"))
  22184. (let* ((deactivate-mark nil)
  22185. (element (org-element-at-point))
  22186. (type (org-element-type element))
  22187. (contents-begin (org-element-property :contents-begin element))
  22188. (contents-end (org-element-property :contents-end element))
  22189. (post-affiliated (org-element-property :post-affiliated element))
  22190. (begin (org-element-property :begin element)))
  22191. (cond
  22192. ((not element) (goto-char (point-min)))
  22193. ((= (point) begin)
  22194. (backward-char)
  22195. (org-backward-paragraph))
  22196. ((<= (point) post-affiliated) (goto-char begin))
  22197. ((memq type '(node-property table-row))
  22198. (goto-char (org-element-property
  22199. :post-affiliated (org-element-property :parent element))))
  22200. ((memq type '(property-drawer table)) (goto-char begin))
  22201. ((memq type '(src-block verse-block))
  22202. (when (eq type 'src-block)
  22203. (setq contents-begin
  22204. (save-excursion (goto-char begin) (forward-line) (point))))
  22205. (if (= (point) contents-begin) (goto-char post-affiliated)
  22206. ;; Inside a verse block, see blank lines as paragraph
  22207. ;; separators.
  22208. (let ((origin (point)))
  22209. (skip-chars-backward " \r\t\n" contents-begin)
  22210. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22211. (skip-chars-forward " \r\t\n" origin)
  22212. (if (= (point) origin) (goto-char contents-begin)
  22213. (beginning-of-line))))))
  22214. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22215. ((eq type 'paragraph)
  22216. (goto-char contents-begin)
  22217. ;; When at first paragraph in an item or a footnote definition,
  22218. ;; move directly to beginning of line.
  22219. (let ((parent-contents
  22220. (org-element-property
  22221. :contents-begin (org-element-property :parent element))))
  22222. (when (and parent-contents (= parent-contents contents-begin))
  22223. (beginning-of-line))))
  22224. ;; At the end of a greater element, move to the beginning of the
  22225. ;; last element within.
  22226. ((>= (point) contents-end)
  22227. (goto-char (1- contents-end))
  22228. (org-backward-paragraph))
  22229. (t (goto-char (or post-affiliated begin))))
  22230. ;; Ensure we never leave point invisible.
  22231. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22232. (defun org-forward-element ()
  22233. "Move forward by one element.
  22234. Move to the next element at the same level, when possible."
  22235. (interactive)
  22236. (cond ((eobp) (user-error "Cannot move further down"))
  22237. ((org-with-limited-levels (org-at-heading-p))
  22238. (let ((origin (point)))
  22239. (goto-char (org-end-of-subtree nil t))
  22240. (unless (org-with-limited-levels (org-at-heading-p))
  22241. (goto-char origin)
  22242. (user-error "Cannot move further down"))))
  22243. (t
  22244. (let* ((elem (org-element-at-point))
  22245. (end (org-element-property :end elem))
  22246. (parent (org-element-property :parent elem)))
  22247. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22248. (goto-char (org-element-property :end parent)))
  22249. ((integer-or-marker-p end) (goto-char end))
  22250. (t (message "No element at point")))))))
  22251. (defun org-backward-element ()
  22252. "Move backward by one element.
  22253. Move to the previous element at the same level, when possible."
  22254. (interactive)
  22255. (cond ((bobp) (user-error "Cannot move further up"))
  22256. ((org-with-limited-levels (org-at-heading-p))
  22257. ;; At a headline, move to the previous one, if any, or stay
  22258. ;; here.
  22259. (let ((origin (point)))
  22260. (org-with-limited-levels (org-backward-heading-same-level 1))
  22261. ;; When current headline has no sibling above, move to its
  22262. ;; parent.
  22263. (when (= (point) origin)
  22264. (or (org-with-limited-levels (org-up-heading-safe))
  22265. (progn (goto-char origin)
  22266. (user-error "Cannot move further up"))))))
  22267. (t
  22268. (let* ((elem (org-element-at-point))
  22269. (beg (org-element-property :begin elem)))
  22270. (cond
  22271. ;; Move to beginning of current element if point isn't
  22272. ;; there already.
  22273. ((null beg) (message "No element at point"))
  22274. ((/= (point) beg) (goto-char beg))
  22275. (t (goto-char beg)
  22276. (skip-chars-backward " \r\t\n")
  22277. (unless (bobp)
  22278. (let ((prev (org-element-at-point)))
  22279. (goto-char (org-element-property :begin prev))
  22280. (while (and (setq prev (org-element-property :parent prev))
  22281. (<= (org-element-property :end prev) beg))
  22282. (goto-char (org-element-property :begin prev)))))))))))
  22283. (defun org-up-element ()
  22284. "Move to upper element."
  22285. (interactive)
  22286. (if (org-with-limited-levels (org-at-heading-p))
  22287. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22288. (let* ((elem (org-element-at-point))
  22289. (parent (org-element-property :parent elem)))
  22290. (if parent (goto-char (org-element-property :begin parent))
  22291. (if (org-with-limited-levels (org-before-first-heading-p))
  22292. (user-error "No surrounding element")
  22293. (org-with-limited-levels (org-back-to-heading)))))))
  22294. (defvar org-element-greater-elements)
  22295. (defun org-down-element ()
  22296. "Move to inner element."
  22297. (interactive)
  22298. (let ((element (org-element-at-point)))
  22299. (cond
  22300. ((memq (org-element-type element) '(plain-list table))
  22301. (goto-char (org-element-property :contents-begin element))
  22302. (forward-char))
  22303. ((memq (org-element-type element) org-element-greater-elements)
  22304. ;; If contents are hidden, first disclose them.
  22305. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22306. (goto-char (or (org-element-property :contents-begin element)
  22307. (user-error "No content for this element"))))
  22308. (t (user-error "No inner element")))))
  22309. (defun org-drag-element-backward ()
  22310. "Move backward element at point."
  22311. (interactive)
  22312. (let ((elem (or (org-element-at-point)
  22313. (user-error "No element at point"))))
  22314. (if (eq (org-element-type elem) 'headline)
  22315. ;; Preserve point when moving a whole tree, even if point was
  22316. ;; on blank lines below the headline.
  22317. (let ((offset (skip-chars-backward " \t\n")))
  22318. (unwind-protect (org-move-subtree-up)
  22319. (forward-char (- offset))))
  22320. (let ((prev-elem
  22321. (save-excursion
  22322. (goto-char (org-element-property :begin elem))
  22323. (skip-chars-backward " \r\t\n")
  22324. (unless (bobp)
  22325. (let* ((beg (org-element-property :begin elem))
  22326. (prev (org-element-at-point))
  22327. (up prev))
  22328. (while (and (setq up (org-element-property :parent up))
  22329. (<= (org-element-property :end up) beg))
  22330. (setq prev up))
  22331. prev)))))
  22332. ;; Error out if no previous element or previous element is
  22333. ;; a parent of the current one.
  22334. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22335. (user-error "Cannot drag element backward")
  22336. (let ((pos (point)))
  22337. (org-element-swap-A-B prev-elem elem)
  22338. (goto-char (+ (org-element-property :begin prev-elem)
  22339. (- pos (org-element-property :begin elem))))))))))
  22340. (defun org-drag-element-forward ()
  22341. "Move forward element at point."
  22342. (interactive)
  22343. (let* ((pos (point))
  22344. (elem (or (org-element-at-point)
  22345. (user-error "No element at point"))))
  22346. (when (= (point-max) (org-element-property :end elem))
  22347. (user-error "Cannot drag element forward"))
  22348. (goto-char (org-element-property :end elem))
  22349. (let ((next-elem (org-element-at-point)))
  22350. (when (or (org-element-nested-p elem next-elem)
  22351. (and (eq (org-element-type next-elem) 'headline)
  22352. (not (eq (org-element-type elem) 'headline))))
  22353. (goto-char pos)
  22354. (user-error "Cannot drag element forward"))
  22355. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22356. ;; body's length (without final blanks) and by the length of
  22357. ;; blanks between ELEM and NEXT-ELEM.
  22358. (let ((size-next (- (save-excursion
  22359. (goto-char (org-element-property :end next-elem))
  22360. (skip-chars-backward " \r\t\n")
  22361. (forward-line)
  22362. ;; Small correction if buffer doesn't end
  22363. ;; with a newline character.
  22364. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22365. (org-element-property :begin next-elem)))
  22366. (size-blank (- (org-element-property :end elem)
  22367. (save-excursion
  22368. (goto-char (org-element-property :end elem))
  22369. (skip-chars-backward " \r\t\n")
  22370. (forward-line)
  22371. (point)))))
  22372. (org-element-swap-A-B elem next-elem)
  22373. (goto-char (+ pos size-next size-blank))))))
  22374. (defun org-drag-line-forward (arg)
  22375. "Drag the line at point ARG lines forward."
  22376. (interactive "p")
  22377. (dotimes (_ (abs arg))
  22378. (let ((c (current-column)))
  22379. (if (< 0 arg)
  22380. (progn
  22381. (beginning-of-line 2)
  22382. (transpose-lines 1)
  22383. (beginning-of-line 0))
  22384. (transpose-lines 1)
  22385. (beginning-of-line -1))
  22386. (org-move-to-column c))))
  22387. (defun org-drag-line-backward (arg)
  22388. "Drag the line at point ARG lines backward."
  22389. (interactive "p")
  22390. (org-drag-line-forward (- arg)))
  22391. (defun org-mark-element ()
  22392. "Put point at beginning of this element, mark at end.
  22393. Interactively, if this command is repeated or (in Transient Mark
  22394. mode) if the mark is active, it marks the next element after the
  22395. ones already marked."
  22396. (interactive)
  22397. (let (deactivate-mark)
  22398. (if (and (called-interactively-p 'any)
  22399. (or (and (eq last-command this-command) (mark t))
  22400. (and transient-mark-mode mark-active)))
  22401. (set-mark
  22402. (save-excursion
  22403. (goto-char (mark))
  22404. (goto-char (org-element-property :end (org-element-at-point)))))
  22405. (let ((element (org-element-at-point)))
  22406. (end-of-line)
  22407. (push-mark (org-element-property :end element) t t)
  22408. (goto-char (org-element-property :begin element))))))
  22409. (defun org-narrow-to-element ()
  22410. "Narrow buffer to current element."
  22411. (interactive)
  22412. (let ((elem (org-element-at-point)))
  22413. (cond
  22414. ((eq (car elem) 'headline)
  22415. (narrow-to-region
  22416. (org-element-property :begin elem)
  22417. (org-element-property :end elem)))
  22418. ((memq (car elem) org-element-greater-elements)
  22419. (narrow-to-region
  22420. (org-element-property :contents-begin elem)
  22421. (org-element-property :contents-end elem)))
  22422. (t
  22423. (narrow-to-region
  22424. (org-element-property :begin elem)
  22425. (org-element-property :end elem))))))
  22426. (defun org-transpose-element ()
  22427. "Transpose current and previous elements, keeping blank lines between.
  22428. Point is moved after both elements."
  22429. (interactive)
  22430. (org-skip-whitespace)
  22431. (let ((end (org-element-property :end (org-element-at-point))))
  22432. (org-drag-element-backward)
  22433. (goto-char end)))
  22434. (defun org-unindent-buffer ()
  22435. "Un-indent the visible part of the buffer.
  22436. Relative indentation (between items, inside blocks, etc.) isn't
  22437. modified."
  22438. (interactive)
  22439. (unless (eq major-mode 'org-mode)
  22440. (user-error "Cannot un-indent a buffer not in Org mode"))
  22441. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22442. (unindent-tree
  22443. (lambda (contents)
  22444. (dolist (element (reverse contents))
  22445. (if (memq (org-element-type element) '(headline section))
  22446. (funcall unindent-tree (org-element-contents element))
  22447. (save-excursion
  22448. (save-restriction
  22449. (narrow-to-region
  22450. (org-element-property :begin element)
  22451. (org-element-property :end element))
  22452. (org-do-remove-indentation))))))))
  22453. (funcall unindent-tree (org-element-contents parse-tree))))
  22454. (defun org-show-children (&optional level)
  22455. "Show all direct subheadings of this heading.
  22456. Prefix arg LEVEL is how many levels below the current level
  22457. should be shown. Default is enough to cause the following
  22458. heading to appear."
  22459. (interactive "p")
  22460. ;; If `orgstruct-mode' is active, use the slower version.
  22461. (if orgstruct-mode (call-interactively #'outline-show-children)
  22462. (save-excursion
  22463. (org-back-to-heading t)
  22464. (let* ((current-level (funcall outline-level))
  22465. (max-level (org-get-valid-level
  22466. current-level
  22467. (if level (prefix-numeric-value level) 1)))
  22468. (end (save-excursion (org-end-of-subtree t t)))
  22469. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22470. (past-first-child nil)
  22471. ;; Make sure to skip inlinetasks.
  22472. (re (format regexp-fmt
  22473. current-level
  22474. (cond
  22475. ((not (featurep 'org-inlinetask)) "")
  22476. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22477. 3))
  22478. (t (1- org-inlinetask-min-level))))))
  22479. ;; Display parent heading.
  22480. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22481. (forward-line)
  22482. ;; Display children. First child may be deeper than expected
  22483. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22484. ;; MAX-LEVEL accordingly.
  22485. (while (re-search-forward re end t)
  22486. (unless past-first-child
  22487. (setq re (format regexp-fmt
  22488. current-level
  22489. (max (funcall outline-level) max-level)))
  22490. (setq past-first-child t))
  22491. (outline-flag-region
  22492. (line-end-position 0) (line-end-position) nil))))))
  22493. (defun org-show-subtree ()
  22494. "Show everything after this heading at deeper levels."
  22495. (interactive)
  22496. (outline-flag-region
  22497. (point)
  22498. (save-excursion
  22499. (org-end-of-subtree t t))
  22500. nil))
  22501. (defun org-show-entry ()
  22502. "Show the body directly following this heading.
  22503. Show the heading too, if it is currently invisible."
  22504. (interactive)
  22505. (save-excursion
  22506. (ignore-errors
  22507. (org-back-to-heading t)
  22508. (outline-flag-region
  22509. (max (point-min) (1- (point)))
  22510. (save-excursion
  22511. (if (re-search-forward
  22512. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22513. (match-beginning 1)
  22514. (point-max)))
  22515. nil)
  22516. (org-cycle-hide-drawers 'children))))
  22517. (defun org-make-options-regexp (kwds &optional extra)
  22518. "Make a regular expression for keyword lines.
  22519. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22520. when non-nil, is a regexp matching keywords names."
  22521. (concat "^[ \t]*#\\+\\("
  22522. (regexp-opt kwds)
  22523. (and extra (concat (and kwds "\\|") extra))
  22524. "\\):[ \t]*\\(.*\\)"))
  22525. ;;;; Integration with and fixes for other packages
  22526. ;;; Imenu support
  22527. (defvar-local org-imenu-markers nil
  22528. "All markers currently used by Imenu.")
  22529. (defun org-imenu-new-marker (&optional pos)
  22530. "Return a new marker for use by Imenu, and remember the marker."
  22531. (let ((m (make-marker)))
  22532. (move-marker m (or pos (point)))
  22533. (push m org-imenu-markers)
  22534. m))
  22535. (defun org-imenu-get-tree ()
  22536. "Produce the index for Imenu."
  22537. (dolist (x org-imenu-markers) (move-marker x nil))
  22538. (setq org-imenu-markers nil)
  22539. (let* ((case-fold-search nil)
  22540. (n org-imenu-depth)
  22541. (re (concat "^" (org-get-limited-outline-regexp)))
  22542. (subs (make-vector (1+ n) nil))
  22543. (last-level 0)
  22544. m level head0 head)
  22545. (org-with-wide-buffer
  22546. (goto-char (point-max))
  22547. (while (re-search-backward re nil t)
  22548. (setq level (org-reduced-level (funcall outline-level)))
  22549. (when (and (<= level n)
  22550. (looking-at org-complex-heading-regexp)
  22551. (setq head0 (match-string-no-properties 4)))
  22552. (setq head (org-link-display-format head0)
  22553. m (org-imenu-new-marker))
  22554. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22555. (if (>= level last-level)
  22556. (push (cons head m) (aref subs level))
  22557. (push (cons head (aref subs (1+ level))) (aref subs level))
  22558. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22559. (setq last-level level))))
  22560. (aref subs 1)))
  22561. (eval-after-load "imenu"
  22562. '(progn
  22563. (add-hook 'imenu-after-jump-hook
  22564. (lambda ()
  22565. (when (derived-mode-p 'org-mode)
  22566. (org-show-context 'org-goto))))))
  22567. (defun org-link-display-format (s)
  22568. "Replace links in string S with their description.
  22569. If there is no description, use the link target."
  22570. (save-match-data
  22571. (replace-regexp-in-string
  22572. org-bracket-link-analytic-regexp
  22573. (lambda (m)
  22574. (if (match-end 5) (match-string 5 m)
  22575. (concat (match-string 1 m) (match-string 3 m))))
  22576. s nil t)))
  22577. (defun org-toggle-link-display ()
  22578. "Toggle the literal or descriptive display of links."
  22579. (interactive)
  22580. (if org-descriptive-links
  22581. (progn (org-remove-from-invisibility-spec '(org-link))
  22582. (org-restart-font-lock)
  22583. (setq org-descriptive-links nil))
  22584. (progn (add-to-invisibility-spec '(org-link))
  22585. (org-restart-font-lock)
  22586. (setq org-descriptive-links t))))
  22587. ;; Speedbar support
  22588. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22589. "Overlay marking the agenda restriction line in speedbar.")
  22590. (overlay-put org-speedbar-restriction-lock-overlay
  22591. 'face 'org-agenda-restriction-lock)
  22592. (overlay-put org-speedbar-restriction-lock-overlay
  22593. 'help-echo "Agendas are currently limited to this item.")
  22594. (delete-overlay org-speedbar-restriction-lock-overlay)
  22595. (defun org-speedbar-set-agenda-restriction ()
  22596. "Restrict future agenda commands to the location at point in speedbar.
  22597. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22598. (interactive)
  22599. (require 'org-agenda)
  22600. (let (p m tp np dir txt)
  22601. (cond
  22602. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22603. 'org-imenu t))
  22604. (setq m (get-text-property p 'org-imenu-marker))
  22605. (with-current-buffer (marker-buffer m)
  22606. (goto-char m)
  22607. (org-agenda-set-restriction-lock 'subtree)))
  22608. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22609. 'speedbar-function 'speedbar-find-file))
  22610. (setq tp (previous-single-property-change
  22611. (1+ p) 'speedbar-function)
  22612. np (next-single-property-change
  22613. tp 'speedbar-function)
  22614. dir (speedbar-line-directory)
  22615. txt (buffer-substring-no-properties (or tp (point-min))
  22616. (or np (point-max))))
  22617. (with-current-buffer (find-file-noselect
  22618. (let ((default-directory dir))
  22619. (expand-file-name txt)))
  22620. (unless (derived-mode-p 'org-mode)
  22621. (user-error "Cannot restrict to non-Org mode file"))
  22622. (org-agenda-set-restriction-lock 'file)))
  22623. (t (user-error "Don't know how to restrict Org mode agenda")))
  22624. (move-overlay org-speedbar-restriction-lock-overlay
  22625. (point-at-bol) (point-at-eol))
  22626. (setq current-prefix-arg nil)
  22627. (org-agenda-maybe-redo)))
  22628. (defvar speedbar-file-key-map)
  22629. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22630. (eval-after-load "speedbar"
  22631. '(progn
  22632. (speedbar-add-supported-extension ".org")
  22633. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22634. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22635. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22636. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22637. (add-hook 'speedbar-visiting-tag-hook
  22638. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22639. ;;; Fixes and Hacks for problems with other packages
  22640. (defun org--flyspell-object-check-p (element)
  22641. "Non-nil when Flyspell can check object at point.
  22642. ELEMENT is the element at point."
  22643. (let ((object (save-excursion
  22644. (when (looking-at-p "\\>") (backward-char))
  22645. (org-element-context element))))
  22646. (cl-case (org-element-type object)
  22647. ;; Prevent checks in links due to keybinding conflict with
  22648. ;; Flyspell.
  22649. ((code entity export-snippet inline-babel-call
  22650. inline-src-block line-break latex-fragment link macro
  22651. statistics-cookie target timestamp verbatim)
  22652. nil)
  22653. (footnote-reference
  22654. ;; Only in inline footnotes, within the definition.
  22655. (and (eq (org-element-property :type object) 'inline)
  22656. (< (save-excursion
  22657. (goto-char (org-element-property :begin object))
  22658. (search-forward ":" nil t 2))
  22659. (point))))
  22660. (otherwise t))))
  22661. (defun org-mode-flyspell-verify ()
  22662. "Function used for `flyspell-generic-check-word-predicate'."
  22663. (if (org-at-heading-p)
  22664. ;; At a headline or an inlinetask, check title only. This is
  22665. ;; faster than relying on `org-element-at-point'.
  22666. (and (save-excursion (beginning-of-line)
  22667. (and (let ((case-fold-search t))
  22668. (not (looking-at-p "\\*+ END[ \t]*$")))
  22669. (let ((case-fold-search nil))
  22670. (looking-at org-complex-heading-regexp))))
  22671. (match-beginning 4)
  22672. (>= (point) (match-beginning 4))
  22673. (or (not (match-beginning 5))
  22674. (< (point) (match-beginning 5))))
  22675. (let* ((element (org-element-at-point))
  22676. (post-affiliated (org-element-property :post-affiliated element)))
  22677. (cond
  22678. ;; Ignore checks in all affiliated keywords but captions.
  22679. ((< (point) post-affiliated)
  22680. (and (save-excursion
  22681. (beginning-of-line)
  22682. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22683. (> (point) (match-end 0))
  22684. (org--flyspell-object-check-p element)))
  22685. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22686. ((let ((log (org-log-into-drawer)))
  22687. (and log
  22688. (let ((drawer (org-element-lineage element '(drawer))))
  22689. (and drawer
  22690. (eq (compare-strings
  22691. log nil nil
  22692. (org-element-property :drawer-name drawer) nil nil t)
  22693. t)))))
  22694. nil)
  22695. (t
  22696. (cl-case (org-element-type element)
  22697. ((comment quote-section) t)
  22698. (comment-block
  22699. ;; Allow checks between block markers, not on them.
  22700. (and (> (line-beginning-position) post-affiliated)
  22701. (save-excursion
  22702. (end-of-line)
  22703. (skip-chars-forward " \r\t\n")
  22704. (< (point) (org-element-property :end element)))))
  22705. ;; Arbitrary list of keywords where checks are meaningful.
  22706. ;; Make sure point is on the value part of the element.
  22707. (keyword
  22708. (and (member (org-element-property :key element)
  22709. '("DESCRIPTION" "TITLE"))
  22710. (save-excursion
  22711. (search-backward ":" (line-beginning-position) t))))
  22712. ;; Check is globally allowed in paragraphs verse blocks and
  22713. ;; table rows (after affiliated keywords) but some objects
  22714. ;; must not be affected.
  22715. ((paragraph table-row verse-block)
  22716. (let ((cbeg (org-element-property :contents-begin element))
  22717. (cend (org-element-property :contents-end element)))
  22718. (and cbeg (>= (point) cbeg) (< (point) cend)
  22719. (org--flyspell-object-check-p element))))))))))
  22720. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22721. (defun org-remove-flyspell-overlays-in (beg end)
  22722. "Remove flyspell overlays in region."
  22723. (and (bound-and-true-p flyspell-mode)
  22724. (fboundp 'flyspell-delete-region-overlays)
  22725. (flyspell-delete-region-overlays beg end)))
  22726. (defvar flyspell-delayed-commands)
  22727. (eval-after-load "flyspell"
  22728. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22729. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22730. (eval-after-load "bookmark"
  22731. '(if (boundp 'bookmark-after-jump-hook)
  22732. ;; We can use the hook
  22733. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22734. ;; Hook not available, use advice
  22735. (defadvice bookmark-jump (after org-make-visible activate)
  22736. "Make the position visible."
  22737. (org-bookmark-jump-unhide))))
  22738. ;; Make sure saveplace shows the location if it was hidden
  22739. (eval-after-load "saveplace"
  22740. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22741. "Make the position visible."
  22742. (org-bookmark-jump-unhide)))
  22743. ;; Make sure ecb shows the location if it was hidden
  22744. (eval-after-load "ecb"
  22745. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22746. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22747. (when (derived-mode-p 'org-mode)
  22748. (org-show-context))))
  22749. (defun org-bookmark-jump-unhide ()
  22750. "Unhide the current position, to show the bookmark location."
  22751. (and (derived-mode-p 'org-mode)
  22752. (or (outline-invisible-p)
  22753. (save-excursion (goto-char (max (point-min) (1- (point))))
  22754. (outline-invisible-p)))
  22755. (org-show-context 'bookmark-jump)))
  22756. (defun org-mark-jump-unhide ()
  22757. "Make the point visible with `org-show-context' after jumping to the mark."
  22758. (when (and (derived-mode-p 'org-mode)
  22759. (outline-invisible-p))
  22760. (org-show-context 'mark-goto)))
  22761. (eval-after-load "simple"
  22762. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22763. "Make the point visible with `org-show-context'."
  22764. (org-mark-jump-unhide)))
  22765. (eval-after-load "simple"
  22766. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22767. "Make the point visible with `org-show-context'."
  22768. (org-mark-jump-unhide)))
  22769. (eval-after-load "simple"
  22770. '(defadvice pop-global-mark (after org-make-visible activate)
  22771. "Make the point visible with `org-show-context'."
  22772. (org-mark-jump-unhide)))
  22773. ;; Make session.el ignore our circular variable
  22774. (defvar session-globals-exclude)
  22775. (eval-after-load "session"
  22776. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22777. ;;;; Finish up
  22778. (provide 'org)
  22779. (run-hooks 'org-load-hook)
  22780. ;;; org.el ends here