org.el 940 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871
  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 <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-wrap-region "org-table" (arg))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  166. (declare-function orgtbl-mode "org-table" (&optional arg))
  167. (declare-function org-export-get-backend "ox" (name))
  168. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  169. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  170. (defvar ffap-url-regexp) ;Silence byte-compiler
  171. (defsubst org-uniquify (list)
  172. "Non-destructively remove duplicate elements from LIST."
  173. (let ((res (copy-sequence list))) (delete-dups res)))
  174. (defsubst org-get-at-bol (property)
  175. "Get text property PROPERTY at the beginning of line."
  176. (get-text-property (point-at-bol) property))
  177. (defsubst org-trim (s &optional keep-lead)
  178. "Remove whitespace at the beginning and the end of string S.
  179. When optional argument KEEP-LEAD is non-nil, removing blank lines
  180. at the beginning of the string does not affect leading indentation."
  181. (replace-regexp-in-string
  182. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  183. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  184. ;; load languages based on value of `org-babel-load-languages'
  185. (defvar org-babel-load-languages)
  186. ;;;###autoload
  187. (defun org-babel-do-load-languages (sym value)
  188. "Load the languages defined in `org-babel-load-languages'."
  189. (set-default sym value)
  190. (dolist (pair org-babel-load-languages)
  191. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  192. (if active
  193. (require (intern (concat "ob-" lang)))
  194. (funcall 'fmakunbound
  195. (intern (concat "org-babel-execute:" lang)))
  196. (funcall 'fmakunbound
  197. (intern (concat "org-babel-expand-body:" lang)))))))
  198. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  199. ;;;###autoload
  200. (defun org-babel-load-file (file &optional compile)
  201. "Load Emacs Lisp source code blocks in the Org FILE.
  202. This function exports the source code using `org-babel-tangle'
  203. and then loads the resulting file using `load-file'. With prefix
  204. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  205. file to byte-code before it is loaded."
  206. (interactive "fFile to load: \nP")
  207. (let* ((age (lambda (file)
  208. (float-time
  209. (time-subtract (current-time)
  210. (nth 5 (or (file-attributes (file-truename file))
  211. (file-attributes file)))))))
  212. (base-name (file-name-sans-extension file))
  213. (exported-file (concat base-name ".el")))
  214. ;; tangle if the Org file is newer than the elisp file
  215. (unless (and (file-exists-p exported-file)
  216. (> (funcall age file) (funcall age exported-file)))
  217. ;; Tangle-file traversal returns reversed list of tangled files
  218. ;; and we want to evaluate the first target.
  219. (setq exported-file
  220. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  221. (message "%s %s"
  222. (if compile
  223. (progn (byte-compile-file exported-file 'load)
  224. "Compiled and loaded")
  225. (progn (load-file exported-file) "Loaded"))
  226. exported-file)))
  227. (defcustom org-babel-load-languages '((emacs-lisp . t))
  228. "Languages which can be evaluated in Org buffers.
  229. This list can be used to load support for any of the languages
  230. below, note that each language will depend on a different set of
  231. system executables and/or Emacs modes. When a language is
  232. \"loaded\", then code blocks in that language can be evaluated
  233. with `org-babel-execute-src-block' bound by default to C-c
  234. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  235. be set to remove code block evaluation from the C-c C-c
  236. keybinding. By default only Emacs Lisp (which has no
  237. requirements) is loaded."
  238. :group 'org-babel
  239. :set 'org-babel-do-load-languages
  240. :version "24.1"
  241. :type '(alist :tag "Babel Languages"
  242. :key-type
  243. (choice
  244. (const :tag "Awk" awk)
  245. (const :tag "C" C)
  246. (const :tag "R" R)
  247. (const :tag "Asymptote" asymptote)
  248. (const :tag "Calc" calc)
  249. (const :tag "Clojure" clojure)
  250. (const :tag "CSS" css)
  251. (const :tag "Ditaa" ditaa)
  252. (const :tag "Dot" dot)
  253. (const :tag "Ebnf2ps" ebnf2ps)
  254. (const :tag "Emacs Lisp" emacs-lisp)
  255. (const :tag "Forth" forth)
  256. (const :tag "Fortran" fortran)
  257. (const :tag "Gnuplot" gnuplot)
  258. (const :tag "Haskell" haskell)
  259. (const :tag "hledger" hledger)
  260. (const :tag "IO" io)
  261. (const :tag "J" J)
  262. (const :tag "Java" java)
  263. (const :tag "Javascript" js)
  264. (const :tag "LaTeX" latex)
  265. (const :tag "Ledger" ledger)
  266. (const :tag "Lilypond" lilypond)
  267. (const :tag "Lisp" lisp)
  268. (const :tag "Makefile" makefile)
  269. (const :tag "Maxima" maxima)
  270. (const :tag "Matlab" matlab)
  271. (const :tag "Mscgen" mscgen)
  272. (const :tag "Ocaml" ocaml)
  273. (const :tag "Octave" octave)
  274. (const :tag "Org" org)
  275. (const :tag "Perl" perl)
  276. (const :tag "Pico Lisp" picolisp)
  277. (const :tag "PlantUML" plantuml)
  278. (const :tag "Python" python)
  279. (const :tag "Ruby" ruby)
  280. (const :tag "Sass" sass)
  281. (const :tag "Scala" scala)
  282. (const :tag "Scheme" scheme)
  283. (const :tag "Screen" screen)
  284. (const :tag "Shell Script" shell)
  285. (const :tag "Shen" shen)
  286. (const :tag "Sql" sql)
  287. (const :tag "Sqlite" sqlite)
  288. (const :tag "Stan" stan)
  289. (const :tag "Vala" vala))
  290. :value-type (boolean :tag "Activate" :value t)))
  291. ;;;; Customization variables
  292. (defcustom org-clone-delete-id nil
  293. "Remove ID property of clones of a subtree.
  294. When non-nil, clones of a subtree don't inherit the ID property.
  295. Otherwise they inherit the ID property with a new unique
  296. identifier."
  297. :type 'boolean
  298. :version "24.1"
  299. :group 'org-id)
  300. ;;; Version
  301. (org-check-version)
  302. ;;;###autoload
  303. (defun org-version (&optional here full message)
  304. "Show the Org version.
  305. Interactively, or when MESSAGE is non-nil, show it in echo area.
  306. With prefix argument, or when HERE is non-nil, insert it at point.
  307. In non-interactive uses, a reduced version string is output unless
  308. FULL is given."
  309. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  310. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  311. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  312. (load-suffixes (list ".el"))
  313. (org-install-dir
  314. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  315. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  316. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  317. (let* ((load-suffixes save-load-suffixes)
  318. (release (org-release))
  319. (git-version (org-git-version))
  320. (version (format "Org mode version %s (%s @ %s)"
  321. release
  322. git-version
  323. (if org-install-dir
  324. (if (string= org-dir org-install-dir)
  325. org-install-dir
  326. (concat "mixed installation! "
  327. org-install-dir
  328. " and "
  329. org-dir))
  330. "org-loaddefs.el can not be found!")))
  331. (version1 (if full version release)))
  332. (when here (insert version1))
  333. (when message (message "%s" version1))
  334. version1)))
  335. (defconst org-version (org-version))
  336. ;;; Syntax Constants
  337. ;;;; Block
  338. (defconst org-block-regexp
  339. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  340. "Regular expression for hiding blocks.")
  341. (defconst org-dblock-start-re
  342. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  343. "Matches the start line of a dynamic block, with parameters.")
  344. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  345. "Matches the end of a dynamic block.")
  346. ;;;; Clock and Planning
  347. (defconst org-clock-string "CLOCK:"
  348. "String used as prefix for timestamps clocking work hours on an item.")
  349. (defvar org-closed-string "CLOSED:"
  350. "String used as the prefix for timestamps logging closing a TODO entry.")
  351. (defvar org-deadline-string "DEADLINE:"
  352. "String to mark deadline entries.
  353. \\<org-mode-map>
  354. A deadline is this string, followed by a time stamp. It must be
  355. a word, terminated by a colon. You can insert a schedule keyword
  356. and a timestamp with `\\[org-deadline]'.")
  357. (defvar org-scheduled-string "SCHEDULED:"
  358. "String to mark scheduled TODO entries.
  359. \\<org-mode-map>
  360. A schedule is this string, followed by a time stamp. It must be
  361. a word, terminated by a colon. You can insert a schedule keyword
  362. and a timestamp with `\\[org-schedule]'.")
  363. (defconst org-ds-keyword-length
  364. (+ 2
  365. (apply #'max
  366. (mapcar #'length
  367. (list org-deadline-string org-scheduled-string
  368. org-clock-string org-closed-string))))
  369. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  370. (defconst org-planning-line-re
  371. (concat "^[ \t]*"
  372. (regexp-opt
  373. (list org-closed-string org-deadline-string org-scheduled-string)
  374. t))
  375. "Matches a line with planning info.
  376. Matched keyword is in group 1.")
  377. (defconst org-clock-line-re
  378. (concat "^[ \t]*" org-clock-string)
  379. "Matches a line with clock info.")
  380. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  381. "Matches the DEADLINE keyword.")
  382. (defconst org-deadline-time-regexp
  383. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  384. "Matches the DEADLINE keyword together with a time stamp.")
  385. (defconst org-deadline-time-hour-regexp
  386. (concat "\\<" org-deadline-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  389. (defconst org-deadline-line-regexp
  390. (concat "\\<\\(" org-deadline-string "\\).*")
  391. "Matches the DEADLINE keyword and the rest of the line.")
  392. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  393. "Matches the SCHEDULED keyword.")
  394. (defconst org-scheduled-time-regexp
  395. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  396. "Matches the SCHEDULED keyword together with a time stamp.")
  397. (defconst org-scheduled-time-hour-regexp
  398. (concat "\\<" org-scheduled-string
  399. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  400. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  401. (defconst org-closed-time-regexp
  402. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  403. "Matches the CLOSED keyword together with a time stamp.")
  404. (defconst org-keyword-time-regexp
  405. (concat "\\<"
  406. (regexp-opt
  407. (list org-scheduled-string org-deadline-string org-closed-string
  408. org-clock-string)
  409. t)
  410. " *[[<]\\([^]>]+\\)[]>]")
  411. "Matches any of the 4 keywords, together with the time stamp.")
  412. (defconst org-keyword-time-not-clock-regexp
  413. (concat
  414. "\\<"
  415. (regexp-opt
  416. (list org-scheduled-string org-deadline-string org-closed-string) t)
  417. " *[[<]\\([^]>]+\\)[]>]")
  418. "Matches any of the 3 keywords, together with the time stamp.")
  419. (defconst org-maybe-keyword-time-regexp
  420. (concat "\\(\\<"
  421. (regexp-opt
  422. (list org-scheduled-string org-deadline-string org-closed-string
  423. org-clock-string)
  424. t)
  425. "\\)?"
  426. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  427. "\\|"
  428. "<%%([^\r\n>]*>\\)")
  429. "Matches a timestamp, possibly preceded by a keyword.")
  430. (defconst org-all-time-keywords
  431. (mapcar (lambda (w) (substring w 0 -1))
  432. (list org-scheduled-string org-deadline-string
  433. org-clock-string org-closed-string))
  434. "List of time keywords.")
  435. ;;;; Drawer
  436. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  437. "Matches first or last line of a hidden block.
  438. Group 1 contains drawer's name or \"END\".")
  439. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  440. "Regular expression matching the first line of a property drawer.")
  441. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  442. "Regular expression matching the last line of a property drawer.")
  443. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  444. "Regular expression matching the first line of a clock drawer.")
  445. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  446. "Regular expression matching the last line of a clock drawer.")
  447. (defconst org-property-drawer-re
  448. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  449. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  450. "[ \t]*:END:[ \t]*$")
  451. "Matches an entire property drawer.")
  452. (defconst org-clock-drawer-re
  453. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  454. org-clock-drawer-end-re "\\)\n?")
  455. "Matches an entire clock drawer.")
  456. ;;;; Headline
  457. (defconst org-heading-keyword-regexp-format
  458. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  459. "Printf format for a regexp matching a headline with some keyword.
  460. This regexp will match the headline of any node which has the
  461. exact keyword that is put into the format. The keyword isn't in
  462. any group by default, but the stars and the body are.")
  463. (defconst org-heading-keyword-maybe-regexp-format
  464. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  465. "Printf format for a regexp matching a headline, possibly with some keyword.
  466. This regexp can match any headline with the specified keyword, or
  467. without a keyword. The keyword isn't in any group by default,
  468. but the stars and the body are.")
  469. (defconst org-archive-tag "ARCHIVE"
  470. "The tag that marks a subtree as archived.
  471. An archived subtree does not open during visibility cycling, and does
  472. not contribute to the agenda listings.")
  473. (eval-and-compile
  474. (defconst org-comment-string "COMMENT"
  475. "Entries starting with this keyword will never be exported.
  476. \\<org-mode-map>
  477. An entry can be toggled between COMMENT and normal with
  478. `\\[org-toggle-comment]'."))
  479. ;;;; LaTeX Environments and Fragments
  480. (defconst org-latex-regexps
  481. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  482. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  483. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  484. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  486. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  487. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  488. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  489. "Regular expressions for matching embedded LaTeX.")
  490. ;;;; Node Property
  491. (defconst org-effort-property "Effort"
  492. "The property that is being used to keep track of effort estimates.
  493. Effort estimates given in this property need to have the format H:MM.")
  494. ;;;; Table
  495. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  496. "Detect an org-type or table-type table.")
  497. (defconst org-table-line-regexp "^[ \t]*|"
  498. "Detect an org-type table line.")
  499. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  500. "Detect an org-type table line.")
  501. (defconst org-table-hline-regexp "^[ \t]*|-"
  502. "Detect an org-type table hline.")
  503. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  504. "Detect a table-type table hline.")
  505. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  506. "Detect the first line outside a table when searching from within it.
  507. This works for both table types.")
  508. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  509. "Detect a #+TBLFM line.")
  510. ;;;; Timestamp
  511. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  512. "Regular expression for fast time stamp matching.")
  513. (defconst org-ts-regexp-inactive
  514. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  515. "Regular expression for fast inactive time stamp matching.")
  516. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  517. "Regular expression for fast time stamp matching.")
  518. (defconst org-ts-regexp0
  519. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  520. "Regular expression matching time strings for analysis.
  521. This one does not require the space after the date, so it can be used
  522. on a string that terminates immediately after the date.")
  523. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  524. "Regular expression matching time strings for analysis.")
  525. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  526. "Regular expression matching time stamps, with groups.")
  527. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  528. "Regular expression matching time stamps (also [..]), with groups.")
  529. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  530. "Regular expression matching a time stamp range.")
  531. (defconst org-tr-regexp-both
  532. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  533. "Regular expression matching a time stamp range.")
  534. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  535. org-ts-regexp "\\)?")
  536. "Regular expression matching a time stamp or time stamp range.")
  537. (defconst org-tsr-regexp-both
  538. (concat org-ts-regexp-both "\\(--?-?"
  539. org-ts-regexp-both "\\)?")
  540. "Regular expression matching a time stamp or time stamp range.
  541. The time stamps may be either active or inactive.")
  542. (defconst org-repeat-re
  543. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  544. "Regular expression for specifying repeated events.
  545. After a match, group 1 contains the repeat expression.")
  546. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  547. "Formats for `format-time-string' which are used for time stamps.")
  548. ;;; The custom variables
  549. (defgroup org nil
  550. "Outline-based notes management and organizer."
  551. :tag "Org"
  552. :group 'outlines
  553. :group 'calendar)
  554. (defcustom org-mode-hook nil
  555. "Mode hook for Org mode, run after the mode was turned on."
  556. :group 'org
  557. :type 'hook)
  558. (defcustom org-load-hook nil
  559. "Hook that is run after org.el has been loaded."
  560. :group 'org
  561. :type 'hook)
  562. (defcustom org-log-buffer-setup-hook nil
  563. "Hook that is run after an Org log buffer is created."
  564. :group 'org
  565. :version "24.1"
  566. :type 'hook)
  567. (defvar org-modules) ; defined below
  568. (defvar org-modules-loaded nil
  569. "Have the modules been loaded already?")
  570. (defun org-load-modules-maybe (&optional force)
  571. "Load all extensions listed in `org-modules'."
  572. (when (or force (not org-modules-loaded))
  573. (dolist (ext org-modules)
  574. (condition-case nil (require ext)
  575. (error (message "Problems while trying to load feature `%s'" ext))))
  576. (setq org-modules-loaded t)))
  577. (defun org-set-modules (var value)
  578. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  579. (set var value)
  580. (when (featurep 'org)
  581. (org-load-modules-maybe 'force)
  582. (org-element-cache-reset 'all)))
  583. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  584. "Modules that should always be loaded together with org.el.
  585. If a description starts with <C>, the file is not part of Emacs
  586. and loading it will require that you have downloaded and properly
  587. installed the Org mode distribution.
  588. You can also use this system to load external packages (i.e. neither Org
  589. core modules, nor modules from the CONTRIB directory). Just add symbols
  590. to the end of the list. If the package is called org-xyz.el, then you need
  591. to add the symbol `xyz', and the package must have a call to:
  592. (provide \\='org-xyz)
  593. For export specific modules, see also `org-export-backends'."
  594. :group 'org
  595. :set 'org-set-modules
  596. :version "24.4"
  597. :package-version '(Org . "8.0")
  598. :type
  599. '(set :greedy t
  600. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  601. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  602. (const :tag " crypt: Encryption of subtrees" org-crypt)
  603. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  604. (const :tag " docview: Links to doc-view buffers" org-docview)
  605. (const :tag " eww: Store link to url of eww" org-eww)
  606. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  607. (const :tag " habit: Track your consistency with habits" org-habit)
  608. (const :tag " id: Global IDs for identifying entries" org-id)
  609. (const :tag " info: Links to Info nodes" org-info)
  610. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  611. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  612. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  613. (const :tag " mouse: Additional mouse support" org-mouse)
  614. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  615. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  616. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  617. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  618. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  619. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  620. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  621. (const :tag "C collector: Collect properties into tables" org-collector)
  622. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  623. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  624. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  625. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  626. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  627. (const :tag "C eval: Include command output as text" org-eval)
  628. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  629. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  630. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  631. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  632. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  633. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  634. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  635. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  636. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  637. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  638. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  639. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  640. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  641. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  642. (const :tag "C registry: A registry for Org links" org-registry)
  643. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  644. (const :tag "C secretary: Team management with org-mode" org-secretary)
  645. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  646. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  647. (const :tag "C track: Keep up with Org mode development" org-track)
  648. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  649. (const :tag "C vm: Links to VM folders/messages" org-vm)
  650. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  651. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  652. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  653. (defvar org-export-registered-backends) ; From ox.el.
  654. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  655. (declare-function org-export-backend-name "ox" (backend) t)
  656. (defcustom org-export-backends '(ascii html icalendar latex odt)
  657. "List of export back-ends that should be always available.
  658. If a description starts with <C>, the file is not part of Emacs
  659. and loading it will require that you have downloaded and properly
  660. installed the Org mode distribution.
  661. Unlike to `org-modules', libraries in this list will not be
  662. loaded along with Org, but only once the export framework is
  663. needed.
  664. This variable needs to be set before org.el is loaded. If you
  665. need to make a change while Emacs is running, use the customize
  666. interface or run the following code, where VAL stands for the new
  667. value of the variable, after updating it:
  668. (progn
  669. (setq org-export-registered-backends
  670. (cl-remove-if-not
  671. (lambda (backend)
  672. (let ((name (org-export-backend-name backend)))
  673. (or (memq name val)
  674. (catch \\='parentp
  675. (dolist (b val)
  676. (and (org-export-derived-backend-p b name)
  677. (throw \\='parentp t)))))))
  678. org-export-registered-backends))
  679. (let ((new-list (mapcar #\\='org-export-backend-name
  680. org-export-registered-backends)))
  681. (dolist (backend val)
  682. (cond
  683. ((not (load (format \"ox-%s\" backend) t t))
  684. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  685. backend))
  686. ((not (memq backend new-list)) (push backend new-list))))
  687. (set-default \\='org-export-backends new-list)))
  688. Adding a back-end to this list will also pull the back-end it
  689. depends on, if any."
  690. :group 'org
  691. :group 'org-export
  692. :version "26.1"
  693. :package-version '(Org . "9.0")
  694. :initialize 'custom-initialize-set
  695. :set (lambda (var val)
  696. (if (not (featurep 'ox)) (set-default var val)
  697. ;; Any back-end not required anymore (not present in VAL and not
  698. ;; a parent of any back-end in the new value) is removed from the
  699. ;; list of registered back-ends.
  700. (setq org-export-registered-backends
  701. (cl-remove-if-not
  702. (lambda (backend)
  703. (let ((name (org-export-backend-name backend)))
  704. (or (memq name val)
  705. (catch 'parentp
  706. (dolist (b val)
  707. (and (org-export-derived-backend-p b name)
  708. (throw 'parentp t)))))))
  709. org-export-registered-backends))
  710. ;; Now build NEW-LIST of both new back-ends and required
  711. ;; parents.
  712. (let ((new-list (mapcar #'org-export-backend-name
  713. org-export-registered-backends)))
  714. (dolist (backend val)
  715. (cond
  716. ((not (load (format "ox-%s" backend) t t))
  717. (message "Problems while trying to load export back-end `%s'"
  718. backend))
  719. ((not (memq backend new-list)) (push backend new-list))))
  720. ;; Set VAR to that list with fixed dependencies.
  721. (set-default var new-list))))
  722. :type '(set :greedy t
  723. (const :tag " ascii Export buffer to ASCII format" ascii)
  724. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  725. (const :tag " html Export buffer to HTML format" html)
  726. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  727. (const :tag " latex Export buffer to LaTeX format" latex)
  728. (const :tag " man Export buffer to MAN format" man)
  729. (const :tag " md Export buffer to Markdown format" md)
  730. (const :tag " odt Export buffer to ODT format" odt)
  731. (const :tag " org Export buffer to Org format" org)
  732. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  733. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  734. (const :tag "C deck Export buffer to deck.js presentations" deck)
  735. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  736. (const :tag "C groff Export buffer to Groff format" groff)
  737. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  738. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  739. (const :tag "C s5 Export buffer to s5 presentations" s5)
  740. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  741. (eval-after-load 'ox
  742. '(dolist (backend org-export-backends)
  743. (condition-case nil (require (intern (format "ox-%s" backend)))
  744. (error (message "Problems while trying to load export back-end `%s'"
  745. backend)))))
  746. (defcustom org-support-shift-select nil
  747. "Non-nil means make shift-cursor commands select text when possible.
  748. \\<org-mode-map>\
  749. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  750. start selecting a region, or enlarge regions started in this way.
  751. In Org mode, in special contexts, these same keys are used for
  752. other purposes, important enough to compete with shift selection.
  753. Org tries to balance these needs by supporting `shift-select-mode'
  754. outside these special contexts, under control of this variable.
  755. The default of this variable is nil, to avoid confusing behavior. Shifted
  756. cursor keys will then execute Org commands in the following contexts:
  757. - on a headline, changing TODO state (left/right) and priority (up/down)
  758. - on a time stamp, changing the time
  759. - in a plain list item, changing the bullet type
  760. - in a property definition line, switching between allowed values
  761. - in the BEGIN line of a clock table (changing the time block).
  762. Outside these contexts, the commands will throw an error.
  763. When this variable is t and the cursor is not in a special
  764. context, Org mode will support shift-selection for making and
  765. enlarging regions. To make this more effective, the bullet
  766. cycling will no longer happen anywhere in an item line, but only
  767. if the cursor is exactly on the bullet.
  768. If you set this variable to the symbol `always', then the keys
  769. will not be special in headlines, property lines, and item lines,
  770. to make shift selection work there as well. If this is what you
  771. want, you can use the following alternative commands:
  772. `\\[org-todo]' and `\\[org-priority]' \
  773. to change TODO state and priority,
  774. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  775. can be used to switch TODO sets,
  776. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  777. and properties can be edited by hand or in column view.
  778. However, when the cursor is on a timestamp, shift-cursor commands
  779. will still edit the time stamp - this is just too good to give up."
  780. :group 'org
  781. :type '(choice
  782. (const :tag "Never" nil)
  783. (const :tag "When outside special context" t)
  784. (const :tag "Everywhere except timestamps" always)))
  785. (defcustom org-loop-over-headlines-in-active-region nil
  786. "Shall some commands act upon headlines in the active region?
  787. When set to t, some commands will be performed in all headlines
  788. within the active region.
  789. When set to `start-level', some commands will be performed in all
  790. headlines within the active region, provided that these headlines
  791. are of the same level than the first one.
  792. When set to a string, those commands will be performed on the
  793. matching headlines within the active region. Such string must be
  794. a tags/property/todo match as it is used in the agenda tags view.
  795. The list of commands is: `org-schedule', `org-deadline',
  796. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  797. `org-archive-to-archive-sibling'. The archiving commands skip
  798. already archived entries."
  799. :type '(choice (const :tag "Don't loop" nil)
  800. (const :tag "All headlines in active region" t)
  801. (const :tag "In active region, headlines at the same level than the first one" start-level)
  802. (string :tag "Tags/Property/Todo matcher"))
  803. :version "24.1"
  804. :group 'org-todo
  805. :group 'org-archive)
  806. (defgroup org-startup nil
  807. "Options concerning startup of Org mode."
  808. :tag "Org Startup"
  809. :group 'org)
  810. (defcustom org-startup-folded t
  811. "Non-nil means entering Org mode will switch to OVERVIEW.
  812. This can also be configured on a per-file basis by adding one of
  813. the following lines anywhere in the buffer:
  814. #+STARTUP: fold (or `overview', this is equivalent)
  815. #+STARTUP: nofold (or `showall', this is equivalent)
  816. #+STARTUP: content
  817. #+STARTUP: showeverything
  818. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  819. to ignore this option when Org opens agenda files for the first
  820. time."
  821. :group 'org-startup
  822. :type '(choice
  823. (const :tag "nofold: show all" nil)
  824. (const :tag "fold: overview" t)
  825. (const :tag "content: all headlines" content)
  826. (const :tag "show everything, even drawers" showeverything)))
  827. (defcustom org-startup-truncated t
  828. "Non-nil means entering Org mode will set `truncate-lines'.
  829. This is useful since some lines containing links can be very long and
  830. uninteresting. Also tables look terrible when wrapped.
  831. The variable `org-startup-truncated' allows to configure
  832. truncation for Org mode different to the other modes that use the
  833. variable `truncate-lines' and as a shortcut instead of putting
  834. the variable `truncate-lines' into the `org-mode-hook'. If one
  835. wants to configure truncation for Org mode not statically but
  836. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  837. the variable `truncate-lines' has to be used because in such a
  838. case it is too late to set the variable `org-startup-truncated'."
  839. :group 'org-startup
  840. :type 'boolean)
  841. (defcustom org-startup-indented nil
  842. "Non-nil means turn on `org-indent-mode' on startup.
  843. This can also be configured on a per-file basis by adding one of
  844. the following lines anywhere in the buffer:
  845. #+STARTUP: indent
  846. #+STARTUP: noindent"
  847. :group 'org-structure
  848. :type '(choice
  849. (const :tag "Not" nil)
  850. (const :tag "Globally (slow on startup in large files)" t)))
  851. (defcustom org-use-sub-superscripts t
  852. "Non-nil means interpret \"_\" and \"^\" for display.
  853. If you want to control how Org exports those characters, see
  854. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  855. used to be an alias for `org-export-with-sub-superscripts' in
  856. Org <8.0, it is not anymore.
  857. When this option is turned on, you can use TeX-like syntax for
  858. sub- and superscripts within the buffer. Several characters after
  859. \"_\" or \"^\" will be considered as a single item - so grouping
  860. with {} is normally not needed. For example, the following things
  861. will be parsed as single sub- or superscripts:
  862. 10^24 or 10^tau several digits will be considered 1 item.
  863. 10^-12 or 10^-tau a leading sign with digits or a word
  864. x^2-y^3 will be read as x^2 - y^3, because items are
  865. terminated by almost any nonword/nondigit char.
  866. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  867. Still, ambiguity is possible. So when in doubt, use {} to enclose
  868. the sub/superscript. If you set this variable to the symbol `{}',
  869. the braces are *required* in order to trigger interpretations as
  870. sub/superscript. This can be helpful in documents that need \"_\"
  871. frequently in plain text."
  872. :group 'org-startup
  873. :version "24.4"
  874. :package-version '(Org . "8.0")
  875. :type '(choice
  876. (const :tag "Always interpret" t)
  877. (const :tag "Only with braces" {})
  878. (const :tag "Never interpret" nil)))
  879. (defcustom org-startup-with-beamer-mode nil
  880. "Non-nil means turn on `org-beamer-mode' on startup.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: beamer"
  884. :group 'org-startup
  885. :version "24.1"
  886. :type 'boolean)
  887. (defcustom org-startup-align-all-tables nil
  888. "Non-nil means align all tables when visiting a file.
  889. This is useful when the column width in tables is forced with <N> cookies
  890. in table fields. Such tables will look correct only after the first re-align.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: align
  894. #+STARTUP: noalign"
  895. :group 'org-startup
  896. :type 'boolean)
  897. (defcustom org-startup-with-inline-images nil
  898. "Non-nil means show inline images when loading a new Org file.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: inlineimages
  902. #+STARTUP: noinlineimages"
  903. :group 'org-startup
  904. :version "24.1"
  905. :type 'boolean)
  906. (defcustom org-startup-with-latex-preview nil
  907. "Non-nil means preview LaTeX fragments when loading a new Org file.
  908. This can also be configured on a per-file basis by adding one of
  909. the following lines anywhere in the buffer:
  910. #+STARTUP: latexpreview
  911. #+STARTUP: nolatexpreview"
  912. :group 'org-startup
  913. :version "24.4"
  914. :package-version '(Org . "8.0")
  915. :type 'boolean)
  916. (defcustom org-insert-mode-line-in-empty-file nil
  917. "Non-nil means insert the first line setting Org mode in empty files.
  918. When the function `org-mode' is called interactively in an empty file, this
  919. normally means that the file name does not automatically trigger Org mode.
  920. To ensure that the file will always be in Org mode in the future, a
  921. line enforcing Org mode will be inserted into the buffer, if this option
  922. has been set."
  923. :group 'org-startup
  924. :type 'boolean)
  925. (defcustom org-replace-disputed-keys nil
  926. "Non-nil means use alternative key bindings for some keys.
  927. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  928. These keys are also used by other packages like shift-selection-mode'
  929. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  930. If you want to use Org mode together with one of these other modes,
  931. or more generally if you would like to move some Org mode commands to
  932. other keys, set this variable and configure the keys with the variable
  933. `org-disputed-keys'.
  934. This option is only relevant at load-time of Org mode, and must be set
  935. *before* org.el is loaded. Changing it requires a restart of Emacs to
  936. become effective."
  937. :group 'org-startup
  938. :type 'boolean)
  939. (defcustom org-use-extra-keys nil
  940. "Non-nil means use extra key sequence definitions for certain commands.
  941. This happens automatically if `window-system' is nil. This
  942. variable lets you do the same manually. You must set it before
  943. loading Org."
  944. :group 'org-startup
  945. :type 'boolean)
  946. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  947. (defcustom org-disputed-keys
  948. '(([(shift up)] . [(meta p)])
  949. ([(shift down)] . [(meta n)])
  950. ([(shift left)] . [(meta -)])
  951. ([(shift right)] . [(meta +)])
  952. ([(control shift right)] . [(meta shift +)])
  953. ([(control shift left)] . [(meta shift -)]))
  954. "Keys for which Org mode and other modes compete.
  955. This is an alist, cars are the default keys, second element specifies
  956. the alternative to use when `org-replace-disputed-keys' is t.
  957. Keys can be specified in any syntax supported by `define-key'.
  958. The value of this option takes effect only at Org mode startup,
  959. therefore you'll have to restart Emacs to apply it after changing."
  960. :group 'org-startup
  961. :type 'alist)
  962. (defun org-key (key)
  963. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  964. Or return the original if not disputed."
  965. (when org-replace-disputed-keys
  966. (let* ((nkey (key-description key))
  967. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  968. org-disputed-keys)))
  969. (setq key (if x (cdr x) key))))
  970. key)
  971. (defun org-defkey (keymap key def)
  972. "Define a key, possibly translated, as returned by `org-key'."
  973. (define-key keymap (org-key key) def))
  974. (defcustom org-ellipsis nil
  975. "The ellipsis to use in the Org mode outline.
  976. When nil, just use the standard three dots. When a non-empty string,
  977. use that string instead.
  978. The change affects only Org mode (which will then use its own display table).
  979. Changing this requires executing `\\[org-mode]' in a buffer to become
  980. effective."
  981. :group 'org-startup
  982. :type '(choice (const :tag "Default" nil)
  983. (string :tag "String" :value "...#"))
  984. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  985. (defvar org-display-table nil
  986. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  987. (defgroup org-keywords nil
  988. "Keywords in Org mode."
  989. :tag "Org Keywords"
  990. :group 'org)
  991. (defcustom org-closed-keep-when-no-todo nil
  992. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  993. :group 'org-todo
  994. :group 'org-keywords
  995. :version "24.4"
  996. :package-version '(Org . "8.0")
  997. :type 'boolean)
  998. (defgroup org-structure nil
  999. "Options concerning the general structure of Org files."
  1000. :tag "Org Structure"
  1001. :group 'org)
  1002. (defgroup org-reveal-location nil
  1003. "Options about how to make context of a location visible."
  1004. :tag "Org Reveal Location"
  1005. :group 'org-structure)
  1006. (defcustom org-show-context-detail '((agenda . local)
  1007. (bookmark-jump . lineage)
  1008. (isearch . lineage)
  1009. (default . ancestors))
  1010. "Alist between context and visibility span when revealing a location.
  1011. \\<org-mode-map>Some actions may move point into invisible
  1012. locations. As a consequence, Org always expose a neighborhood
  1013. around point. How much is shown depends on the initial action,
  1014. or context. Valid contexts are
  1015. agenda when exposing an entry from the agenda
  1016. org-goto when using the command `org-goto' (`\\[org-goto]')
  1017. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1018. tags-tree when constructing a sparse tree based on tags matches
  1019. link-search when exposing search matches associated with a link
  1020. mark-goto when exposing the jump goal of a mark
  1021. bookmark-jump when exposing a bookmark location
  1022. isearch when exiting from an incremental search
  1023. default default for all contexts not set explicitly
  1024. Allowed visibility spans are
  1025. minimal show current headline; if point is not on headline,
  1026. also show entry
  1027. local show current headline, entry and next headline
  1028. ancestors show current headline and its direct ancestors; if
  1029. point is not on headline, also show entry
  1030. lineage show current headline, its direct ancestors and all
  1031. their children; if point is not on headline, also show
  1032. entry and first child
  1033. tree show current headline, its direct ancestors and all
  1034. their children; if point is not on headline, also show
  1035. entry and all children
  1036. canonical show current headline, its direct ancestors along with
  1037. their entries and children; if point is not located on
  1038. the headline, also show current entry and all children
  1039. As special cases, a nil or t value means show all contexts in
  1040. `minimal' or `canonical' view, respectively.
  1041. Some views can make displayed information very compact, but also
  1042. make it harder to edit the location of the match. In such
  1043. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1044. more context."
  1045. :group 'org-reveal-location
  1046. :version "26.1"
  1047. :package-version '(Org . "9.0")
  1048. :type '(choice
  1049. (const :tag "Canonical" t)
  1050. (const :tag "Minimal" nil)
  1051. (repeat :greedy t :tag "Individual contexts"
  1052. (cons
  1053. (choice :tag "Context"
  1054. (const agenda)
  1055. (const org-goto)
  1056. (const occur-tree)
  1057. (const tags-tree)
  1058. (const link-search)
  1059. (const mark-goto)
  1060. (const bookmark-jump)
  1061. (const isearch)
  1062. (const default))
  1063. (choice :tag "Detail level"
  1064. (const minimal)
  1065. (const local)
  1066. (const ancestors)
  1067. (const lineage)
  1068. (const tree)
  1069. (const canonical))))))
  1070. (defcustom org-indirect-buffer-display 'other-window
  1071. "How should indirect tree buffers be displayed?
  1072. This applies to indirect buffers created with the commands
  1073. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1074. Valid values are:
  1075. current-window Display in the current window
  1076. other-window Just display in another window.
  1077. dedicated-frame Create one new frame, and re-use it each time.
  1078. new-frame Make a new frame each time. Note that in this case
  1079. previously-made indirect buffers are kept, and you need to
  1080. kill these buffers yourself."
  1081. :group 'org-structure
  1082. :group 'org-agenda-windows
  1083. :type '(choice
  1084. (const :tag "In current window" current-window)
  1085. (const :tag "In current frame, other window" other-window)
  1086. (const :tag "Each time a new frame" new-frame)
  1087. (const :tag "One dedicated frame" dedicated-frame)))
  1088. (defcustom org-use-speed-commands nil
  1089. "Non-nil means activate single letter commands at beginning of a headline.
  1090. This may also be a function to test for appropriate locations where speed
  1091. commands should be active.
  1092. For example, to activate speed commands when the point is on any
  1093. star at the beginning of the headline, you can do this:
  1094. (setq org-use-speed-commands
  1095. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1096. :group 'org-structure
  1097. :type '(choice
  1098. (const :tag "Never" nil)
  1099. (const :tag "At beginning of headline stars" t)
  1100. (function)))
  1101. (defcustom org-speed-commands-user nil
  1102. "Alist of additional speed commands.
  1103. This list will be checked before `org-speed-commands-default'
  1104. when the variable `org-use-speed-commands' is non-nil
  1105. and when the cursor is at the beginning of a headline.
  1106. The car if each entry is a string with a single letter, which must
  1107. be assigned to `self-insert-command' in the global map.
  1108. The cdr is either a command to be called interactively, a function
  1109. to be called, or a form to be evaluated.
  1110. An entry that is just a list with a single string will be interpreted
  1111. as a descriptive headline that will be added when listing the speed
  1112. commands in the Help buffer using the `?' speed command."
  1113. :group 'org-structure
  1114. :type '(repeat :value ("k" . ignore)
  1115. (choice :value ("k" . ignore)
  1116. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1117. (cons :tag "Letter and Command"
  1118. (string :tag "Command letter")
  1119. (choice
  1120. (function)
  1121. (sexp))))))
  1122. (defcustom org-bookmark-names-plist
  1123. '(:last-capture "org-capture-last-stored"
  1124. :last-refile "org-refile-last-stored"
  1125. :last-capture-marker "org-capture-last-stored-marker")
  1126. "Names for bookmarks automatically set by some Org commands.
  1127. This can provide strings as names for a number of bookmarks Org sets
  1128. automatically. The following keys are currently implemented:
  1129. :last-capture
  1130. :last-capture-marker
  1131. :last-refile
  1132. When a key does not show up in the property list, the corresponding bookmark
  1133. is not set."
  1134. :group 'org-structure
  1135. :type 'plist)
  1136. (defgroup org-cycle nil
  1137. "Options concerning visibility cycling in Org mode."
  1138. :tag "Org Cycle"
  1139. :group 'org-structure)
  1140. (defcustom org-cycle-skip-children-state-if-no-children t
  1141. "Non-nil means skip CHILDREN state in entries that don't have any."
  1142. :group 'org-cycle
  1143. :type 'boolean)
  1144. (defcustom org-cycle-max-level nil
  1145. "Maximum level which should still be subject to visibility cycling.
  1146. Levels higher than this will, for cycling, be treated as text, not a headline.
  1147. When `org-odd-levels-only' is set, a value of N in this variable actually
  1148. means 2N-1 stars as the limiting headline.
  1149. When nil, cycle all levels.
  1150. Note that the limiting level of cycling is also influenced by
  1151. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1152. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1153. than its value."
  1154. :group 'org-cycle
  1155. :type '(choice
  1156. (const :tag "No limit" nil)
  1157. (integer :tag "Maximum level")))
  1158. (defcustom org-hide-block-startup nil
  1159. "Non-nil means entering Org mode will fold all blocks.
  1160. This can also be set in on a per-file basis with
  1161. #+STARTUP: hideblocks
  1162. #+STARTUP: showblocks"
  1163. :group 'org-startup
  1164. :group 'org-cycle
  1165. :type 'boolean)
  1166. (defcustom org-cycle-global-at-bob nil
  1167. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1168. This makes it possible to do global cycling without having to use `S-TAB'
  1169. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1170. line of the buffer
  1171. must not be a headline -- it may be empty or some other text.
  1172. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1173. sure the cursor stays at the beginning of the buffer.
  1174. When this option is nil, don't do anything special at the beginning of
  1175. the buffer."
  1176. :group 'org-cycle
  1177. :type 'boolean)
  1178. (defcustom org-cycle-level-after-item/entry-creation t
  1179. "Non-nil means cycle entry level or item indentation in new empty entries.
  1180. When the cursor is at the end of an empty headline, i.e., with only stars
  1181. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1182. and then all possible ancestor states, before returning to the original state.
  1183. This makes data entry extremely fast: M-RET to create a new headline,
  1184. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1185. When the cursor is at the end of an empty plain list item, one TAB will
  1186. make it a subitem, two or more tabs will back up to make this an item
  1187. higher up in the item hierarchy."
  1188. :group 'org-cycle
  1189. :type 'boolean)
  1190. (defcustom org-cycle-emulate-tab t
  1191. "Where should `org-cycle' emulate TAB.
  1192. nil Never
  1193. white Only in completely white lines
  1194. whitestart Only at the beginning of lines, before the first non-white char
  1195. t Everywhere except in headlines
  1196. exc-hl-bol Everywhere except at the start of a headline
  1197. If TAB is used in a place where it does not emulate TAB, the current subtree
  1198. visibility is cycled."
  1199. :group 'org-cycle
  1200. :type '(choice (const :tag "Never" nil)
  1201. (const :tag "Only in completely white lines" white)
  1202. (const :tag "Before first char in a line" whitestart)
  1203. (const :tag "Everywhere except in headlines" t)
  1204. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1205. (defcustom org-cycle-separator-lines 2
  1206. "Number of empty lines needed to keep an empty line between collapsed trees.
  1207. If you leave an empty line between the end of a subtree and the following
  1208. headline, this empty line is hidden when the subtree is folded.
  1209. Org mode will leave (exactly) one empty line visible if the number of
  1210. empty lines is equal or larger to the number given in this variable.
  1211. So the default 2 means at least 2 empty lines after the end of a subtree
  1212. are needed to produce free space between a collapsed subtree and the
  1213. following headline.
  1214. If the number is negative, and the number of empty lines is at least -N,
  1215. all empty lines are shown.
  1216. Special case: when 0, never leave empty lines in collapsed view."
  1217. :group 'org-cycle
  1218. :type 'integer)
  1219. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1220. (defcustom org-pre-cycle-hook nil
  1221. "Hook that is run before visibility cycling is happening.
  1222. The function(s) in this hook must accept a single argument which indicates
  1223. the new state that will be set right after running this hook. The
  1224. argument is a symbol. Before a global state change, it can have the values
  1225. `overview', `content', or `all'. Before a local state change, it can have
  1226. the values `folded', `children', or `subtree'."
  1227. :group 'org-cycle
  1228. :type 'hook)
  1229. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1230. org-cycle-hide-drawers
  1231. org-cycle-show-empty-lines
  1232. org-optimize-window-after-visibility-change)
  1233. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1234. The function(s) in this hook must accept a single argument which indicates
  1235. the new state that was set by the most recent `org-cycle' command. The
  1236. argument is a symbol. After a global state change, it can have the values
  1237. `overview', `contents', or `all'. After a local state change, it can have
  1238. the values `folded', `children', or `subtree'."
  1239. :group 'org-cycle
  1240. :type 'hook
  1241. :version "26.1"
  1242. :package-version '(Org . "8.3"))
  1243. (defgroup org-edit-structure nil
  1244. "Options concerning structure editing in Org mode."
  1245. :tag "Org Edit Structure"
  1246. :group 'org-structure)
  1247. (defcustom org-odd-levels-only nil
  1248. "Non-nil means skip even levels and only use odd levels for the outline.
  1249. This has the effect that two stars are being added/taken away in
  1250. promotion/demotion commands. It also influences how levels are
  1251. handled by the exporters.
  1252. Changing it requires restart of `font-lock-mode' to become effective
  1253. for fontification also in regions already fontified.
  1254. You may also set this on a per-file basis by adding one of the following
  1255. lines to the buffer:
  1256. #+STARTUP: odd
  1257. #+STARTUP: oddeven"
  1258. :group 'org-edit-structure
  1259. :group 'org-appearance
  1260. :type 'boolean)
  1261. (defcustom org-adapt-indentation t
  1262. "Non-nil means adapt indentation to outline node level.
  1263. When this variable is set, Org assumes that you write outlines by
  1264. indenting text in each node to align with the headline (after the
  1265. stars). The following issues are influenced by this variable:
  1266. - The indentation is increased by one space in a demotion
  1267. command, and decreased by one in a promotion command. However,
  1268. in the latter case, if shifting some line in the entry body
  1269. would alter document structure (e.g., insert a new headline),
  1270. indentation is not changed at all.
  1271. - Property drawers and planning information is inserted indented
  1272. when this variable is set. When nil, they will not be indented.
  1273. - TAB indents a line relative to current level. The lines below
  1274. a headline will be indented when this variable is set.
  1275. Note that this is all about true indentation, by adding and
  1276. removing space characters. See also `org-indent.el' which does
  1277. level-dependent indentation in a virtual way, i.e. at display
  1278. time in Emacs."
  1279. :group 'org-edit-structure
  1280. :type 'boolean)
  1281. (defcustom org-special-ctrl-a/e nil
  1282. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1283. When t, `C-a' will bring back the cursor to the beginning of the
  1284. headline text, i.e. after the stars and after a possible TODO
  1285. keyword. In an item, this will be the position after bullet and
  1286. check-box, if any. When the cursor is already at that position,
  1287. another `C-a' will bring it to the beginning of the line.
  1288. `C-e' will jump to the end of the headline, ignoring the presence
  1289. of tags in the headline. A second `C-e' will then jump to the
  1290. true end of the line, after any tags. This also means that, when
  1291. this variable is non-nil, `C-e' also will never jump beyond the
  1292. end of the heading of a folded section, i.e. not after the
  1293. ellipses.
  1294. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1295. normally, going to the true line boundary first. Only a directly
  1296. following, identical keypress will bring the cursor to the
  1297. special positions.
  1298. This may also be a cons cell where the behavior for `C-a' and
  1299. `C-e' is set separately."
  1300. :group 'org-edit-structure
  1301. :type '(choice
  1302. (const :tag "off" nil)
  1303. (const :tag "on: after stars/bullet and before tags first" t)
  1304. (const :tag "reversed: true line boundary first" reversed)
  1305. (cons :tag "Set C-a and C-e separately"
  1306. (choice :tag "Special C-a"
  1307. (const :tag "off" nil)
  1308. (const :tag "on: after stars/bullet first" t)
  1309. (const :tag "reversed: before stars/bullet first" reversed))
  1310. (choice :tag "Special C-e"
  1311. (const :tag "off" nil)
  1312. (const :tag "on: before tags first" t)
  1313. (const :tag "reversed: after tags first" reversed)))))
  1314. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1315. (defcustom org-special-ctrl-k nil
  1316. "Non-nil means `C-k' will behave specially in headlines.
  1317. When nil, `C-k' will call the default `kill-line' command.
  1318. When t, the following will happen while the cursor is in the headline:
  1319. - When the cursor is at the beginning of a headline, kill the entire
  1320. line and possible the folded subtree below the line.
  1321. - When in the middle of the headline text, kill the headline up to the tags.
  1322. - When after the headline text, kill the tags."
  1323. :group 'org-edit-structure
  1324. :type 'boolean)
  1325. (defcustom org-ctrl-k-protect-subtree nil
  1326. "Non-nil means, do not delete a hidden subtree with C-k.
  1327. When set to the symbol `error', simply throw an error when C-k is
  1328. used to kill (part-of) a headline that has hidden text behind it.
  1329. Any other non-nil value will result in a query to the user, if it is
  1330. OK to kill that hidden subtree. When nil, kill without remorse."
  1331. :group 'org-edit-structure
  1332. :version "24.1"
  1333. :type '(choice
  1334. (const :tag "Do not protect hidden subtrees" nil)
  1335. (const :tag "Protect hidden subtrees with a security query" t)
  1336. (const :tag "Never kill a hidden subtree with C-k" error)))
  1337. (defcustom org-special-ctrl-o t
  1338. "Non-nil means, make `C-o' insert a row in tables."
  1339. :group 'org-edit-structure
  1340. :type 'boolean)
  1341. (defcustom org-catch-invisible-edits nil
  1342. "Check if in invisible region before inserting or deleting a character.
  1343. Valid values are:
  1344. nil Do not check, so just do invisible edits.
  1345. error Throw an error and do nothing.
  1346. show Make point visible, and do the requested edit.
  1347. show-and-error Make point visible, then throw an error and abort the edit.
  1348. smart Make point visible, and do insertion/deletion if it is
  1349. adjacent to visible text and the change feels predictable.
  1350. Never delete a previously invisible character or add in the
  1351. middle or right after an invisible region. Basically, this
  1352. allows insertion and backward-delete right before ellipses.
  1353. FIXME: maybe in this case we should not even show?"
  1354. :group 'org-edit-structure
  1355. :version "24.1"
  1356. :type '(choice
  1357. (const :tag "Do not check" nil)
  1358. (const :tag "Throw error when trying to edit" error)
  1359. (const :tag "Unhide, but do not do the edit" show-and-error)
  1360. (const :tag "Show invisible part and do the edit" show)
  1361. (const :tag "Be smart and do the right thing" smart)))
  1362. (defcustom org-yank-folded-subtrees t
  1363. "Non-nil means when yanking subtrees, fold them.
  1364. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1365. it starts with a heading and all other headings in it are either children
  1366. or siblings, then fold all the subtrees. However, do this only if no
  1367. text after the yank would be swallowed into a folded tree by this action."
  1368. :group 'org-edit-structure
  1369. :type 'boolean)
  1370. (defcustom org-yank-adjusted-subtrees nil
  1371. "Non-nil means when yanking subtrees, adjust the level.
  1372. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1373. this function for details."
  1374. :group 'org-edit-structure
  1375. :type 'boolean)
  1376. (defcustom org-M-RET-may-split-line '((default . t))
  1377. "Non-nil means M-RET will split the line at the cursor position.
  1378. When nil, it will go to the end of the line before making a
  1379. new line.
  1380. You may also set this option in a different way for different
  1381. contexts. Valid contexts are:
  1382. headline when creating a new headline
  1383. item when creating a new item
  1384. table in a table field
  1385. default the value to be used for all contexts not explicitly
  1386. customized"
  1387. :group 'org-structure
  1388. :group 'org-table
  1389. :type '(choice
  1390. (const :tag "Always" t)
  1391. (const :tag "Never" nil)
  1392. (repeat :greedy t :tag "Individual contexts"
  1393. (cons
  1394. (choice :tag "Context"
  1395. (const headline)
  1396. (const item)
  1397. (const table)
  1398. (const default))
  1399. (boolean)))))
  1400. (defcustom org-insert-heading-respect-content nil
  1401. "Non-nil means insert new headings after the current subtree.
  1402. \\<org-mode-map>
  1403. When nil, the new heading is created directly after the current line.
  1404. The commands `\\[org-insert-heading-respect-content]' and \
  1405. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1406. for the duration of the command."
  1407. :group 'org-structure
  1408. :type 'boolean)
  1409. (defcustom org-blank-before-new-entry '((heading . auto)
  1410. (plain-list-item . auto))
  1411. "Should `org-insert-heading' leave a blank line before new heading/item?
  1412. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1413. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1414. which case Org will look at the surrounding headings/items and try to
  1415. make an intelligent decision whether to insert a blank line or not."
  1416. :group 'org-edit-structure
  1417. :type '(list
  1418. (cons (const heading)
  1419. (choice (const :tag "Never" nil)
  1420. (const :tag "Always" t)
  1421. (const :tag "Auto" auto)))
  1422. (cons (const plain-list-item)
  1423. (choice (const :tag "Never" nil)
  1424. (const :tag "Always" t)
  1425. (const :tag "Auto" auto)))))
  1426. (defcustom org-insert-heading-hook nil
  1427. "Hook being run after inserting a new heading."
  1428. :group 'org-edit-structure
  1429. :type 'hook)
  1430. (defcustom org-enable-fixed-width-editor t
  1431. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1432. This currently only means they are never auto-wrapped.
  1433. When nil, such lines will be treated like ordinary lines."
  1434. :group 'org-edit-structure
  1435. :type 'boolean)
  1436. (defcustom org-goto-auto-isearch t
  1437. "Non-nil means typing characters in `org-goto' starts incremental search.
  1438. When nil, you can use these keybindings to navigate the buffer:
  1439. q Quit the org-goto interface
  1440. n Go to the next visible heading
  1441. p Go to the previous visible heading
  1442. f Go one heading forward on same level
  1443. b Go one heading backward on same level
  1444. u Go one heading up"
  1445. :group 'org-edit-structure
  1446. :type 'boolean)
  1447. (defgroup org-sparse-trees nil
  1448. "Options concerning sparse trees in Org mode."
  1449. :tag "Org Sparse Trees"
  1450. :group 'org-structure)
  1451. (defcustom org-highlight-sparse-tree-matches t
  1452. "Non-nil means highlight all matches that define a sparse tree.
  1453. The highlights will automatically disappear the next time the buffer is
  1454. changed by an edit command."
  1455. :group 'org-sparse-trees
  1456. :type 'boolean)
  1457. (defcustom org-remove-highlights-with-change t
  1458. "Non-nil means any change to the buffer will remove temporary highlights.
  1459. \\<org-mode-map>\
  1460. Such highlights are created by `org-occur' and `org-clock-display'.
  1461. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1462. to get rid of the highlights.
  1463. The highlights created by `org-toggle-latex-fragment' always need
  1464. `\\[org-toggle-latex-fragment]' to be removed."
  1465. :group 'org-sparse-trees
  1466. :group 'org-time
  1467. :type 'boolean)
  1468. (defcustom org-occur-case-fold-search t
  1469. "Non-nil means `org-occur' should be case-insensitive.
  1470. If set to `smart' the search will be case-insensitive only if it
  1471. doesn't specify any upper case character."
  1472. :group 'org-sparse-trees
  1473. :version "26.1"
  1474. :type '(choice
  1475. (const :tag "Case-sensitive" nil)
  1476. (const :tag "Case-insensitive" t)
  1477. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1478. (defcustom org-occur-hook '(org-first-headline-recenter)
  1479. "Hook that is run after `org-occur' has constructed a sparse tree.
  1480. This can be used to recenter the window to show as much of the structure
  1481. as possible."
  1482. :group 'org-sparse-trees
  1483. :type 'hook)
  1484. (defgroup org-imenu-and-speedbar nil
  1485. "Options concerning imenu and speedbar in Org mode."
  1486. :tag "Org Imenu and Speedbar"
  1487. :group 'org-structure)
  1488. (defcustom org-imenu-depth 2
  1489. "The maximum level for Imenu access to Org headlines.
  1490. This also applied for speedbar access."
  1491. :group 'org-imenu-and-speedbar
  1492. :type 'integer)
  1493. (defgroup org-table nil
  1494. "Options concerning tables in Org mode."
  1495. :tag "Org Table"
  1496. :group 'org)
  1497. (defcustom org-self-insert-cluster-for-undo nil
  1498. "Non-nil means cluster self-insert commands for undo when possible.
  1499. If this is set, then, like in the Emacs command loop, 20 consecutive
  1500. characters will be undone together.
  1501. This is configurable, because there is some impact on typing performance."
  1502. :group 'org-table
  1503. :type 'boolean)
  1504. (defcustom org-table-tab-recognizes-table.el t
  1505. "Non-nil means TAB will automatically notice a table.el table.
  1506. When it sees such a table, it moves point into it and - if necessary -
  1507. calls `table-recognize-table'."
  1508. :group 'org-table-editing
  1509. :type 'boolean)
  1510. (defgroup org-link nil
  1511. "Options concerning links in Org mode."
  1512. :tag "Org Link"
  1513. :group 'org)
  1514. (defvar-local org-link-abbrev-alist-local nil
  1515. "Buffer-local version of `org-link-abbrev-alist', which see.
  1516. The value of this is taken from the #+LINK lines.")
  1517. (defcustom org-link-parameters
  1518. '(("doi" :follow org--open-doi-link)
  1519. ("elisp" :follow org--open-elisp-link)
  1520. ("file" :complete org-file-complete-link)
  1521. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1522. ("help" :follow org--open-help-link)
  1523. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1524. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1525. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1526. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1527. ("shell" :follow org--open-shell-link))
  1528. "An alist of properties that defines all the links in Org mode.
  1529. The key in each association is a string of the link type.
  1530. Subsequent optional elements make up a p-list of link properties.
  1531. :follow - A function that takes the link path as an argument.
  1532. :export - A function that takes the link path, description and
  1533. export-backend as arguments.
  1534. :store - A function responsible for storing the link. See the
  1535. function `org-store-link-functions'.
  1536. :complete - A function that inserts a link with completion. The
  1537. function takes one optional prefix arg.
  1538. :face - A face for the link, or a function that returns a face.
  1539. The function takes one argument which is the link path. The
  1540. default face is `org-link'.
  1541. :mouse-face - The mouse-face. The default is `highlight'.
  1542. :display - `full' will not fold the link in descriptive
  1543. display. Default is `org-link'.
  1544. :help-echo - A string or function that takes (window object position)
  1545. as arguments and returns a string.
  1546. :keymap - A keymap that is active on the link. The default is
  1547. `org-mouse-map'.
  1548. :htmlize-link - A function for the htmlize-link. Defaults
  1549. to (list :uri \"type:path\")
  1550. :activate-func - A function to run at the end of font-lock
  1551. activation. The function must accept (link-start link-end path bracketp)
  1552. as arguments."
  1553. :group 'org-link
  1554. :type '(alist :tag "Link display parameters"
  1555. :value-type plist)
  1556. :version "26.1"
  1557. :package-version '(Org . "9.1"))
  1558. (defun org-link-get-parameter (type key)
  1559. "Get TYPE link property for KEY.
  1560. TYPE is a string and KEY is a plist keyword."
  1561. (plist-get
  1562. (cdr (assoc type org-link-parameters))
  1563. key))
  1564. (defun org-link-set-parameters (type &rest parameters)
  1565. "Set link TYPE properties to PARAMETERS.
  1566. PARAMETERS should be :key val pairs."
  1567. (let ((data (assoc type org-link-parameters)))
  1568. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1569. (push (cons type parameters) org-link-parameters)
  1570. (org-make-link-regexps)
  1571. (org-element-update-syntax))))
  1572. (defun org-link-types ()
  1573. "Return a list of known link types."
  1574. (mapcar #'car org-link-parameters))
  1575. (defcustom org-link-abbrev-alist nil
  1576. "Alist of link abbreviations.
  1577. The car of each element is a string, to be replaced at the start of a link.
  1578. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1579. links in Org buffers can have an optional tag after a double colon, e.g.,
  1580. [[linkkey:tag][description]]
  1581. The `linkkey' must be a single word, starting with a letter, followed
  1582. by letters, numbers, `-' or `_'.
  1583. If REPLACE is a string, the tag will simply be appended to create the link.
  1584. If the string contains \"%s\", the tag will be inserted there. If the string
  1585. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1586. at that point (see the function `url-hexify-string'). If the string contains
  1587. the specifier \"%(my-function)\", then the custom function `my-function' will
  1588. be invoked: this function takes the tag as its only argument and must return
  1589. a string.
  1590. REPLACE may also be a function that will be called with the tag as the
  1591. only argument to create the link, which should be returned as a string.
  1592. See the manual for examples."
  1593. :group 'org-link
  1594. :type '(repeat
  1595. (cons
  1596. (string :tag "Protocol")
  1597. (choice
  1598. (string :tag "Format")
  1599. (function)))))
  1600. (defcustom org-descriptive-links t
  1601. "Non-nil means Org will display descriptive links.
  1602. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1603. \"Org Website\", hiding the link itself and just displaying its
  1604. description. When set to nil, Org will display the full links
  1605. literally.
  1606. You can interactively set the value of this variable by calling
  1607. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1608. :group 'org-link
  1609. :type 'boolean)
  1610. (defcustom org-link-file-path-type 'adaptive
  1611. "How the path name in file links should be stored.
  1612. Valid values are:
  1613. relative Relative to the current directory, i.e. the directory of the file
  1614. into which the link is being inserted.
  1615. absolute Absolute path, if possible with ~ for home directory.
  1616. noabbrev Absolute path, no abbreviation of home directory.
  1617. adaptive Use relative path for files in the current directory and sub-
  1618. directories of it. For other files, use an absolute path."
  1619. :group 'org-link
  1620. :type '(choice
  1621. (const relative)
  1622. (const absolute)
  1623. (const noabbrev)
  1624. (const adaptive)))
  1625. (defvaralias 'org-activate-links 'org-highlight-links)
  1626. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1627. "Types of links that should be highlighted in Org files.
  1628. This is a list of symbols, each one of them leading to the
  1629. highlighting of a certain link type.
  1630. You can still open links that are not highlighted.
  1631. In principle, it does not hurt to turn on highlighting for all
  1632. link types. There may be a small gain when turning off unused
  1633. link types. The types are:
  1634. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1635. angle Links in angular brackets that may contain whitespace like
  1636. <bbdb:Carsten Dominik>.
  1637. plain Plain links in normal text, no whitespace, like http://google.com.
  1638. radio Text that is matched by a radio target, see manual for details.
  1639. tag Tag settings in a headline (link to tag search).
  1640. date Time stamps (link to calendar).
  1641. footnote Footnote labels.
  1642. If you set this variable during an Emacs session, use `org-mode-restart'
  1643. in the Org buffer so that the change takes effect."
  1644. :group 'org-link
  1645. :group 'org-appearance
  1646. :type '(set :greedy t
  1647. (const :tag "Double bracket links" bracket)
  1648. (const :tag "Angular bracket links" angle)
  1649. (const :tag "Plain text links" plain)
  1650. (const :tag "Radio target matches" radio)
  1651. (const :tag "Tags" tag)
  1652. (const :tag "Timestamps" date)
  1653. (const :tag "Footnotes" footnote)))
  1654. (defcustom org-make-link-description-function nil
  1655. "Function to use for generating link descriptions from links.
  1656. This function must take two parameters: the first one is the
  1657. link, the second one is the description generated by
  1658. `org-insert-link'. The function should return the description to
  1659. use."
  1660. :group 'org-link
  1661. :type '(choice (const nil) (function)))
  1662. (defgroup org-link-store nil
  1663. "Options concerning storing links in Org mode."
  1664. :tag "Org Store Link"
  1665. :group 'org-link)
  1666. (defcustom org-url-hexify-p t
  1667. "When non-nil, hexify URL when creating a link."
  1668. :type 'boolean
  1669. :version "24.3"
  1670. :group 'org-link-store)
  1671. (defcustom org-email-link-description-format "Email %c: %.30s"
  1672. "Format of the description part of a link to an email or usenet message.
  1673. The following %-escapes will be replaced by corresponding information:
  1674. %F full \"From\" field
  1675. %f name, taken from \"From\" field, address if no name
  1676. %T full \"To\" field
  1677. %t first name in \"To\" field, address if no name
  1678. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1679. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1680. %s subject
  1681. %d date
  1682. %m message-id.
  1683. You may use normal field width specification between the % and the letter.
  1684. This is for example useful to limit the length of the subject.
  1685. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1686. :group 'org-link-store
  1687. :type 'string)
  1688. (defcustom org-from-is-user-regexp
  1689. (let (r1 r2)
  1690. (when (and user-mail-address (not (string= user-mail-address "")))
  1691. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1692. (when (and user-full-name (not (string= user-full-name "")))
  1693. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1694. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1695. "Regexp matched against the \"From:\" header of an email or usenet message.
  1696. It should match if the message is from the user him/herself."
  1697. :group 'org-link-store
  1698. :type 'regexp)
  1699. (defcustom org-context-in-file-links t
  1700. "Non-nil means file links from `org-store-link' contain context.
  1701. \\<org-mode-map>
  1702. A search string will be added to the file name with :: as separator
  1703. and used to find the context when the link is activated by the command
  1704. `org-open-at-point'. When this option is t, the entire active region
  1705. will be placed in the search string of the file link. If set to a
  1706. positive integer, only the first n lines of context will be stored.
  1707. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1708. \\[org-store-link]')
  1709. negates this setting for the duration of the command."
  1710. :group 'org-link-store
  1711. :type '(choice boolean integer))
  1712. (defcustom org-keep-stored-link-after-insertion nil
  1713. "Non-nil means keep link in list for entire session.
  1714. \\<org-mode-map>
  1715. The command `org-store-link' adds a link pointing to the current
  1716. location to an internal list. These links accumulate during a session.
  1717. The command `org-insert-link' can be used to insert links into any
  1718. Org file (offering completion for all stored links).
  1719. When this option is nil, every link which has been inserted once using
  1720. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1721. unused
  1722. links more efficient."
  1723. :group 'org-link-store
  1724. :type 'boolean)
  1725. (defgroup org-link-follow nil
  1726. "Options concerning following links in Org mode."
  1727. :tag "Org Follow Link"
  1728. :group 'org-link)
  1729. (defcustom org-link-translation-function nil
  1730. "Function to translate links with different syntax to Org syntax.
  1731. This can be used to translate links created for example by the Planner
  1732. or emacs-wiki packages to Org syntax.
  1733. The function must accept two parameters, a TYPE containing the link
  1734. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1735. which is everything after the link protocol. It should return a cons
  1736. with possibly modified values of type and path.
  1737. Org contains a function for this, so if you set this variable to
  1738. `org-translate-link-from-planner', you should be able follow many
  1739. links created by planner."
  1740. :group 'org-link-follow
  1741. :type '(choice (const nil) (function)))
  1742. (defcustom org-follow-link-hook nil
  1743. "Hook that is run after a link has been followed."
  1744. :group 'org-link-follow
  1745. :type 'hook)
  1746. (defcustom org-tab-follows-link nil
  1747. "Non-nil means on links TAB will follow the link.
  1748. Needs to be set before org.el is loaded.
  1749. This really should not be used, it does not make sense, and the
  1750. implementation is bad."
  1751. :group 'org-link-follow
  1752. :type 'boolean)
  1753. (defcustom org-return-follows-link nil
  1754. "Non-nil means on links RET will follow the link.
  1755. In tables, the special behavior of RET has precedence."
  1756. :group 'org-link-follow
  1757. :type 'boolean)
  1758. (defcustom org-mouse-1-follows-link
  1759. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1760. "Non-nil means mouse-1 on a link will follow the link.
  1761. A longer mouse click will still set point. Needs to be set
  1762. before org.el is loaded."
  1763. :group 'org-link-follow
  1764. :version "26.1"
  1765. :package-version '(Org . "8.3")
  1766. :type '(choice
  1767. (const :tag "A double click follows the link" double)
  1768. (const :tag "Unconditionally follow the link with mouse-1" t)
  1769. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1770. (defcustom org-mark-ring-length 4
  1771. "Number of different positions to be recorded in the ring.
  1772. Changing this requires a restart of Emacs to work correctly."
  1773. :group 'org-link-follow
  1774. :type 'integer)
  1775. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1776. "Non-nil means internal fuzzy links can only match headlines.
  1777. When nil, the a fuzzy link may point to a target or a named
  1778. construct in the document. When set to the special value
  1779. `query-to-create', offer to create a new headline when none
  1780. matched.
  1781. Spaces and statistics cookies are ignored during heading searches."
  1782. :group 'org-link-follow
  1783. :version "24.1"
  1784. :type '(choice
  1785. (const :tag "Use fuzzy text search" nil)
  1786. (const :tag "Match only exact headline" t)
  1787. (const :tag "Match exact headline or query to create it"
  1788. query-to-create))
  1789. :safe #'symbolp)
  1790. (defcustom org-link-frame-setup
  1791. '((vm . vm-visit-folder-other-frame)
  1792. (vm-imap . vm-visit-imap-folder-other-frame)
  1793. (gnus . org-gnus-no-new-news)
  1794. (file . find-file-other-window)
  1795. (wl . wl-other-frame))
  1796. "Setup the frame configuration for following links.
  1797. When following a link with Emacs, it may often be useful to display
  1798. this link in another window or frame. This variable can be used to
  1799. set this up for the different types of links.
  1800. For VM, use any of
  1801. `vm-visit-folder'
  1802. `vm-visit-folder-other-window'
  1803. `vm-visit-folder-other-frame'
  1804. For Gnus, use any of
  1805. `gnus'
  1806. `gnus-other-frame'
  1807. `org-gnus-no-new-news'
  1808. For FILE, use any of
  1809. `find-file'
  1810. `find-file-other-window'
  1811. `find-file-other-frame'
  1812. For Wanderlust use any of
  1813. `wl'
  1814. `wl-other-frame'
  1815. For the calendar, use the variable `calendar-setup'.
  1816. For BBDB, it is currently only possible to display the matches in
  1817. another window."
  1818. :group 'org-link-follow
  1819. :type '(list
  1820. (cons (const vm)
  1821. (choice
  1822. (const vm-visit-folder)
  1823. (const vm-visit-folder-other-window)
  1824. (const vm-visit-folder-other-frame)))
  1825. (cons (const vm-imap)
  1826. (choice
  1827. (const vm-visit-imap-folder)
  1828. (const vm-visit-imap-folder-other-window)
  1829. (const vm-visit-imap-folder-other-frame)))
  1830. (cons (const gnus)
  1831. (choice
  1832. (const gnus)
  1833. (const gnus-other-frame)
  1834. (const org-gnus-no-new-news)))
  1835. (cons (const file)
  1836. (choice
  1837. (const find-file)
  1838. (const find-file-other-window)
  1839. (const find-file-other-frame)))
  1840. (cons (const wl)
  1841. (choice
  1842. (const wl)
  1843. (const wl-other-frame)))))
  1844. (defcustom org-display-internal-link-with-indirect-buffer nil
  1845. "Non-nil means use indirect buffer to display infile links.
  1846. Activating internal links (from one location in a file to another location
  1847. in the same file) normally just jumps to the location. When the link is
  1848. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1849. is displayed in
  1850. another window. When this option is set, the other window actually displays
  1851. an indirect buffer clone of the current buffer, to avoid any visibility
  1852. changes to the current buffer."
  1853. :group 'org-link-follow
  1854. :type 'boolean)
  1855. (defcustom org-open-non-existing-files nil
  1856. "Non-nil means `org-open-file' will open non-existing files.
  1857. When nil, an error will be generated.
  1858. This variable applies only to external applications because they
  1859. might choke on non-existing files. If the link is to a file that
  1860. will be opened in Emacs, the variable is ignored."
  1861. :group 'org-link-follow
  1862. :type 'boolean)
  1863. (defcustom org-open-directory-means-index-dot-org nil
  1864. "Non-nil means a link to a directory really means to index.org.
  1865. When nil, following a directory link will run dired or open a finder/explorer
  1866. window on that directory."
  1867. :group 'org-link-follow
  1868. :type 'boolean)
  1869. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1870. "Non-nil means ask for confirmation before executing shell links.
  1871. Shell links can be dangerous: just think about a link
  1872. [[shell:rm -rf ~/*][Google Search]]
  1873. This link would show up in your Org document as \"Google Search\",
  1874. but really it would remove your entire home directory.
  1875. Therefore we advise against setting this variable to nil.
  1876. Just change it to `y-or-n-p' if you want to confirm with a
  1877. single keystroke rather than having to type \"yes\"."
  1878. :group 'org-link-follow
  1879. :type '(choice
  1880. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1881. (const :tag "with y-or-n (faster)" y-or-n-p)
  1882. (const :tag "no confirmation (dangerous)" nil)))
  1883. (put 'org-confirm-shell-link-function
  1884. 'safe-local-variable
  1885. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1886. (defcustom org-confirm-shell-link-not-regexp ""
  1887. "A regexp to skip confirmation for shell links."
  1888. :group 'org-link-follow
  1889. :version "24.1"
  1890. :type 'regexp)
  1891. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1892. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1893. Elisp links can be dangerous: just think about a link
  1894. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1895. This link would show up in your Org document as \"Google Search\",
  1896. but really it would remove your entire home directory.
  1897. Therefore we advise against setting this variable to nil.
  1898. Just change it to `y-or-n-p' if you want to confirm with a
  1899. single keystroke rather than having to type \"yes\"."
  1900. :group 'org-link-follow
  1901. :type '(choice
  1902. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1903. (const :tag "with y-or-n (faster)" y-or-n-p)
  1904. (const :tag "no confirmation (dangerous)" nil)))
  1905. (put 'org-confirm-shell-link-function
  1906. 'safe-local-variable
  1907. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1908. (defcustom org-confirm-elisp-link-not-regexp ""
  1909. "A regexp to skip confirmation for Elisp links."
  1910. :group 'org-link-follow
  1911. :version "24.1"
  1912. :type 'regexp)
  1913. (defconst org-file-apps-defaults-gnu
  1914. '((remote . emacs)
  1915. (system . mailcap)
  1916. (t . mailcap))
  1917. "Default file applications on a UNIX or GNU/Linux system.
  1918. See `org-file-apps'.")
  1919. (defconst org-file-apps-defaults-macosx
  1920. '((remote . emacs)
  1921. (system . "open %s")
  1922. ("ps.gz" . "gv %s")
  1923. ("eps.gz" . "gv %s")
  1924. ("dvi" . "xdvi %s")
  1925. ("fig" . "xfig %s")
  1926. (t . "open %s"))
  1927. "Default file applications on a macOS system.
  1928. The system \"open\" is known as a default, but we use X11 applications
  1929. for some files for which the OS does not have a good default.
  1930. See `org-file-apps'.")
  1931. (defconst org-file-apps-defaults-windowsnt
  1932. (list '(remote . emacs)
  1933. (cons 'system (lambda (file _path)
  1934. (with-no-warnings (w32-shell-execute "open" file))))
  1935. (cons t (lambda (file _path)
  1936. (with-no-warnings (w32-shell-execute "open" file)))))
  1937. "Default file applications on a Windows NT system.
  1938. The system \"open\" is used for most files.
  1939. See `org-file-apps'.")
  1940. (defcustom org-file-apps
  1941. '((auto-mode . emacs)
  1942. ("\\.mm\\'" . default)
  1943. ("\\.x?html?\\'" . default)
  1944. ("\\.pdf\\'" . default))
  1945. "External applications for opening `file:path' items in a document.
  1946. \\<org-mode-map>\
  1947. Org mode uses system defaults for different file types, but
  1948. you can use this variable to set the application for a given file
  1949. extension. The entries in this list are cons cells where the car identifies
  1950. files and the cdr the corresponding command.
  1951. Possible values for the file identifier are:
  1952. \"string\" A string as a file identifier can be interpreted in different
  1953. ways, depending on its contents:
  1954. - Alphanumeric characters only:
  1955. Match links with this file extension.
  1956. Example: (\"pdf\" . \"evince %s\")
  1957. to open PDFs with evince.
  1958. - Regular expression: Match links where the
  1959. filename matches the regexp. If you want to
  1960. use groups here, use shy groups.
  1961. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1962. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1963. to open *.html and *.xhtml with firefox.
  1964. - Regular expression which contains (non-shy) groups:
  1965. Match links where the whole link, including \"::\", and
  1966. anything after that, matches the regexp.
  1967. In a custom command string, %1, %2, etc. are replaced with
  1968. the parts of the link that were matched by the groups.
  1969. For backwards compatibility, if a command string is given
  1970. that does not use any of the group matches, this case is
  1971. handled identically to the second one (i.e. match against
  1972. file name only).
  1973. In a custom function, you can access the group matches with
  1974. (match-string n link).
  1975. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1976. \"evince -p %1 %s\")
  1977. to open [[file:document.pdf::5]] with evince at page 5.
  1978. `directory' Matches a directory
  1979. `remote' Matches a remote file, accessible through tramp or efs.
  1980. Remote files most likely should be visited through Emacs
  1981. because external applications cannot handle such paths.
  1982. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1983. so all files Emacs knows how to handle. Using this with
  1984. command `emacs' will open most files in Emacs. Beware that this
  1985. will also open html files inside Emacs, unless you add
  1986. (\"html\" . default) to the list as well.
  1987. `system' The system command to open files, like `open' on Windows
  1988. and macOS, and mailcap under GNU/Linux. This is the command
  1989. that will be selected if you call `org-open-at-point' with a
  1990. double prefix argument (`\\[universal-argument] \
  1991. \\[universal-argument] \\[org-open-at-point]').
  1992. t Default for files not matched by any of the other options.
  1993. Possible values for the command are:
  1994. `emacs' The file will be visited by the current Emacs process.
  1995. `default' Use the default application for this file type, which is the
  1996. association for t in the list, most likely in the system-specific
  1997. part. This can be used to overrule an unwanted setting in the
  1998. system-specific variable.
  1999. `system' Use the system command for opening files, like \"open\".
  2000. This command is specified by the entry whose car is `system'.
  2001. Most likely, the system-specific version of this variable
  2002. does define this command, but you can overrule/replace it
  2003. here.
  2004. `mailcap' Use command specified in the mailcaps.
  2005. string A command to be executed by a shell; %s will be replaced
  2006. by the path to the file.
  2007. function A Lisp function, which will be called with two arguments:
  2008. the file path and the original link string, without the
  2009. \"file:\" prefix.
  2010. For more examples, see the system specific constants
  2011. `org-file-apps-defaults-macosx'
  2012. `org-file-apps-defaults-windowsnt'
  2013. `org-file-apps-defaults-gnu'."
  2014. :group 'org-link-follow
  2015. :type '(repeat
  2016. (cons (choice :value ""
  2017. (string :tag "Extension")
  2018. (const :tag "System command to open files" system)
  2019. (const :tag "Default for unrecognized files" t)
  2020. (const :tag "Remote file" remote)
  2021. (const :tag "Links to a directory" directory)
  2022. (const :tag "Any files that have Emacs modes"
  2023. auto-mode))
  2024. (choice :value ""
  2025. (const :tag "Visit with Emacs" emacs)
  2026. (const :tag "Use default" default)
  2027. (const :tag "Use the system command" system)
  2028. (string :tag "Command")
  2029. (function :tag "Function")))))
  2030. (defcustom org-doi-server-url "http://dx.doi.org/"
  2031. "The URL of the DOI server."
  2032. :type 'string
  2033. :version "24.3"
  2034. :group 'org-link-follow)
  2035. (defgroup org-refile nil
  2036. "Options concerning refiling entries in Org mode."
  2037. :tag "Org Refile"
  2038. :group 'org)
  2039. (defcustom org-directory "~/org"
  2040. "Directory with Org files.
  2041. This is just a default location to look for Org files. There is no need
  2042. at all to put your files into this directory. It is used in the
  2043. following situations:
  2044. 1. When a capture template specifies a target file that is not an
  2045. absolute path. The path will then be interpreted relative to
  2046. `org-directory'
  2047. 2. When the value of variable `org-agenda-files' is a single file, any
  2048. relative paths in this file will be taken as relative to
  2049. `org-directory'."
  2050. :group 'org-refile
  2051. :group 'org-capture
  2052. :type 'directory)
  2053. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2054. "Default target for storing notes.
  2055. Used as a fall back file for org-capture.el, for templates that
  2056. do not specify a target file."
  2057. :group 'org-refile
  2058. :group 'org-capture
  2059. :type 'file)
  2060. (defcustom org-goto-interface 'outline
  2061. "The default interface to be used for `org-goto'.
  2062. Allowed values are:
  2063. outline The interface shows an outline of the relevant file
  2064. and the correct heading is found by moving through
  2065. the outline or by searching with incremental search.
  2066. outline-path-completion Headlines in the current buffer are offered via
  2067. completion. This is the interface also used by
  2068. the refile command."
  2069. :group 'org-refile
  2070. :type '(choice
  2071. (const :tag "Outline" outline)
  2072. (const :tag "Outline-path-completion" outline-path-completion)))
  2073. (defcustom org-goto-max-level 5
  2074. "Maximum target level when running `org-goto' with refile interface."
  2075. :group 'org-refile
  2076. :type 'integer)
  2077. (defcustom org-reverse-note-order nil
  2078. "Non-nil means store new notes at the beginning of a file or entry.
  2079. When nil, new notes will be filed to the end of a file or entry.
  2080. This can also be a list with cons cells of regular expressions that
  2081. are matched against file names, and values."
  2082. :group 'org-capture
  2083. :group 'org-refile
  2084. :type '(choice
  2085. (const :tag "Reverse always" t)
  2086. (const :tag "Reverse never" nil)
  2087. (repeat :tag "By file name regexp"
  2088. (cons regexp boolean))))
  2089. (defcustom org-log-refile nil
  2090. "Information to record when a task is refiled.
  2091. Possible values are:
  2092. nil Don't add anything
  2093. time Add a time stamp to the task
  2094. note Prompt for a note and add it with template `org-log-note-headings'
  2095. This option can also be set with on a per-file-basis with
  2096. #+STARTUP: nologrefile
  2097. #+STARTUP: logrefile
  2098. #+STARTUP: lognoterefile
  2099. You can have local logging settings for a subtree by setting the LOGGING
  2100. property to one or more of these keywords.
  2101. When bulk-refiling from the agenda, the value `note' is forbidden and
  2102. will temporarily be changed to `time'."
  2103. :group 'org-refile
  2104. :group 'org-progress
  2105. :version "24.1"
  2106. :type '(choice
  2107. (const :tag "No logging" nil)
  2108. (const :tag "Record timestamp" time)
  2109. (const :tag "Record timestamp with note." note)))
  2110. (defcustom org-refile-targets nil
  2111. "Targets for refiling entries with `\\[org-refile]'.
  2112. This is a list of cons cells. Each cell contains:
  2113. - a specification of the files to be considered, either a list of files,
  2114. or a symbol whose function or variable value will be used to retrieve
  2115. a file name or a list of file names. If you use `org-agenda-files' for
  2116. that, all agenda files will be scanned for targets. Nil means consider
  2117. headings in the current buffer.
  2118. - A specification of how to find candidate refile targets. This may be
  2119. any of:
  2120. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2121. This tag has to be present in all target headlines, inheritance will
  2122. not be considered.
  2123. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2124. todo keyword.
  2125. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2126. headlines that are refiling targets.
  2127. - a cons cell (:level . N). Any headline of level N is considered a target.
  2128. Note that, when `org-odd-levels-only' is set, level corresponds to
  2129. order in hierarchy, not to the number of stars.
  2130. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2131. Note that, when `org-odd-levels-only' is set, level corresponds to
  2132. order in hierarchy, not to the number of stars.
  2133. Each element of this list generates a set of possible targets.
  2134. The union of these sets is presented (with completion) to
  2135. the user by `org-refile'.
  2136. You can set the variable `org-refile-target-verify-function' to a function
  2137. to verify each headline found by the simple criteria above.
  2138. When this variable is nil, all top-level headlines in the current buffer
  2139. are used, equivalent to the value `((nil . (:level . 1))'."
  2140. :group 'org-refile
  2141. :type '(repeat
  2142. (cons
  2143. (choice :value org-agenda-files
  2144. (const :tag "All agenda files" org-agenda-files)
  2145. (const :tag "Current buffer" nil)
  2146. (function) (variable) (file))
  2147. (choice :tag "Identify target headline by"
  2148. (cons :tag "Specific tag" (const :value :tag) (string))
  2149. (cons :tag "TODO keyword" (const :value :todo) (string))
  2150. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2151. (cons :tag "Level number" (const :value :level) (integer))
  2152. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2153. (defcustom org-refile-target-verify-function nil
  2154. "Function to verify if the headline at point should be a refile target.
  2155. The function will be called without arguments, with point at the
  2156. beginning of the headline. It should return t and leave point
  2157. where it is if the headline is a valid target for refiling.
  2158. If the target should not be selected, the function must return nil.
  2159. In addition to this, it may move point to a place from where the search
  2160. should be continued. For example, the function may decide that the entire
  2161. subtree of the current entry should be excluded and move point to the end
  2162. of the subtree."
  2163. :group 'org-refile
  2164. :type '(choice
  2165. (const nil)
  2166. (function)))
  2167. (defcustom org-refile-use-cache nil
  2168. "Non-nil means cache refile targets to speed up the process.
  2169. \\<org-mode-map>\
  2170. The cache for a particular file will be updated automatically when
  2171. the buffer has been killed, or when any of the marker used for flagging
  2172. refile targets no longer points at a live buffer.
  2173. If you have added new entries to a buffer that might themselves be targets,
  2174. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2175. if you find that easier, \
  2176. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2177. \\[org-refile]'."
  2178. :group 'org-refile
  2179. :version "24.1"
  2180. :type 'boolean)
  2181. (defcustom org-refile-use-outline-path nil
  2182. "Non-nil means provide refile targets as paths.
  2183. So a level 3 headline will be available as level1/level2/level3.
  2184. When the value is `file', also include the file name (without directory)
  2185. into the path. In this case, you can also stop the completion after
  2186. the file name, to get entries inserted as top level in the file.
  2187. When `full-file-path', include the full file path.
  2188. When `buffer-name', use the buffer name."
  2189. :group 'org-refile
  2190. :type '(choice
  2191. (const :tag "Not" nil)
  2192. (const :tag "Yes" t)
  2193. (const :tag "Start with file name" file)
  2194. (const :tag "Start with full file path" full-file-path)
  2195. (const :tag "Start with buffer name" buffer-name)))
  2196. (defcustom org-outline-path-complete-in-steps t
  2197. "Non-nil means complete the outline path in hierarchical steps.
  2198. When Org uses the refile interface to select an outline path (see
  2199. `org-refile-use-outline-path'), the completion of the path can be
  2200. done in a single go, or it can be done in steps down the headline
  2201. hierarchy. Going in steps is probably the best if you do not use
  2202. a special completion package like `ido' or `icicles'. However,
  2203. when using these packages, going in one step can be very fast,
  2204. while still showing the whole path to the entry."
  2205. :group 'org-refile
  2206. :type 'boolean)
  2207. (defcustom org-refile-allow-creating-parent-nodes nil
  2208. "Non-nil means allow the creation of new nodes as refile targets.
  2209. New nodes are then created by adding \"/new node name\" to the completion
  2210. of an existing node. When the value of this variable is `confirm',
  2211. new node creation must be confirmed by the user (recommended).
  2212. When nil, the completion must match an existing entry.
  2213. Note that, if the new heading is not seen by the criteria
  2214. listed in `org-refile-targets', multiple instances of the same
  2215. heading would be created by trying again to file under the new
  2216. heading."
  2217. :group 'org-refile
  2218. :type '(choice
  2219. (const :tag "Never" nil)
  2220. (const :tag "Always" t)
  2221. (const :tag "Prompt for confirmation" confirm)))
  2222. (defcustom org-refile-active-region-within-subtree nil
  2223. "Non-nil means also refile active region within a subtree.
  2224. By default `org-refile' doesn't allow refiling regions if they
  2225. don't contain a set of subtrees, but it might be convenient to
  2226. do so sometimes: in that case, the first line of the region is
  2227. converted to a headline before refiling."
  2228. :group 'org-refile
  2229. :version "24.1"
  2230. :type 'boolean)
  2231. (defgroup org-todo nil
  2232. "Options concerning TODO items in Org mode."
  2233. :tag "Org TODO"
  2234. :group 'org)
  2235. (defgroup org-progress nil
  2236. "Options concerning Progress logging in Org mode."
  2237. :tag "Org Progress"
  2238. :group 'org-time)
  2239. (defvar org-todo-interpretation-widgets
  2240. '((:tag "Sequence (cycling hits every state)" sequence)
  2241. (:tag "Type (cycling directly to DONE)" type))
  2242. "The available interpretation symbols for customizing `org-todo-keywords'.
  2243. Interested libraries should add to this list.")
  2244. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2245. "List of TODO entry keyword sequences and their interpretation.
  2246. \\<org-mode-map>This is a list of sequences.
  2247. Each sequence starts with a symbol, either `sequence' or `type',
  2248. indicating if the keywords should be interpreted as a sequence of
  2249. action steps, or as different types of TODO items. The first
  2250. keywords are states requiring action - these states will select a headline
  2251. for inclusion into the global TODO list Org produces. If one of the
  2252. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2253. signify that no further action is necessary. If \"|\" is not found,
  2254. the last keyword is treated as the only DONE state of the sequence.
  2255. The command `\\[org-todo]' cycles an entry through these states, and one
  2256. additional state where no keyword is present. For details about this
  2257. cycling, see the manual.
  2258. TODO keywords and interpretation can also be set on a per-file basis with
  2259. the special #+SEQ_TODO and #+TYP_TODO lines.
  2260. Each keyword can optionally specify a character for fast state selection
  2261. \(in combination with the variable `org-use-fast-todo-selection')
  2262. and specifiers for state change logging, using the same syntax that
  2263. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2264. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2265. indicates to record a time stamp each time this state is selected.
  2266. Each keyword may also specify if a timestamp or a note should be
  2267. recorded when entering or leaving the state, by adding additional
  2268. characters in the parenthesis after the keyword. This looks like this:
  2269. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2270. record only the time of the state change. With X and Y being either
  2271. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2272. Y when leaving the state if and only if the *target* state does not
  2273. define X. You may omit any of the fast-selection key or X or /Y,
  2274. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2275. For backward compatibility, this variable may also be just a list
  2276. of keywords. In this case the interpretation (sequence or type) will be
  2277. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2278. :group 'org-todo
  2279. :group 'org-keywords
  2280. :type '(choice
  2281. (repeat :tag "Old syntax, just keywords"
  2282. (string :tag "Keyword"))
  2283. (repeat :tag "New syntax"
  2284. (cons
  2285. (choice
  2286. :tag "Interpretation"
  2287. ;;Quick and dirty way to see
  2288. ;;`org-todo-interpretations'. This takes the
  2289. ;;place of item arguments
  2290. :convert-widget
  2291. (lambda (widget)
  2292. (widget-put widget
  2293. :args (mapcar
  2294. (lambda (x)
  2295. (widget-convert
  2296. (cons 'const x)))
  2297. org-todo-interpretation-widgets))
  2298. widget))
  2299. (repeat
  2300. (string :tag "Keyword"))))))
  2301. (defvar-local org-todo-keywords-1 nil
  2302. "All TODO and DONE keywords active in a buffer.")
  2303. (defvar org-todo-keywords-for-agenda nil)
  2304. (defvar org-done-keywords-for-agenda nil)
  2305. (defvar org-todo-keyword-alist-for-agenda nil)
  2306. (defvar org-tag-alist-for-agenda nil
  2307. "Alist of all tags from all agenda files.")
  2308. (defvar org-tag-groups-alist-for-agenda nil
  2309. "Alist of all groups tags from all current agenda files.")
  2310. (defvar-local org-tag-groups-alist nil)
  2311. (defvar org-agenda-contributing-files nil)
  2312. (defvar-local org-current-tag-alist nil
  2313. "Alist of all tag groups in current buffer.
  2314. This variable takes into consideration `org-tag-alist',
  2315. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2316. (defvar-local org-not-done-keywords nil)
  2317. (defvar-local org-done-keywords nil)
  2318. (defvar-local org-todo-heads nil)
  2319. (defvar-local org-todo-sets nil)
  2320. (defvar-local org-todo-log-states nil)
  2321. (defvar-local org-todo-kwd-alist nil)
  2322. (defvar-local org-todo-key-alist nil)
  2323. (defvar-local org-todo-key-trigger nil)
  2324. (defcustom org-todo-interpretation 'sequence
  2325. "Controls how TODO keywords are interpreted.
  2326. This variable is in principle obsolete and is only used for
  2327. backward compatibility, if the interpretation of todo keywords is
  2328. not given already in `org-todo-keywords'. See that variable for
  2329. more information."
  2330. :group 'org-todo
  2331. :group 'org-keywords
  2332. :type '(choice (const sequence)
  2333. (const type)))
  2334. (defcustom org-use-fast-todo-selection t
  2335. "\\<org-mode-map>\
  2336. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2337. This variable describes if and under what circumstances the cycling
  2338. mechanism for TODO keywords will be replaced by a single-key, direct
  2339. selection scheme.
  2340. When nil, fast selection is never used.
  2341. When the symbol `prefix', it will be used when `org-todo' is called
  2342. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2343. in an Org buffer, and
  2344. `\\[universal-argument] t' in an agenda buffer.
  2345. When t, fast selection is used by default. In this case, the prefix
  2346. argument forces cycling instead.
  2347. In all cases, the special interface is only used if access keys have
  2348. actually been assigned by the user, i.e. if keywords in the configuration
  2349. are followed by a letter in parenthesis, like TODO(t)."
  2350. :group 'org-todo
  2351. :type '(choice
  2352. (const :tag "Never" nil)
  2353. (const :tag "By default" t)
  2354. (const :tag "Only with C-u C-c C-t" prefix)))
  2355. (defcustom org-provide-todo-statistics t
  2356. "Non-nil means update todo statistics after insert and toggle.
  2357. ALL-HEADLINES means update todo statistics by including headlines
  2358. with no TODO keyword as well, counting them as not done.
  2359. A list of TODO keywords means the same, but skip keywords that are
  2360. not in this list.
  2361. When set to a list of two lists, the first list contains keywords
  2362. to consider as TODO keywords, the second list contains keywords
  2363. to consider as DONE keywords.
  2364. When this is set, todo statistics is updated in the parent of the
  2365. current entry each time a todo state is changed."
  2366. :group 'org-todo
  2367. :type '(choice
  2368. (const :tag "Yes, only for TODO entries" t)
  2369. (const :tag "Yes, including all entries" all-headlines)
  2370. (repeat :tag "Yes, for TODOs in this list"
  2371. (string :tag "TODO keyword"))
  2372. (list :tag "Yes, for TODOs and DONEs in these lists"
  2373. (repeat (string :tag "TODO keyword"))
  2374. (repeat (string :tag "DONE keyword")))
  2375. (other :tag "No TODO statistics" nil)))
  2376. (defcustom org-hierarchical-todo-statistics t
  2377. "Non-nil means TODO statistics covers just direct children.
  2378. When nil, all entries in the subtree are considered.
  2379. This has only an effect if `org-provide-todo-statistics' is set.
  2380. To set this to nil for only a single subtree, use a COOKIE_DATA
  2381. property and include the word \"recursive\" into the value."
  2382. :group 'org-todo
  2383. :type 'boolean)
  2384. (defcustom org-after-todo-state-change-hook nil
  2385. "Hook which is run after the state of a TODO item was changed.
  2386. The new state (a string with a TODO keyword, or nil) is available in the
  2387. Lisp variable `org-state'."
  2388. :group 'org-todo
  2389. :type 'hook)
  2390. (defvar org-blocker-hook nil
  2391. "Hook for functions that are allowed to block a state change.
  2392. Functions in this hook should not modify the buffer.
  2393. Each function gets as its single argument a property list,
  2394. see `org-trigger-hook' for more information about this list.
  2395. If any of the functions in this hook returns nil, the state change
  2396. is blocked.")
  2397. (defvar org-trigger-hook nil
  2398. "Hook for functions that are triggered by a state change.
  2399. Each function gets as its single argument a property list with at
  2400. least the following elements:
  2401. (:type type-of-change :position pos-at-entry-start
  2402. :from old-state :to new-state)
  2403. Depending on the type, more properties may be present.
  2404. This mechanism is currently implemented for:
  2405. TODO state changes
  2406. ------------------
  2407. :type todo-state-change
  2408. :from previous state (keyword as a string), or nil, or a symbol
  2409. `todo' or `done', to indicate the general type of state.
  2410. :to new state, like in :from")
  2411. (defcustom org-enforce-todo-dependencies nil
  2412. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2413. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2414. be blocked if any prior sibling is not yet done.
  2415. Finally, if the parent is blocked because of ordered siblings of its own,
  2416. the child will also be blocked."
  2417. :set (lambda (var val)
  2418. (set var val)
  2419. (if val
  2420. (add-hook 'org-blocker-hook
  2421. 'org-block-todo-from-children-or-siblings-or-parent)
  2422. (remove-hook 'org-blocker-hook
  2423. 'org-block-todo-from-children-or-siblings-or-parent)))
  2424. :group 'org-todo
  2425. :type 'boolean)
  2426. (defcustom org-enforce-todo-checkbox-dependencies nil
  2427. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2428. When this is nil, checkboxes have no influence on switching TODO states.
  2429. When non-nil, you first need to check off all check boxes before the TODO
  2430. entry can be switched to DONE.
  2431. This variable needs to be set before org.el is loaded, and you need to
  2432. restart Emacs after a change to make the change effective. The only way
  2433. to change is while Emacs is running is through the customize interface."
  2434. :set (lambda (var val)
  2435. (set var val)
  2436. (if val
  2437. (add-hook 'org-blocker-hook
  2438. 'org-block-todo-from-checkboxes)
  2439. (remove-hook 'org-blocker-hook
  2440. 'org-block-todo-from-checkboxes)))
  2441. :group 'org-todo
  2442. :type 'boolean)
  2443. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2444. "Non-nil means inserting a TODO heading is treated as state change.
  2445. So when the command `\\[org-insert-todo-heading]' is used, state change
  2446. logging will apply if appropriate. When nil, the new TODO item will
  2447. be inserted directly, and no logging will take place."
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2451. "Non-nil means switching TODO states with S-cursor counts as state change.
  2452. This is the default behavior. However, setting this to nil allows a
  2453. convenient way to select a TODO state and bypass any logging associated
  2454. with that."
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-todo-state-tags-triggers nil
  2458. "Tag changes that should be triggered by TODO state changes.
  2459. This is a list. Each entry is
  2460. (state-change (tag . flag) .......)
  2461. State-change can be a string with a state, and empty string to indicate the
  2462. state that has no TODO keyword, or it can be one of the symbols `todo'
  2463. or `done', meaning any not-done or done state, respectively."
  2464. :group 'org-todo
  2465. :group 'org-tags
  2466. :type '(repeat
  2467. (cons (choice :tag "When changing to"
  2468. (const :tag "Not-done state" todo)
  2469. (const :tag "Done state" done)
  2470. (string :tag "State"))
  2471. (repeat
  2472. (cons :tag "Tag action"
  2473. (string :tag "Tag")
  2474. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2475. (defcustom org-log-done nil
  2476. "Information to record when a task moves to the DONE state.
  2477. Possible values are:
  2478. nil Don't add anything, just change the keyword
  2479. time Add a time stamp to the task
  2480. note Prompt for a note and add it with template `org-log-note-headings'
  2481. This option can also be set with on a per-file-basis with
  2482. #+STARTUP: nologdone
  2483. #+STARTUP: logdone
  2484. #+STARTUP: lognotedone
  2485. You can have local logging settings for a subtree by setting the LOGGING
  2486. property to one or more of these keywords."
  2487. :group 'org-todo
  2488. :group 'org-progress
  2489. :type '(choice
  2490. (const :tag "No logging" nil)
  2491. (const :tag "Record CLOSED timestamp" time)
  2492. (const :tag "Record CLOSED timestamp with note." note)))
  2493. ;; Normalize old uses of org-log-done.
  2494. (cond
  2495. ((eq org-log-done t) (setq org-log-done 'time))
  2496. ((and (listp org-log-done) (memq 'done org-log-done))
  2497. (setq org-log-done 'note)))
  2498. (defcustom org-log-reschedule nil
  2499. "Information to record when the scheduling date of a tasks is modified.
  2500. Possible values are:
  2501. nil Don't add anything, just change the date
  2502. time Add a time stamp to the task
  2503. note Prompt for a note and add it with template `org-log-note-headings'
  2504. This option can also be set with on a per-file-basis with
  2505. #+STARTUP: nologreschedule
  2506. #+STARTUP: logreschedule
  2507. #+STARTUP: lognotereschedule"
  2508. :group 'org-todo
  2509. :group 'org-progress
  2510. :type '(choice
  2511. (const :tag "No logging" nil)
  2512. (const :tag "Record timestamp" time)
  2513. (const :tag "Record timestamp with note." note)))
  2514. (defcustom org-log-redeadline nil
  2515. "Information to record when the deadline date of a tasks is modified.
  2516. Possible values are:
  2517. nil Don't add anything, just change the date
  2518. time Add a time stamp to the task
  2519. note Prompt for a note and add it with template `org-log-note-headings'
  2520. This option can also be set with on a per-file-basis with
  2521. #+STARTUP: nologredeadline
  2522. #+STARTUP: logredeadline
  2523. #+STARTUP: lognoteredeadline
  2524. You can have local logging settings for a subtree by setting the LOGGING
  2525. property to one or more of these keywords."
  2526. :group 'org-todo
  2527. :group 'org-progress
  2528. :type '(choice
  2529. (const :tag "No logging" nil)
  2530. (const :tag "Record timestamp" time)
  2531. (const :tag "Record timestamp with note." note)))
  2532. (defcustom org-log-note-clock-out nil
  2533. "Non-nil means record a note when clocking out of an item.
  2534. This can also be configured on a per-file basis by adding one of
  2535. the following lines anywhere in the buffer:
  2536. #+STARTUP: lognoteclock-out
  2537. #+STARTUP: nolognoteclock-out"
  2538. :group 'org-todo
  2539. :group 'org-progress
  2540. :type 'boolean)
  2541. (defcustom org-log-done-with-time t
  2542. "Non-nil means the CLOSED time stamp will contain date and time.
  2543. When nil, only the date will be recorded."
  2544. :group 'org-progress
  2545. :type 'boolean)
  2546. (defcustom org-log-note-headings
  2547. '((done . "CLOSING NOTE %t")
  2548. (state . "State %-12s from %-12S %t")
  2549. (note . "Note taken on %t")
  2550. (reschedule . "Rescheduled from %S on %t")
  2551. (delschedule . "Not scheduled, was %S on %t")
  2552. (redeadline . "New deadline from %S on %t")
  2553. (deldeadline . "Removed deadline, was %S on %t")
  2554. (refile . "Refiled on %t")
  2555. (clock-out . ""))
  2556. "Headings for notes added to entries.
  2557. The value is an alist, with the car being a symbol indicating the
  2558. note context, and the cdr is the heading to be used. The heading
  2559. may also be the empty string. The following placeholders can be
  2560. used:
  2561. %t a time stamp.
  2562. %T an active time stamp instead the default inactive one
  2563. %d a short-format time stamp.
  2564. %D an active short-format time stamp.
  2565. %s the new TODO state or time stamp (inactive), in double quotes.
  2566. %S the old TODO state or time stamp (inactive), in double quotes.
  2567. %u the user name.
  2568. %U full user name.
  2569. In fact, it is not a good idea to change the `state' entry,
  2570. because Agenda Log mode depends on the format of these entries."
  2571. :group 'org-todo
  2572. :group 'org-progress
  2573. :type '(list :greedy t
  2574. (cons (const :tag "Heading when closing an item" done) string)
  2575. (cons (const :tag
  2576. "Heading when changing todo state (todo sequence only)"
  2577. state) string)
  2578. (cons (const :tag "Heading when just taking a note" note) string)
  2579. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2580. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2581. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2582. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2583. (cons (const :tag "Heading when refiling" refile) string)
  2584. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2585. (unless (assq 'note org-log-note-headings)
  2586. (push '(note . "%t") org-log-note-headings))
  2587. (defcustom org-log-into-drawer nil
  2588. "Non-nil means insert state change notes and time stamps into a drawer.
  2589. When nil, state changes notes will be inserted after the headline and
  2590. any scheduling and clock lines, but not inside a drawer.
  2591. The value of this variable should be the name of the drawer to use.
  2592. LOGBOOK is proposed as the default drawer for this purpose, you can
  2593. also set this to a string to define the drawer of your choice.
  2594. A value of t is also allowed, representing \"LOGBOOK\".
  2595. A value of t or nil can also be set with on a per-file-basis with
  2596. #+STARTUP: logdrawer
  2597. #+STARTUP: nologdrawer
  2598. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2599. will be ignored.
  2600. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2601. a subtree.
  2602. Do not check directly this variable in a Lisp program. Call
  2603. function `org-log-into-drawer' instead."
  2604. :group 'org-todo
  2605. :group 'org-progress
  2606. :type '(choice
  2607. (const :tag "Not into a drawer" nil)
  2608. (const :tag "LOGBOOK" t)
  2609. (string :tag "Other")))
  2610. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2611. (defun org-log-into-drawer ()
  2612. "Name of the log drawer, as a string, or nil.
  2613. This is the value of `org-log-into-drawer'. However, if the
  2614. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2615. be used instead of the default value."
  2616. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2617. (cond ((equal p "nil") nil)
  2618. ((equal p "t") "LOGBOOK")
  2619. ((stringp p) p)
  2620. (p "LOGBOOK")
  2621. ((stringp org-log-into-drawer) org-log-into-drawer)
  2622. (org-log-into-drawer "LOGBOOK"))))
  2623. (defcustom org-log-state-notes-insert-after-drawers nil
  2624. "Non-nil means insert state change notes after any drawers in entry.
  2625. Only the drawers that *immediately* follow the headline and the
  2626. deadline/scheduled line are skipped.
  2627. When nil, insert notes right after the heading and perhaps the line
  2628. with deadline/scheduling if present.
  2629. This variable will have no effect if `org-log-into-drawer' is
  2630. set."
  2631. :group 'org-todo
  2632. :group 'org-progress
  2633. :type 'boolean)
  2634. (defcustom org-log-states-order-reversed t
  2635. "Non-nil means the latest state note will be directly after heading.
  2636. When nil, the state change notes will be ordered according to time.
  2637. This option can also be set with on a per-file-basis with
  2638. #+STARTUP: logstatesreversed
  2639. #+STARTUP: nologstatesreversed"
  2640. :group 'org-todo
  2641. :group 'org-progress
  2642. :type 'boolean)
  2643. (defcustom org-todo-repeat-to-state nil
  2644. "The TODO state to which a repeater should return the repeating task.
  2645. By default this is the first task in a TODO sequence, or the previous state
  2646. in a TODO_TYP set. But you can specify another task here.
  2647. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2648. :group 'org-todo
  2649. :version "24.1"
  2650. :type '(choice (const :tag "Head of sequence" nil)
  2651. (string :tag "Specific state")))
  2652. (defcustom org-log-repeat 'time
  2653. "Non-nil means record moving through the DONE state when triggering repeat.
  2654. An auto-repeating task is immediately switched back to TODO when
  2655. marked DONE. If you are not logging state changes (by adding \"@\"
  2656. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2657. record a closing note, there will be no record of the task moving
  2658. through DONE. This variable forces taking a note anyway.
  2659. nil Don't force a record
  2660. time Record a time stamp
  2661. note Prompt for a note and add it with template `org-log-note-headings'
  2662. This option can also be set with on a per-file-basis with
  2663. #+STARTUP: nologrepeat
  2664. #+STARTUP: logrepeat
  2665. #+STARTUP: lognoterepeat
  2666. You can have local logging settings for a subtree by setting the LOGGING
  2667. property to one or more of these keywords."
  2668. :group 'org-todo
  2669. :group 'org-progress
  2670. :type '(choice
  2671. (const :tag "Don't force a record" nil)
  2672. (const :tag "Force recording the DONE state" time)
  2673. (const :tag "Force recording a note with the DONE state" note)))
  2674. (defgroup org-priorities nil
  2675. "Priorities in Org mode."
  2676. :tag "Org Priorities"
  2677. :group 'org-todo)
  2678. (defcustom org-enable-priority-commands t
  2679. "Non-nil means priority commands are active.
  2680. When nil, these commands will be disabled, so that you never accidentally
  2681. set a priority."
  2682. :group 'org-priorities
  2683. :type 'boolean)
  2684. (defcustom org-highest-priority ?A
  2685. "The highest priority of TODO items. A character like ?A, ?B etc.
  2686. Must have a smaller ASCII number than `org-lowest-priority'."
  2687. :group 'org-priorities
  2688. :type 'character)
  2689. (defcustom org-lowest-priority ?C
  2690. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2691. Must have a larger ASCII number than `org-highest-priority'."
  2692. :group 'org-priorities
  2693. :type 'character)
  2694. (defcustom org-default-priority ?B
  2695. "The default priority of TODO items.
  2696. This is the priority an item gets if no explicit priority is given.
  2697. When starting to cycle on an empty priority the first step in the cycle
  2698. depends on `org-priority-start-cycle-with-default'. The resulting first
  2699. step priority must not exceed the range from `org-highest-priority' to
  2700. `org-lowest-priority' which means that `org-default-priority' has to be
  2701. in this range exclusive or inclusive the range boundaries. Else the
  2702. first step refuses to set the default and the second will fall back
  2703. to (depending on the command used) the highest or lowest priority."
  2704. :group 'org-priorities
  2705. :type 'character)
  2706. (defcustom org-priority-start-cycle-with-default t
  2707. "Non-nil means start with default priority when starting to cycle.
  2708. When this is nil, the first step in the cycle will be (depending on the
  2709. command used) one higher or lower than the default priority.
  2710. See also `org-default-priority'."
  2711. :group 'org-priorities
  2712. :type 'boolean)
  2713. (defcustom org-get-priority-function nil
  2714. "Function to extract the priority from a string.
  2715. The string is normally the headline. If this is nil Org computes the
  2716. priority from the priority cookie like [#A] in the headline. It returns
  2717. an integer, increasing by 1000 for each priority level.
  2718. The user can set a different function here, which should take a string
  2719. as an argument and return the numeric priority."
  2720. :group 'org-priorities
  2721. :version "24.1"
  2722. :type '(choice
  2723. (const nil)
  2724. (function)))
  2725. (defgroup org-time nil
  2726. "Options concerning time stamps and deadlines in Org mode."
  2727. :tag "Org Time"
  2728. :group 'org)
  2729. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2730. "Number of minutes to round time stamps to.
  2731. \\<org-mode-map>\
  2732. These are two values, the first applies when first creating a time stamp.
  2733. The second applies when changing it with the commands `S-up' and `S-down'.
  2734. When changing the time stamp, this means that it will change in steps
  2735. of N minutes, as given by the second value.
  2736. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2737. numbers should be factors of 60, so for example 5, 10, 15.
  2738. When this is larger than 1, you can still force an exact time stamp by using
  2739. a double prefix argument to a time stamp command like \
  2740. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2741. and by using a prefix arg to `S-up/down' to specify the exact number
  2742. of minutes to shift."
  2743. :group 'org-time
  2744. :get (lambda (var) ; Make sure both elements are there
  2745. (if (integerp (default-value var))
  2746. (list (default-value var) 5)
  2747. (default-value var)))
  2748. :type '(list
  2749. (integer :tag "when inserting times")
  2750. (integer :tag "when modifying times")))
  2751. ;; Normalize old customizations of this variable.
  2752. (when (integerp org-time-stamp-rounding-minutes)
  2753. (setq org-time-stamp-rounding-minutes
  2754. (list org-time-stamp-rounding-minutes
  2755. org-time-stamp-rounding-minutes)))
  2756. (defcustom org-display-custom-times nil
  2757. "Non-nil means overlay custom formats over all time stamps.
  2758. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2759. To turn this on on a per-file basis, insert anywhere in the file:
  2760. #+STARTUP: customtime"
  2761. :group 'org-time
  2762. :set 'set-default
  2763. :type 'sexp)
  2764. (make-variable-buffer-local 'org-display-custom-times)
  2765. (defcustom org-time-stamp-custom-formats
  2766. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2767. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2768. These are overlaid over the default ISO format if the variable
  2769. `org-display-custom-times' is set. Time like %H:%M should be at the
  2770. end of the second format. The custom formats are also honored by export
  2771. commands, if custom time display is turned on at the time of export."
  2772. :group 'org-time
  2773. :type 'sexp)
  2774. (defun org-time-stamp-format (&optional long inactive)
  2775. "Get the right format for a time string."
  2776. (let ((f (if long (cdr org-time-stamp-formats)
  2777. (car org-time-stamp-formats))))
  2778. (if inactive
  2779. (concat "[" (substring f 1 -1) "]")
  2780. f)))
  2781. (defcustom org-deadline-warning-days 14
  2782. "Number of days before expiration during which a deadline becomes active.
  2783. This variable governs the display in sparse trees and in the agenda.
  2784. When 0 or negative, it means use this number (the absolute value of it)
  2785. even if a deadline has a different individual lead time specified.
  2786. Custom commands can set this variable in the options section."
  2787. :group 'org-time
  2788. :group 'org-agenda-daily/weekly
  2789. :type 'integer)
  2790. (defcustom org-scheduled-delay-days 0
  2791. "Number of days before a scheduled item becomes active.
  2792. This variable governs the display in sparse trees and in the agenda.
  2793. The default value (i.e. 0) means: don't delay scheduled item.
  2794. When negative, it means use this number (the absolute value of it)
  2795. even if a scheduled item has a different individual delay time
  2796. specified.
  2797. Custom commands can set this variable in the options section."
  2798. :group 'org-time
  2799. :group 'org-agenda-daily/weekly
  2800. :version "24.4"
  2801. :package-version '(Org . "8.0")
  2802. :type 'integer)
  2803. (defcustom org-read-date-prefer-future t
  2804. "Non-nil means assume future for incomplete date input from user.
  2805. This affects the following situations:
  2806. 1. The user gives a month but not a year.
  2807. For example, if it is April and you enter \"feb 2\", this will be read
  2808. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2809. 2. The user gives a day, but no month.
  2810. For example, if today is the 15th, and you enter \"3\", Org will read
  2811. this as the third of *next* month. However, if you enter \"17\",
  2812. it will be considered as *this* month.
  2813. If you set this variable to the symbol `time', then also the following
  2814. will work:
  2815. 3. If the user gives a time.
  2816. If the time is before now, it will be interpreted as tomorrow.
  2817. Currently none of this works for ISO week specifications.
  2818. When this option is nil, the current day, month and year will always be
  2819. used as defaults.
  2820. See also `org-agenda-jump-prefer-future'."
  2821. :group 'org-time
  2822. :type '(choice
  2823. (const :tag "Never" nil)
  2824. (const :tag "Check month and day" t)
  2825. (const :tag "Check month, day, and time" time)))
  2826. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2827. "Should the agenda jump command prefer the future for incomplete dates?
  2828. The default is to do the same as configured in `org-read-date-prefer-future'.
  2829. But you can also set a deviating value here.
  2830. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2831. :group 'org-agenda
  2832. :group 'org-time
  2833. :version "24.1"
  2834. :type '(choice
  2835. (const :tag "Use org-read-date-prefer-future"
  2836. org-read-date-prefer-future)
  2837. (const :tag "Never" nil)
  2838. (const :tag "Always" t)))
  2839. (defcustom org-read-date-force-compatible-dates t
  2840. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2841. Depending on the system Emacs is running on, certain dates cannot
  2842. be represented with the type used internally to represent time.
  2843. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2844. correctly. Some systems allow for earlier dates, some for later,
  2845. some for both. One way to find out it to insert any date into an
  2846. Org buffer, putting the cursor on the year and hitting S-up and
  2847. S-down to test the range.
  2848. When this variable is set to t, the date/time prompt will not let
  2849. you specify dates outside the 1970-2037 range, so it is certain that
  2850. these dates will work in whatever version of Emacs you are
  2851. running, and also that you can move a file from one Emacs implementation
  2852. to another. WHenever Org is forcing the year for you, it will display
  2853. a message and beep.
  2854. When this variable is nil, Org will check if the date is
  2855. representable in the specific Emacs implementation you are using.
  2856. If not, it will force a year, usually the current year, and beep
  2857. to remind you. Currently this setting is not recommended because
  2858. the likelihood that you will open your Org files in an Emacs that
  2859. has limited date range is not negligible.
  2860. A workaround for this problem is to use diary sexp dates for time
  2861. stamps outside of this range."
  2862. :group 'org-time
  2863. :version "24.1"
  2864. :type 'boolean)
  2865. (defcustom org-read-date-display-live t
  2866. "Non-nil means display current interpretation of date prompt live.
  2867. This display will be in an overlay, in the minibuffer."
  2868. :group 'org-time
  2869. :type 'boolean)
  2870. (defcustom org-read-date-popup-calendar t
  2871. "Non-nil means pop up a calendar when prompting for a date.
  2872. In the calendar, the date can be selected with mouse-1. However, the
  2873. minibuffer will also be active, and you can simply enter the date as well.
  2874. When nil, only the minibuffer will be available."
  2875. :group 'org-time
  2876. :type 'boolean)
  2877. (defvaralias 'org-popup-calendar-for-date-prompt
  2878. 'org-read-date-popup-calendar)
  2879. (defcustom org-extend-today-until 0
  2880. "The hour when your day really ends. Must be an integer.
  2881. This has influence for the following applications:
  2882. - When switching the agenda to \"today\". It it is still earlier than
  2883. the time given here, the day recognized as TODAY is actually yesterday.
  2884. - When a date is read from the user and it is still before the time given
  2885. here, the current date and time will be assumed to be yesterday, 23:59.
  2886. Also, timestamps inserted in capture templates follow this rule.
  2887. IMPORTANT: This is a feature whose implementation is and likely will
  2888. remain incomplete. Really, it is only here because past midnight seems to
  2889. be the favorite working time of John Wiegley :-)"
  2890. :group 'org-time
  2891. :type 'integer)
  2892. (defcustom org-use-effective-time nil
  2893. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2894. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2895. \"effective time\" of any timestamps between midnight and 8am will be
  2896. 23:59 of the previous day."
  2897. :group 'org-time
  2898. :version "24.1"
  2899. :type 'boolean)
  2900. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2901. "When non-nil, use the last clock out time for `org-todo'.
  2902. Note that this option has precedence over the combined use of
  2903. `org-use-effective-time' and `org-extend-today-until'."
  2904. :group 'org-time
  2905. :version "24.4"
  2906. :package-version '(Org . "8.0")
  2907. :type 'boolean)
  2908. (defcustom org-edit-timestamp-down-means-later nil
  2909. "Non-nil means S-down will increase the time in a time stamp.
  2910. When nil, S-up will increase."
  2911. :group 'org-time
  2912. :type 'boolean)
  2913. (defcustom org-calendar-follow-timestamp-change t
  2914. "Non-nil means make the calendar window follow timestamp changes.
  2915. When a timestamp is modified and the calendar window is visible, it will be
  2916. moved to the new date."
  2917. :group 'org-time
  2918. :type 'boolean)
  2919. (defgroup org-tags nil
  2920. "Options concerning tags in Org mode."
  2921. :tag "Org Tags"
  2922. :group 'org)
  2923. (defcustom org-tag-alist nil
  2924. "Default tags available in Org files.
  2925. The value of this variable is an alist. Associations either:
  2926. (TAG)
  2927. (TAG . SELECT)
  2928. (SPECIAL)
  2929. where TAG is a tag as a string, SELECT is character, used to
  2930. select that tag through the fast tag selection interface, and
  2931. SPECIAL is one of the following keywords: `:startgroup',
  2932. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2933. `:newline'. These keywords are used to define a hierarchy of
  2934. tags. See manual for details.
  2935. When this variable is nil, Org mode bases tag input on what is
  2936. already in the buffer. The value can be overridden locally by
  2937. using a TAGS keyword, e.g.,
  2938. #+TAGS: tag1 tag2
  2939. See also `org-tag-persistent-alist' to sidestep this behavior."
  2940. :group 'org-tags
  2941. :type '(repeat
  2942. (choice
  2943. (cons :tag "Tag with key"
  2944. (string :tag "Tag name")
  2945. (character :tag "Access char"))
  2946. (list :tag "Tag" (string :tag "Tag name"))
  2947. (const :tag "Start radio group" (:startgroup))
  2948. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2949. (const :tag "Group tags delimiter" (:grouptags))
  2950. (const :tag "End radio group" (:endgroup))
  2951. (const :tag "End tag group, non distinct" (:endgrouptag))
  2952. (const :tag "New line" (:newline)))))
  2953. (defcustom org-tag-persistent-alist nil
  2954. "Tags always available in Org files.
  2955. The value of this variable is an alist. Associations either:
  2956. (TAG)
  2957. (TAG . SELECT)
  2958. (SPECIAL)
  2959. where TAG is a tag as a string, SELECT is a character, used to
  2960. select that tag through the fast tag selection interface, and
  2961. SPECIAL is one of the following keywords: `:startgroup',
  2962. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2963. `:newline'. These keywords are used to define a hierarchy of
  2964. tags. See manual for details.
  2965. Unlike to `org-tag-alist', tags defined in this variable do not
  2966. depend on a local TAGS keyword. Instead, to disable these tags
  2967. on a per-file basis, insert anywhere in the file:
  2968. #+STARTUP: noptag"
  2969. :group 'org-tags
  2970. :type '(repeat
  2971. (choice
  2972. (cons :tag "Tag with key"
  2973. (string :tag "Tag name")
  2974. (character :tag "Access char"))
  2975. (list :tag "Tag" (string :tag "Tag name"))
  2976. (const :tag "Start radio group" (:startgroup))
  2977. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2978. (const :tag "Group tags delimiter" (:grouptags))
  2979. (const :tag "End radio group" (:endgroup))
  2980. (const :tag "End tag group, non distinct" (:endgrouptag))
  2981. (const :tag "New line" (:newline)))))
  2982. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2983. "If non-nil, always offer completion for all tags of all agenda files.
  2984. Instead of customizing this variable directly, you might want to
  2985. set it locally for capture buffers, because there no list of
  2986. tags in that file can be created dynamically (there are none).
  2987. (add-hook \\='org-capture-mode-hook
  2988. (lambda ()
  2989. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2990. :group 'org-tags
  2991. :version "24.1"
  2992. :type 'boolean)
  2993. (defvar org-file-tags nil
  2994. "List of tags that can be inherited by all entries in the file.
  2995. The tags will be inherited if the variable `org-use-tag-inheritance'
  2996. says they should be.
  2997. This variable is populated from #+FILETAGS lines.")
  2998. (defcustom org-use-fast-tag-selection 'auto
  2999. "Non-nil means use fast tag selection scheme.
  3000. This is a special interface to select and deselect tags with single keys.
  3001. When nil, fast selection is never used.
  3002. When the symbol `auto', fast selection is used if and only if selection
  3003. characters for tags have been configured, either through the variable
  3004. `org-tag-alist' or through a #+TAGS line in the buffer.
  3005. When t, fast selection is always used and selection keys are assigned
  3006. automatically if necessary."
  3007. :group 'org-tags
  3008. :type '(choice
  3009. (const :tag "Always" t)
  3010. (const :tag "Never" nil)
  3011. (const :tag "When selection characters are configured" auto)))
  3012. (defcustom org-fast-tag-selection-single-key nil
  3013. "Non-nil means fast tag selection exits after first change.
  3014. When nil, you have to press RET to exit it.
  3015. During fast tag selection, you can toggle this flag with `C-c'.
  3016. This variable can also have the value `expert'. In this case, the window
  3017. displaying the tags menu is not even shown, until you press C-c again."
  3018. :group 'org-tags
  3019. :type '(choice
  3020. (const :tag "No" nil)
  3021. (const :tag "Yes" t)
  3022. (const :tag "Expert" expert)))
  3023. (defvar org-fast-tag-selection-include-todo nil
  3024. "Non-nil means fast tags selection interface will also offer TODO states.
  3025. This is an undocumented feature, you should not rely on it.")
  3026. (defcustom org-tags-column -77
  3027. "The column to which tags should be indented in a headline.
  3028. If this number is positive, it specifies the column. If it is negative,
  3029. it means that the tags should be flushright to that column. For example,
  3030. -80 works well for a normal 80 character screen.
  3031. When 0, place tags directly after headline text, with only one space in
  3032. between."
  3033. :group 'org-tags
  3034. :type 'integer)
  3035. (defcustom org-auto-align-tags t
  3036. "Non-nil keeps tags aligned when modifying headlines.
  3037. Some operations (i.e. demoting) change the length of a headline and
  3038. therefore shift the tags around. With this option turned on, after
  3039. each such operation the tags are again aligned to `org-tags-column'."
  3040. :group 'org-tags
  3041. :type 'boolean)
  3042. (defcustom org-use-tag-inheritance t
  3043. "Non-nil means tags in levels apply also for sublevels.
  3044. When nil, only the tags directly given in a specific line apply there.
  3045. This may also be a list of tags that should be inherited, or a regexp that
  3046. matches tags that should be inherited. Additional control is possible
  3047. with the variable `org-tags-exclude-from-inheritance' which gives an
  3048. explicit list of tags to be excluded from inheritance, even if the value of
  3049. `org-use-tag-inheritance' would select it for inheritance.
  3050. If this option is t, a match early-on in a tree can lead to a large
  3051. number of matches in the subtree when constructing the agenda or creating
  3052. a sparse tree. If you only want to see the first match in a tree during
  3053. a search, check out the variable `org-tags-match-list-sublevels'."
  3054. :group 'org-tags
  3055. :type '(choice
  3056. (const :tag "Not" nil)
  3057. (const :tag "Always" t)
  3058. (repeat :tag "Specific tags" (string :tag "Tag"))
  3059. (regexp :tag "Tags matched by regexp")))
  3060. (defcustom org-tags-exclude-from-inheritance nil
  3061. "List of tags that should never be inherited.
  3062. This is a way to exclude a few tags from inheritance. For way to do
  3063. the opposite, to actively allow inheritance for selected tags,
  3064. see the variable `org-use-tag-inheritance'."
  3065. :group 'org-tags
  3066. :type '(repeat (string :tag "Tag")))
  3067. (defun org-tag-inherit-p (tag)
  3068. "Check if TAG is one that should be inherited."
  3069. (cond
  3070. ((member tag org-tags-exclude-from-inheritance) nil)
  3071. ((eq org-use-tag-inheritance t) t)
  3072. ((not org-use-tag-inheritance) nil)
  3073. ((stringp org-use-tag-inheritance)
  3074. (string-match org-use-tag-inheritance tag))
  3075. ((listp org-use-tag-inheritance)
  3076. (member tag org-use-tag-inheritance))
  3077. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3078. (defcustom org-tags-match-list-sublevels t
  3079. "Non-nil means list also sublevels of headlines matching a search.
  3080. This variable applies to tags/property searches, and also to stuck
  3081. projects because this search is based on a tags match as well.
  3082. When set to the symbol `indented', sublevels are indented with
  3083. leading dots.
  3084. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3085. the sublevels of a headline matching a tag search often also match
  3086. the same search. Listing all of them can create very long lists.
  3087. Setting this variable to nil causes subtrees of a match to be skipped.
  3088. This variable is semi-obsolete and probably should always be true. It
  3089. is better to limit inheritance to certain tags using the variables
  3090. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3091. :group 'org-tags
  3092. :type '(choice
  3093. (const :tag "No, don't list them" nil)
  3094. (const :tag "Yes, do list them" t)
  3095. (const :tag "List them, indented with leading dots" indented)))
  3096. (defcustom org-tags-sort-function nil
  3097. "When set, tags are sorted using this function as a comparator."
  3098. :group 'org-tags
  3099. :type '(choice
  3100. (const :tag "No sorting" nil)
  3101. (const :tag "Alphabetical" string<)
  3102. (const :tag "Reverse alphabetical" string>)
  3103. (function :tag "Custom function" nil)))
  3104. (defvar org-tags-history nil
  3105. "History of minibuffer reads for tags.")
  3106. (defvar org-last-tags-completion-table nil
  3107. "The last used completion table for tags.")
  3108. (defvar org-after-tags-change-hook nil
  3109. "Hook that is run after the tags in a line have changed.")
  3110. (defgroup org-properties nil
  3111. "Options concerning properties in Org mode."
  3112. :tag "Org Properties"
  3113. :group 'org)
  3114. (defcustom org-property-format "%-10s %s"
  3115. "How property key/value pairs should be formatted by `indent-line'.
  3116. When `indent-line' hits a property definition, it will format the line
  3117. according to this format, mainly to make sure that the values are
  3118. lined-up with respect to each other."
  3119. :group 'org-properties
  3120. :type 'string)
  3121. (defcustom org-properties-postprocess-alist nil
  3122. "Alist of properties and functions to adjust inserted values.
  3123. Elements of this alist must be of the form
  3124. ([string] [function])
  3125. where [string] must be a property name and [function] must be a
  3126. lambda expression: this lambda expression must take one argument,
  3127. the value to adjust, and return the new value as a string.
  3128. For example, this element will allow the property \"Remaining\"
  3129. to be updated wrt the relation between the \"Effort\" property
  3130. and the clock summary:
  3131. ((\"Remaining\" (lambda(value)
  3132. (let ((clocksum (org-clock-sum-current-item))
  3133. (effort (org-duration-to-minutes
  3134. (org-entry-get (point) \"Effort\"))))
  3135. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3136. :group 'org-properties
  3137. :version "24.1"
  3138. :type '(alist :key-type (string :tag "Property")
  3139. :value-type (function :tag "Function")))
  3140. (defcustom org-use-property-inheritance nil
  3141. "Non-nil means properties apply also for sublevels.
  3142. This setting is chiefly used during property searches. Turning it on can
  3143. cause significant overhead when doing a search, which is why it is not
  3144. on by default.
  3145. When nil, only the properties directly given in the current entry count.
  3146. When t, every property is inherited. The value may also be a list of
  3147. properties that should have inheritance, or a regular expression matching
  3148. properties that should be inherited.
  3149. However, note that some special properties use inheritance under special
  3150. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3151. and the properties ending in \"_ALL\" when they are used as descriptor
  3152. for valid values of a property.
  3153. Note for programmers:
  3154. When querying an entry with `org-entry-get', you can control if inheritance
  3155. should be used. By default, `org-entry-get' looks only at the local
  3156. properties. You can request inheritance by setting the inherit argument
  3157. to t (to force inheritance) or to `selective' (to respect the setting
  3158. in this variable)."
  3159. :group 'org-properties
  3160. :type '(choice
  3161. (const :tag "Not" nil)
  3162. (const :tag "Always" t)
  3163. (repeat :tag "Specific properties" (string :tag "Property"))
  3164. (regexp :tag "Properties matched by regexp")))
  3165. (defun org-property-inherit-p (property)
  3166. "Return a non-nil value if PROPERTY should be inherited."
  3167. (cond
  3168. ((eq org-use-property-inheritance t) t)
  3169. ((not org-use-property-inheritance) nil)
  3170. ((stringp org-use-property-inheritance)
  3171. (string-match org-use-property-inheritance property))
  3172. ((listp org-use-property-inheritance)
  3173. (member-ignore-case property org-use-property-inheritance))
  3174. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3175. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3176. "The default column format, if no other format has been defined.
  3177. This variable can be set on the per-file basis by inserting a line
  3178. #+COLUMNS: %25ITEM ....."
  3179. :group 'org-properties
  3180. :type 'string)
  3181. (defcustom org-columns-ellipses ".."
  3182. "The ellipses to be used when a field in column view is truncated.
  3183. When this is the empty string, as many characters as possible are shown,
  3184. but then there will be no visual indication that the field has been truncated.
  3185. When this is a string of length N, the last N characters of a truncated
  3186. field are replaced by this string. If the column is narrower than the
  3187. ellipses string, only part of the ellipses string will be shown."
  3188. :group 'org-properties
  3189. :type 'string)
  3190. (defconst org-global-properties-fixed
  3191. '(("VISIBILITY_ALL" . "folded children content all")
  3192. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3193. "List of property/value pairs that can be inherited by any entry.
  3194. These are fixed values, for the preset properties. The user variable
  3195. that can be used to add to this list is `org-global-properties'.
  3196. The entries in this list are cons cells where the car is a property
  3197. name and cdr is a string with the value. If the value represents
  3198. multiple items like an \"_ALL\" property, separate the items by
  3199. spaces.")
  3200. (defcustom org-global-properties nil
  3201. "List of property/value pairs that can be inherited by any entry.
  3202. This list will be combined with the constant `org-global-properties-fixed'.
  3203. The entries in this list are cons cells where the car is a property
  3204. name and cdr is a string with the value.
  3205. You can set buffer-local values for the same purpose in the variable
  3206. `org-file-properties' this by adding lines like
  3207. #+PROPERTY: NAME VALUE"
  3208. :group 'org-properties
  3209. :type '(repeat
  3210. (cons (string :tag "Property")
  3211. (string :tag "Value"))))
  3212. (defvar-local org-file-properties nil
  3213. "List of property/value pairs that can be inherited by any entry.
  3214. Valid for the current buffer.
  3215. This variable is populated from #+PROPERTY lines.")
  3216. (defgroup org-agenda nil
  3217. "Options concerning agenda views in Org mode."
  3218. :tag "Org Agenda"
  3219. :group 'org)
  3220. (defvar-local org-category nil
  3221. "Variable used by org files to set a category for agenda display.
  3222. Such files should use a file variable to set it, for example
  3223. # -*- mode: org; org-category: \"ELisp\"
  3224. or contain a special line
  3225. #+CATEGORY: ELisp
  3226. If the file does not specify a category, then file's base name
  3227. is used instead.")
  3228. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3229. (defcustom org-agenda-files nil
  3230. "The files to be used for agenda display.
  3231. If an entry is a directory, all files in that directory that are matched
  3232. by `org-agenda-file-regexp' will be part of the file list.
  3233. If the value of the variable is not a list but a single file name, then
  3234. the list of agenda files is actually stored and maintained in that file,
  3235. one agenda file per line. In this file paths can be given relative to
  3236. `org-directory'. Tilde expansion and environment variable substitution
  3237. are also made.
  3238. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3239. and removed with `\\[org-remove-file]'."
  3240. :group 'org-agenda
  3241. :type '(choice
  3242. (repeat :tag "List of files and directories" file)
  3243. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3244. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3245. "Regular expression to match files for `org-agenda-files'.
  3246. If any element in the list in that variable contains a directory instead
  3247. of a normal file, all files in that directory that are matched by this
  3248. regular expression will be included."
  3249. :group 'org-agenda
  3250. :type 'regexp)
  3251. (defcustom org-agenda-text-search-extra-files nil
  3252. "List of extra files to be searched by text search commands.
  3253. These files will be searched in addition to the agenda files by the
  3254. commands `org-search-view' (`\\[org-agenda] s') \
  3255. and `org-occur-in-agenda-files'.
  3256. Note that these files will only be searched for text search commands,
  3257. not for the other agenda views like todo lists, tag searches or the weekly
  3258. agenda. This variable is intended to list notes and possibly archive files
  3259. that should also be searched by these two commands.
  3260. In fact, if the first element in the list is the symbol `agenda-archives',
  3261. then all archive files of all agenda files will be added to the search
  3262. scope."
  3263. :group 'org-agenda
  3264. :type '(set :greedy t
  3265. (const :tag "Agenda Archives" agenda-archives)
  3266. (repeat :inline t (file))))
  3267. (defvaralias 'org-agenda-multi-occur-extra-files
  3268. 'org-agenda-text-search-extra-files)
  3269. (defcustom org-agenda-skip-unavailable-files nil
  3270. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3271. A nil value means to remove them, after a query, from the list."
  3272. :group 'org-agenda
  3273. :type 'boolean)
  3274. (defcustom org-calendar-to-agenda-key [?c]
  3275. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3276. The command `org-calendar-goto-agenda' will be bound to this key. The
  3277. default is the character `c' because then `c' can be used to switch back and
  3278. forth between agenda and calendar."
  3279. :group 'org-agenda
  3280. :type 'sexp)
  3281. (defcustom org-calendar-insert-diary-entry-key [?i]
  3282. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3283. This option is irrelevant until `org-agenda-diary-file' has been configured
  3284. to point to an Org file. When that is the case, the command
  3285. `org-agenda-diary-entry' will be bound to the key given here, by default
  3286. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3287. if you want to continue doing this, you need to change this to a different
  3288. key."
  3289. :group 'org-agenda
  3290. :type 'sexp)
  3291. (defcustom org-agenda-diary-file 'diary-file
  3292. "File to which to add new entries with the `i' key in agenda and calendar.
  3293. When this is the symbol `diary-file', the functionality in the Emacs
  3294. calendar will be used to add entries to the `diary-file'. But when this
  3295. points to a file, `org-agenda-diary-entry' will be used instead."
  3296. :group 'org-agenda
  3297. :type '(choice
  3298. (const :tag "The standard Emacs diary file" diary-file)
  3299. (file :tag "Special Org file diary entries")))
  3300. (eval-after-load "calendar"
  3301. '(progn
  3302. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3303. 'org-calendar-goto-agenda)
  3304. (add-hook 'calendar-mode-hook
  3305. (lambda ()
  3306. (unless (eq org-agenda-diary-file 'diary-file)
  3307. (define-key calendar-mode-map
  3308. org-calendar-insert-diary-entry-key
  3309. 'org-agenda-diary-entry))))))
  3310. (defgroup org-latex nil
  3311. "Options for embedding LaTeX code into Org mode."
  3312. :tag "Org LaTeX"
  3313. :group 'org)
  3314. (defcustom org-format-latex-options
  3315. '(:foreground default :background default :scale 1.0
  3316. :html-foreground "Black" :html-background "Transparent"
  3317. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3318. "Options for creating images from LaTeX fragments.
  3319. This is a property list with the following properties:
  3320. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3321. `default' means use the foreground of the default face.
  3322. `auto' means use the foreground from the text face.
  3323. :background the background color, or \"Transparent\".
  3324. `default' means use the background of the default face.
  3325. `auto' means use the background from the text face.
  3326. :scale a scaling factor for the size of the images, to get more pixels
  3327. :html-foreground, :html-background, :html-scale
  3328. the same numbers for HTML export.
  3329. :matchers a list indicating which matchers should be used to
  3330. find LaTeX fragments. Valid members of this list are:
  3331. \"begin\" find environments
  3332. \"$1\" find single characters surrounded by $.$
  3333. \"$\" find math expressions surrounded by $...$
  3334. \"$$\" find math expressions surrounded by $$....$$
  3335. \"\\(\" find math expressions surrounded by \\(...\\)
  3336. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3337. :group 'org-latex
  3338. :type 'plist)
  3339. (defcustom org-format-latex-signal-error t
  3340. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3341. When nil, just push out a message."
  3342. :group 'org-latex
  3343. :version "24.1"
  3344. :type 'boolean)
  3345. (defcustom org-latex-to-mathml-jar-file nil
  3346. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3347. Use this to specify additional executable file say a jar file.
  3348. When using MathToWeb as the converter, specify the full-path to
  3349. your mathtoweb.jar file."
  3350. :group 'org-latex
  3351. :version "24.1"
  3352. :type '(choice
  3353. (const :tag "None" nil)
  3354. (file :tag "JAR file" :must-match t)))
  3355. (defcustom org-latex-to-mathml-convert-command nil
  3356. "Command to convert LaTeX fragments to MathML.
  3357. Replace format-specifiers in the command as noted below and use
  3358. `shell-command' to convert LaTeX to MathML.
  3359. %j: Executable file in fully expanded form as specified by
  3360. `org-latex-to-mathml-jar-file'.
  3361. %I: Input LaTeX file in fully expanded form.
  3362. %i: The latex fragment to be converted.
  3363. %o: Output MathML file.
  3364. This command is used by `org-create-math-formula'.
  3365. When using MathToWeb as the converter, set this option to
  3366. \"java -jar %j -unicode -force -df %o %I\".
  3367. When using LaTeXML set this option to
  3368. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3369. :group 'org-latex
  3370. :version "24.1"
  3371. :type '(choice
  3372. (const :tag "None" nil)
  3373. (string :tag "\nShell command")))
  3374. (defcustom org-preview-latex-default-process 'dvipng
  3375. "The default process to convert LaTeX fragments to image files.
  3376. All available processes and theirs documents can be found in
  3377. `org-preview-latex-process-alist', which see."
  3378. :group 'org-latex
  3379. :version "26.1"
  3380. :package-version '(Org . "9.0")
  3381. :type 'symbol)
  3382. (defcustom org-preview-latex-process-alist
  3383. '((dvipng
  3384. :programs ("latex" "dvipng")
  3385. :description "dvi > png"
  3386. :message "you need to install the programs: latex and dvipng."
  3387. :image-input-type "dvi"
  3388. :image-output-type "png"
  3389. :image-size-adjust (1.0 . 1.0)
  3390. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3391. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3392. (dvisvgm
  3393. :programs ("latex" "dvisvgm")
  3394. :description "dvi > svg"
  3395. :message "you need to install the programs: latex and dvisvgm."
  3396. :use-xcolor t
  3397. :image-input-type "dvi"
  3398. :image-output-type "svg"
  3399. :image-size-adjust (1.7 . 1.5)
  3400. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3401. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3402. (imagemagick
  3403. :programs ("latex" "convert")
  3404. :description "pdf > png"
  3405. :message "you need to install the programs: latex and imagemagick."
  3406. :use-xcolor t
  3407. :image-input-type "pdf"
  3408. :image-output-type "png"
  3409. :image-size-adjust (1.0 . 1.0)
  3410. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3411. :image-converter
  3412. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3413. "Definitions of external processes for LaTeX previewing.
  3414. Org mode can use some external commands to generate TeX snippet's images for
  3415. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3416. `org-create-formula-image' how to call them.
  3417. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3418. PROPERTIES accepts the following attributes:
  3419. :programs list of strings, required programs.
  3420. :description string, describe the process.
  3421. :message string, message it when required programs cannot be found.
  3422. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3423. :image-output-type string, output file type of image converter (e.g., \"png\").
  3424. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3425. deal with background and foreground color of image.
  3426. Otherwise, dvipng style background and foreground color
  3427. format are generated. You may then refer to them in
  3428. command options with \"%F\" and \"%B\".
  3429. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3430. image size showed in buffer and the cdr element is for
  3431. HTML file. This option is only useful for process
  3432. developers, users should use variable
  3433. `org-format-latex-options' instead.
  3434. :post-clean list of strings, files matched are to be cleaned up once
  3435. the image is generated. When nil, the files with \".dvi\",
  3436. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3437. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3438. be cleaned up.
  3439. :latex-header list of strings, the LaTeX header of the snippet file.
  3440. When nil, the fallback value is used instead, which is
  3441. controlled by `org-format-latex-header',
  3442. `org-latex-default-packages-alist' and
  3443. `org-latex-packages-alist', which see.
  3444. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3445. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3446. replaced with values defined below.
  3447. :image-converter list of image converter commands strings. Each of them is
  3448. given to the shell and supports any of the following
  3449. place-holders defined below.
  3450. Place-holders used by `:image-converter' and `:latex-compiler':
  3451. %f input file name
  3452. %b base name of input file
  3453. %o base directory of input file
  3454. %O absolute output file name
  3455. Place-holders only used by `:image-converter':
  3456. %F foreground of image
  3457. %B background of image
  3458. %D dpi, which is used to adjust image size by some processing commands.
  3459. %S the image size scale ratio, which is used to adjust image size by some
  3460. processing commands."
  3461. :group 'org-latex
  3462. :version "26.1"
  3463. :package-version '(Org . "9.0")
  3464. :type '(alist :tag "LaTeX to image backends"
  3465. :value-type (plist)))
  3466. (defcustom org-preview-latex-image-directory "ltximg/"
  3467. "Path to store latex preview images.
  3468. A relative path here creates many directories relative to the
  3469. processed org files paths. An absolute path puts all preview
  3470. images at the same place."
  3471. :group 'org-latex
  3472. :version "26.1"
  3473. :package-version '(Org . "9.0")
  3474. :type 'string)
  3475. (defun org-format-latex-mathml-available-p ()
  3476. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3477. (save-match-data
  3478. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3479. org-latex-to-mathml-convert-command)
  3480. (let ((executable (car (split-string
  3481. org-latex-to-mathml-convert-command))))
  3482. (when (executable-find executable)
  3483. (if (string-match
  3484. "%j" org-latex-to-mathml-convert-command)
  3485. (file-readable-p org-latex-to-mathml-jar-file)
  3486. t))))))
  3487. (defcustom org-format-latex-header "\\documentclass{article}
  3488. \\usepackage[usenames]{color}
  3489. \[PACKAGES]
  3490. \[DEFAULT-PACKAGES]
  3491. \\pagestyle{empty} % do not remove
  3492. % The settings below are copied from fullpage.sty
  3493. \\setlength{\\textwidth}{\\paperwidth}
  3494. \\addtolength{\\textwidth}{-3cm}
  3495. \\setlength{\\oddsidemargin}{1.5cm}
  3496. \\addtolength{\\oddsidemargin}{-2.54cm}
  3497. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3498. \\setlength{\\textheight}{\\paperheight}
  3499. \\addtolength{\\textheight}{-\\headheight}
  3500. \\addtolength{\\textheight}{-\\headsep}
  3501. \\addtolength{\\textheight}{-\\footskip}
  3502. \\addtolength{\\textheight}{-3cm}
  3503. \\setlength{\\topmargin}{1.5cm}
  3504. \\addtolength{\\topmargin}{-2.54cm}"
  3505. "The document header used for processing LaTeX fragments.
  3506. It is imperative that this header make sure that no page number
  3507. appears on the page. The package defined in the variables
  3508. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3509. will either replace the placeholder \"[PACKAGES]\" in this
  3510. header, or they will be appended."
  3511. :group 'org-latex
  3512. :type 'string)
  3513. (defun org-set-packages-alist (var val)
  3514. "Set the packages alist and make sure it has 3 elements per entry."
  3515. (set var (mapcar (lambda (x)
  3516. (if (and (consp x) (= (length x) 2))
  3517. (list (car x) (nth 1 x) t)
  3518. x))
  3519. val)))
  3520. (defun org-get-packages-alist (var)
  3521. "Get the packages alist and make sure it has 3 elements per entry."
  3522. (mapcar (lambda (x)
  3523. (if (and (consp x) (= (length x) 2))
  3524. (list (car x) (nth 1 x) t)
  3525. x))
  3526. (default-value var)))
  3527. (defcustom org-latex-default-packages-alist
  3528. '(("AUTO" "inputenc" t ("pdflatex"))
  3529. ("T1" "fontenc" t ("pdflatex"))
  3530. ("" "graphicx" t)
  3531. ("" "grffile" t)
  3532. ("" "longtable" nil)
  3533. ("" "wrapfig" nil)
  3534. ("" "rotating" nil)
  3535. ("normalem" "ulem" t)
  3536. ("" "amsmath" t)
  3537. ("" "textcomp" t)
  3538. ("" "amssymb" t)
  3539. ("" "capt-of" nil)
  3540. ("" "hyperref" nil))
  3541. "Alist of default packages to be inserted in the header.
  3542. Change this only if one of the packages here causes an
  3543. incompatibility with another package you are using.
  3544. The packages in this list are needed by one part or another of
  3545. Org mode to function properly:
  3546. - inputenc, fontenc: for basic font and character selection
  3547. - graphicx: for including images
  3548. - grffile: allow periods and spaces in graphics file names
  3549. - longtable: For multipage tables
  3550. - wrapfig: for figure placement
  3551. - rotating: for sideways figures and tables
  3552. - ulem: for underline and strike-through
  3553. - amsmath: for subscript and superscript and math environments
  3554. - textcomp, amssymb: for various symbols used
  3555. for interpreting the entities in `org-entities'. You can skip
  3556. some of these packages if you don't use any of their symbols.
  3557. - capt-of: for captions outside of floats
  3558. - hyperref: for cross references
  3559. Therefore you should not modify this variable unless you know
  3560. what you are doing. The one reason to change it anyway is that
  3561. you might be loading some other package that conflicts with one
  3562. of the default packages. Each element is either a cell or
  3563. a string.
  3564. A cell is of the format
  3565. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3566. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3567. when compiling LaTeX snippets into images for inclusion into
  3568. non-LaTeX output. COMPILERS is a list of compilers that should
  3569. include the package, see `org-latex-compiler'. If the document
  3570. compiler is not in the list, and the list is non-nil, the package
  3571. will not be inserted in the final document.
  3572. A string will be inserted as-is in the header of the document."
  3573. :group 'org-latex
  3574. :group 'org-export-latex
  3575. :set 'org-set-packages-alist
  3576. :get 'org-get-packages-alist
  3577. :version "26.1"
  3578. :package-version '(Org . "8.3")
  3579. :type '(repeat
  3580. (choice
  3581. (list :tag "options/package pair"
  3582. (string :tag "options")
  3583. (string :tag "package")
  3584. (boolean :tag "Snippet"))
  3585. (string :tag "A line of LaTeX"))))
  3586. (defcustom org-latex-packages-alist nil
  3587. "Alist of packages to be inserted in every LaTeX header.
  3588. These will be inserted after `org-latex-default-packages-alist'.
  3589. Each element is either a cell or a string.
  3590. A cell is of the format:
  3591. (\"options\" \"package\" SNIPPET-FLAG)
  3592. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3593. needed when turning LaTeX snippets into images for inclusion into
  3594. non-LaTeX output.
  3595. A string will be inserted as-is in the header of the document.
  3596. Make sure that you only list packages here which:
  3597. - you want in every file;
  3598. - do not conflict with the setup in `org-format-latex-header';
  3599. - do not conflict with the default packages in
  3600. `org-latex-default-packages-alist'."
  3601. :group 'org-latex
  3602. :group 'org-export-latex
  3603. :set 'org-set-packages-alist
  3604. :get 'org-get-packages-alist
  3605. :type '(repeat
  3606. (choice
  3607. (list :tag "options/package pair"
  3608. (string :tag "options")
  3609. (string :tag "package")
  3610. (boolean :tag "Snippet"))
  3611. (string :tag "A line of LaTeX"))))
  3612. (defgroup org-appearance nil
  3613. "Settings for Org mode appearance."
  3614. :tag "Org Appearance"
  3615. :group 'org)
  3616. (defcustom org-level-color-stars-only nil
  3617. "Non-nil means fontify only the stars in each headline.
  3618. When nil, the entire headline is fontified.
  3619. Changing it requires restart of `font-lock-mode' to become effective
  3620. also in regions already fontified."
  3621. :group 'org-appearance
  3622. :type 'boolean)
  3623. (defcustom org-hide-leading-stars nil
  3624. "Non-nil means hide the first N-1 stars in a headline.
  3625. This works by using the face `org-hide' for these stars. This
  3626. face is white for a light background, and black for a dark
  3627. background. You may have to customize the face `org-hide' to
  3628. make this work.
  3629. Changing it requires restart of `font-lock-mode' to become effective
  3630. also in regions already fontified.
  3631. You may also set this on a per-file basis by adding one of the following
  3632. lines to the buffer:
  3633. #+STARTUP: hidestars
  3634. #+STARTUP: showstars"
  3635. :group 'org-appearance
  3636. :type 'boolean)
  3637. (defcustom org-hidden-keywords nil
  3638. "List of symbols corresponding to keywords to be hidden the org buffer.
  3639. For example, a value \\='(title) for this list will make the document's title
  3640. appear in the buffer without the initial #+TITLE: keyword."
  3641. :group 'org-appearance
  3642. :version "24.1"
  3643. :type '(set (const :tag "#+AUTHOR" author)
  3644. (const :tag "#+DATE" date)
  3645. (const :tag "#+EMAIL" email)
  3646. (const :tag "#+TITLE" title)))
  3647. (defcustom org-custom-properties nil
  3648. "List of properties (as strings) with a special meaning.
  3649. The default use of these custom properties is to let the user
  3650. hide them with `org-toggle-custom-properties-visibility'."
  3651. :group 'org-properties
  3652. :group 'org-appearance
  3653. :version "24.3"
  3654. :type '(repeat (string :tag "Property Name")))
  3655. (defcustom org-fontify-done-headline nil
  3656. "Non-nil means change the face of a headline if it is marked DONE.
  3657. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3658. When this is non-nil, the headline after the keyword is set to the
  3659. `org-headline-done' as an additional indication."
  3660. :group 'org-appearance
  3661. :type 'boolean)
  3662. (defcustom org-fontify-emphasized-text t
  3663. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3664. Changing this variable requires a restart of Emacs to take effect."
  3665. :group 'org-appearance
  3666. :type 'boolean)
  3667. (defcustom org-fontify-whole-heading-line nil
  3668. "Non-nil means fontify the whole line for headings.
  3669. This is useful when setting a background color for the
  3670. org-level-* faces."
  3671. :group 'org-appearance
  3672. :type 'boolean)
  3673. (defcustom org-highlight-latex-and-related nil
  3674. "Non-nil means highlight LaTeX related syntax in the buffer.
  3675. When non nil, the value should be a list containing any of the
  3676. following symbols:
  3677. `latex' Highlight LaTeX snippets and environments.
  3678. `script' Highlight subscript and superscript.
  3679. `entities' Highlight entities."
  3680. :group 'org-appearance
  3681. :version "24.4"
  3682. :package-version '(Org . "8.0")
  3683. :type '(choice
  3684. (const :tag "No highlighting" nil)
  3685. (set :greedy t :tag "Highlight"
  3686. (const :tag "LaTeX snippets and environments" latex)
  3687. (const :tag "Subscript and superscript" script)
  3688. (const :tag "Entities" entities))))
  3689. (defcustom org-hide-emphasis-markers nil
  3690. "Non-nil mean font-lock should hide the emphasis marker characters."
  3691. :group 'org-appearance
  3692. :type 'boolean)
  3693. (defcustom org-hide-macro-markers nil
  3694. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3695. :group 'org-appearance
  3696. :type 'boolean)
  3697. (defcustom org-pretty-entities nil
  3698. "Non-nil means show entities as UTF8 characters.
  3699. When nil, the \\name form remains in the buffer."
  3700. :group 'org-appearance
  3701. :version "24.1"
  3702. :type 'boolean)
  3703. (defcustom org-pretty-entities-include-sub-superscripts t
  3704. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3705. :group 'org-appearance
  3706. :version "24.1"
  3707. :type 'boolean)
  3708. (defvar org-emph-re nil
  3709. "Regular expression for matching emphasis.
  3710. After a match, the match groups contain these elements:
  3711. 0 The match of the full regular expression, including the characters
  3712. before and after the proper match
  3713. 1 The character before the proper match, or empty at beginning of line
  3714. 2 The proper match, including the leading and trailing markers
  3715. 3 The leading marker like * or /, indicating the type of highlighting
  3716. 4 The text between the emphasis markers, not including the markers
  3717. 5 The character after the match, empty at the end of a line")
  3718. (defvar org-verbatim-re nil
  3719. "Regular expression for matching verbatim text.")
  3720. (defvar org-emphasis-regexp-components) ; defined just below
  3721. (defvar org-emphasis-alist) ; defined just below
  3722. (defun org-set-emph-re (var val)
  3723. "Set variable and compute the emphasis regular expression."
  3724. (set var val)
  3725. (when (and (boundp 'org-emphasis-alist)
  3726. (boundp 'org-emphasis-regexp-components)
  3727. org-emphasis-alist org-emphasis-regexp-components)
  3728. (pcase-let*
  3729. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3730. (body (if (<= nl 0) body
  3731. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3732. (template
  3733. (format (concat "\\([%s]\\|^\\)" ;before markers
  3734. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3735. "\\([%s]\\|$\\)") ;after markers
  3736. pre border border body border post)))
  3737. (setq org-emph-re (format template "*/_+"))
  3738. (setq org-verbatim-re (format template "=~")))))
  3739. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3740. ;; set this option proved cumbersome. See this message/thread:
  3741. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3742. (defvar org-emphasis-regexp-components
  3743. '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3744. "Components used to build the regular expression for emphasis.
  3745. This is a list with five entries. Terminology: In an emphasis string
  3746. like \" *strong word* \", we call the initial space PREMATCH, the final
  3747. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3748. and \"trong wor\" is the body. The different components in this variable
  3749. specify what is allowed/forbidden in each part:
  3750. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3751. post Chars allowed as postmatch. End of line will be allowed too.
  3752. border The chars *forbidden* as border characters.
  3753. body-regexp A regexp like \".\" to match a body character. Don't use
  3754. non-shy groups here, and don't allow newline here.
  3755. newline The maximum number of newlines allowed in an emphasis exp.
  3756. You need to reload Org or to restart Emacs after customizing this.")
  3757. (defcustom org-emphasis-alist
  3758. '(("*" bold)
  3759. ("/" italic)
  3760. ("_" underline)
  3761. ("=" org-verbatim verbatim)
  3762. ("~" org-code verbatim)
  3763. ("+" (:strike-through t)))
  3764. "Alist of characters and faces to emphasize text.
  3765. Text starting and ending with a special character will be emphasized,
  3766. for example *bold*, _underlined_ and /italic/. This variable sets the
  3767. marker characters and the face to be used by font-lock for highlighting
  3768. in Org buffers.
  3769. You need to reload Org or to restart Emacs after customizing this."
  3770. :group 'org-appearance
  3771. :set 'org-set-emph-re
  3772. :version "24.4"
  3773. :package-version '(Org . "8.0")
  3774. :type '(repeat
  3775. (list
  3776. (string :tag "Marker character")
  3777. (choice
  3778. (face :tag "Font-lock-face")
  3779. (plist :tag "Face property list"))
  3780. (option (const verbatim)))))
  3781. (defvar org-protecting-blocks '("src" "example" "export")
  3782. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3783. This is needed for font-lock setup.")
  3784. ;;; Functions and variables from their packages
  3785. ;; Declared here to avoid compiler warnings
  3786. (defvar mark-active)
  3787. ;; Various packages
  3788. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3789. (declare-function calendar-forward-day "cal-move" (arg))
  3790. (declare-function calendar-goto-date "cal-move" (date))
  3791. (declare-function calendar-goto-today "cal-move" ())
  3792. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3793. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3794. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3795. (declare-function cdlatex-tab "ext:cdlatex" ())
  3796. (declare-function dired-get-filename
  3797. "dired"
  3798. (&optional localp no-error-if-not-filep))
  3799. (declare-function iswitchb-read-buffer
  3800. "iswitchb"
  3801. (prompt &optional
  3802. default require-match _predicate start matches-set))
  3803. (declare-function org-agenda-change-all-lines
  3804. "org-agenda"
  3805. (newhead hdmarker &optional fixface just-this))
  3806. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3807. "org-agenda"
  3808. (&optional end))
  3809. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3810. (declare-function org-agenda-format-item
  3811. "org-agenda"
  3812. (extra txt &optional level category tags dotime
  3813. remove-re habitp))
  3814. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3815. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3816. (declare-function org-agenda-save-markers-for-cut-and-paste
  3817. "org-agenda"
  3818. (beg end))
  3819. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3820. (declare-function org-agenda-skip "org-agenda" ())
  3821. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3822. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3823. (declare-function org-indent-mode "org-indent" (&optional arg))
  3824. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3825. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3826. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3827. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3828. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3829. (declare-function parse-time-string "parse-time" (string))
  3830. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3831. (defvar align-mode-rules-list)
  3832. (defvar calc-embedded-close-formula)
  3833. (defvar calc-embedded-open-formula)
  3834. (defvar calc-embedded-open-mode)
  3835. (defvar font-lock-unfontify-region-function)
  3836. (defvar iswitchb-temp-buflist)
  3837. (defvar org-agenda-tags-todo-honor-ignore-options)
  3838. (defvar remember-data-file)
  3839. (defvar texmathp-why)
  3840. ;;;###autoload
  3841. (defun turn-on-orgtbl ()
  3842. "Unconditionally turn on `orgtbl-mode'."
  3843. (require 'org-table)
  3844. (orgtbl-mode 1))
  3845. (defun org-at-table-p (&optional table-type)
  3846. "Non-nil if the cursor is inside an Org table.
  3847. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3848. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3849. (or (not (derived-mode-p 'org-mode))
  3850. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3851. (and e (or table-type
  3852. (eq 'org (org-element-property :type e))))))))
  3853. (defun org-at-table.el-p ()
  3854. "Non-nil when point is at a table.el table."
  3855. (and (org-match-line "[ \t]*[|+]")
  3856. (let ((element (org-element-at-point)))
  3857. (and (eq (org-element-type element) 'table)
  3858. (eq (org-element-property :type element) 'table.el)))))
  3859. (defun org-at-table-hline-p ()
  3860. "Non-nil when point is inside a hline in a table.
  3861. Assume point is already in a table."
  3862. (org-match-line org-table-hline-regexp))
  3863. (defun org-table-map-tables (function &optional quietly)
  3864. "Apply FUNCTION to the start of all tables in the buffer."
  3865. (org-with-wide-buffer
  3866. (goto-char (point-min))
  3867. (while (re-search-forward org-table-any-line-regexp nil t)
  3868. (unless quietly
  3869. (message "Mapping tables: %d%%"
  3870. (floor (* 100.0 (point)) (buffer-size))))
  3871. (beginning-of-line 1)
  3872. (when (and (looking-at org-table-line-regexp)
  3873. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3874. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3875. (save-excursion (funcall function))
  3876. (or (looking-at org-table-line-regexp)
  3877. (forward-char 1)))
  3878. (re-search-forward org-table-any-border-regexp nil 1)))
  3879. (unless quietly (message "Mapping tables: done")))
  3880. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3881. (declare-function org-clock-update-mode-line "org-clock" ())
  3882. (declare-function org-resolve-clocks "org-clock"
  3883. (&optional also-non-dangling-p prompt last-valid))
  3884. (defun org-at-TBLFM-p (&optional pos)
  3885. "Non-nil when point (or POS) is in #+TBLFM line."
  3886. (save-excursion
  3887. (goto-char (or pos (point)))
  3888. (beginning-of-line)
  3889. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3890. (eq (org-element-type (org-element-at-point)) 'table))))
  3891. (defvar org-clock-start-time)
  3892. (defvar org-clock-marker (make-marker)
  3893. "Marker recording the last clock-in.")
  3894. (defvar org-clock-hd-marker (make-marker)
  3895. "Marker recording the last clock-in, but the headline position.")
  3896. (defvar org-clock-heading ""
  3897. "The heading of the current clock entry.")
  3898. (defun org-clock-is-active ()
  3899. "Return the buffer where the clock is currently running.
  3900. Return nil if no clock is running."
  3901. (marker-buffer org-clock-marker))
  3902. (defun org-check-running-clock ()
  3903. "Check if the current buffer contains the running clock.
  3904. If yes, offer to stop it and to save the buffer with the changes."
  3905. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3906. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3907. (buffer-name))))
  3908. (org-clock-out)
  3909. (when (y-or-n-p "Save changed buffer?")
  3910. (save-buffer))))
  3911. (defun org-clocktable-try-shift (dir n)
  3912. "Check if this line starts a clock table, if yes, shift the time block."
  3913. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3914. (org-clocktable-shift dir n)))
  3915. ;;;###autoload
  3916. (defun org-clock-persistence-insinuate ()
  3917. "Set up hooks for clock persistence."
  3918. (require 'org-clock)
  3919. (add-hook 'org-mode-hook 'org-clock-load)
  3920. (add-hook 'kill-emacs-hook 'org-clock-save))
  3921. (defgroup org-archive nil
  3922. "Options concerning archiving in Org mode."
  3923. :tag "Org Archive"
  3924. :group 'org-structure)
  3925. (defcustom org-archive-location "%s_archive::"
  3926. "The location where subtrees should be archived.
  3927. The value of this variable is a string, consisting of two parts,
  3928. separated by a double-colon. The first part is a filename and
  3929. the second part is a headline.
  3930. When the filename is omitted, archiving happens in the same file.
  3931. %s in the filename will be replaced by the current file
  3932. name (without the directory part). Archiving to a different file
  3933. is useful to keep archived entries from contributing to the
  3934. Org Agenda.
  3935. The archived entries will be filed as subtrees of the specified
  3936. headline. When the headline is omitted, the subtrees are simply
  3937. filed away at the end of the file, as top-level entries. Also in
  3938. the heading you can use %s to represent the file name, this can be
  3939. useful when using the same archive for a number of different files.
  3940. Here are a few examples:
  3941. \"%s_archive::\"
  3942. If the current file is Projects.org, archive in file
  3943. Projects.org_archive, as top-level trees. This is the default.
  3944. \"::* Archived Tasks\"
  3945. Archive in the current file, under the top-level headline
  3946. \"* Archived Tasks\".
  3947. \"~/org/archive.org::\"
  3948. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3949. \"~/org/archive.org::* From %s\"
  3950. Archive in file ~/org/archive.org (absolute path), under headlines
  3951. \"From FILENAME\" where file name is the current file name.
  3952. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3953. The \"datetree/\" string is special, signifying to archive
  3954. items to the datetree. Items are placed in either the CLOSED
  3955. date of the item, or the current date if there is no CLOSED date.
  3956. The heading will be a subentry to the current date. There doesn't
  3957. need to be a heading, but there always needs to be a slash after
  3958. datetree. For example, to store archived items directly in the
  3959. datetree, use \"~/org/datetree.org::datetree/\".
  3960. \"basement::** Finished Tasks\"
  3961. Archive in file ./basement (relative path), as level 3 trees
  3962. below the level 2 heading \"** Finished Tasks\".
  3963. You may set this option on a per-file basis by adding to the buffer a
  3964. line like
  3965. #+ARCHIVE: basement::** Finished Tasks
  3966. You may also define it locally for a subtree by setting an ARCHIVE property
  3967. in the entry. If such a property is found in an entry, or anywhere up
  3968. the hierarchy, it will be used."
  3969. :group 'org-archive
  3970. :type 'string)
  3971. (defcustom org-agenda-skip-archived-trees t
  3972. "Non-nil means the agenda will skip any items located in archived trees.
  3973. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3974. variable is no longer recommended, you should leave it at the value t.
  3975. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3976. :group 'org-archive
  3977. :group 'org-agenda-skip
  3978. :type 'boolean)
  3979. (defcustom org-columns-skip-archived-trees t
  3980. "Non-nil means ignore archived trees when creating column view."
  3981. :group 'org-archive
  3982. :group 'org-properties
  3983. :type 'boolean)
  3984. (defcustom org-cycle-open-archived-trees nil
  3985. "Non-nil means `org-cycle' will open archived trees.
  3986. An archived tree is a tree marked with the tag ARCHIVE.
  3987. When nil, archived trees will stay folded. You can still open them with
  3988. normal outline commands like `show-all', but not with the cycling commands."
  3989. :group 'org-archive
  3990. :group 'org-cycle
  3991. :type 'boolean)
  3992. (defcustom org-sparse-tree-open-archived-trees nil
  3993. "Non-nil means sparse tree construction shows matches in archived trees.
  3994. When nil, matches in these trees are highlighted, but the trees are kept in
  3995. collapsed state."
  3996. :group 'org-archive
  3997. :group 'org-sparse-trees
  3998. :type 'boolean)
  3999. (defcustom org-sparse-tree-default-date-type nil
  4000. "The default date type when building a sparse tree.
  4001. When this is nil, a date is a scheduled or a deadline timestamp.
  4002. Otherwise, these types are allowed:
  4003. all: all timestamps
  4004. active: only active timestamps (<...>)
  4005. inactive: only inactive timestamps ([...])
  4006. scheduled: only scheduled timestamps
  4007. deadline: only deadline timestamps"
  4008. :type '(choice (const :tag "Scheduled or deadline" nil)
  4009. (const :tag "All timestamps" all)
  4010. (const :tag "Only active timestamps" active)
  4011. (const :tag "Only inactive timestamps" inactive)
  4012. (const :tag "Only scheduled timestamps" scheduled)
  4013. (const :tag "Only deadline timestamps" deadline)
  4014. (const :tag "Only closed timestamps" closed))
  4015. :version "26.1"
  4016. :package-version '(Org . "8.3")
  4017. :group 'org-sparse-trees)
  4018. (defun org-cycle-hide-archived-subtrees (state)
  4019. "Re-hide all archived subtrees after a visibility state change.
  4020. STATE should be one of the symbols listed in the docstring of
  4021. `org-cycle-hook'."
  4022. (when (and (not org-cycle-open-archived-trees)
  4023. (not (memq state '(overview folded))))
  4024. (save-excursion
  4025. (let* ((globalp (memq state '(contents all)))
  4026. (beg (if globalp (point-min) (point)))
  4027. (end (if globalp (point-max) (org-end-of-subtree t))))
  4028. (org-hide-archived-subtrees beg end)
  4029. (goto-char beg)
  4030. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4031. (message "%s" (substitute-command-keys
  4032. "Subtree is archived and stays closed. Use \
  4033. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4034. (defun org-force-cycle-archived ()
  4035. "Cycle subtree even if it is archived."
  4036. (interactive)
  4037. (setq this-command 'org-cycle)
  4038. (let ((org-cycle-open-archived-trees t))
  4039. (call-interactively 'org-cycle)))
  4040. (defun org-hide-archived-subtrees (beg end)
  4041. "Re-hide all archived subtrees after a visibility state change."
  4042. (org-with-wide-buffer
  4043. (let ((case-fold-search nil)
  4044. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4045. (goto-char beg)
  4046. ;; Include headline point is currently on.
  4047. (beginning-of-line)
  4048. (while (and (< (point) end) (re-search-forward re end t))
  4049. (when (member org-archive-tag (org-get-tags))
  4050. (org-flag-subtree t)
  4051. (org-end-of-subtree t))))))
  4052. (declare-function outline-end-of-heading "outline" ())
  4053. (declare-function outline-flag-region "outline" (from to flag))
  4054. (defun org-flag-subtree (flag)
  4055. (save-excursion
  4056. (org-back-to-heading t)
  4057. (outline-end-of-heading)
  4058. (outline-flag-region (point)
  4059. (progn (org-end-of-subtree t) (point))
  4060. flag)))
  4061. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4062. ;; Declare Column View Code
  4063. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4064. (declare-function org-columns-compute "org-colview" (property))
  4065. ;; Declare ID code
  4066. (declare-function org-id-store-link "org-id")
  4067. (declare-function org-id-locations-load "org-id")
  4068. (declare-function org-id-locations-save "org-id")
  4069. (defvar org-id-track-globally)
  4070. ;;; Variables for pre-computed regular expressions, all buffer local
  4071. (defvar-local org-todo-regexp nil
  4072. "Matches any of the TODO state keywords.
  4073. Since TODO keywords are case-sensitive, `case-fold-search' is
  4074. expected to be bound to nil when matching against this regexp.")
  4075. (defvar-local org-not-done-regexp nil
  4076. "Matches any of the TODO state keywords except the last one.
  4077. Since TODO keywords are case-sensitive, `case-fold-search' is
  4078. expected to be bound to nil when matching against this regexp.")
  4079. (defvar-local org-not-done-heading-regexp nil
  4080. "Matches a TODO headline that is not done.
  4081. Since TODO keywords are case-sensitive, `case-fold-search' is
  4082. expected to be bound to nil when matching against this regexp.")
  4083. (defvar-local org-todo-line-regexp nil
  4084. "Matches a headline and puts TODO state into group 2 if present.
  4085. Since TODO keywords are case-sensitive, `case-fold-search' is
  4086. expected to be bound to nil when matching against this regexp.")
  4087. (defvar-local org-complex-heading-regexp nil
  4088. "Matches a headline and puts everything into groups:
  4089. group 1: Stars
  4090. group 2: The TODO keyword, maybe
  4091. group 3: Priority cookie
  4092. group 4: True headline
  4093. group 5: Tags
  4094. Since TODO keywords are case-sensitive, `case-fold-search' is
  4095. expected to be bound to nil when matching against this regexp.")
  4096. (defvar-local org-complex-heading-regexp-format nil
  4097. "Printf format to make regexp to match an exact headline.
  4098. This regexp will match the headline of any node which has the
  4099. exact headline text that is put into the format, but may have any
  4100. TODO state, priority and tags.")
  4101. (defvar-local org-todo-line-tags-regexp nil
  4102. "Matches a headline and puts TODO state into group 2 if present.
  4103. Also put tags into group 4 if tags are present.")
  4104. (defconst org-plain-time-of-day-regexp
  4105. (concat
  4106. "\\(\\<[012]?[0-9]"
  4107. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4108. "\\(--?"
  4109. "\\(\\<[012]?[0-9]"
  4110. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4111. "\\)?")
  4112. "Regular expression to match a plain time or time range.
  4113. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4114. groups carry important information:
  4115. 0 the full match
  4116. 1 the first time, range or not
  4117. 8 the second time, if it is a range.")
  4118. (defconst org-plain-time-extension-regexp
  4119. (concat
  4120. "\\(\\<[012]?[0-9]"
  4121. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4122. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4123. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4124. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4125. groups carry important information:
  4126. 0 the full match
  4127. 7 hours of duration
  4128. 9 minutes of duration")
  4129. (defconst org-stamp-time-of-day-regexp
  4130. (concat
  4131. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4132. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4133. "\\(--?"
  4134. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4135. "Regular expression to match a timestamp time or time range.
  4136. After a match, the following groups carry important information:
  4137. 0 the full match
  4138. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4139. 2 the first time, range or not
  4140. 4 the second time, if it is a range.")
  4141. (defconst org-startup-options
  4142. '(("fold" org-startup-folded t)
  4143. ("overview" org-startup-folded t)
  4144. ("nofold" org-startup-folded nil)
  4145. ("showall" org-startup-folded nil)
  4146. ("showeverything" org-startup-folded showeverything)
  4147. ("content" org-startup-folded content)
  4148. ("indent" org-startup-indented t)
  4149. ("noindent" org-startup-indented nil)
  4150. ("hidestars" org-hide-leading-stars t)
  4151. ("showstars" org-hide-leading-stars nil)
  4152. ("odd" org-odd-levels-only t)
  4153. ("oddeven" org-odd-levels-only nil)
  4154. ("align" org-startup-align-all-tables t)
  4155. ("noalign" org-startup-align-all-tables nil)
  4156. ("inlineimages" org-startup-with-inline-images t)
  4157. ("noinlineimages" org-startup-with-inline-images nil)
  4158. ("latexpreview" org-startup-with-latex-preview t)
  4159. ("nolatexpreview" org-startup-with-latex-preview nil)
  4160. ("customtime" org-display-custom-times t)
  4161. ("logdone" org-log-done time)
  4162. ("lognotedone" org-log-done note)
  4163. ("nologdone" org-log-done nil)
  4164. ("lognoteclock-out" org-log-note-clock-out t)
  4165. ("nolognoteclock-out" org-log-note-clock-out nil)
  4166. ("logrepeat" org-log-repeat state)
  4167. ("lognoterepeat" org-log-repeat note)
  4168. ("logdrawer" org-log-into-drawer t)
  4169. ("nologdrawer" org-log-into-drawer nil)
  4170. ("logstatesreversed" org-log-states-order-reversed t)
  4171. ("nologstatesreversed" org-log-states-order-reversed nil)
  4172. ("nologrepeat" org-log-repeat nil)
  4173. ("logreschedule" org-log-reschedule time)
  4174. ("lognotereschedule" org-log-reschedule note)
  4175. ("nologreschedule" org-log-reschedule nil)
  4176. ("logredeadline" org-log-redeadline time)
  4177. ("lognoteredeadline" org-log-redeadline note)
  4178. ("nologredeadline" org-log-redeadline nil)
  4179. ("logrefile" org-log-refile time)
  4180. ("lognoterefile" org-log-refile note)
  4181. ("nologrefile" org-log-refile nil)
  4182. ("fninline" org-footnote-define-inline t)
  4183. ("nofninline" org-footnote-define-inline nil)
  4184. ("fnlocal" org-footnote-section nil)
  4185. ("fnauto" org-footnote-auto-label t)
  4186. ("fnprompt" org-footnote-auto-label nil)
  4187. ("fnconfirm" org-footnote-auto-label confirm)
  4188. ("fnplain" org-footnote-auto-label plain)
  4189. ("fnadjust" org-footnote-auto-adjust t)
  4190. ("nofnadjust" org-footnote-auto-adjust nil)
  4191. ("constcgs" constants-unit-system cgs)
  4192. ("constSI" constants-unit-system SI)
  4193. ("noptag" org-tag-persistent-alist nil)
  4194. ("hideblocks" org-hide-block-startup t)
  4195. ("nohideblocks" org-hide-block-startup nil)
  4196. ("beamer" org-startup-with-beamer-mode t)
  4197. ("entitiespretty" org-pretty-entities t)
  4198. ("entitiesplain" org-pretty-entities nil))
  4199. "Variable associated with STARTUP options for org-mode.
  4200. Each element is a list of three items: the startup options (as written
  4201. in the #+STARTUP line), the corresponding variable, and the value to set
  4202. this variable to if the option is found. An optional forth element PUSH
  4203. means to push this value onto the list in the variable.")
  4204. (defcustom org-group-tags t
  4205. "When non-nil (the default), use group tags.
  4206. This can be turned on/off through `org-toggle-tags-groups'."
  4207. :group 'org-tags
  4208. :group 'org-startup
  4209. :type 'boolean)
  4210. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4211. (defun org-toggle-tags-groups ()
  4212. "Toggle support for group tags.
  4213. Support for group tags is controlled by the option
  4214. `org-group-tags', which is non-nil by default."
  4215. (interactive)
  4216. (setq org-group-tags (not org-group-tags))
  4217. (cond ((and (derived-mode-p 'org-agenda-mode)
  4218. org-group-tags)
  4219. (org-agenda-redo))
  4220. ((derived-mode-p 'org-mode)
  4221. (let ((org-inhibit-startup t)) (org-mode))))
  4222. (message "Groups tags support has been turned %s"
  4223. (if org-group-tags "on" "off")))
  4224. (defun org-set-regexps-and-options (&optional tags-only)
  4225. "Precompute regular expressions used in the current buffer.
  4226. When optional argument TAGS-ONLY is non-nil, only compute tags
  4227. related expressions."
  4228. (when (derived-mode-p 'org-mode)
  4229. (let ((alist (org--setup-collect-keywords
  4230. (org-make-options-regexp
  4231. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4232. (and (not tags-only)
  4233. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4234. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4235. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4236. ;; Startup options. Get this early since it does change
  4237. ;; behavior for other options (e.g., tags).
  4238. (let ((startup (cdr (assq 'startup alist))))
  4239. (dolist (option startup)
  4240. (let ((entry (assoc-string option org-startup-options t)))
  4241. (when entry
  4242. (let ((var (nth 1 entry))
  4243. (val (nth 2 entry)))
  4244. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4245. (unless (listp (symbol-value var))
  4246. (set (make-local-variable var) nil))
  4247. (add-to-list var val)))))))
  4248. (setq-local org-file-tags
  4249. (mapcar #'org-add-prop-inherited
  4250. (cdr (assq 'filetags alist))))
  4251. (setq org-current-tag-alist
  4252. (append org-tag-persistent-alist
  4253. (let ((tags (cdr (assq 'tags alist))))
  4254. (if tags (org-tag-string-to-alist tags)
  4255. org-tag-alist))))
  4256. (setq org-tag-groups-alist
  4257. (org-tag-alist-to-groups org-current-tag-alist))
  4258. (unless tags-only
  4259. ;; File properties.
  4260. (setq-local org-file-properties (cdr (assq 'property alist)))
  4261. ;; Archive location.
  4262. (let ((archive (cdr (assq 'archive alist))))
  4263. (when archive (setq-local org-archive-location archive)))
  4264. ;; Category.
  4265. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4266. (when cat
  4267. (setq-local org-category (intern cat))
  4268. (setq-local org-file-properties
  4269. (org--update-property-plist
  4270. "CATEGORY" cat org-file-properties))))
  4271. ;; Columns.
  4272. (let ((column (cdr (assq 'columns alist))))
  4273. (when column (setq-local org-columns-default-format column)))
  4274. ;; Constants.
  4275. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4276. ;; Link abbreviations.
  4277. (let ((links (cdr (assq 'link alist))))
  4278. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4279. ;; Priorities.
  4280. (let ((priorities (cdr (assq 'priorities alist))))
  4281. (when priorities
  4282. (setq-local org-highest-priority (nth 0 priorities))
  4283. (setq-local org-lowest-priority (nth 1 priorities))
  4284. (setq-local org-default-priority (nth 2 priorities))))
  4285. ;; Scripts.
  4286. (let ((scripts (assq 'scripts alist)))
  4287. (when scripts
  4288. (setq-local org-use-sub-superscripts (cdr scripts))))
  4289. ;; TODO keywords.
  4290. (setq-local org-todo-kwd-alist nil)
  4291. (setq-local org-todo-key-alist nil)
  4292. (setq-local org-todo-key-trigger nil)
  4293. (setq-local org-todo-keywords-1 nil)
  4294. (setq-local org-done-keywords nil)
  4295. (setq-local org-todo-heads nil)
  4296. (setq-local org-todo-sets nil)
  4297. (setq-local org-todo-log-states nil)
  4298. (let ((todo-sequences
  4299. (or (nreverse (cdr (assq 'todo alist)))
  4300. (let ((d (default-value 'org-todo-keywords)))
  4301. (if (not (stringp (car d))) d
  4302. ;; XXX: Backward compatibility code.
  4303. (list (cons org-todo-interpretation d)))))))
  4304. (dolist (sequence todo-sequences)
  4305. (let* ((sequence (or (run-hook-with-args-until-success
  4306. 'org-todo-setup-filter-hook sequence)
  4307. sequence))
  4308. (sequence-type (car sequence))
  4309. (keywords (cdr sequence))
  4310. (sep (member "|" keywords))
  4311. names alist)
  4312. (dolist (k (remove "|" keywords))
  4313. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4314. k)
  4315. (error "Invalid TODO keyword %s" k))
  4316. (let ((name (match-string 1 k))
  4317. (key (match-string 2 k))
  4318. (log (org-extract-log-state-settings k)))
  4319. (push name names)
  4320. (push (cons name (and key (string-to-char key))) alist)
  4321. (when log (push log org-todo-log-states))))
  4322. (let* ((names (nreverse names))
  4323. (done (if sep (org-remove-keyword-keys (cdr sep))
  4324. (last names)))
  4325. (head (car names))
  4326. (tail (list sequence-type head (car done) (org-last done))))
  4327. (add-to-list 'org-todo-heads head 'append)
  4328. (push names org-todo-sets)
  4329. (setq org-done-keywords (append org-done-keywords done nil))
  4330. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4331. (setq org-todo-key-alist
  4332. (append org-todo-key-alist
  4333. (and alist
  4334. (append '((:startgroup))
  4335. (nreverse alist)
  4336. '((:endgroup))))))
  4337. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4338. (setq org-todo-sets (nreverse org-todo-sets)
  4339. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4340. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4341. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4342. ;; Compute the regular expressions and other local variables.
  4343. ;; Using `org-outline-regexp-bol' would complicate them much,
  4344. ;; because of the fixed white space at the end of that string.
  4345. (unless org-done-keywords
  4346. (setq org-done-keywords
  4347. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4348. (setq org-not-done-keywords
  4349. (org-delete-all org-done-keywords
  4350. (copy-sequence org-todo-keywords-1))
  4351. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4352. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4353. org-not-done-heading-regexp
  4354. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4355. org-todo-line-regexp
  4356. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4357. org-complex-heading-regexp
  4358. (concat "^\\(\\*+\\)"
  4359. "\\(?: +" org-todo-regexp "\\)?"
  4360. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4361. "\\(?: +\\(.*?\\)\\)??"
  4362. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4363. "[ \t]*$")
  4364. org-complex-heading-regexp-format
  4365. (concat "^\\(\\*+\\)"
  4366. "\\(?: +" org-todo-regexp "\\)?"
  4367. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4368. "\\(?: +"
  4369. ;; Stats cookies can be stuck to body.
  4370. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4371. "\\(%s\\)"
  4372. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4373. "\\)"
  4374. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4375. "[ \t]*$")
  4376. org-todo-line-tags-regexp
  4377. (concat "^\\(\\*+\\)"
  4378. "\\(?: +" org-todo-regexp "\\)?"
  4379. "\\(?: +\\(.*?\\)\\)??"
  4380. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4381. "[ \t]*$"))
  4382. (org-compute-latex-and-related-regexp)))))
  4383. (defun org--setup-collect-keywords (regexp &optional files alist)
  4384. "Return setup keywords values as an alist.
  4385. REGEXP matches a subset of setup keywords. FILES is a list of
  4386. file names already visited. It is used to avoid circular setup
  4387. files. ALIST, when non-nil, is the alist computed so far.
  4388. Return value contains the following keys: `archive', `category',
  4389. `columns', `constants', `filetags', `link', `priorities',
  4390. `property', `scripts', `startup', `tags' and `todo'."
  4391. (org-with-wide-buffer
  4392. (goto-char (point-min))
  4393. (let ((case-fold-search t))
  4394. (while (re-search-forward regexp nil t)
  4395. (let ((element (org-element-at-point)))
  4396. (when (eq (org-element-type element) 'keyword)
  4397. (let ((key (org-element-property :key element))
  4398. (value (org-element-property :value element)))
  4399. (cond
  4400. ((equal key "ARCHIVE")
  4401. (when (org-string-nw-p value)
  4402. (push (cons 'archive value) alist)))
  4403. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4404. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4405. ((equal key "CONSTANTS")
  4406. (let* ((constants (assq 'constants alist))
  4407. (store (cdr constants)))
  4408. (dolist (pair (split-string value))
  4409. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4410. pair)
  4411. (let* ((name (match-string 1 pair))
  4412. (value (match-string 2 pair))
  4413. (old (assoc name store)))
  4414. (if old (setcdr old value)
  4415. (push (cons name value) store)))))
  4416. (if constants (setcdr constants store)
  4417. (push (cons 'constants store) alist))))
  4418. ((equal key "FILETAGS")
  4419. (when (org-string-nw-p value)
  4420. (let ((old (assq 'filetags alist))
  4421. (new (apply #'nconc
  4422. (mapcar (lambda (x) (org-split-string x ":"))
  4423. (split-string value)))))
  4424. (if old (setcdr old (append new (cdr old)))
  4425. (push (cons 'filetags new) alist)))))
  4426. ((equal key "LINK")
  4427. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4428. (let ((links (assq 'link alist))
  4429. (pair (cons (match-string-no-properties 1 value)
  4430. (match-string-no-properties 2 value))))
  4431. (if links (push pair (cdr links))
  4432. (push (list 'link pair) alist)))))
  4433. ((equal key "OPTIONS")
  4434. (when (and (org-string-nw-p value)
  4435. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4436. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4437. ((equal key "PRIORITIES")
  4438. (push (cons 'priorities
  4439. (let ((prio (split-string value)))
  4440. (if (< (length prio) 3) '(?A ?C ?B)
  4441. (mapcar #'string-to-char prio))))
  4442. alist))
  4443. ((equal key "PROPERTY")
  4444. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4445. (let* ((property (assq 'property alist))
  4446. (value (org--update-property-plist
  4447. (match-string-no-properties 1 value)
  4448. (match-string-no-properties 2 value)
  4449. (cdr property))))
  4450. (if property (setcdr property value)
  4451. (push (cons 'property value) alist)))))
  4452. ((equal key "STARTUP")
  4453. (let ((startup (assq 'startup alist)))
  4454. (if startup
  4455. (setcdr startup
  4456. (append (cdr startup) (split-string value)))
  4457. (push (cons 'startup (split-string value)) alist))))
  4458. ((equal key "TAGS")
  4459. (let ((tag-cell (assq 'tags alist)))
  4460. (if tag-cell
  4461. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4462. (push (cons 'tags value) alist))))
  4463. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4464. (let ((todo (assq 'todo alist))
  4465. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4466. (split-string value))))
  4467. (if todo (push value (cdr todo))
  4468. (push (list 'todo value) alist))))
  4469. ((equal key "SETUPFILE")
  4470. (unless buffer-read-only ; Do not check in Gnus messages.
  4471. (let ((f (and (org-string-nw-p value)
  4472. (expand-file-name
  4473. (org-unbracket-string "\"" "\"" value)))))
  4474. (when (and f (file-readable-p f) (not (member f files)))
  4475. (with-temp-buffer
  4476. (setq default-directory (file-name-directory f))
  4477. (insert-file-contents f)
  4478. (setq alist
  4479. ;; Fake Org mode to benefit from cache
  4480. ;; without recurring needlessly.
  4481. (let ((major-mode 'org-mode))
  4482. (org--setup-collect-keywords
  4483. regexp (cons f files) alist)))))))))))))))
  4484. alist)
  4485. (defun org-tag-string-to-alist (s)
  4486. "Return tag alist associated to string S.
  4487. S is a value for TAGS keyword or produced with
  4488. `org-tag-alist-to-string'. Return value is an alist suitable for
  4489. `org-tag-alist' or `org-tag-persistent-alist'."
  4490. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4491. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4492. "\\|{.+?}\\)" ; regular expression
  4493. "\\(?:(\\(.\\))\\)?\\'"))
  4494. alist group-flag)
  4495. (dolist (tokens lines (cdr (nreverse alist)))
  4496. (push '(:newline) alist)
  4497. (while tokens
  4498. (let ((token (pop tokens)))
  4499. (pcase token
  4500. ("{"
  4501. (push '(:startgroup) alist)
  4502. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4503. ("}"
  4504. (push '(:endgroup) alist)
  4505. (setq group-flag nil))
  4506. ("["
  4507. (push '(:startgrouptag) alist)
  4508. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4509. ("]"
  4510. (push '(:endgrouptag) alist)
  4511. (setq group-flag nil))
  4512. (":"
  4513. (push '(:grouptags) alist))
  4514. ((guard (string-match tag-re token))
  4515. (let ((tag (match-string 1 token))
  4516. (key (and (match-beginning 2)
  4517. (string-to-char (match-string 2 token)))))
  4518. ;; Push all tags in groups, no matter if they already
  4519. ;; appear somewhere else in the list.
  4520. (when (or group-flag (not (assoc tag alist)))
  4521. (push (cons tag key) alist))))))))))
  4522. (defun org-tag-alist-to-string (alist &optional skip-key)
  4523. "Return tag string associated to ALIST.
  4524. ALIST is an alist, as defined in `org-tag-alist' or
  4525. `org-tag-persistent-alist', or produced with
  4526. `org-tag-string-to-alist'.
  4527. Return value is a string suitable as a value for \"TAGS\"
  4528. keyword.
  4529. When optional argument SKIP-KEY is non-nil, skip selection keys
  4530. next to tags."
  4531. (mapconcat (lambda (token)
  4532. (pcase token
  4533. (`(:startgroup) "{")
  4534. (`(:endgroup) "}")
  4535. (`(:startgrouptag) "[")
  4536. (`(:endgrouptag) "]")
  4537. (`(:grouptags) ":")
  4538. (`(:newline) "\\n")
  4539. ((and
  4540. (guard (not skip-key))
  4541. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4542. (format "%s(%c)" tag key))
  4543. (`(,(and tag (pred stringp)) . ,_) tag)
  4544. (_ (user-error "Invalid tag token: %S" token))))
  4545. alist
  4546. " "))
  4547. (defun org-tag-alist-to-groups (alist)
  4548. "Return group alist from tag ALIST.
  4549. ALIST is an alist, as defined in `org-tag-alist' or
  4550. `org-tag-persistent-alist', or produced with
  4551. `org-tag-string-to-alist'. Return value is an alist following
  4552. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4553. a string, summarizing TAGS, as a list of strings."
  4554. (let (groups group-status current-group)
  4555. (dolist (token alist (nreverse groups))
  4556. (pcase token
  4557. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4558. (`(,(or :endgroup :endgrouptag))
  4559. (when (eq group-status 'append)
  4560. (push (nreverse current-group) groups))
  4561. (setq group-status nil))
  4562. (`(:grouptags) (setq group-status 'append))
  4563. ((and `(,tag . ,_) (guard group-status))
  4564. (if (eq group-status 'append) (push tag current-group)
  4565. (setq current-group (list tag))))
  4566. (_ nil)))))
  4567. (defvar org--file-cache (make-hash-table :test #'equal)
  4568. "Hash table to store contents of files referenced via a URL.
  4569. This is the cache of file URLs read using `org-file-contents'.")
  4570. (defun org-reset-file-cache ()
  4571. "Reset the cache of files downloaded by `org-file-contents'."
  4572. (clrhash org--file-cache))
  4573. (defun org-file-url-p (file)
  4574. "Non-nil if FILE is a URL."
  4575. (require 'ffap)
  4576. (string-match-p ffap-url-regexp file))
  4577. (defun org-file-contents (file &optional noerror nocache)
  4578. "Return the contents of FILE, as a string.
  4579. FILE can be a file name or URL.
  4580. If FILE is a URL, download the contents. If the URL contents are
  4581. already cached in the `org--file-cache' hash table, the download step
  4582. is skipped.
  4583. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4584. from file or URL.
  4585. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4586. is available. This option applies only if FILE is a URL."
  4587. (let* ((is-url (org-file-url-p file))
  4588. (cache (and is-url
  4589. (not nocache)
  4590. (gethash file org--file-cache))))
  4591. (cond
  4592. (cache)
  4593. (is-url
  4594. (with-current-buffer (url-retrieve-synchronously file)
  4595. (goto-char (point-min))
  4596. ;; Move point to after the url-retrieve header.
  4597. (search-forward "\n\n" nil :move)
  4598. ;; Search for the success code only in the url-retrieve header.
  4599. (if (save-excursion
  4600. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4601. ;; Update the cache `org--file-cache' and return contents.
  4602. (puthash file
  4603. (buffer-substring-no-properties (point) (point-max))
  4604. org--file-cache)
  4605. (funcall (if noerror #'message #'user-error)
  4606. "Unable to fetch file from %S"
  4607. file))))
  4608. (t
  4609. (with-temp-buffer
  4610. (condition-case nil
  4611. (progn
  4612. (insert-file-contents file)
  4613. (buffer-string))
  4614. (file-error
  4615. (funcall (if noerror #'message #'user-error)
  4616. "Unable to read file %S"
  4617. file))))))))
  4618. (defun org-extract-log-state-settings (x)
  4619. "Extract the log state setting from a TODO keyword string.
  4620. This will extract info from a string like \"WAIT(w@/!)\"."
  4621. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4622. (let ((kw (match-string 1 x))
  4623. (log1 (and (match-end 3) (match-string 3 x)))
  4624. (log2 (and (match-end 4) (match-string 4 x))))
  4625. (and (or log1 log2)
  4626. (list kw
  4627. (and log1 (if (equal log1 "!") 'time 'note))
  4628. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4629. (defun org-remove-keyword-keys (list)
  4630. "Remove a pair of parenthesis at the end of each string in LIST."
  4631. (mapcar (lambda (x)
  4632. (if (string-match "(.*)$" x)
  4633. (substring x 0 (match-beginning 0))
  4634. x))
  4635. list))
  4636. (defun org-assign-fast-keys (alist)
  4637. "Assign fast keys to a keyword-key alist.
  4638. Respect keys that are already there."
  4639. (let (new e (alt ?0))
  4640. (while (setq e (pop alist))
  4641. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4642. (cdr e)) ;; Key already assigned.
  4643. (push e new)
  4644. (let ((clist (string-to-list (downcase (car e))))
  4645. (used (append new alist)))
  4646. (when (= (car clist) ?@)
  4647. (pop clist))
  4648. (while (and clist (rassoc (car clist) used))
  4649. (pop clist))
  4650. (unless clist
  4651. (while (rassoc alt used)
  4652. (cl-incf alt)))
  4653. (push (cons (car e) (or (car clist) alt)) new))))
  4654. (nreverse new)))
  4655. ;;; Some variables used in various places
  4656. (defvar org-window-configuration nil
  4657. "Used in various places to store a window configuration.")
  4658. (defvar org-selected-window nil
  4659. "Used in various places to store a window configuration.")
  4660. (defvar org-finish-function nil
  4661. "Function to be called when `C-c C-c' is used.
  4662. This is for getting out of special buffers like capture.")
  4663. (defvar org-last-state)
  4664. ;; Defined somewhere in this file, but used before definition.
  4665. (defvar org-entities) ;; defined in org-entities.el
  4666. (defvar org-struct-menu)
  4667. (defvar org-org-menu)
  4668. (defvar org-tbl-menu)
  4669. ;;;; Define the Org mode
  4670. ;; We use a before-change function to check if a table might need
  4671. ;; an update.
  4672. (defvar org-table-may-need-update t
  4673. "Indicates that a table might need an update.
  4674. This variable is set by `org-before-change-function'.
  4675. `org-table-align' sets it back to nil.")
  4676. (defun org-before-change-function (_beg _end)
  4677. "Every change indicates that a table might need an update."
  4678. (setq org-table-may-need-update t))
  4679. (defvar org-mode-map)
  4680. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4681. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4682. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4683. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4684. (defvar org-table-buffer-is-an nil)
  4685. (defvar bidi-paragraph-direction)
  4686. (defvar buffer-face-mode-face)
  4687. (require 'outline)
  4688. ;; Other stuff we need.
  4689. (require 'time-date)
  4690. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4691. (require 'easymenu)
  4692. (autoload 'easy-menu-add "easymenu")
  4693. (require 'overlay)
  4694. ;; (require 'org-macs) moved higher up in the file before it is first used
  4695. (require 'org-entities)
  4696. ;; (require 'org-compat) moved higher up in the file before it is first used
  4697. (require 'org-faces)
  4698. (require 'org-list)
  4699. (require 'org-pcomplete)
  4700. (require 'org-src)
  4701. (require 'org-footnote)
  4702. (require 'org-macro)
  4703. ;; babel
  4704. (require 'ob)
  4705. ;;;###autoload
  4706. (define-derived-mode org-mode outline-mode "Org"
  4707. "Outline-based notes management and organizer, alias
  4708. \"Carsten's outline-mode for keeping track of everything.\"
  4709. Org mode develops organizational tasks around a NOTES file which
  4710. contains information about projects as plain text. Org mode is
  4711. implemented on top of Outline mode, which is ideal to keep the content
  4712. of large files well structured. It supports ToDo items, deadlines and
  4713. time stamps, which magically appear in the diary listing of the Emacs
  4714. calendar. Tables are easily created with a built-in table editor.
  4715. Plain text URL-like links connect to websites, emails (VM), Usenet
  4716. messages (Gnus), BBDB entries, and any files related to the project.
  4717. For printing and sharing of notes, an Org file (or a part of it)
  4718. can be exported as a structured ASCII or HTML file.
  4719. The following commands are available:
  4720. \\{org-mode-map}"
  4721. ;; Get rid of Outline menus, they are not needed
  4722. ;; Need to do this here because define-derived-mode sets up
  4723. ;; the keymap so late. Still, it is a waste to call this each time
  4724. ;; we switch another buffer into Org mode.
  4725. (define-key org-mode-map [menu-bar headings] 'undefined)
  4726. (define-key org-mode-map [menu-bar hide] 'undefined)
  4727. (define-key org-mode-map [menu-bar show] 'undefined)
  4728. (org-load-modules-maybe)
  4729. (org-install-agenda-files-menu)
  4730. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4731. (add-to-invisibility-spec '(org-cwidth))
  4732. (add-to-invisibility-spec '(org-hide-block . t))
  4733. (setq-local outline-regexp org-outline-regexp)
  4734. (setq-local outline-level 'org-outline-level)
  4735. (setq bidi-paragraph-direction 'left-to-right)
  4736. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4737. (unless org-display-table
  4738. (setq org-display-table (make-display-table)))
  4739. (set-display-table-slot
  4740. org-display-table 4
  4741. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4742. org-ellipsis)))
  4743. (setq buffer-display-table org-display-table))
  4744. (org-set-regexps-and-options)
  4745. (org-set-font-lock-defaults)
  4746. (when (and org-tag-faces (not org-tags-special-faces-re))
  4747. ;; tag faces set outside customize.... force initialization.
  4748. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4749. ;; Calc embedded
  4750. (setq-local calc-embedded-open-mode "# ")
  4751. ;; Modify a few syntax entries
  4752. (modify-syntax-entry ?@ "w")
  4753. (modify-syntax-entry ?\" "\"")
  4754. (modify-syntax-entry ?\\ "_")
  4755. (modify-syntax-entry ?~ "_")
  4756. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4757. ;; Activate before-change-function
  4758. (setq-local org-table-may-need-update t)
  4759. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4760. ;; Check for running clock before killing a buffer
  4761. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4762. ;; Initialize macros templates.
  4763. (org-macro-initialize-templates)
  4764. ;; Initialize radio targets.
  4765. (org-update-radio-target-regexp)
  4766. ;; Indentation.
  4767. (setq-local indent-line-function 'org-indent-line)
  4768. (setq-local indent-region-function 'org-indent-region)
  4769. ;; Filling and auto-filling.
  4770. (org-setup-filling)
  4771. ;; Comments.
  4772. (org-setup-comments-handling)
  4773. ;; Initialize cache.
  4774. (org-element-cache-reset)
  4775. ;; Beginning/end of defun
  4776. (setq-local beginning-of-defun-function 'org-backward-element)
  4777. (setq-local end-of-defun-function
  4778. (lambda ()
  4779. (if (not (org-at-heading-p))
  4780. (org-forward-element)
  4781. (org-forward-element)
  4782. (forward-char -1))))
  4783. ;; Next error for sparse trees
  4784. (setq-local next-error-function 'org-occur-next-match)
  4785. ;; Make sure dependence stuff works reliably, even for users who set it
  4786. ;; too late :-(
  4787. (if org-enforce-todo-dependencies
  4788. (add-hook 'org-blocker-hook
  4789. 'org-block-todo-from-children-or-siblings-or-parent)
  4790. (remove-hook 'org-blocker-hook
  4791. 'org-block-todo-from-children-or-siblings-or-parent))
  4792. (if org-enforce-todo-checkbox-dependencies
  4793. (add-hook 'org-blocker-hook
  4794. 'org-block-todo-from-checkboxes)
  4795. (remove-hook 'org-blocker-hook
  4796. 'org-block-todo-from-checkboxes))
  4797. ;; Align options lines
  4798. (setq-local
  4799. align-mode-rules-list
  4800. '((org-in-buffer-settings
  4801. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4802. (modes . '(org-mode)))))
  4803. ;; Imenu
  4804. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4805. ;; Make isearch reveal context
  4806. (setq-local outline-isearch-open-invisible-function
  4807. (lambda (&rest _) (org-show-context 'isearch)))
  4808. ;; Setup the pcomplete hooks
  4809. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4810. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4811. (setq-local pcomplete-default-completion-function 'ignore)
  4812. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4813. (setq-local pcomplete-termination-string "")
  4814. (setq-local buffer-face-mode-face 'org-default)
  4815. ;; If empty file that did not turn on Org mode automatically, make
  4816. ;; it to.
  4817. (when (and org-insert-mode-line-in-empty-file
  4818. (called-interactively-p 'any)
  4819. (= (point-min) (point-max)))
  4820. (insert "# -*- mode: org -*-\n\n"))
  4821. (unless org-inhibit-startup
  4822. (org-unmodified
  4823. (when org-startup-with-beamer-mode (org-beamer-mode))
  4824. (when org-startup-align-all-tables
  4825. (org-table-map-tables #'org-table-align t))
  4826. (when org-startup-with-inline-images (org-display-inline-images))
  4827. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4828. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4829. (when org-startup-truncated (setq truncate-lines t))
  4830. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4831. (org-refresh-effort-properties)))
  4832. ;; Try to set `org-hide' face correctly.
  4833. (let ((foreground (org-find-invisible-foreground)))
  4834. (when foreground
  4835. (set-face-foreground 'org-hide foreground))))
  4836. ;; Update `customize-package-emacs-version-alist'
  4837. (add-to-list 'customize-package-emacs-version-alist
  4838. '(Org ("8.0" . "24.4")
  4839. ("8.1" . "24.4")
  4840. ("8.2" . "24.4")
  4841. ("8.2.7" . "24.4")
  4842. ("8.3" . "26.1")
  4843. ("9.0" . "26.1")
  4844. ("9.1" . "26.1")))
  4845. (defvar org-mode-transpose-word-syntax-table
  4846. (let ((st (make-syntax-table text-mode-syntax-table)))
  4847. (dolist (c org-emphasis-alist st)
  4848. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4849. (when (fboundp 'abbrev-table-put)
  4850. (abbrev-table-put org-mode-abbrev-table
  4851. :parents (list text-mode-abbrev-table)))
  4852. (defun org-find-invisible-foreground ()
  4853. (let ((candidates (remove
  4854. "unspecified-bg"
  4855. (nconc
  4856. (list (face-background 'default)
  4857. (face-background 'org-default))
  4858. (mapcar
  4859. (lambda (alist)
  4860. (when (boundp alist)
  4861. (cdr (assq 'background-color (symbol-value alist)))))
  4862. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4863. (list (face-foreground 'org-hide))))))
  4864. (car (remove nil candidates))))
  4865. (defun org-current-time (&optional rounding-minutes past)
  4866. "Current time, possibly rounded to ROUNDING-MINUTES.
  4867. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4868. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4869. the rounding returns a past time."
  4870. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4871. (car org-time-stamp-rounding-minutes)))
  4872. (time (decode-time)) res)
  4873. (if (< r 1)
  4874. (current-time)
  4875. (setq res
  4876. (apply 'encode-time
  4877. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4878. (nthcdr 2 time))))
  4879. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4880. (seconds-to-time (- (float-time res) (* r 60)))
  4881. res))))
  4882. (defun org-today ()
  4883. "Return today date, considering `org-extend-today-until'."
  4884. (time-to-days
  4885. (time-subtract (current-time)
  4886. (list 0 (* 3600 org-extend-today-until) 0))))
  4887. ;;;; Font-Lock stuff, including the activators
  4888. (defvar org-mouse-map (make-sparse-keymap))
  4889. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4890. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4891. (when org-mouse-1-follows-link
  4892. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4893. (when org-tab-follows-link
  4894. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4895. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4896. (require 'font-lock)
  4897. (defconst org-non-link-chars "]\t\n\r<>")
  4898. (defvar org-link-types-re nil
  4899. "Matches a link that has a url-like prefix like \"http:\"")
  4900. (defvar org-link-re-with-space nil
  4901. "Matches a link with spaces, optional angular brackets around it.")
  4902. (defvar org-link-re-with-space2 nil
  4903. "Matches a link with spaces, optional angular brackets around it.")
  4904. (defvar org-link-re-with-space3 nil
  4905. "Matches a link with spaces, only for internal part in bracket links.")
  4906. (defvar org-angle-link-re nil
  4907. "Matches link with angular brackets, spaces are allowed.")
  4908. (defvar org-plain-link-re nil
  4909. "Matches plain link, without spaces.")
  4910. (defvar org-bracket-link-regexp nil
  4911. "Matches a link in double brackets.")
  4912. (defvar org-bracket-link-analytic-regexp nil
  4913. "Regular expression used to analyze links.
  4914. Here is what the match groups contain after a match:
  4915. 1: http:
  4916. 2: http
  4917. 3: path
  4918. 4: [desc]
  4919. 5: desc")
  4920. (defvar org-bracket-link-analytic-regexp++ nil
  4921. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4922. (defvar org-any-link-re nil
  4923. "Regular expression matching any link.")
  4924. (defconst org-match-sexp-depth 3
  4925. "Number of stacked braces for sub/superscript matching.")
  4926. (defun org-create-multibrace-regexp (left right n)
  4927. "Create a regular expression which will match a balanced sexp.
  4928. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4929. as single character strings.
  4930. The regexp returned will match the entire expression including the
  4931. delimiters. It will also define a single group which contains the
  4932. match except for the outermost delimiters. The maximum depth of
  4933. stacked delimiters is N. Escaping delimiters is not possible."
  4934. (let* ((nothing (concat "[^" left right "]*?"))
  4935. (or "\\|")
  4936. (re nothing)
  4937. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4938. (while (> n 1)
  4939. (setq n (1- n)
  4940. re (concat re or next)
  4941. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4942. (concat left "\\(" re "\\)" right)))
  4943. (defconst org-match-substring-regexp
  4944. (concat
  4945. "\\(\\S-\\)\\([_^]\\)\\("
  4946. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4947. "\\|"
  4948. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4949. "\\|"
  4950. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4951. "The regular expression matching a sub- or superscript.")
  4952. (defconst org-match-substring-with-braces-regexp
  4953. (concat
  4954. "\\(\\S-\\)\\([_^]\\)"
  4955. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4956. "The regular expression matching a sub- or superscript, forcing braces.")
  4957. (defun org-make-link-regexps ()
  4958. "Update the link regular expressions.
  4959. This should be called after the variable `org-link-parameters' has changed."
  4960. (let ((types-re (regexp-opt (org-link-types) t)))
  4961. (setq org-link-types-re
  4962. (concat "\\`" types-re ":")
  4963. org-link-re-with-space
  4964. (concat "<?" types-re ":"
  4965. "\\([^" org-non-link-chars " ]"
  4966. "[^" org-non-link-chars "]*"
  4967. "[^" org-non-link-chars " ]\\)>?")
  4968. org-link-re-with-space2
  4969. (concat "<?" types-re ":"
  4970. "\\([^" org-non-link-chars " ]"
  4971. "[^\t\n\r]*"
  4972. "[^" org-non-link-chars " ]\\)>?")
  4973. org-link-re-with-space3
  4974. (concat "<?" types-re ":"
  4975. "\\([^" org-non-link-chars " ]"
  4976. "[^\t\n\r]*\\)")
  4977. org-angle-link-re
  4978. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4979. types-re)
  4980. org-plain-link-re
  4981. (concat
  4982. "\\<" types-re ":"
  4983. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4984. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4985. org-bracket-link-regexp
  4986. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4987. org-bracket-link-analytic-regexp
  4988. (concat
  4989. "\\[\\["
  4990. "\\(" types-re ":\\)?"
  4991. "\\([^]]+\\)"
  4992. "\\]"
  4993. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4994. "\\]")
  4995. org-bracket-link-analytic-regexp++
  4996. (concat
  4997. "\\[\\["
  4998. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4999. "\\([^]]+\\)"
  5000. "\\]"
  5001. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5002. "\\]")
  5003. org-any-link-re
  5004. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5005. org-angle-link-re "\\)\\|\\("
  5006. org-plain-link-re "\\)"))))
  5007. (org-make-link-regexps)
  5008. (defvar org-emph-face nil)
  5009. (defun org-do-emphasis-faces (limit)
  5010. "Run through the buffer and emphasize strings."
  5011. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5012. (car org-emphasis-regexp-components))))
  5013. (catch :exit
  5014. (while (re-search-forward quick-re limit t)
  5015. (let* ((marker (match-string 2))
  5016. (verbatim? (member marker '("~" "="))))
  5017. (when (save-excursion
  5018. (goto-char (match-beginning 0))
  5019. (and
  5020. ;; Do not match headline stars. Do not consider
  5021. ;; stars of a headline as closing marker for bold
  5022. ;; markup either.
  5023. (not (and (equal marker "*")
  5024. (save-excursion
  5025. (forward-char)
  5026. (skip-chars-backward "*")
  5027. (looking-at-p org-outline-regexp-bol))))
  5028. ;; Do not match table hlines.
  5029. (not (and (equal marker "+")
  5030. (org-match-line
  5031. "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5032. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5033. ;; At a table row, do not cross cell boundaries.
  5034. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5035. (string-match-p "|" (match-string 4))))))
  5036. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5037. (font-lock-prepend-text-property
  5038. (match-beginning 2) (match-end 2) 'face face)
  5039. (when verbatim?
  5040. (org-remove-flyspell-overlays-in
  5041. (match-beginning 0) (match-end 0)))
  5042. (add-text-properties (match-beginning 2) (match-end 2)
  5043. '(font-lock-multiline t org-emphasis t))
  5044. (when org-hide-emphasis-markers
  5045. (add-text-properties (match-end 4) (match-beginning 5)
  5046. '(invisible org-link))
  5047. (add-text-properties (match-beginning 3) (match-end 3)
  5048. '(invisible org-link)))
  5049. (throw :exit t))))))))
  5050. (defun org-emphasize (&optional char)
  5051. "Insert or change an emphasis, i.e. a font like bold or italic.
  5052. If there is an active region, change that region to a new emphasis.
  5053. If there is no region, just insert the marker characters and position
  5054. the cursor between them.
  5055. CHAR should be the marker character. If it is a space, it means to
  5056. remove the emphasis of the selected region.
  5057. If CHAR is not given (for example in an interactive call) it will be
  5058. prompted for."
  5059. (interactive)
  5060. (let ((erc org-emphasis-regexp-components)
  5061. (string "") beg end move s)
  5062. (if (org-region-active-p)
  5063. (setq beg (region-beginning)
  5064. end (region-end)
  5065. string (buffer-substring beg end))
  5066. (setq move t))
  5067. (unless char
  5068. (message "Emphasis marker or tag: [%s]"
  5069. (mapconcat #'car org-emphasis-alist ""))
  5070. (setq char (read-char-exclusive)))
  5071. (if (equal char ?\s)
  5072. (setq s ""
  5073. move nil)
  5074. (unless (assoc (char-to-string char) org-emphasis-alist)
  5075. (user-error "No such emphasis marker: \"%c\"" char))
  5076. (setq s (char-to-string char)))
  5077. (while (and (> (length string) 1)
  5078. (equal (substring string 0 1) (substring string -1))
  5079. (assoc (substring string 0 1) org-emphasis-alist))
  5080. (setq string (substring string 1 -1)))
  5081. (setq string (concat s string s))
  5082. (when beg (delete-region beg end))
  5083. (unless (or (bolp)
  5084. (string-match (concat "[" (nth 0 erc) "\n]")
  5085. (char-to-string (char-before (point)))))
  5086. (insert " "))
  5087. (unless (or (eobp)
  5088. (string-match (concat "[" (nth 1 erc) "\n]")
  5089. (char-to-string (char-after (point)))))
  5090. (insert " ") (backward-char 1))
  5091. (insert string)
  5092. (and move (backward-char 1))))
  5093. (defconst org-nonsticky-props
  5094. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5095. (defsubst org-rear-nonsticky-at (pos)
  5096. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5097. (defun org-activate-links (limit)
  5098. "Add link properties to links.
  5099. This includes angle, plain, and bracket links."
  5100. (catch :exit
  5101. (while (re-search-forward org-any-link-re limit t)
  5102. (let* ((start (match-beginning 0))
  5103. (end (match-end 0))
  5104. (style (cond ((eq ?< (char-after start)) 'angle)
  5105. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5106. (t 'plain))))
  5107. (when (and (memq style org-highlight-links)
  5108. ;; Do not confuse plain links with tags.
  5109. (not (and (eq style 'plain)
  5110. (let ((face (get-text-property
  5111. (max (1- start) (point-min)) 'face)))
  5112. (if (consp face) (memq 'org-tag face)
  5113. (eq 'org-tag face))))))
  5114. (let* ((link-object (save-excursion
  5115. (goto-char start)
  5116. (save-match-data (org-element-link-parser))))
  5117. (link (org-element-property :raw-link link-object))
  5118. (type (org-element-property :type link-object))
  5119. (path (org-element-property :path link-object))
  5120. (properties ;for link's visible part
  5121. (list
  5122. 'face (pcase (org-link-get-parameter type :face)
  5123. ((and (pred functionp) face) (funcall face path))
  5124. ((and (pred facep) face) face)
  5125. ((and (pred consp) face) face) ;anonymous
  5126. (_ 'org-link))
  5127. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5128. 'highlight)
  5129. 'keymap (or (org-link-get-parameter type :keymap)
  5130. org-mouse-map)
  5131. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5132. ((and (pred stringp) echo) echo)
  5133. ((and (pred functionp) echo) echo)
  5134. (_ (concat "LINK: " link)))
  5135. 'htmlize-link (pcase (org-link-get-parameter type
  5136. :htmlize-link)
  5137. ((and (pred functionp) f) (funcall f))
  5138. (_ `(:uri ,link)))
  5139. 'font-lock-multiline t)))
  5140. (org-remove-flyspell-overlays-in start end)
  5141. (org-rear-nonsticky-at end)
  5142. (if (not (eq 'bracket style))
  5143. (add-text-properties start end properties)
  5144. ;; Handle invisible parts in bracket links.
  5145. (remove-text-properties start end '(invisible nil))
  5146. (let ((hidden
  5147. (append `(invisible
  5148. ,(or (org-link-get-parameter type :display)
  5149. 'org-link))
  5150. properties))
  5151. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5152. (visible-end (or (match-end 4) (match-end 2))))
  5153. (add-text-properties start visible-start hidden)
  5154. (add-text-properties visible-start visible-end properties)
  5155. (add-text-properties visible-end end hidden)
  5156. (org-rear-nonsticky-at visible-start)
  5157. (org-rear-nonsticky-at visible-end)))
  5158. (let ((f (org-link-get-parameter type :activate-func)))
  5159. (when (functionp f)
  5160. (funcall f start end path (eq style 'bracket))))
  5161. (throw :exit t))))) ;signal success
  5162. nil))
  5163. (defun org-activate-code (limit)
  5164. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5165. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5166. (remove-text-properties (match-beginning 0) (match-end 0)
  5167. '(display t invisible t intangible t))
  5168. t))
  5169. (defcustom org-src-fontify-natively t
  5170. "When non-nil, fontify code in code blocks.
  5171. See also the `org-block' face."
  5172. :type 'boolean
  5173. :version "26.1"
  5174. :package-version '(Org . "8.3")
  5175. :group 'org-appearance
  5176. :group 'org-babel)
  5177. (defcustom org-allow-promoting-top-level-subtree nil
  5178. "When non-nil, allow promoting a top level subtree.
  5179. The leading star of the top level headline will be replaced
  5180. by a #."
  5181. :type 'boolean
  5182. :version "24.1"
  5183. :group 'org-appearance)
  5184. (defun org-fontify-meta-lines-and-blocks (limit)
  5185. (condition-case nil
  5186. (org-fontify-meta-lines-and-blocks-1 limit)
  5187. (error (message "org-mode fontification error in %S at %d"
  5188. (current-buffer)
  5189. (line-number-at-pos)))))
  5190. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5191. "Fontify #+ lines and blocks."
  5192. (let ((case-fold-search t))
  5193. (when (re-search-forward
  5194. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5195. limit t)
  5196. (let ((beg (match-beginning 0))
  5197. (block-start (match-end 0))
  5198. (block-end nil)
  5199. (lang (match-string 7))
  5200. (beg1 (line-beginning-position 2))
  5201. (dc1 (downcase (match-string 2)))
  5202. (dc3 (downcase (match-string 3)))
  5203. end end1 quoting block-type)
  5204. (cond
  5205. ((and (match-end 4) (equal dc3 "+begin"))
  5206. ;; Truly a block
  5207. (setq block-type (downcase (match-string 5))
  5208. quoting (member block-type org-protecting-blocks))
  5209. (when (re-search-forward
  5210. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5211. nil t) ;; on purpose, we look further than LIMIT
  5212. (setq end (min (point-max) (match-end 0))
  5213. end1 (min (point-max) (1- (match-beginning 0))))
  5214. (setq block-end (match-beginning 0))
  5215. (when quoting
  5216. (org-remove-flyspell-overlays-in beg1 end1)
  5217. (remove-text-properties beg end
  5218. '(display t invisible t intangible t)))
  5219. (add-text-properties
  5220. beg end '(font-lock-fontified t font-lock-multiline t))
  5221. (add-text-properties beg beg1 '(face org-meta-line))
  5222. (org-remove-flyspell-overlays-in beg beg1)
  5223. (add-text-properties ; For end_src
  5224. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5225. (org-remove-flyspell-overlays-in end1 end)
  5226. (cond
  5227. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5228. (org-src-font-lock-fontify-block lang block-start block-end)
  5229. (add-text-properties beg1 block-end '(src-block t)))
  5230. (quoting
  5231. (add-text-properties beg1 (min (point-max) (1+ end1))
  5232. (list 'face
  5233. (list :inherit
  5234. (let ((face-name
  5235. (intern (format "org-block-%s" lang))))
  5236. (append (and (facep face-name) (list face-name))
  5237. '(org-block))))))) ; end of source block
  5238. ((not org-fontify-quote-and-verse-blocks))
  5239. ((string= block-type "quote")
  5240. (add-face-text-property
  5241. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5242. ((string= block-type "verse")
  5243. (add-face-text-property
  5244. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5245. (add-text-properties beg beg1 '(face org-block-begin-line))
  5246. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5247. '(face org-block-end-line))
  5248. t))
  5249. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5250. (org-remove-flyspell-overlays-in
  5251. (match-beginning 0)
  5252. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5253. (add-text-properties
  5254. beg (match-end 3)
  5255. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5256. '(font-lock-fontified t invisible t)
  5257. '(font-lock-fontified t face org-document-info-keyword)))
  5258. (add-text-properties
  5259. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5260. (if (string-equal dc1 "+title:")
  5261. '(font-lock-fontified t face org-document-title)
  5262. '(font-lock-fontified t face org-document-info))))
  5263. ((string-prefix-p "+caption" dc1)
  5264. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5265. (remove-text-properties (match-beginning 0) (match-end 0)
  5266. '(display t invisible t intangible t))
  5267. ;; Handle short captions.
  5268. (save-excursion
  5269. (beginning-of-line)
  5270. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5271. (add-text-properties (line-beginning-position) (match-end 1)
  5272. '(font-lock-fontified t face org-meta-line))
  5273. (add-text-properties (match-end 0) (line-end-position)
  5274. '(font-lock-fontified t face org-block))
  5275. t)
  5276. ((member dc3 '(" " ""))
  5277. (org-remove-flyspell-overlays-in beg (match-end 0))
  5278. (add-text-properties
  5279. beg (match-end 0)
  5280. '(font-lock-fontified t face font-lock-comment-face)))
  5281. (t ;; just any other in-buffer setting, but not indented
  5282. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5283. (remove-text-properties (match-beginning 0) (match-end 0)
  5284. '(display t invisible t intangible t))
  5285. (add-text-properties beg (match-end 0)
  5286. '(font-lock-fontified t face org-meta-line))
  5287. t))))))
  5288. (defun org-fontify-drawers (limit)
  5289. "Fontify drawers."
  5290. (when (re-search-forward org-drawer-regexp limit t)
  5291. (add-text-properties
  5292. (match-beginning 0) (match-end 0)
  5293. '(font-lock-fontified t face org-special-keyword))
  5294. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5295. t))
  5296. (defun org-fontify-macros (limit)
  5297. "Fontify macros."
  5298. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5299. (add-text-properties
  5300. (match-beginning 0) (match-end 0)
  5301. '(font-lock-fontified t face org-macro))
  5302. (when org-hide-macro-markers
  5303. (add-text-properties (match-end 2) (match-beginning 2)
  5304. '(invisible t))
  5305. (add-text-properties (match-beginning 1) (match-end 1)
  5306. '(invisible t)))
  5307. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5308. t))
  5309. (defun org-activate-footnote-links (limit)
  5310. "Add text properties for footnotes."
  5311. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5312. (when fn
  5313. (let* ((beg (nth 1 fn))
  5314. (end (nth 2 fn))
  5315. (label (car fn))
  5316. (referencep (/= (line-beginning-position) beg)))
  5317. (when (and referencep (nth 3 fn))
  5318. (save-excursion
  5319. (goto-char beg)
  5320. (search-forward (or label "fn:"))
  5321. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5322. (add-text-properties beg end
  5323. (list 'mouse-face 'highlight
  5324. 'keymap org-mouse-map
  5325. 'help-echo
  5326. (if referencep "Footnote reference"
  5327. "Footnote definition")
  5328. 'font-lock-fontified t
  5329. 'font-lock-multiline t
  5330. 'face 'org-footnote))))))
  5331. (defun org-activate-dates (limit)
  5332. "Add text properties for dates."
  5333. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5334. (not (equal (char-before (match-beginning 0)) 91)))
  5335. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5336. (add-text-properties (match-beginning 0) (match-end 0)
  5337. (list 'mouse-face 'highlight
  5338. 'keymap org-mouse-map))
  5339. (org-rear-nonsticky-at (match-end 0))
  5340. (when org-display-custom-times
  5341. ;; If it's a date range, activate custom time for second date.
  5342. (when (match-end 3)
  5343. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5344. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5345. t))
  5346. (defvar-local org-target-link-regexp nil
  5347. "Regular expression matching radio targets in plain text.")
  5348. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5349. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5350. border border border))
  5351. "Regular expression matching a link target.")
  5352. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5353. "Regular expression matching a radio target.")
  5354. (defconst org-any-target-regexp
  5355. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5356. "Regular expression matching any target.")
  5357. (defun org-activate-target-links (limit)
  5358. "Add text properties for target matches."
  5359. (when org-target-link-regexp
  5360. (let ((case-fold-search t))
  5361. (when (re-search-forward org-target-link-regexp limit t)
  5362. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5363. (add-text-properties (match-beginning 1) (match-end 1)
  5364. (list 'mouse-face 'highlight
  5365. 'keymap org-mouse-map
  5366. 'help-echo "Radio target link"
  5367. 'org-linked-text t))
  5368. (org-rear-nonsticky-at (match-end 1))
  5369. t))))
  5370. (defun org-update-radio-target-regexp ()
  5371. "Find all radio targets in this file and update the regular expression.
  5372. Also refresh fontification if needed."
  5373. (interactive)
  5374. (let ((old-regexp org-target-link-regexp)
  5375. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5376. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5377. (targets
  5378. (org-with-wide-buffer
  5379. (goto-char (point-min))
  5380. (let (rtn)
  5381. (while (re-search-forward org-radio-target-regexp nil t)
  5382. ;; Make sure point is really within the object.
  5383. (backward-char)
  5384. (let ((obj (org-element-context)))
  5385. (when (eq (org-element-type obj) 'radio-target)
  5386. (cl-pushnew (org-element-property :value obj) rtn
  5387. :test #'equal))))
  5388. rtn))))
  5389. (setq org-target-link-regexp
  5390. (and targets
  5391. (concat before-re
  5392. (mapconcat
  5393. (lambda (x)
  5394. (replace-regexp-in-string
  5395. " +" "\\s-+" (regexp-quote x) t t))
  5396. targets
  5397. "\\|")
  5398. after-re)))
  5399. (unless (equal old-regexp org-target-link-regexp)
  5400. ;; Clean-up cache.
  5401. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5402. ((not org-target-link-regexp) old-regexp)
  5403. (t
  5404. (concat before-re
  5405. (mapconcat
  5406. (lambda (re)
  5407. (substring re (length before-re)
  5408. (- (length after-re))))
  5409. (list old-regexp org-target-link-regexp)
  5410. "\\|")
  5411. after-re)))))
  5412. (org-with-wide-buffer
  5413. (goto-char (point-min))
  5414. (while (re-search-forward regexp nil t)
  5415. (org-element-cache-refresh (match-beginning 1)))))
  5416. ;; Re fontify buffer.
  5417. (when (memq 'radio org-highlight-links)
  5418. (org-restart-font-lock)))))
  5419. (defun org-hide-wide-columns (limit)
  5420. (let (s e)
  5421. (setq s (text-property-any (point) (or limit (point-max))
  5422. 'org-cwidth t))
  5423. (when s
  5424. (setq e (next-single-property-change s 'org-cwidth))
  5425. (add-text-properties s e '(invisible org-cwidth))
  5426. (goto-char e)
  5427. t)))
  5428. (defvar org-latex-and-related-regexp nil
  5429. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5430. (defun org-compute-latex-and-related-regexp ()
  5431. "Compute regular expression for LaTeX, entities and sub/superscript.
  5432. Result depends on variable `org-highlight-latex-and-related'."
  5433. (setq-local
  5434. org-latex-and-related-regexp
  5435. (let* ((re-sub
  5436. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5437. ((eq org-use-sub-superscripts '{})
  5438. (list org-match-substring-with-braces-regexp))
  5439. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5440. (re-latex
  5441. (when (memq 'latex org-highlight-latex-and-related)
  5442. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5443. (delq nil
  5444. (mapcar (lambda (x)
  5445. (and (member (car x) matchers) (nth 1 x)))
  5446. org-latex-regexps)))))
  5447. (re-entities
  5448. (when (memq 'entities org-highlight-latex-and-related)
  5449. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5450. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5451. (defun org-do-latex-and-related (limit)
  5452. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5453. LIMIT bounds the search for syntax to highlight. Stop at first
  5454. highlighted object, if any. Return t if some highlighting was
  5455. done, nil otherwise."
  5456. (when (org-string-nw-p org-latex-and-related-regexp)
  5457. (catch 'found
  5458. (while (re-search-forward org-latex-and-related-regexp limit t)
  5459. (unless
  5460. (cl-some
  5461. (lambda (f)
  5462. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5463. (save-excursion
  5464. (goto-char (1+ (match-beginning 0)))
  5465. (face-at-point nil t)))
  5466. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5467. '(?_ ?^))
  5468. 1
  5469. 0)))
  5470. (font-lock-prepend-text-property
  5471. (+ offset (match-beginning 0)) (match-end 0)
  5472. 'face 'org-latex-and-related)
  5473. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5474. '(font-lock-multiline t)))
  5475. (throw 'found t)))
  5476. nil)))
  5477. (defun org-restart-font-lock ()
  5478. "Restart `font-lock-mode', to force refontification."
  5479. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5480. (font-lock-mode -1)
  5481. (font-lock-mode 1)))
  5482. (defun org-activate-tags (limit)
  5483. (when (re-search-forward
  5484. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5485. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5486. (add-text-properties (match-beginning 1) (match-end 1)
  5487. (list 'mouse-face 'highlight
  5488. 'keymap org-mouse-map))
  5489. (org-rear-nonsticky-at (match-end 1))
  5490. t))
  5491. (defun org-outline-level ()
  5492. "Compute the outline level of the heading at point.
  5493. If this is called at a normal headline, the level is the number
  5494. of stars. Use `org-reduced-level' to remove the effect of
  5495. `org-odd-levels'. Unlike to `org-current-level', this function
  5496. takes into consideration inlinetasks."
  5497. (org-with-wide-buffer
  5498. (end-of-line)
  5499. (if (re-search-backward org-outline-regexp-bol nil t)
  5500. (1- (- (match-end 0) (match-beginning 0)))
  5501. 0)))
  5502. (defvar org-font-lock-keywords nil)
  5503. (defsubst org-re-property (property &optional literal allow-null value)
  5504. "Return a regexp matching a PROPERTY line.
  5505. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5506. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5507. non-nil, match properties even without a value.
  5508. Match group 3 is set to the value when it exists. If there is no
  5509. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5510. With optional argument VALUE, match only property lines with
  5511. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5512. unless LITERAL is non-nil."
  5513. (concat
  5514. "^\\(?4:[ \t]*\\)"
  5515. (format "\\(?1::\\(?2:%s\\):\\)"
  5516. (if literal property (regexp-quote property)))
  5517. (cond (value
  5518. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5519. (if literal value (regexp-quote value))))
  5520. (allow-null
  5521. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5522. (t
  5523. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5524. (defconst org-property-re
  5525. (org-re-property "\\S-+" 'literal t)
  5526. "Regular expression matching a property line.
  5527. There are four matching groups:
  5528. 1: :PROPKEY: including the leading and trailing colon,
  5529. 2: PROPKEY without the leading and trailing colon,
  5530. 3: PROPVAL without leading or trailing spaces,
  5531. 4: the indentation of the current line,
  5532. 5: trailing whitespace.")
  5533. (defvar org-font-lock-hook nil
  5534. "Functions to be called for special font lock stuff.")
  5535. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5536. (defvar org-font-lock-set-keywords-hook nil
  5537. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5538. This is called after `org-font-lock-extra-keywords' is defined, but before
  5539. it is installed to be used by font lock. This can be useful if something
  5540. needs to be inserted at a specific position in the font-lock sequence.")
  5541. (defun org-font-lock-hook (limit)
  5542. "Run `org-font-lock-hook' within LIMIT."
  5543. (run-hook-with-args 'org-font-lock-hook limit))
  5544. (defun org-set-font-lock-defaults ()
  5545. "Set font lock defaults for the current buffer."
  5546. (let* ((em org-fontify-emphasized-text)
  5547. (lk org-highlight-links)
  5548. (org-font-lock-extra-keywords
  5549. (list
  5550. ;; Call the hook
  5551. '(org-font-lock-hook)
  5552. ;; Headlines
  5553. `(,(if org-fontify-whole-heading-line
  5554. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5555. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5556. (1 (org-get-level-face 1))
  5557. (2 (org-get-level-face 2))
  5558. (3 (org-get-level-face 3)))
  5559. ;; Table lines
  5560. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5561. (1 'org-table t))
  5562. ;; Table internals
  5563. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5564. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5565. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5566. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5567. ;; Drawers
  5568. '(org-fontify-drawers)
  5569. ;; Properties
  5570. (list org-property-re
  5571. '(1 'org-special-keyword t)
  5572. '(3 'org-property-value t))
  5573. ;; Link related fontification.
  5574. '(org-activate-links)
  5575. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5576. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5577. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5578. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5579. ;; Targets.
  5580. (list org-any-target-regexp '(0 'org-target t))
  5581. ;; Diary sexps.
  5582. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5583. ;; Macro
  5584. '(org-fontify-macros)
  5585. '(org-hide-wide-columns (0 nil append))
  5586. ;; TODO keyword
  5587. (list (format org-heading-keyword-regexp-format
  5588. org-todo-regexp)
  5589. '(2 (org-get-todo-face 2) t))
  5590. ;; DONE
  5591. (if org-fontify-done-headline
  5592. (list (format org-heading-keyword-regexp-format
  5593. (concat
  5594. "\\(?:"
  5595. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5596. "\\)"))
  5597. '(2 'org-headline-done t))
  5598. nil)
  5599. ;; Priorities
  5600. '(org-font-lock-add-priority-faces)
  5601. ;; Tags
  5602. '(org-font-lock-add-tag-faces)
  5603. ;; Tags groups
  5604. (when (and org-group-tags org-tag-groups-alist)
  5605. (list (concat org-outline-regexp-bol ".+\\(:"
  5606. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5607. ":\\).*$")
  5608. '(1 'org-tag-group prepend)))
  5609. ;; Special keywords
  5610. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5611. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5612. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5613. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5614. ;; Emphasis
  5615. (when em '(org-do-emphasis-faces))
  5616. ;; Checkboxes
  5617. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5618. 1 'org-checkbox prepend)
  5619. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5620. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5621. (0 (org-get-checkbox-statistics-face) t)))
  5622. ;; Description list items
  5623. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5624. 1 'org-list-dt prepend)
  5625. ;; ARCHIVEd headings
  5626. (list (concat
  5627. org-outline-regexp-bol
  5628. "\\(.*:" org-archive-tag ":.*\\)")
  5629. '(1 'org-archived prepend))
  5630. ;; Specials
  5631. '(org-do-latex-and-related)
  5632. '(org-fontify-entities)
  5633. '(org-raise-scripts)
  5634. ;; Code
  5635. '(org-activate-code (1 'org-code t))
  5636. ;; COMMENT
  5637. (list (format
  5638. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5639. org-todo-regexp
  5640. org-comment-string)
  5641. '(9 'org-special-keyword t))
  5642. ;; Blocks and meta lines
  5643. '(org-fontify-meta-lines-and-blocks))))
  5644. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5645. (run-hooks 'org-font-lock-set-keywords-hook)
  5646. ;; Now set the full font-lock-keywords
  5647. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5648. (setq-local font-lock-defaults
  5649. '(org-font-lock-keywords t nil nil backward-paragraph))
  5650. (kill-local-variable 'font-lock-keywords)
  5651. nil))
  5652. (defun org-toggle-pretty-entities ()
  5653. "Toggle the composition display of entities as UTF8 characters."
  5654. (interactive)
  5655. (setq-local org-pretty-entities (not org-pretty-entities))
  5656. (org-restart-font-lock)
  5657. (if org-pretty-entities
  5658. (message "Entities are now displayed as UTF8 characters")
  5659. (save-restriction
  5660. (widen)
  5661. (decompose-region (point-min) (point-max))
  5662. (message "Entities are now displayed as plain text"))))
  5663. (defvar-local org-custom-properties-overlays nil
  5664. "List of overlays used for custom properties.")
  5665. (defun org-toggle-custom-properties-visibility ()
  5666. "Display or hide properties in `org-custom-properties'."
  5667. (interactive)
  5668. (if org-custom-properties-overlays
  5669. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5670. (setq org-custom-properties-overlays nil))
  5671. (when org-custom-properties
  5672. (org-with-wide-buffer
  5673. (goto-char (point-min))
  5674. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5675. (while (re-search-forward regexp nil t)
  5676. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5677. (when (and end (< (point) end))
  5678. ;; Hide first custom property in current drawer.
  5679. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5680. (overlay-put o 'invisible t)
  5681. (overlay-put o 'org-custom-property t)
  5682. (push o org-custom-properties-overlays))
  5683. ;; Hide additional custom properties in the same drawer.
  5684. (while (re-search-forward regexp end t)
  5685. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5686. (overlay-put o 'invisible t)
  5687. (overlay-put o 'org-custom-property t)
  5688. (push o org-custom-properties-overlays)))))
  5689. ;; Each entry is limited to a single property drawer.
  5690. (outline-next-heading)))))))
  5691. (defun org-fontify-entities (limit)
  5692. "Find an entity to fontify."
  5693. (let (ee)
  5694. (when org-pretty-entities
  5695. (catch 'match
  5696. ;; "\_ "-family is left out on purpose. Only the first one,
  5697. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5698. ;; confusing when adding a second white space character.
  5699. (while (re-search-forward
  5700. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5701. limit t)
  5702. (when (and (not (org-at-comment-p))
  5703. (setq ee (org-entity-get (match-string 1)))
  5704. (= (length (nth 6 ee)) 1))
  5705. (let* ((end (if (equal (match-string 2) "{}")
  5706. (match-end 2)
  5707. (match-end 1))))
  5708. (add-text-properties
  5709. (match-beginning 0) end
  5710. (list 'font-lock-fontified t))
  5711. (compose-region (match-beginning 0) end
  5712. (nth 6 ee) nil)
  5713. (backward-char 1)
  5714. (throw 'match t))))
  5715. nil))))
  5716. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5717. "Fontify string S like in Org mode."
  5718. (with-temp-buffer
  5719. (insert s)
  5720. (let ((org-odd-levels-only odd-levels))
  5721. (org-mode)
  5722. (org-font-lock-ensure)
  5723. (buffer-string))))
  5724. (defvar org-m nil)
  5725. (defvar org-l nil)
  5726. (defvar org-f nil)
  5727. (defun org-get-level-face (n)
  5728. "Get the right face for match N in font-lock matching of headlines."
  5729. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5730. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5731. (if org-cycle-level-faces
  5732. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5733. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5734. (cond
  5735. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5736. ((eq n 2) org-f)
  5737. (t (unless org-level-color-stars-only org-f))))
  5738. (defun org-face-from-face-or-color (context inherit face-or-color)
  5739. "Create a face list that inherits INHERIT, but sets the foreground color.
  5740. When FACE-OR-COLOR is not a string, just return it."
  5741. (if (stringp face-or-color)
  5742. (list :inherit inherit
  5743. (cdr (assoc context org-faces-easy-properties))
  5744. face-or-color)
  5745. face-or-color))
  5746. (defun org-get-todo-face (kwd)
  5747. "Get the right face for a TODO keyword KWD.
  5748. If KWD is a number, get the corresponding match group."
  5749. (when (numberp kwd) (setq kwd (match-string kwd)))
  5750. (or (org-face-from-face-or-color
  5751. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5752. (and (member kwd org-done-keywords) 'org-done)
  5753. 'org-todo))
  5754. (defun org-get-priority-face (priority)
  5755. "Get the right face for PRIORITY.
  5756. PRIORITY is a character."
  5757. (or (org-face-from-face-or-color
  5758. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5759. 'org-priority))
  5760. (defun org-get-tag-face (tag)
  5761. "Get the right face for TAG.
  5762. If TAG is a number, get the corresponding match group."
  5763. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5764. (or (org-face-from-face-or-color
  5765. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5766. 'org-tag)))
  5767. (defun org-font-lock-add-priority-faces (limit)
  5768. "Add the special priority faces."
  5769. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5770. (add-text-properties
  5771. (match-beginning 1) (match-end 1)
  5772. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5773. 'font-lock-fontified t))))
  5774. (defun org-font-lock-add-tag-faces (limit)
  5775. "Add the special tag faces."
  5776. (when (and org-tag-faces org-tags-special-faces-re)
  5777. (while (re-search-forward org-tags-special-faces-re limit t)
  5778. (add-text-properties (match-beginning 1) (match-end 1)
  5779. (list 'face (org-get-tag-face 1)
  5780. 'font-lock-fontified t))
  5781. (backward-char 1))))
  5782. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5783. "Remove fontification and activation overlays from links."
  5784. (font-lock-default-unfontify-region beg end)
  5785. (let* ((buffer-undo-list t)
  5786. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5787. (inhibit-modification-hooks t)
  5788. deactivate-mark buffer-file-name buffer-file-truename)
  5789. (decompose-region beg end)
  5790. (remove-text-properties beg end
  5791. '(mouse-face t keymap t org-linked-text t
  5792. invisible t intangible t
  5793. org-emphasis t))
  5794. (org-remove-font-lock-display-properties beg end)))
  5795. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5796. ((raise 0.3) (height 0.7))
  5797. ((raise -0.5))
  5798. ((raise 0.5)))
  5799. "Display properties for showing superscripts and subscripts.")
  5800. (defun org-remove-font-lock-display-properties (beg end)
  5801. "Remove specific display properties that have been added by font lock.
  5802. The will remove the raise properties that are used to show superscripts
  5803. and subscripts."
  5804. (let (next prop)
  5805. (while (< beg end)
  5806. (setq next (next-single-property-change beg 'display nil end)
  5807. prop (get-text-property beg 'display))
  5808. (when (member prop org-script-display)
  5809. (put-text-property beg next 'display nil))
  5810. (setq beg next))))
  5811. (defun org-raise-scripts (limit)
  5812. "Add raise properties to sub/superscripts."
  5813. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5814. (re-search-forward
  5815. (if (eq org-use-sub-superscripts t)
  5816. org-match-substring-regexp
  5817. org-match-substring-with-braces-regexp)
  5818. limit t))
  5819. (let* ((pos (point)) table-p comment-p
  5820. (mpos (match-beginning 3))
  5821. (emph-p (get-text-property mpos 'org-emphasis))
  5822. (link-p (get-text-property mpos 'mouse-face))
  5823. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5824. (goto-char (point-at-bol))
  5825. (setq table-p (looking-at-p org-table-dataline-regexp)
  5826. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5827. (goto-char pos)
  5828. ;; Handle a_b^c
  5829. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5830. (unless (or comment-p emph-p link-p keyw-p)
  5831. (put-text-property (match-beginning 3) (match-end 0)
  5832. 'display
  5833. (if (equal (char-after (match-beginning 2)) ?^)
  5834. (nth (if table-p 3 1) org-script-display)
  5835. (nth (if table-p 2 0) org-script-display)))
  5836. (add-text-properties (match-beginning 2) (match-end 2)
  5837. (list 'invisible t))
  5838. (when (and (eq (char-after (match-beginning 3)) ?{)
  5839. (eq (char-before (match-end 3)) ?}))
  5840. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5841. (list 'invisible t))
  5842. (add-text-properties (1- (match-end 3)) (match-end 3)
  5843. (list 'invisible t))))
  5844. t)))
  5845. ;;;; Visibility cycling, including org-goto and indirect buffer
  5846. ;;; Cycling
  5847. (defvar-local org-cycle-global-status nil)
  5848. (put 'org-cycle-global-status 'org-state t)
  5849. (defvar-local org-cycle-subtree-status nil)
  5850. (put 'org-cycle-subtree-status 'org-state t)
  5851. (defvar org-inlinetask-min-level)
  5852. (defun org-unlogged-message (&rest args)
  5853. "Display a message, but avoid logging it in the *Messages* buffer."
  5854. (let ((message-log-max nil))
  5855. (apply 'message args)))
  5856. ;;;###autoload
  5857. (defun org-cycle (&optional arg)
  5858. "TAB-action and visibility cycling for Org mode.
  5859. This is the command invoked in Org mode by the `TAB' key. Its main
  5860. purpose is outline visibility cycling, but it also invokes other actions
  5861. in special contexts.
  5862. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5863. the entire
  5864. buffer through 3 states (global cycling)
  5865. 1. OVERVIEW: Show only top-level headlines.
  5866. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5867. 3. SHOW ALL: Show everything.
  5868. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5869. switch to the startup visibility,
  5870. determined by the variable `org-startup-folded', and by any VISIBILITY
  5871. properties in the buffer.
  5872. With a `\\[universal-argument] \\[universal-argument] \
  5873. \\[universal-argument]' prefix argument, show the entire buffer, including
  5874. any drawers.
  5875. When inside a table, re-align the table and move to the next field.
  5876. When point is at the beginning of a headline, rotate the subtree started
  5877. by this line through 3 different states (local cycling)
  5878. 1. FOLDED: Only the main headline is shown.
  5879. 2. CHILDREN: The main headline and the direct children are shown.
  5880. From this state, you can move to one of the children
  5881. and zoom in further.
  5882. 3. SUBTREE: Show the entire subtree, including body text.
  5883. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5884. When point is at the beginning of an empty headline and the variable
  5885. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5886. of the headline by demoting and promoting it to likely levels. This
  5887. speeds up creation document structure by pressing `TAB' once or several
  5888. times right after creating a new headline.
  5889. When there is a numeric prefix, go up to a heading with level ARG, do
  5890. a `show-subtree' and return to the previous cursor position. If ARG
  5891. is negative, go up that many levels.
  5892. When point is not at the beginning of a headline, execute the global
  5893. binding for `TAB', which is re-indenting the line. See the option
  5894. `org-cycle-emulate-tab' for details.
  5895. As a special case, if point is at the beginning of the buffer and there is
  5896. no headline in line 1, this function will act as if called with prefix arg
  5897. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5898. prefix arg, but only
  5899. if the variable `org-cycle-global-at-bob' is t."
  5900. (interactive "P")
  5901. (org-load-modules-maybe)
  5902. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5903. (and org-cycle-level-after-item/entry-creation
  5904. (or (org-cycle-level)
  5905. (org-cycle-item-indentation))))
  5906. (let* ((limit-level
  5907. (or org-cycle-max-level
  5908. (and (boundp 'org-inlinetask-min-level)
  5909. org-inlinetask-min-level
  5910. (1- org-inlinetask-min-level))))
  5911. (nstars (and limit-level
  5912. (if org-odd-levels-only
  5913. (and limit-level (1- (* limit-level 2)))
  5914. limit-level)))
  5915. (org-outline-regexp
  5916. (if (not (derived-mode-p 'org-mode))
  5917. outline-regexp
  5918. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5919. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5920. (not (looking-at org-outline-regexp))))
  5921. (org-cycle-hook
  5922. (if bob-special
  5923. (delq 'org-optimize-window-after-visibility-change
  5924. (copy-sequence org-cycle-hook))
  5925. org-cycle-hook))
  5926. (pos (point)))
  5927. (cond
  5928. ((equal arg '(16))
  5929. (setq last-command 'dummy)
  5930. (org-set-startup-visibility)
  5931. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5932. ((equal arg '(64))
  5933. (outline-show-all)
  5934. (org-unlogged-message "Entire buffer visible, including drawers"))
  5935. ((equal arg '(4)) (org-cycle-internal-global))
  5936. ;; Try hiding block at point.
  5937. ((org-hide-block-toggle-maybe))
  5938. ;; Try cdlatex TAB completion
  5939. ((org-try-cdlatex-tab))
  5940. ;; Table: enter it or move to the next field.
  5941. ((org-at-table-p 'any)
  5942. (if (org-at-table.el-p)
  5943. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5944. Use `\\[org-edit-special]' to edit table.el tables"))
  5945. (if arg (org-table-edit-field t)
  5946. (org-table-justify-field-maybe)
  5947. (call-interactively 'org-table-next-field))))
  5948. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5949. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5950. (bob-special (org-cycle-internal-global))
  5951. ;; Drawers: delegate to `org-flag-drawer'.
  5952. ((save-excursion
  5953. (beginning-of-line 1)
  5954. (looking-at org-drawer-regexp))
  5955. (org-flag-drawer ; toggle block visibility
  5956. (not (get-char-property (match-end 0) 'invisible))))
  5957. ;; Show-subtree, ARG levels up from here.
  5958. ((integerp arg)
  5959. (save-excursion
  5960. (org-back-to-heading)
  5961. (outline-up-heading (if (< arg 0) (- arg)
  5962. (- (funcall outline-level) arg)))
  5963. (org-show-subtree)))
  5964. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5965. ((and (featurep 'org-inlinetask)
  5966. (org-inlinetask-at-task-p)
  5967. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5968. (org-inlinetask-toggle-visibility))
  5969. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5970. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5971. (save-excursion (move-beginning-of-line 1)
  5972. (looking-at org-outline-regexp)))
  5973. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5974. (org-cycle-internal-local))
  5975. ;; From there: TAB emulation and template completion.
  5976. (buffer-read-only (org-back-to-heading))
  5977. ((run-hook-with-args-until-success
  5978. 'org-tab-after-check-for-cycling-hook))
  5979. ((org-try-structure-completion))
  5980. ((run-hook-with-args-until-success
  5981. 'org-tab-before-tab-emulation-hook))
  5982. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5983. (or (not (bolp))
  5984. (not (looking-at org-outline-regexp))))
  5985. (call-interactively (global-key-binding "\t")))
  5986. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5987. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5988. (or (and (eq org-cycle-emulate-tab 'white)
  5989. (= (match-end 0) (point-at-eol)))
  5990. (and (eq org-cycle-emulate-tab 'whitestart)
  5991. (>= (match-end 0) pos))))
  5992. t
  5993. (eq org-cycle-emulate-tab t))
  5994. (call-interactively (global-key-binding "\t")))
  5995. (t (save-excursion
  5996. (org-back-to-heading)
  5997. (org-cycle)))))))
  5998. (defun org-cycle-internal-global ()
  5999. "Do the global cycling action."
  6000. ;; Hack to avoid display of messages for .org attachments in Gnus
  6001. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6002. (cond
  6003. ((and (eq last-command this-command)
  6004. (eq org-cycle-global-status 'overview))
  6005. ;; We just created the overview - now do table of contents
  6006. ;; This can be slow in very large buffers, so indicate action
  6007. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6008. (unless ga (org-unlogged-message "CONTENTS..."))
  6009. (org-content)
  6010. (unless ga (org-unlogged-message "CONTENTS...done"))
  6011. (setq org-cycle-global-status 'contents)
  6012. (run-hook-with-args 'org-cycle-hook 'contents))
  6013. ((and (eq last-command this-command)
  6014. (eq org-cycle-global-status 'contents))
  6015. ;; We just showed the table of contents - now show everything
  6016. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6017. (outline-show-all)
  6018. (unless ga (org-unlogged-message "SHOW ALL"))
  6019. (setq org-cycle-global-status 'all)
  6020. (run-hook-with-args 'org-cycle-hook 'all))
  6021. (t
  6022. ;; Default action: go to overview
  6023. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6024. (org-overview)
  6025. (unless ga (org-unlogged-message "OVERVIEW"))
  6026. (setq org-cycle-global-status 'overview)
  6027. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6028. (defvar org-called-with-limited-levels nil
  6029. "Non-nil when `org-with-limited-levels' is currently active.")
  6030. (defun org-invisible-p (&optional pos)
  6031. "Non-nil if the character after POS is invisible.
  6032. If POS is nil, use `point' instead."
  6033. (get-char-property (or pos (point)) 'invisible))
  6034. (defun org-cycle-internal-local ()
  6035. "Do the local cycling action."
  6036. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6037. ;; First, determine end of headline (EOH), end of subtree or item
  6038. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6039. (save-excursion
  6040. (if (org-at-item-p)
  6041. (progn
  6042. (beginning-of-line)
  6043. (setq struct (org-list-struct))
  6044. (setq eoh (point-at-eol))
  6045. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6046. (setq has-children (org-list-has-child-p (point) struct)))
  6047. (org-back-to-heading)
  6048. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6049. (setq eos (save-excursion (org-end-of-subtree t t)
  6050. (when (bolp) (backward-char)) (point)))
  6051. (setq has-children
  6052. (or (save-excursion
  6053. (let ((level (funcall outline-level)))
  6054. (outline-next-heading)
  6055. (and (org-at-heading-p t)
  6056. (> (funcall outline-level) level))))
  6057. (save-excursion
  6058. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6059. ;; Determine end invisible part of buffer (EOL)
  6060. (beginning-of-line 2)
  6061. (while (and (not (eobp)) ;This is like `next-line'.
  6062. (get-char-property (1- (point)) 'invisible))
  6063. (goto-char (next-single-char-property-change (point) 'invisible))
  6064. (and (eolp) (beginning-of-line 2)))
  6065. (setq eol (point)))
  6066. ;; Find out what to do next and set `this-command'
  6067. (cond
  6068. ((= eos eoh)
  6069. ;; Nothing is hidden behind this heading
  6070. (unless (org-before-first-heading-p)
  6071. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6072. (org-unlogged-message "EMPTY ENTRY")
  6073. (setq org-cycle-subtree-status nil)
  6074. (save-excursion
  6075. (goto-char eos)
  6076. (outline-next-heading)
  6077. (when (org-invisible-p) (org-flag-heading nil))))
  6078. ((and (or (>= eol eos)
  6079. (not (string-match "\\S-" (buffer-substring eol eos))))
  6080. (or has-children
  6081. (not (setq children-skipped
  6082. org-cycle-skip-children-state-if-no-children))))
  6083. ;; Entire subtree is hidden in one line: children view
  6084. (unless (org-before-first-heading-p)
  6085. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6086. (if (org-at-item-p)
  6087. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6088. (org-show-entry)
  6089. (org-with-limited-levels (org-show-children))
  6090. ;; FIXME: This slows down the func way too much.
  6091. ;; How keep drawers hidden in subtree anyway?
  6092. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6093. ;; (org-cycle-hide-drawers 'subtree))
  6094. ;; Fold every list in subtree to top-level items.
  6095. (when (eq org-cycle-include-plain-lists 'integrate)
  6096. (save-excursion
  6097. (org-back-to-heading)
  6098. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6099. (beginning-of-line 1)
  6100. (let* ((struct (org-list-struct))
  6101. (prevs (org-list-prevs-alist struct))
  6102. (end (org-list-get-bottom-point struct)))
  6103. (dolist (e (org-list-get-all-items (point) struct prevs))
  6104. (org-list-set-item-visibility e struct 'folded))
  6105. (goto-char (if (< end eos) end eos)))))))
  6106. (org-unlogged-message "CHILDREN")
  6107. (save-excursion
  6108. (goto-char eos)
  6109. (outline-next-heading)
  6110. (when (org-invisible-p) (org-flag-heading nil)))
  6111. (setq org-cycle-subtree-status 'children)
  6112. (unless (org-before-first-heading-p)
  6113. (run-hook-with-args 'org-cycle-hook 'children)))
  6114. ((or children-skipped
  6115. (and (eq last-command this-command)
  6116. (eq org-cycle-subtree-status 'children)))
  6117. ;; We just showed the children, or no children are there,
  6118. ;; now show everything.
  6119. (unless (org-before-first-heading-p)
  6120. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6121. (outline-flag-region eoh eos nil)
  6122. (org-unlogged-message
  6123. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6124. (setq org-cycle-subtree-status 'subtree)
  6125. (unless (org-before-first-heading-p)
  6126. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6127. (t
  6128. ;; Default action: hide the subtree.
  6129. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6130. (outline-flag-region eoh eos t)
  6131. (org-unlogged-message "FOLDED")
  6132. (setq org-cycle-subtree-status 'folded)
  6133. (unless (org-before-first-heading-p)
  6134. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6135. ;;;###autoload
  6136. (defun org-global-cycle (&optional arg)
  6137. "Cycle the global visibility. For details see `org-cycle'.
  6138. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6139. With a numeric prefix, show all headlines up to that level."
  6140. (interactive "P")
  6141. (let ((org-cycle-include-plain-lists
  6142. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6143. (cond
  6144. ((integerp arg)
  6145. (outline-show-all)
  6146. (outline-hide-sublevels arg)
  6147. (setq org-cycle-global-status 'contents))
  6148. ((equal arg '(4))
  6149. (org-set-startup-visibility)
  6150. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6151. (t
  6152. (org-cycle '(4))))))
  6153. (defun org-set-startup-visibility ()
  6154. "Set the visibility required by startup options and properties."
  6155. (cond
  6156. ((eq org-startup-folded t)
  6157. (org-overview))
  6158. ((eq org-startup-folded 'content)
  6159. (org-content))
  6160. ((or (eq org-startup-folded 'showeverything)
  6161. (eq org-startup-folded nil))
  6162. (outline-show-all)))
  6163. (unless (eq org-startup-folded 'showeverything)
  6164. (when org-hide-block-startup (org-hide-block-all))
  6165. (org-set-visibility-according-to-property 'no-cleanup)
  6166. (org-cycle-hide-archived-subtrees 'all)
  6167. (org-cycle-hide-drawers 'all)
  6168. (org-cycle-show-empty-lines t)))
  6169. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6170. "Switch subtree visibilities according to :VISIBILITY: property."
  6171. (interactive)
  6172. (org-with-wide-buffer
  6173. (goto-char (point-min))
  6174. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6175. (if (not (org-at-property-p)) (outline-next-heading)
  6176. (let ((state (match-string 3)))
  6177. (save-excursion
  6178. (org-back-to-heading t)
  6179. (outline-hide-subtree)
  6180. (org-reveal)
  6181. (cond
  6182. ((equal state "folded")
  6183. (outline-hide-subtree))
  6184. ((equal state "children")
  6185. (org-show-hidden-entry)
  6186. (org-show-children))
  6187. ((equal state "content")
  6188. (save-excursion
  6189. (save-restriction
  6190. (org-narrow-to-subtree)
  6191. (org-content))))
  6192. ((member state '("all" "showall"))
  6193. (outline-show-subtree)))))))
  6194. (unless no-cleanup
  6195. (org-cycle-hide-archived-subtrees 'all)
  6196. (org-cycle-hide-drawers 'all)
  6197. (org-cycle-show-empty-lines 'all))))
  6198. ;; This function uses outline-regexp instead of the more fundamental
  6199. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6200. ;; buffers, where outline-regexp is needed.
  6201. (defun org-overview ()
  6202. "Switch to overview mode, showing only top-level headlines.
  6203. This shows all headlines with a level equal or greater than the level
  6204. of the first headline in the buffer. This is important, because if the
  6205. first headline is not level one, then (hide-sublevels 1) gives confusing
  6206. results."
  6207. (interactive)
  6208. (save-excursion
  6209. (let ((level
  6210. (save-excursion
  6211. (goto-char (point-min))
  6212. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6213. (goto-char (match-beginning 0))
  6214. (funcall outline-level)))))
  6215. (and level (outline-hide-sublevels level)))))
  6216. (defun org-content (&optional arg)
  6217. "Show all headlines in the buffer, like a table of contents.
  6218. With numerical argument N, show content up to level N."
  6219. (interactive "P")
  6220. (org-overview)
  6221. (save-excursion
  6222. ;; Visit all headings and show their offspring
  6223. (and (integerp arg) (org-overview))
  6224. (goto-char (point-max))
  6225. (catch 'exit
  6226. (while (and (progn (condition-case nil
  6227. (outline-previous-visible-heading 1)
  6228. (error (goto-char (point-min))))
  6229. t)
  6230. (looking-at org-outline-regexp))
  6231. (if (integerp arg)
  6232. (org-show-children (1- arg))
  6233. (outline-show-branches))
  6234. (when (bobp) (throw 'exit nil))))))
  6235. (defun org-optimize-window-after-visibility-change (state)
  6236. "Adjust the window after a change in outline visibility.
  6237. This function is the default value of the hook `org-cycle-hook'."
  6238. (when (get-buffer-window (current-buffer))
  6239. (cond
  6240. ((eq state 'content) nil)
  6241. ((eq state 'all) nil)
  6242. ((eq state 'folded) nil)
  6243. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6244. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6245. (defun org-remove-empty-overlays-at (pos)
  6246. "Remove outline overlays that do not contain non-white stuff."
  6247. (dolist (o (overlays-at pos))
  6248. (and (eq 'outline (overlay-get o 'invisible))
  6249. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6250. (overlay-end o))))
  6251. (delete-overlay o))))
  6252. (defun org-clean-visibility-after-subtree-move ()
  6253. "Fix visibility issues after moving a subtree."
  6254. ;; First, find a reasonable region to look at:
  6255. ;; Start two siblings above, end three below
  6256. (let* ((beg (save-excursion
  6257. (and (org-get-last-sibling)
  6258. (org-get-last-sibling))
  6259. (point)))
  6260. (end (save-excursion
  6261. (and (org-get-next-sibling)
  6262. (org-get-next-sibling)
  6263. (org-get-next-sibling))
  6264. (if (org-at-heading-p)
  6265. (point-at-eol)
  6266. (point))))
  6267. (level (looking-at "\\*+"))
  6268. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6269. (save-excursion
  6270. (save-restriction
  6271. (narrow-to-region beg end)
  6272. (when re
  6273. ;; Properly fold already folded siblings
  6274. (goto-char (point-min))
  6275. (while (re-search-forward re nil t)
  6276. (when (and (not (org-invisible-p))
  6277. (save-excursion
  6278. (goto-char (point-at-eol)) (org-invisible-p)))
  6279. (outline-hide-entry))))
  6280. (org-cycle-show-empty-lines 'overview)
  6281. (org-cycle-hide-drawers 'overview)))))
  6282. (defun org-cycle-show-empty-lines (state)
  6283. "Show empty lines above all visible headlines.
  6284. The region to be covered depends on STATE when called through
  6285. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6286. entire buffer covered. Note that an empty line is only shown if there
  6287. are at least `org-cycle-separator-lines' empty lines before the headline."
  6288. (when (/= org-cycle-separator-lines 0)
  6289. (save-excursion
  6290. (let* ((n (abs org-cycle-separator-lines))
  6291. (re (cond
  6292. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6293. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6294. (t (let ((ns (number-to-string (- n 2))))
  6295. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6296. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6297. beg end)
  6298. (cond
  6299. ((memq state '(overview contents t))
  6300. (setq beg (point-min) end (point-max)))
  6301. ((memq state '(children folded))
  6302. (setq beg (point)
  6303. end (progn (org-end-of-subtree t t)
  6304. (line-beginning-position 2)))))
  6305. (when beg
  6306. (goto-char beg)
  6307. (while (re-search-forward re end t)
  6308. (unless (get-char-property (match-end 1) 'invisible)
  6309. (let ((e (match-end 1))
  6310. (b (if (>= org-cycle-separator-lines 0)
  6311. (match-beginning 1)
  6312. (save-excursion
  6313. (goto-char (match-beginning 0))
  6314. (skip-chars-backward " \t\n")
  6315. (line-end-position)))))
  6316. (outline-flag-region b e nil))))))))
  6317. ;; Never hide empty lines at the end of the file.
  6318. (save-excursion
  6319. (goto-char (point-max))
  6320. (outline-previous-heading)
  6321. (outline-end-of-heading)
  6322. (when (and (looking-at "[ \t\n]+")
  6323. (= (match-end 0) (point-max)))
  6324. (outline-flag-region (point) (match-end 0) nil))))
  6325. (defun org-show-empty-lines-in-parent ()
  6326. "Move to the parent and re-show empty lines before visible headlines."
  6327. (save-excursion
  6328. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6329. (org-cycle-show-empty-lines context))))
  6330. (defun org-files-list ()
  6331. "Return `org-agenda-files' list, plus all open Org files.
  6332. This is useful for operations that need to scan all of a user's
  6333. open and agenda-wise Org files."
  6334. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6335. (dolist (buf (buffer-list))
  6336. (with-current-buffer buf
  6337. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6338. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6339. files))
  6340. (defsubst org-entry-beginning-position ()
  6341. "Return the beginning position of the current entry."
  6342. (save-excursion (org-back-to-heading t) (point)))
  6343. (defsubst org-entry-end-position ()
  6344. "Return the end position of the current entry."
  6345. (save-excursion (outline-next-heading) (point)))
  6346. (defun org-cycle-hide-drawers (state &optional exceptions)
  6347. "Re-hide all drawers after a visibility state change.
  6348. STATE should be one of the symbols listed in the docstring of
  6349. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6350. a list of strings specifying which drawers should not be hidden."
  6351. (when (and (derived-mode-p 'org-mode)
  6352. (not (memq state '(overview folded contents))))
  6353. (save-excursion
  6354. (let* ((globalp (eq state 'all))
  6355. (beg (if globalp (point-min) (point)))
  6356. (end (if globalp (point-max)
  6357. (if (eq state 'children)
  6358. (save-excursion (outline-next-heading) (point))
  6359. (org-end-of-subtree t)))))
  6360. (goto-char beg)
  6361. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6362. (unless (member-ignore-case (match-string 1) exceptions)
  6363. (let ((drawer (org-element-at-point)))
  6364. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6365. (org-flag-drawer t drawer)
  6366. ;; Make sure to skip drawer entirely or we might flag
  6367. ;; it another time when matching its ending line with
  6368. ;; `org-drawer-regexp'.
  6369. (goto-char (org-element-property :end drawer))))))))))
  6370. (defun org-flag-drawer (flag &optional element)
  6371. "When FLAG is non-nil, hide the drawer we are at.
  6372. Otherwise make it visible. When optional argument ELEMENT is
  6373. a parsed drawer, as returned by `org-element-at-point', hide or
  6374. show that drawer instead."
  6375. (let ((drawer (or element
  6376. (and (save-excursion
  6377. (beginning-of-line)
  6378. (looking-at-p org-drawer-regexp))
  6379. (org-element-at-point)))))
  6380. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6381. (let ((post (org-element-property :post-affiliated drawer)))
  6382. (save-excursion
  6383. (outline-flag-region
  6384. (progn (goto-char post) (line-end-position))
  6385. (progn (goto-char (org-element-property :end drawer))
  6386. (skip-chars-backward " \r\t\n")
  6387. (line-end-position))
  6388. flag))
  6389. ;; When the drawer is hidden away, make sure point lies in
  6390. ;; a visible part of the buffer.
  6391. (when (and flag (> (line-beginning-position) post))
  6392. (goto-char post))))))
  6393. (defun org-subtree-end-visible-p ()
  6394. "Is the end of the current subtree visible?"
  6395. (pos-visible-in-window-p
  6396. (save-excursion (org-end-of-subtree t) (point))))
  6397. (defun org-first-headline-recenter ()
  6398. "Move cursor to the first headline and recenter the headline."
  6399. (let ((window (get-buffer-window)))
  6400. (when window
  6401. (goto-char (point-min))
  6402. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6403. (set-window-start window (line-beginning-position))))))
  6404. ;;; Saving and restoring visibility
  6405. (defun org-outline-overlay-data (&optional use-markers)
  6406. "Return a list of the locations of all outline overlays.
  6407. These are overlays with the `invisible' property value `outline'.
  6408. The return value is a list of cons cells, with start and stop
  6409. positions for each overlay.
  6410. If USE-MARKERS is set, return the positions as markers."
  6411. (let (beg end)
  6412. (org-with-wide-buffer
  6413. (delq nil
  6414. (mapcar (lambda (o)
  6415. (when (eq (overlay-get o 'invisible) 'outline)
  6416. (setq beg (overlay-start o)
  6417. end (overlay-end o))
  6418. (and beg end (> end beg)
  6419. (if use-markers
  6420. (cons (copy-marker beg)
  6421. (copy-marker end t))
  6422. (cons beg end)))))
  6423. (overlays-in (point-min) (point-max)))))))
  6424. (defun org-set-outline-overlay-data (data)
  6425. "Create visibility overlays for all positions in DATA.
  6426. DATA should have been made by `org-outline-overlay-data'."
  6427. (org-with-wide-buffer
  6428. (outline-show-all)
  6429. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6430. ;;; Folding of blocks
  6431. (defvar-local org-hide-block-overlays nil
  6432. "Overlays hiding blocks.")
  6433. (defun org-block-map (function &optional start end)
  6434. "Call FUNCTION at the head of all source blocks in the current buffer.
  6435. Optional arguments START and END can be used to limit the range."
  6436. (let ((start (or start (point-min)))
  6437. (end (or end (point-max))))
  6438. (save-excursion
  6439. (goto-char start)
  6440. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6441. (save-excursion
  6442. (save-match-data
  6443. (goto-char (match-beginning 0))
  6444. (funcall function)))))))
  6445. (defun org-hide-block-toggle-all ()
  6446. "Toggle the visibility of all blocks in the current buffer."
  6447. (org-block-map 'org-hide-block-toggle))
  6448. (defun org-hide-block-all ()
  6449. "Fold all blocks in the current buffer."
  6450. (interactive)
  6451. (org-show-block-all)
  6452. (org-block-map 'org-hide-block-toggle-maybe))
  6453. (defun org-show-block-all ()
  6454. "Unfold all blocks in the current buffer."
  6455. (interactive)
  6456. (mapc #'delete-overlay org-hide-block-overlays)
  6457. (setq org-hide-block-overlays nil))
  6458. (defun org-hide-block-toggle-maybe ()
  6459. "Toggle visibility of block at point.
  6460. Unlike to `org-hide-block-toggle', this function does not throw
  6461. an error. Return a non-nil value when toggling is successful."
  6462. (interactive)
  6463. (ignore-errors (org-hide-block-toggle)))
  6464. (defun org-hide-block-toggle (&optional force)
  6465. "Toggle the visibility of the current block.
  6466. When optional argument FORCE is `off', make block visible. If it
  6467. is non-nil, hide it unconditionally. Throw an error when not at
  6468. a block. Return a non-nil value when toggling is successful."
  6469. (interactive)
  6470. (let ((element (org-element-at-point)))
  6471. (unless (memq (org-element-type element)
  6472. '(center-block comment-block dynamic-block example-block
  6473. export-block quote-block special-block
  6474. src-block verse-block))
  6475. (user-error "Not at a block"))
  6476. (let* ((start (save-excursion
  6477. (goto-char (org-element-property :post-affiliated element))
  6478. (line-end-position)))
  6479. (end (save-excursion
  6480. (goto-char (org-element-property :end element))
  6481. (skip-chars-backward " \r\t\n")
  6482. (line-end-position)))
  6483. (overlays (overlays-at start)))
  6484. (cond
  6485. ;; Do nothing when not before or at the block opening line or
  6486. ;; at the block closing line.
  6487. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6488. ((and (not (eq force 'off))
  6489. (not (memq t (mapcar
  6490. (lambda (o)
  6491. (eq (overlay-get o 'invisible) 'org-hide-block))
  6492. overlays))))
  6493. (let ((ov (make-overlay start end)))
  6494. (overlay-put ov 'invisible 'org-hide-block)
  6495. ;; Make the block accessible to `isearch'.
  6496. (overlay-put
  6497. ov 'isearch-open-invisible
  6498. (lambda (ov)
  6499. (when (memq ov org-hide-block-overlays)
  6500. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6501. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6502. (delete-overlay ov))))
  6503. (push ov org-hide-block-overlays)
  6504. ;; When the block is hidden away, make sure point is left in
  6505. ;; a visible part of the buffer.
  6506. (when (> (line-beginning-position) start)
  6507. (goto-char start)
  6508. (beginning-of-line))
  6509. ;; Signal successful toggling.
  6510. t))
  6511. ((or (not force) (eq force 'off))
  6512. (dolist (ov overlays t)
  6513. (when (memq ov org-hide-block-overlays)
  6514. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6515. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6516. (delete-overlay ov))))))))
  6517. ;; Remove overlays when changing major mode
  6518. (add-hook 'org-mode-hook
  6519. (lambda () (add-hook 'change-major-mode-hook
  6520. 'org-show-block-all 'append 'local)))
  6521. ;;; Org-goto
  6522. (defvar org-goto-window-configuration nil)
  6523. (defvar org-goto-marker nil)
  6524. (defvar org-goto-map)
  6525. (defun org-goto-map ()
  6526. "Set the keymap `org-goto'."
  6527. (setq org-goto-map
  6528. (let ((map (make-sparse-keymap)))
  6529. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6530. mouse-drag-region universal-argument org-occur)))
  6531. (dolist (cmd cmds)
  6532. (substitute-key-definition cmd cmd map global-map)))
  6533. (suppress-keymap map)
  6534. (org-defkey map "\C-m" 'org-goto-ret)
  6535. (org-defkey map [(return)] 'org-goto-ret)
  6536. (org-defkey map [(left)] 'org-goto-left)
  6537. (org-defkey map [(right)] 'org-goto-right)
  6538. (org-defkey map [(control ?g)] 'org-goto-quit)
  6539. (org-defkey map "\C-i" 'org-cycle)
  6540. (org-defkey map [(tab)] 'org-cycle)
  6541. (org-defkey map [(down)] 'outline-next-visible-heading)
  6542. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6543. (if org-goto-auto-isearch
  6544. (if (fboundp 'define-key-after)
  6545. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6546. nil)
  6547. (org-defkey map "q" 'org-goto-quit)
  6548. (org-defkey map "n" 'outline-next-visible-heading)
  6549. (org-defkey map "p" 'outline-previous-visible-heading)
  6550. (org-defkey map "f" 'outline-forward-same-level)
  6551. (org-defkey map "b" 'outline-backward-same-level)
  6552. (org-defkey map "u" 'outline-up-heading))
  6553. (org-defkey map "/" 'org-occur)
  6554. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6555. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6556. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6557. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6558. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6559. map)))
  6560. (defconst org-goto-help
  6561. "Browse buffer copy, to find location or copy text.%s
  6562. RET=jump to location C-g=quit and return to previous location
  6563. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6564. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6565. (defun org-goto (&optional alternative-interface)
  6566. "Look up a different location in the current file, keeping current visibility.
  6567. When you want look-up or go to a different location in a
  6568. document, the fastest way is often to fold the entire buffer and
  6569. then dive into the tree. This method has the disadvantage, that
  6570. the previous location will be folded, which may not be what you
  6571. want.
  6572. This command works around this by showing a copy of the current
  6573. buffer in an indirect buffer, in overview mode. You can dive
  6574. into the tree in that copy, use org-occur and incremental search
  6575. to find a location. When pressing RET or `Q', the command
  6576. returns to the original buffer in which the visibility is still
  6577. unchanged. After RET it will also jump to the location selected
  6578. in the indirect buffer and expose the headline hierarchy above.
  6579. With a prefix argument, use the alternative interface: e.g., if
  6580. `org-goto-interface' is `outline' use `outline-path-completion'."
  6581. (interactive "P")
  6582. (org-goto-map)
  6583. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6584. (org-refile-use-outline-path t)
  6585. (org-refile-target-verify-function nil)
  6586. (interface
  6587. (if (not alternative-interface)
  6588. org-goto-interface
  6589. (if (eq org-goto-interface 'outline)
  6590. 'outline-path-completion
  6591. 'outline)))
  6592. (org-goto-start-pos (point))
  6593. (selected-point
  6594. (if (eq interface 'outline)
  6595. (car (org-get-location (current-buffer) org-goto-help))
  6596. (let ((pa (org-refile-get-location "Goto")))
  6597. (org-refile-check-position pa)
  6598. (nth 3 pa)))))
  6599. (if selected-point
  6600. (progn
  6601. (org-mark-ring-push org-goto-start-pos)
  6602. (goto-char selected-point)
  6603. (when (or (org-invisible-p) (org-invisible-p2))
  6604. (org-show-context 'org-goto)))
  6605. (message "Quit"))))
  6606. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6607. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6608. (defvar org-goto-local-auto-isearch-map) ; defined below
  6609. (defun org-get-location (_buf help)
  6610. "Let the user select a location in current buffer.
  6611. This function uses a recursive edit. It returns the selected position
  6612. or nil."
  6613. (org-no-popups
  6614. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6615. (isearch-hide-immediately nil)
  6616. (isearch-search-fun-function
  6617. (lambda () 'org-goto-local-search-headings))
  6618. (org-goto-selected-point org-goto-exit-command))
  6619. (save-excursion
  6620. (save-window-excursion
  6621. (delete-other-windows)
  6622. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6623. (pop-to-buffer-same-window
  6624. (condition-case nil
  6625. (make-indirect-buffer (current-buffer) "*org-goto*")
  6626. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6627. (with-output-to-temp-buffer "*Org Help*"
  6628. (princ (format help (if org-goto-auto-isearch
  6629. " Just type for auto-isearch."
  6630. " n/p/f/b/u to navigate, q to quit."))))
  6631. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6632. (setq buffer-read-only nil)
  6633. (let ((org-startup-truncated t)
  6634. (org-startup-folded nil)
  6635. (org-startup-align-all-tables nil))
  6636. (org-mode)
  6637. (org-overview))
  6638. (setq buffer-read-only t)
  6639. (if (and (boundp 'org-goto-start-pos)
  6640. (integer-or-marker-p org-goto-start-pos))
  6641. (progn (goto-char org-goto-start-pos)
  6642. (when (org-invisible-p)
  6643. (org-show-set-visibility 'lineage)))
  6644. (goto-char (point-min)))
  6645. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6646. (message "Select location and press RET")
  6647. (use-local-map org-goto-map)
  6648. (recursive-edit)))
  6649. (kill-buffer "*org-goto*")
  6650. (cons org-goto-selected-point org-goto-exit-command))))
  6651. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6652. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6653. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6654. (if (fboundp 'isearch-other-control-char)
  6655. (progn
  6656. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6657. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6658. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6659. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6660. (define-key org-goto-local-auto-isearch-map [return] nil))
  6661. (defun org-goto-local-search-headings (string bound noerror)
  6662. "Search and make sure that any matches are in headlines."
  6663. (catch 'return
  6664. (while (if isearch-forward
  6665. (search-forward string bound noerror)
  6666. (search-backward string bound noerror))
  6667. (when (save-match-data
  6668. (and (save-excursion
  6669. (beginning-of-line)
  6670. (looking-at org-complex-heading-regexp))
  6671. (or (not (match-beginning 5))
  6672. (< (point) (match-beginning 5)))))
  6673. (throw 'return (point))))))
  6674. (defun org-goto-local-auto-isearch ()
  6675. "Start isearch."
  6676. (interactive)
  6677. (goto-char (point-min))
  6678. (let ((keys (this-command-keys)))
  6679. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6680. (isearch-mode t)
  6681. (isearch-process-search-char (string-to-char keys)))))
  6682. (defun org-goto-ret (&optional _arg)
  6683. "Finish `org-goto' by going to the new location."
  6684. (interactive "P")
  6685. (setq org-goto-selected-point (point))
  6686. (setq org-goto-exit-command 'return)
  6687. (throw 'exit nil))
  6688. (defun org-goto-left ()
  6689. "Finish `org-goto' by going to the new location."
  6690. (interactive)
  6691. (if (org-at-heading-p)
  6692. (progn
  6693. (beginning-of-line 1)
  6694. (setq org-goto-selected-point (point)
  6695. org-goto-exit-command 'left)
  6696. (throw 'exit nil))
  6697. (user-error "Not on a heading")))
  6698. (defun org-goto-right ()
  6699. "Finish `org-goto' by going to the new location."
  6700. (interactive)
  6701. (if (org-at-heading-p)
  6702. (progn
  6703. (setq org-goto-selected-point (point)
  6704. org-goto-exit-command 'right)
  6705. (throw 'exit nil))
  6706. (user-error "Not on a heading")))
  6707. (defun org-goto-quit ()
  6708. "Finish `org-goto' without cursor motion."
  6709. (interactive)
  6710. (setq org-goto-selected-point nil)
  6711. (setq org-goto-exit-command 'quit)
  6712. (throw 'exit nil))
  6713. ;;; Indirect buffer display of subtrees
  6714. (defvar org-indirect-dedicated-frame nil
  6715. "This is the frame being used for indirect tree display.")
  6716. (defvar org-last-indirect-buffer nil)
  6717. (defun org-tree-to-indirect-buffer (&optional arg)
  6718. "Create indirect buffer and narrow it to current subtree.
  6719. With a numerical prefix ARG, go up to this level and then take that tree.
  6720. If ARG is negative, go up that many levels.
  6721. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6722. indirect buffer previously made with this command, to avoid proliferation of
  6723. indirect buffers. However, when you call the command with a \
  6724. `\\[universal-argument]' prefix, or
  6725. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6726. so that you can work with several indirect buffers at the same time. If
  6727. `org-indirect-buffer-display' is `dedicated-frame', the \
  6728. `\\[universal-argument]' prefix also
  6729. requests that a new frame be made for the new buffer, so that the dedicated
  6730. frame is not changed."
  6731. (interactive "P")
  6732. (let ((cbuf (current-buffer))
  6733. (cwin (selected-window))
  6734. (pos (point))
  6735. beg end level heading ibuf)
  6736. (save-excursion
  6737. (org-back-to-heading t)
  6738. (when (numberp arg)
  6739. (setq level (org-outline-level))
  6740. (when (< arg 0) (setq arg (+ level arg)))
  6741. (while (> (setq level (org-outline-level)) arg)
  6742. (org-up-heading-safe)))
  6743. (setq beg (point)
  6744. heading (org-get-heading 'no-tags))
  6745. (org-end-of-subtree t t)
  6746. (when (org-at-heading-p) (backward-char 1))
  6747. (setq end (point)))
  6748. (when (and (buffer-live-p org-last-indirect-buffer)
  6749. (not (eq org-indirect-buffer-display 'new-frame))
  6750. (not arg))
  6751. (kill-buffer org-last-indirect-buffer))
  6752. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6753. org-last-indirect-buffer ibuf)
  6754. (cond
  6755. ((or (eq org-indirect-buffer-display 'new-frame)
  6756. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6757. (select-frame (make-frame))
  6758. (delete-other-windows)
  6759. (pop-to-buffer-same-window ibuf)
  6760. (org-set-frame-title heading))
  6761. ((eq org-indirect-buffer-display 'dedicated-frame)
  6762. (raise-frame
  6763. (select-frame (or (and org-indirect-dedicated-frame
  6764. (frame-live-p org-indirect-dedicated-frame)
  6765. org-indirect-dedicated-frame)
  6766. (setq org-indirect-dedicated-frame (make-frame)))))
  6767. (delete-other-windows)
  6768. (pop-to-buffer-same-window ibuf)
  6769. (org-set-frame-title (concat "Indirect: " heading)))
  6770. ((eq org-indirect-buffer-display 'current-window)
  6771. (pop-to-buffer-same-window ibuf))
  6772. ((eq org-indirect-buffer-display 'other-window)
  6773. (pop-to-buffer ibuf))
  6774. (t (error "Invalid value")))
  6775. (narrow-to-region beg end)
  6776. (outline-show-all)
  6777. (goto-char pos)
  6778. (run-hook-with-args 'org-cycle-hook 'all)
  6779. (and (window-live-p cwin) (select-window cwin))))
  6780. (defun org-get-indirect-buffer (&optional buffer heading)
  6781. (setq buffer (or buffer (current-buffer)))
  6782. (let ((n 1) (base (buffer-name buffer)) bname)
  6783. (while (buffer-live-p
  6784. (get-buffer
  6785. (setq bname
  6786. (concat base "-"
  6787. (if heading (concat heading "-" (number-to-string n))
  6788. (number-to-string n))))))
  6789. (setq n (1+ n)))
  6790. (condition-case nil
  6791. (make-indirect-buffer buffer bname 'clone)
  6792. (error (make-indirect-buffer buffer bname)))))
  6793. (defun org-set-frame-title (title)
  6794. "Set the title of the current frame to the string TITLE."
  6795. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6796. ;;;; Structure editing
  6797. ;;; Inserting headlines
  6798. (defun org--line-empty-p (n)
  6799. "Is the Nth next line empty?
  6800. Counts the current line as N = 1 and the previous line as N = 0;
  6801. see `beginning-of-line'."
  6802. (save-excursion
  6803. (and (not (bobp))
  6804. (or (beginning-of-line n) t)
  6805. (save-match-data
  6806. (looking-at "[ \t]*$")))))
  6807. (defun org-previous-line-empty-p ()
  6808. "Is the previous line a blank line?
  6809. When NEXT is non-nil, check the next line instead."
  6810. (org--line-empty-p 0))
  6811. (defun org-next-line-empty-p ()
  6812. "Is the previous line a blank line?
  6813. When NEXT is non-nil, check the next line instead."
  6814. (org--line-empty-p 2))
  6815. (defun org--blank-before-heading-p (&optional parent)
  6816. "Non-nil when an empty line should precede a new heading here.
  6817. When optional argument PARENT is non-nil, consider parent
  6818. headline instead of current one."
  6819. (pcase (assq 'heading org-blank-before-new-entry)
  6820. (`(heading . auto)
  6821. (save-excursion
  6822. (org-with-limited-levels
  6823. (unless (and (org-before-first-heading-p)
  6824. (not (outline-next-heading)))
  6825. (org-back-to-heading t)
  6826. (when parent (org-up-heading-safe))
  6827. (cond ((not (bobp))
  6828. (org-previous-line-empty-p))
  6829. ((outline-next-heading)
  6830. (org-previous-line-empty-p))
  6831. ;; Ignore trailing spaces on last buffer line.
  6832. ((progn (skip-chars-backward " \t") (bolp))
  6833. (org-previous-line-empty-p))
  6834. (t nil))))))
  6835. (`(heading . ,value) value)
  6836. (_ nil)))
  6837. (defun org-insert-heading (&optional arg invisible-ok top)
  6838. "Insert a new heading or an item with the same depth at point.
  6839. If point is at the beginning of a heading, insert a new heading
  6840. or a new headline above the current one. When at the beginning
  6841. of a regular line of text, turn it into a heading.
  6842. If point is in the middle of a line, split it and create a new
  6843. headline with the text in the current line after point (see
  6844. `org-M-RET-may-split-line' on how to modify this behavior). As
  6845. a special case, on a headline, splitting can only happen on the
  6846. title itself. E.g., this excludes breaking stars or tags.
  6847. With a `\\[universal-argument]' prefix, set \
  6848. `org-insert-heading-respect-content' to
  6849. a non-nil value for the duration of the command. This forces the
  6850. insertion of a heading after the current subtree, independently
  6851. on the location of point.
  6852. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6853. insert the heading at the end of the tree
  6854. above the current heading. For example, if point is within a
  6855. 2nd-level heading, then it will insert a 2nd-level heading at
  6856. the end of the 1st-level parent subtree.
  6857. When INVISIBLE-OK is set, stop at invisible headlines when going
  6858. back. This is important for non-interactive uses of the
  6859. command.
  6860. When optional argument TOP is non-nil, insert a level 1 heading,
  6861. unconditionally."
  6862. (interactive "P")
  6863. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6864. (level (org-current-level))
  6865. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6866. (cond
  6867. ((or org-insert-heading-respect-content
  6868. (member arg '((4) (16)))
  6869. (and (not invisible-ok)
  6870. (invisible-p (max (1- (point)) (point-min)))))
  6871. ;; Position point at the location of insertion.
  6872. (if (not level) ;before first headline
  6873. (org-with-limited-levels (outline-next-heading))
  6874. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6875. ;; is nil.
  6876. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6877. (cond ((equal arg '(16))
  6878. (org-up-heading-safe)
  6879. (org-end-of-subtree t t))
  6880. (t
  6881. (org-end-of-subtree t t))))
  6882. (unless (bolp) (insert "\n")) ;ensure final newline
  6883. (unless (and blank? (org-previous-line-empty-p))
  6884. (org-N-empty-lines-before-current (if blank? 1 0)))
  6885. (insert stars " \n")
  6886. (forward-char -1))
  6887. ;; At a headline...
  6888. ((org-at-heading-p)
  6889. (cond ((bolp)
  6890. (when blank? (save-excursion (insert "\n")))
  6891. (save-excursion (insert stars " \n"))
  6892. (unless (and blank? (org-previous-line-empty-p))
  6893. (org-N-empty-lines-before-current (if blank? 1 0)))
  6894. (end-of-line))
  6895. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6896. (org-match-line org-complex-heading-regexp)
  6897. (org-pos-in-match-range (point) 4))
  6898. ;; Grab the text that should moved to the new headline.
  6899. ;; Preserve tags.
  6900. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6901. (if (looking-at "[ \t]*$") (replace-match "")
  6902. (org-set-tags nil t))
  6903. (end-of-line)
  6904. (when blank? (insert "\n"))
  6905. (insert "\n" stars " ")
  6906. (when (org-string-nw-p split) (insert split))
  6907. (when (eobp) (save-excursion (insert "\n")))))
  6908. (t
  6909. (end-of-line)
  6910. (when blank? (insert "\n"))
  6911. (insert "\n" stars " ")
  6912. (when (eobp) (save-excursion (insert "\n"))))))
  6913. ;; On regular text, turn line into a headline or split, if
  6914. ;; appropriate.
  6915. ((bolp)
  6916. (insert stars " ")
  6917. (unless (and blank? (org-previous-line-empty-p))
  6918. (org-N-empty-lines-before-current (if blank? 1 0))))
  6919. (t
  6920. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6921. (end-of-line))
  6922. (insert "\n" stars " ")
  6923. (unless (and blank? (org-previous-line-empty-p))
  6924. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6925. (run-hooks 'org-insert-heading-hook))
  6926. (defun org-N-empty-lines-before-current (n)
  6927. "Make the number of empty lines before current exactly N.
  6928. So this will delete or add empty lines."
  6929. (let ((column (current-column)))
  6930. (beginning-of-line)
  6931. (unless (bobp)
  6932. (let ((start (save-excursion
  6933. (skip-chars-backward " \r\t\n")
  6934. (line-end-position))))
  6935. (delete-region start (line-end-position 0))))
  6936. (insert (make-string n ?\n))
  6937. (move-to-column column)))
  6938. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6939. "Return the heading of the current entry, without the stars.
  6940. When NO-TAGS is non-nil, don't include tags.
  6941. When NO-TODO is non-nil, don't include TODO keywords.
  6942. When NO-PRIORITY is non-nil, don't include priority cookie.
  6943. When NO-COMMENT is non-nil, don't include COMMENT string."
  6944. (save-excursion
  6945. (org-back-to-heading t)
  6946. (let ((case-fold-search nil))
  6947. (looking-at org-complex-heading-regexp)
  6948. (let ((todo (and (not no-todo) (match-string 2)))
  6949. (priority (and (not no-priority) (match-string 3)))
  6950. (headline (pcase (match-string 4)
  6951. (`nil "")
  6952. ((and (guard no-comment) h)
  6953. (replace-regexp-in-string
  6954. (eval-when-compile
  6955. (format "\\`%s[ \t]+" org-comment-string))
  6956. "" h))
  6957. (h h)))
  6958. (tags (and (not no-tags) (match-string 5))))
  6959. (mapconcat #'identity
  6960. (delq nil (list todo priority headline tags))
  6961. " ")))))
  6962. (defvar orgstruct-mode) ; defined below
  6963. (defun org-heading-components ()
  6964. "Return the components of the current heading.
  6965. This is a list with the following elements:
  6966. - the level as an integer
  6967. - the reduced level, different if `org-odd-levels-only' is set.
  6968. - the TODO keyword, or nil
  6969. - the priority character, like ?A, or nil if no priority is given
  6970. - the headline text itself, or the tags string if no headline text
  6971. - the tags string, or nil."
  6972. (save-excursion
  6973. (org-back-to-heading t)
  6974. (when (let (case-fold-search)
  6975. (looking-at
  6976. (if orgstruct-mode
  6977. org-heading-regexp
  6978. org-complex-heading-regexp)))
  6979. (if orgstruct-mode
  6980. (list (length (match-string 1))
  6981. (org-reduced-level (length (match-string 1)))
  6982. nil
  6983. nil
  6984. (match-string 2)
  6985. nil)
  6986. (list (length (match-string 1))
  6987. (org-reduced-level (length (match-string 1)))
  6988. (match-string-no-properties 2)
  6989. (and (match-end 3) (aref (match-string 3) 2))
  6990. (match-string-no-properties 4)
  6991. (match-string-no-properties 5))))))
  6992. (defun org-get-entry ()
  6993. "Get the entry text, after heading, entire subtree."
  6994. (save-excursion
  6995. (org-back-to-heading t)
  6996. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6997. (defun org-edit-headline (&optional heading)
  6998. "Edit the current headline.
  6999. Set it to HEADING when provided."
  7000. (interactive)
  7001. (org-with-wide-buffer
  7002. (org-back-to-heading t)
  7003. (let ((case-fold-search nil))
  7004. (when (looking-at org-complex-heading-regexp)
  7005. (let* ((old (match-string-no-properties 4))
  7006. (new (save-match-data
  7007. (org-trim (or heading (read-string "Edit: " old))))))
  7008. (unless (equal old new)
  7009. (if old (replace-match new t t nil 4)
  7010. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7011. (insert " " new))
  7012. (org-set-tags nil t)
  7013. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7014. (defun org-insert-heading-after-current ()
  7015. "Insert a new heading with same level as current, after current subtree."
  7016. (interactive)
  7017. (org-back-to-heading)
  7018. (org-insert-heading)
  7019. (org-move-subtree-down)
  7020. (end-of-line 1))
  7021. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7022. "Insert heading with `org-insert-heading-respect-content' set to t."
  7023. (interactive)
  7024. (org-insert-heading '(4) invisible-ok))
  7025. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7026. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7027. (interactive)
  7028. (org-insert-todo-heading force-state '(4)))
  7029. (defun org-insert-todo-heading (arg &optional force-heading)
  7030. "Insert a new heading with the same level and TODO state as current heading.
  7031. If the heading has no TODO state, or if the state is DONE, use
  7032. the first state (TODO by default). Also with one prefix arg,
  7033. force first state. With two prefix args, force inserting at the
  7034. end of the parent subtree.
  7035. When called at a plain list item, insert a new item with an
  7036. unchecked check box."
  7037. (interactive "P")
  7038. (when (or force-heading (not (org-insert-item 'checkbox)))
  7039. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7040. force-heading))
  7041. (save-excursion
  7042. (org-forward-heading-same-level -1)
  7043. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7044. (let* ((new-mark-x
  7045. (if (or (equal arg '(4))
  7046. (not (match-beginning 2))
  7047. (member (match-string 2) org-done-keywords))
  7048. (car org-todo-keywords-1)
  7049. (match-string 2)))
  7050. (new-mark
  7051. (or
  7052. (run-hook-with-args-until-success
  7053. 'org-todo-get-default-hook new-mark-x nil)
  7054. new-mark-x)))
  7055. (beginning-of-line 1)
  7056. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7057. (if org-treat-insert-todo-heading-as-state-change
  7058. (org-todo new-mark)
  7059. (insert new-mark " "))))
  7060. (when org-provide-todo-statistics
  7061. (org-update-parent-todo-statistics))))
  7062. (defun org-insert-subheading (arg)
  7063. "Insert a new subheading and demote it.
  7064. Works for outline headings and for plain lists alike."
  7065. (interactive "P")
  7066. (org-insert-heading arg)
  7067. (cond
  7068. ((org-at-heading-p) (org-do-demote))
  7069. ((org-at-item-p) (org-indent-item))))
  7070. (defun org-insert-todo-subheading (arg)
  7071. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7072. Works for outline headings and for plain lists alike."
  7073. (interactive "P")
  7074. (org-insert-todo-heading arg)
  7075. (cond
  7076. ((org-at-heading-p) (org-do-demote))
  7077. ((org-at-item-p) (org-indent-item))))
  7078. ;;; Promotion and Demotion
  7079. (defvar org-after-demote-entry-hook nil
  7080. "Hook run after an entry has been demoted.
  7081. The cursor will be at the beginning of the entry.
  7082. When a subtree is being demoted, the hook will be called for each node.")
  7083. (defvar org-after-promote-entry-hook nil
  7084. "Hook run after an entry has been promoted.
  7085. The cursor will be at the beginning of the entry.
  7086. When a subtree is being promoted, the hook will be called for each node.")
  7087. (defun org-promote-subtree ()
  7088. "Promote the entire subtree.
  7089. See also `org-promote'."
  7090. (interactive)
  7091. (save-excursion
  7092. (org-with-limited-levels (org-map-tree 'org-promote)))
  7093. (org-fix-position-after-promote))
  7094. (defun org-demote-subtree ()
  7095. "Demote the entire subtree.
  7096. See `org-demote' and `org-promote'."
  7097. (interactive)
  7098. (save-excursion
  7099. (org-with-limited-levels (org-map-tree 'org-demote)))
  7100. (org-fix-position-after-promote))
  7101. (defun org-do-promote ()
  7102. "Promote the current heading higher up the tree.
  7103. If the region is active in `transient-mark-mode', promote all
  7104. headings in the region."
  7105. (interactive)
  7106. (save-excursion
  7107. (if (org-region-active-p)
  7108. (org-map-region 'org-promote (region-beginning) (region-end))
  7109. (org-promote)))
  7110. (org-fix-position-after-promote))
  7111. (defun org-do-demote ()
  7112. "Demote the current heading lower down the tree.
  7113. If the region is active in `transient-mark-mode', demote all
  7114. headings in the region."
  7115. (interactive)
  7116. (save-excursion
  7117. (if (org-region-active-p)
  7118. (org-map-region 'org-demote (region-beginning) (region-end))
  7119. (org-demote)))
  7120. (org-fix-position-after-promote))
  7121. (defun org-fix-position-after-promote ()
  7122. "Fix cursor position and indentation after demoting/promoting."
  7123. (let ((pos (point)))
  7124. (when (save-excursion
  7125. (beginning-of-line)
  7126. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7127. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7128. (cond ((eobp) (insert " "))
  7129. ((eolp) (insert " "))
  7130. ((equal (char-after) ?\s) (forward-char 1))))))
  7131. (defun org-current-level ()
  7132. "Return the level of the current entry, or nil if before the first headline.
  7133. The level is the number of stars at the beginning of the
  7134. headline. Use `org-reduced-level' to remove the effect of
  7135. `org-odd-levels'. Unlike to `org-outline-level', this function
  7136. ignores inlinetasks."
  7137. (let ((level (org-with-limited-levels (org-outline-level))))
  7138. (and (> level 0) level)))
  7139. (defun org-get-previous-line-level ()
  7140. "Return the outline depth of the last headline before the current line.
  7141. Returns 0 for the first headline in the buffer, and nil if before the
  7142. first headline."
  7143. (and (org-current-level)
  7144. (or (and (/= (line-beginning-position) (point-min))
  7145. (save-excursion (beginning-of-line 0) (org-current-level)))
  7146. 0)))
  7147. (defun org-reduced-level (l)
  7148. "Compute the effective level of a heading.
  7149. This takes into account the setting of `org-odd-levels-only'."
  7150. (cond
  7151. ((zerop l) 0)
  7152. (org-odd-levels-only (1+ (floor (/ l 2))))
  7153. (t l)))
  7154. (defun org-level-increment ()
  7155. "Return the number of stars that will be added or removed at a
  7156. time to headlines when structure editing, based on the value of
  7157. `org-odd-levels-only'."
  7158. (if org-odd-levels-only 2 1))
  7159. (defun org-get-valid-level (level &optional change)
  7160. "Rectify a level change under the influence of `org-odd-levels-only'.
  7161. LEVEL is a current level, CHANGE is by how much the level should
  7162. be modified. Even if CHANGE is nil, LEVEL may be returned
  7163. modified because even level numbers will become the next higher
  7164. odd number. Returns values greater than 0."
  7165. (if org-odd-levels-only
  7166. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7167. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7168. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7169. (max 1 (+ level (or change 0)))))
  7170. (defun org-promote ()
  7171. "Promote the current heading higher up the tree."
  7172. (org-with-wide-buffer
  7173. (org-back-to-heading t)
  7174. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7175. after-change-functions))
  7176. (level (save-match-data (funcall outline-level)))
  7177. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7178. (diff (abs (- level (length up-head) -1))))
  7179. (cond
  7180. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7181. (replace-match "# " nil t))
  7182. ((= level 1)
  7183. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7184. (t (replace-match up-head nil t)))
  7185. (unless (= level 1)
  7186. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7187. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7188. (run-hooks 'org-after-promote-entry-hook))))
  7189. (defun org-demote ()
  7190. "Demote the current heading lower down the tree."
  7191. (org-with-wide-buffer
  7192. (org-back-to-heading t)
  7193. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7194. after-change-functions))
  7195. (level (save-match-data (funcall outline-level)))
  7196. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7197. (diff (abs (- level (length down-head) -1))))
  7198. (replace-match down-head nil t)
  7199. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7200. (when org-adapt-indentation (org-fixup-indentation diff))
  7201. (run-hooks 'org-after-demote-entry-hook))))
  7202. (defun org-cycle-level ()
  7203. "Cycle the level of an empty headline through possible states.
  7204. This goes first to child, then to parent, level, then up the hierarchy.
  7205. After top level, it switches back to sibling level."
  7206. (interactive)
  7207. (let ((org-adapt-indentation nil))
  7208. (when (org-point-at-end-of-empty-headline)
  7209. (setq this-command 'org-cycle-level) ; Only needed for caching
  7210. (let ((cur-level (org-current-level))
  7211. (prev-level (org-get-previous-line-level)))
  7212. (cond
  7213. ;; If first headline in file, promote to top-level.
  7214. ((= prev-level 0)
  7215. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7216. do (org-do-promote)))
  7217. ;; If same level as prev, demote one.
  7218. ((= prev-level cur-level)
  7219. (org-do-demote))
  7220. ;; If parent is top-level, promote to top level if not already.
  7221. ((= prev-level 1)
  7222. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7223. do (org-do-promote)))
  7224. ;; If top-level, return to prev-level.
  7225. ((= cur-level 1)
  7226. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7227. do (org-do-demote)))
  7228. ;; If less than prev-level, promote one.
  7229. ((< cur-level prev-level)
  7230. (org-do-promote))
  7231. ;; If deeper than prev-level, promote until higher than
  7232. ;; prev-level.
  7233. ((> cur-level prev-level)
  7234. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7235. do (org-do-promote))))
  7236. t))))
  7237. (defun org-map-tree (fun)
  7238. "Call FUN for every heading underneath the current one."
  7239. (org-back-to-heading t)
  7240. (let ((level (funcall outline-level)))
  7241. (save-excursion
  7242. (funcall fun)
  7243. (while (and (progn
  7244. (outline-next-heading)
  7245. (> (funcall outline-level) level))
  7246. (not (eobp)))
  7247. (funcall fun)))))
  7248. (defun org-map-region (fun beg end)
  7249. "Call FUN for every heading between BEG and END."
  7250. (let ((org-ignore-region t))
  7251. (save-excursion
  7252. (setq end (copy-marker end))
  7253. (goto-char beg)
  7254. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7255. (< (point) end))
  7256. (funcall fun))
  7257. (while (and (progn
  7258. (outline-next-heading)
  7259. (< (point) end))
  7260. (not (eobp)))
  7261. (funcall fun)))))
  7262. (defun org-fixup-indentation (diff)
  7263. "Change the indentation in the current entry by DIFF.
  7264. DIFF is an integer. Indentation is done according to the
  7265. following rules:
  7266. - Planning information and property drawers are always indented
  7267. according to the new level of the headline;
  7268. - Footnote definitions and their contents are ignored;
  7269. - Inlinetasks' boundaries are not shifted;
  7270. - Empty lines are ignored;
  7271. - Other lines' indentation are shifted by DIFF columns, unless
  7272. it would introduce a structural change in the document, in
  7273. which case no shifting is done at all.
  7274. Assume point is at a heading or an inlinetask beginning."
  7275. (org-with-wide-buffer
  7276. (narrow-to-region (line-beginning-position)
  7277. (save-excursion
  7278. (if (org-with-limited-levels (org-at-heading-p))
  7279. (org-with-limited-levels (outline-next-heading))
  7280. (org-inlinetask-goto-end))
  7281. (point)))
  7282. (forward-line)
  7283. ;; Indent properly planning info and property drawer.
  7284. (when (looking-at-p org-planning-line-re)
  7285. (org-indent-line)
  7286. (forward-line))
  7287. (when (looking-at org-property-drawer-re)
  7288. (goto-char (match-end 0))
  7289. (forward-line)
  7290. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7291. (catch 'no-shift
  7292. (when (zerop diff) (throw 'no-shift nil))
  7293. ;; If DIFF is negative, first check if a shift is possible at all
  7294. ;; (e.g., it doesn't break structure). This can only happen if
  7295. ;; some contents are not properly indented.
  7296. (let ((case-fold-search t))
  7297. (when (< diff 0)
  7298. (let ((diff (- diff))
  7299. (forbidden-re (concat org-outline-regexp
  7300. "\\|"
  7301. (substring org-footnote-definition-re 1))))
  7302. (save-excursion
  7303. (while (not (eobp))
  7304. (cond
  7305. ((looking-at-p "[ \t]*$") (forward-line))
  7306. ((and (looking-at-p org-footnote-definition-re)
  7307. (let ((e (org-element-at-point)))
  7308. (and (eq (org-element-type e) 'footnote-definition)
  7309. (goto-char (org-element-property :end e))))))
  7310. ((looking-at-p org-outline-regexp) (forward-line))
  7311. ;; Give up if shifting would move before column 0 or
  7312. ;; if it would introduce a headline or a footnote
  7313. ;; definition.
  7314. (t
  7315. (skip-chars-forward " \t")
  7316. (let ((ind (current-column)))
  7317. (when (or (< ind diff)
  7318. (and (= ind diff) (looking-at-p forbidden-re)))
  7319. (throw 'no-shift nil)))
  7320. ;; Ignore contents of example blocks and source
  7321. ;; blocks if their indentation is meant to be
  7322. ;; preserved. Jump to block's closing line.
  7323. (beginning-of-line)
  7324. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7325. (let ((e (org-element-at-point)))
  7326. (and (memq (org-element-type e)
  7327. '(example-block src-block))
  7328. (or org-src-preserve-indentation
  7329. (org-element-property :preserve-indent e))
  7330. (goto-char (org-element-property :end e))
  7331. (progn (skip-chars-backward " \r\t\n")
  7332. (beginning-of-line)
  7333. t))))
  7334. (forward-line))))))))
  7335. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7336. ;; by DIFF. Also skip contents of source or example blocks
  7337. ;; when indentation is meant to be preserved.
  7338. (while (not (eobp))
  7339. (cond
  7340. ((and (looking-at-p org-footnote-definition-re)
  7341. (let ((e (org-element-at-point)))
  7342. (and (eq (org-element-type e) 'footnote-definition)
  7343. (goto-char (org-element-property :end e))))))
  7344. ((looking-at-p org-outline-regexp) (forward-line))
  7345. ((looking-at-p "[ \t]*$") (forward-line))
  7346. (t
  7347. (indent-line-to (+ (org-get-indentation) diff))
  7348. (beginning-of-line)
  7349. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7350. (let ((e (org-element-at-point)))
  7351. (and (memq (org-element-type e)
  7352. '(example-block src-block))
  7353. (or org-src-preserve-indentation
  7354. (org-element-property :preserve-indent e))
  7355. (goto-char (org-element-property :end e))
  7356. (progn (skip-chars-backward " \r\t\n")
  7357. (beginning-of-line)
  7358. t))))
  7359. (forward-line)))))))))
  7360. (defun org-convert-to-odd-levels ()
  7361. "Convert an Org file with all levels allowed to one with odd levels.
  7362. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7363. level 5 etc."
  7364. (interactive)
  7365. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7366. (let ((outline-level 'org-outline-level)
  7367. (org-odd-levels-only nil) n)
  7368. (save-excursion
  7369. (goto-char (point-min))
  7370. (while (re-search-forward "^\\*\\*+ " nil t)
  7371. (setq n (- (length (match-string 0)) 2))
  7372. (while (>= (setq n (1- n)) 0)
  7373. (org-demote))
  7374. (end-of-line 1))))))
  7375. (defun org-convert-to-oddeven-levels ()
  7376. "Convert an Org file with only odd levels to one with odd/even levels.
  7377. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7378. file contains a section with an even level, conversion would
  7379. destroy the structure of the file. An error is signaled in this
  7380. case."
  7381. (interactive)
  7382. (goto-char (point-min))
  7383. ;; First check if there are no even levels
  7384. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7385. (org-show-set-visibility 'canonical)
  7386. (error "Not all levels are odd in this file. Conversion not possible"))
  7387. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7388. (let ((outline-regexp org-outline-regexp)
  7389. (outline-level 'org-outline-level)
  7390. (org-odd-levels-only nil) n)
  7391. (save-excursion
  7392. (goto-char (point-min))
  7393. (while (re-search-forward "^\\*\\*+ " nil t)
  7394. (setq n (/ (1- (length (match-string 0))) 2))
  7395. (while (>= (setq n (1- n)) 0)
  7396. (org-promote))
  7397. (end-of-line 1))))))
  7398. (defun org-tr-level (n)
  7399. "Make N odd if required."
  7400. (if org-odd-levels-only (1+ (/ n 2)) n))
  7401. ;;; Vertical tree motion, cutting and pasting of subtrees
  7402. (defun org-move-subtree-up (&optional arg)
  7403. "Move the current subtree up past ARG headlines of the same level."
  7404. (interactive "p")
  7405. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7406. (defun org-move-subtree-down (&optional arg)
  7407. "Move the current subtree down past ARG headlines of the same level."
  7408. (interactive "p")
  7409. (setq arg (prefix-numeric-value arg))
  7410. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7411. 'org-get-last-sibling))
  7412. (ins-point (make-marker))
  7413. (cnt (abs arg))
  7414. (col (current-column))
  7415. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7416. ;; Select the tree
  7417. (org-back-to-heading)
  7418. (setq beg0 (point))
  7419. (save-excursion
  7420. (setq ne-beg (org-back-over-empty-lines))
  7421. (setq beg (point)))
  7422. (save-match-data
  7423. (save-excursion (outline-end-of-heading)
  7424. (setq folded (org-invisible-p)))
  7425. (progn (org-end-of-subtree nil t)
  7426. (unless (eobp) (backward-char))))
  7427. (outline-next-heading)
  7428. (setq ne-end (org-back-over-empty-lines))
  7429. (setq end (point))
  7430. (goto-char beg0)
  7431. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7432. ;; include less whitespace
  7433. (save-excursion
  7434. (goto-char beg)
  7435. (forward-line (- ne-beg ne-end))
  7436. (setq beg (point))))
  7437. ;; Find insertion point, with error handling
  7438. (while (> cnt 0)
  7439. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7440. (progn (goto-char beg0)
  7441. (user-error "Cannot move past superior level or buffer limit")))
  7442. (setq cnt (1- cnt)))
  7443. (when (> arg 0)
  7444. ;; Moving forward - still need to move over subtree
  7445. (org-end-of-subtree t t)
  7446. (save-excursion
  7447. (org-back-over-empty-lines)
  7448. (or (bolp) (newline))))
  7449. (setq ne-ins (org-back-over-empty-lines))
  7450. (move-marker ins-point (point))
  7451. (setq txt (buffer-substring beg end))
  7452. (org-save-markers-in-region beg end)
  7453. (delete-region beg end)
  7454. (org-remove-empty-overlays-at beg)
  7455. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7456. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7457. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7458. (let ((bbb (point)))
  7459. (insert-before-markers txt)
  7460. (org-reinstall-markers-in-region bbb)
  7461. (move-marker ins-point bbb))
  7462. (or (bolp) (insert "\n"))
  7463. (setq ins-end (point))
  7464. (goto-char ins-point)
  7465. (org-skip-whitespace)
  7466. (when (and (< arg 0)
  7467. (org-first-sibling-p)
  7468. (> ne-ins ne-beg))
  7469. ;; Move whitespace back to beginning
  7470. (save-excursion
  7471. (goto-char ins-end)
  7472. (let ((kill-whole-line t))
  7473. (kill-line (- ne-ins ne-beg)) (point)))
  7474. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7475. (move-marker ins-point nil)
  7476. (if folded
  7477. (outline-hide-subtree)
  7478. (org-show-entry)
  7479. (org-show-children)
  7480. (org-cycle-hide-drawers 'children))
  7481. (org-clean-visibility-after-subtree-move)
  7482. ;; move back to the initial column we were at
  7483. (move-to-column col)))
  7484. (defvar org-subtree-clip ""
  7485. "Clipboard for cut and paste of subtrees.
  7486. This is actually only a copy of the kill, because we use the normal kill
  7487. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7488. (defvar org-subtree-clip-folded nil
  7489. "Was the last copied subtree folded?
  7490. This is used to fold the tree back after pasting.")
  7491. (defun org-cut-subtree (&optional n)
  7492. "Cut the current subtree into the clipboard.
  7493. With prefix arg N, cut this many sequential subtrees.
  7494. This is a short-hand for marking the subtree and then cutting it."
  7495. (interactive "p")
  7496. (org-copy-subtree n 'cut))
  7497. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7498. "Copy the current subtree it in the clipboard.
  7499. With prefix arg N, copy this many sequential subtrees.
  7500. This is a short-hand for marking the subtree and then copying it.
  7501. If CUT is non-nil, actually cut the subtree.
  7502. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7503. of some markers in the region, even if CUT is non-nil. This is
  7504. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7505. (interactive "p")
  7506. (let (beg end folded (beg0 (point)))
  7507. (if (called-interactively-p 'any)
  7508. (org-back-to-heading nil) ; take what looks like a subtree
  7509. (org-back-to-heading t)) ; take what is really there
  7510. (setq beg (point))
  7511. (skip-chars-forward " \t\r\n")
  7512. (save-match-data
  7513. (if nosubtrees
  7514. (outline-next-heading)
  7515. (save-excursion (outline-end-of-heading)
  7516. (setq folded (org-invisible-p)))
  7517. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7518. (org-end-of-subtree t t)))
  7519. ;; Include the end of an inlinetask
  7520. (when (and (featurep 'org-inlinetask)
  7521. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7522. "END[ \t]*$")))
  7523. (end-of-line))
  7524. (setq end (point))
  7525. (goto-char beg0)
  7526. (when (> end beg)
  7527. (setq org-subtree-clip-folded folded)
  7528. (when (or cut force-store-markers)
  7529. (org-save-markers-in-region beg end))
  7530. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7531. (setq org-subtree-clip (current-kill 0))
  7532. (message "%s: Subtree(s) with %d characters"
  7533. (if cut "Cut" "Copied")
  7534. (length org-subtree-clip)))))
  7535. (defun org-paste-subtree (&optional level tree for-yank remove)
  7536. "Paste the clipboard as a subtree, with modification of headline level.
  7537. The entire subtree is promoted or demoted in order to match a new headline
  7538. level.
  7539. If the cursor is at the beginning of a headline, the same level as
  7540. that headline is used to paste the tree.
  7541. If not, the new level is derived from the *visible* headings
  7542. before and after the insertion point, and taken to be the inferior headline
  7543. level of the two. So if the previous visible heading is level 3 and the
  7544. next is level 4 (or vice versa), level 4 will be used for insertion.
  7545. This makes sure that the subtree remains an independent subtree and does
  7546. not swallow low level entries.
  7547. You can also force a different level, either by using a numeric prefix
  7548. argument, or by inserting the heading marker by hand. For example, if the
  7549. cursor is after \"*****\", then the tree will be shifted to level 5.
  7550. If optional TREE is given, use this text instead of the kill ring.
  7551. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7552. move back over whitespace before inserting, and move point to the end of
  7553. the inserted text when done.
  7554. When REMOVE is non-nil, remove the subtree from the clipboard."
  7555. (interactive "P")
  7556. (setq tree (or tree (and kill-ring (current-kill 0))))
  7557. (unless (org-kill-is-subtree-p tree)
  7558. (user-error "%s"
  7559. (substitute-command-keys
  7560. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7561. (org-with-limited-levels
  7562. (let* ((visp (not (org-invisible-p)))
  7563. (txt tree)
  7564. (^re_ "\\(\\*+\\)[ \t]*")
  7565. (old-level (if (string-match org-outline-regexp-bol txt)
  7566. (- (match-end 0) (match-beginning 0) 1)
  7567. -1))
  7568. (force-level (cond (level (prefix-numeric-value level))
  7569. ((and (looking-at "[ \t]*$")
  7570. (string-match
  7571. "^\\*+$" (buffer-substring
  7572. (point-at-bol) (point))))
  7573. (- (match-end 0) (match-beginning 0)))
  7574. ((and (bolp)
  7575. (looking-at org-outline-regexp))
  7576. (- (match-end 0) (point) 1))))
  7577. (previous-level (save-excursion
  7578. (condition-case nil
  7579. (progn
  7580. (outline-previous-visible-heading 1)
  7581. (if (looking-at ^re_)
  7582. (- (match-end 0) (match-beginning 0) 1)
  7583. 1))
  7584. (error 1))))
  7585. (next-level (save-excursion
  7586. (condition-case nil
  7587. (progn
  7588. (or (looking-at org-outline-regexp)
  7589. (outline-next-visible-heading 1))
  7590. (if (looking-at ^re_)
  7591. (- (match-end 0) (match-beginning 0) 1)
  7592. 1))
  7593. (error 1))))
  7594. (new-level (or force-level (max previous-level next-level)))
  7595. (shift (if (or (= old-level -1)
  7596. (= new-level -1)
  7597. (= old-level new-level))
  7598. 0
  7599. (- new-level old-level)))
  7600. (delta (if (> shift 0) -1 1))
  7601. (func (if (> shift 0) 'org-demote 'org-promote))
  7602. (org-odd-levels-only nil)
  7603. beg end newend)
  7604. ;; Remove the forced level indicator
  7605. (when force-level
  7606. (delete-region (point-at-bol) (point)))
  7607. ;; Paste
  7608. (beginning-of-line (if (bolp) 1 2))
  7609. (setq beg (point))
  7610. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7611. (insert-before-markers txt)
  7612. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7613. (setq newend (point))
  7614. (org-reinstall-markers-in-region beg)
  7615. (setq end (point))
  7616. (goto-char beg)
  7617. (skip-chars-forward " \t\n\r")
  7618. (setq beg (point))
  7619. (when (and (org-invisible-p) visp)
  7620. (save-excursion (outline-show-heading)))
  7621. ;; Shift if necessary
  7622. (unless (= shift 0)
  7623. (save-restriction
  7624. (narrow-to-region beg end)
  7625. (while (not (= shift 0))
  7626. (org-map-region func (point-min) (point-max))
  7627. (setq shift (+ delta shift)))
  7628. (goto-char (point-min))
  7629. (setq newend (point-max))))
  7630. (when (or (called-interactively-p 'interactive) for-yank)
  7631. (message "Clipboard pasted as level %d subtree" new-level))
  7632. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7633. kill-ring
  7634. (eq org-subtree-clip (current-kill 0))
  7635. org-subtree-clip-folded)
  7636. ;; The tree was folded before it was killed/copied
  7637. (outline-hide-subtree))
  7638. (and for-yank (goto-char newend))
  7639. (and remove (setq kill-ring (cdr kill-ring))))))
  7640. (defun org-kill-is-subtree-p (&optional txt)
  7641. "Check if the current kill is an outline subtree, or a set of trees.
  7642. Returns nil if kill does not start with a headline, or if the first
  7643. headline level is not the largest headline level in the tree.
  7644. So this will actually accept several entries of equal levels as well,
  7645. which is OK for `org-paste-subtree'.
  7646. If optional TXT is given, check this string instead of the current kill."
  7647. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7648. (re (org-get-limited-outline-regexp))
  7649. (^re (concat "^" re))
  7650. (start-level (and kill
  7651. (string-match
  7652. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7653. kill)
  7654. (- (match-end 2) (match-beginning 2) 1)))
  7655. (start (1+ (or (match-beginning 2) -1))))
  7656. (if (not start-level)
  7657. (progn
  7658. nil) ;; does not even start with a heading
  7659. (catch 'exit
  7660. (while (setq start (string-match ^re kill (1+ start)))
  7661. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7662. (throw 'exit nil)))
  7663. t))))
  7664. (defvar org-markers-to-move nil
  7665. "Markers that should be moved with a cut-and-paste operation.
  7666. Those markers are stored together with their positions relative to
  7667. the start of the region.")
  7668. (defun org-save-markers-in-region (beg end)
  7669. "Check markers in region.
  7670. If these markers are between BEG and END, record their position relative
  7671. to BEG, so that after moving the block of text, we can put the markers back
  7672. into place.
  7673. This function gets called just before an entry or tree gets cut from the
  7674. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7675. called immediately, to move the markers with the entries."
  7676. (setq org-markers-to-move nil)
  7677. (when (featurep 'org-clock)
  7678. (org-clock-save-markers-for-cut-and-paste beg end))
  7679. (when (featurep 'org-agenda)
  7680. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7681. (defun org-check-and-save-marker (marker beg end)
  7682. "Check if MARKER is between BEG and END.
  7683. If yes, remember the marker and the distance to BEG."
  7684. (when (and (marker-buffer marker)
  7685. (equal (marker-buffer marker) (current-buffer))
  7686. (>= marker beg) (< marker end))
  7687. (push (cons marker (- marker beg)) org-markers-to-move)))
  7688. (defun org-reinstall-markers-in-region (beg)
  7689. "Move all remembered markers to their position relative to BEG."
  7690. (dolist (x org-markers-to-move)
  7691. (move-marker (car x) (+ beg (cdr x))))
  7692. (setq org-markers-to-move nil))
  7693. (defun org-narrow-to-subtree ()
  7694. "Narrow buffer to the current subtree."
  7695. (interactive)
  7696. (save-excursion
  7697. (save-match-data
  7698. (org-with-limited-levels
  7699. (narrow-to-region
  7700. (progn (org-back-to-heading t) (point))
  7701. (progn (org-end-of-subtree t t)
  7702. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7703. (point)))))))
  7704. (defun org-narrow-to-block ()
  7705. "Narrow buffer to the current block."
  7706. (interactive)
  7707. (let* ((case-fold-search t)
  7708. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7709. "^[ \t]*#\\+end_.*")))
  7710. (if blockp
  7711. (narrow-to-region (car blockp) (cdr blockp))
  7712. (user-error "Not in a block"))))
  7713. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7714. "Clone the task (subtree) at point N times.
  7715. The clones will be inserted as siblings.
  7716. In interactive use, the user will be prompted for the number of
  7717. clones to be produced. If the entry has a timestamp, the user
  7718. will also be prompted for a time shift, which may be a repeater
  7719. as used in time stamps, for example `+3d'. To disable this,
  7720. you can call the function with a universal prefix argument.
  7721. When a valid repeater is given and the entry contains any time
  7722. stamps, the clones will become a sequence in time, with time
  7723. stamps in the subtree shifted for each clone produced. If SHIFT
  7724. is nil or the empty string, time stamps will be left alone. The
  7725. ID property of the original subtree is removed.
  7726. In each clone, all the CLOCK entries will be removed. This
  7727. prevents Org from considering that the clocked times overlap.
  7728. If the original subtree did contain time stamps with a repeater,
  7729. the following will happen:
  7730. - the repeater will be removed in each clone
  7731. - an additional clone will be produced, with the current, unshifted
  7732. date(s) in the entry.
  7733. - the original entry will be placed *after* all the clones, with
  7734. repeater intact.
  7735. - the start days in the repeater in the original entry will be shifted
  7736. to past the last clone.
  7737. In this way you can spell out a number of instances of a repeating task,
  7738. and still retain the repeater to cover future instances of the task.
  7739. As described above, N+1 clones are produced when the original
  7740. subtree has a repeater. Setting N to 0, then, can be used to
  7741. remove the repeater from a subtree and create a shifted clone
  7742. with the original repeater."
  7743. (interactive "nNumber of clones to produce: ")
  7744. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7745. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7746. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7747. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7748. (shift
  7749. (or shift
  7750. (if (and (not (equal current-prefix-arg '(4)))
  7751. (save-excursion
  7752. (goto-char beg)
  7753. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7754. (read-from-minibuffer
  7755. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7756. ""))) ;No time shift
  7757. (doshift
  7758. (and (org-string-nw-p shift)
  7759. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7760. shift)
  7761. (user-error "Invalid shift specification %s" shift)))))
  7762. (goto-char end-of-tree)
  7763. (unless (bolp) (insert "\n"))
  7764. (let* ((end (point))
  7765. (template (buffer-substring beg end))
  7766. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7767. (shift-what (pcase (and doshift (match-string 2 shift))
  7768. (`nil nil)
  7769. ("d" 'day)
  7770. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7771. ("m" 'month)
  7772. ("y" 'year)
  7773. (_ (error "Unsupported time unit"))))
  7774. (nmin 1)
  7775. (nmax n)
  7776. (n-no-remove -1)
  7777. (idprop (org-entry-get nil "ID")))
  7778. (when (and doshift
  7779. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7780. template))
  7781. (delete-region beg end)
  7782. (setq end beg)
  7783. (setq nmin 0)
  7784. (setq nmax (1+ nmax))
  7785. (setq n-no-remove nmax))
  7786. (goto-char end)
  7787. (cl-loop for n from nmin to nmax do
  7788. (insert
  7789. ;; Prepare clone.
  7790. (with-temp-buffer
  7791. (insert template)
  7792. (org-mode)
  7793. (goto-char (point-min))
  7794. (org-show-subtree)
  7795. (and idprop (if org-clone-delete-id
  7796. (org-entry-delete nil "ID")
  7797. (org-id-get-create t)))
  7798. (unless (= n 0)
  7799. (while (re-search-forward org-clock-line-re nil t)
  7800. (delete-region (line-beginning-position)
  7801. (line-beginning-position 2)))
  7802. (goto-char (point-min))
  7803. (while (re-search-forward org-drawer-regexp nil t)
  7804. (org-remove-empty-drawer-at (point))))
  7805. (goto-char (point-min))
  7806. (when doshift
  7807. (while (re-search-forward org-ts-regexp-both nil t)
  7808. (org-timestamp-change (* n shift-n) shift-what))
  7809. (unless (= n n-no-remove)
  7810. (goto-char (point-min))
  7811. (while (re-search-forward org-ts-regexp nil t)
  7812. (save-excursion
  7813. (goto-char (match-beginning 0))
  7814. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7815. (delete-region (match-beginning 1) (match-end 1)))))))
  7816. (buffer-string)))))
  7817. (goto-char beg)))
  7818. ;;; Outline Sorting
  7819. (defun org-sort (&optional with-case)
  7820. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7821. Optional argument WITH-CASE means sort case-sensitively."
  7822. (interactive "P")
  7823. (org-call-with-arg
  7824. (cond ((org-at-table-p) #'org-table-sort-lines)
  7825. ((org-at-item-p) #'org-sort-list)
  7826. (t #'org-sort-entries))
  7827. with-case))
  7828. (defun org-sort-remove-invisible (s)
  7829. "Remove invisible part of links and emphasis markers from string S."
  7830. (remove-text-properties 0 (length s) org-rm-props s)
  7831. (replace-regexp-in-string
  7832. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7833. (replace-regexp-in-string
  7834. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7835. (org-link-display-format s)
  7836. t t) t t))
  7837. (defvar org-priority-regexp) ; defined later in the file
  7838. (defvar org-after-sorting-entries-or-items-hook nil
  7839. "Hook that is run after a bunch of entries or items have been sorted.
  7840. When children are sorted, the cursor is in the parent line when this
  7841. hook gets called. When a region or a plain list is sorted, the cursor
  7842. will be in the first entry of the sorted region/list.")
  7843. (defun org-sort-entries
  7844. (&optional with-case sorting-type getkey-func compare-func property
  7845. interactive?)
  7846. "Sort entries on a certain level of an outline tree.
  7847. If there is an active region, the entries in the region are sorted.
  7848. Else, if the cursor is before the first entry, sort the top-level items.
  7849. Else, the children of the entry at point are sorted.
  7850. Sorting can be alphabetically, numerically, by date/time as given by
  7851. a time stamp, by a property, by priority order, or by a custom function.
  7852. The command prompts for the sorting type unless it has been given to the
  7853. function through the SORTING-TYPE argument, which needs to be a character,
  7854. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7855. the precise meaning of each character:
  7856. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7857. c By creation time, which is assumed to be the first inactive time stamp
  7858. at the beginning of a line.
  7859. d By deadline date/time.
  7860. k By clocking time.
  7861. n Numerically, by converting the beginning of the entry/item to a number.
  7862. o By order of TODO keywords.
  7863. p By priority according to the cookie.
  7864. r By the value of a property.
  7865. s By scheduled date/time.
  7866. t By date/time, either the first active time stamp in the entry, or, if
  7867. none exist, by the first inactive one.
  7868. Capital letters will reverse the sort order.
  7869. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7870. called with point at the beginning of the record. It must return a
  7871. value that is compatible with COMPARE-FUNC, the function used to
  7872. compare entries.
  7873. Comparing entries ignores case by default. However, with an optional argument
  7874. WITH-CASE, the sorting considers case as well.
  7875. Sorting is done against the visible part of the headlines, it ignores hidden
  7876. links.
  7877. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7878. A non-nil value for INTERACTIVE? is used to signal that this
  7879. function is being called interactively."
  7880. (interactive (list current-prefix-arg nil nil nil nil t))
  7881. (let ((case-func (if with-case 'identity 'downcase))
  7882. start beg end stars re re2
  7883. txt what tmp)
  7884. ;; Find beginning and end of region to sort
  7885. (cond
  7886. ((org-region-active-p)
  7887. ;; we will sort the region
  7888. (setq end (region-end)
  7889. what "region")
  7890. (goto-char (region-beginning))
  7891. (unless (org-at-heading-p) (outline-next-heading))
  7892. (setq start (point)))
  7893. ((or (org-at-heading-p)
  7894. (ignore-errors (progn (org-back-to-heading) t)))
  7895. ;; we will sort the children of the current headline
  7896. (org-back-to-heading)
  7897. (setq start (point)
  7898. end (progn (org-end-of-subtree t t)
  7899. (or (bolp) (insert "\n"))
  7900. (when (>= (org-back-over-empty-lines) 1)
  7901. (forward-line 1))
  7902. (point))
  7903. what "children")
  7904. (goto-char start)
  7905. (outline-show-subtree)
  7906. (outline-next-heading))
  7907. (t
  7908. ;; we will sort the top-level entries in this file
  7909. (goto-char (point-min))
  7910. (or (org-at-heading-p) (outline-next-heading))
  7911. (setq start (point))
  7912. (goto-char (point-max))
  7913. (beginning-of-line 1)
  7914. (when (looking-at ".*?\\S-")
  7915. ;; File ends in a non-white line
  7916. (end-of-line 1)
  7917. (insert "\n"))
  7918. (setq end (point-max))
  7919. (setq what "top-level")
  7920. (goto-char start)
  7921. (outline-show-all)))
  7922. (setq beg (point))
  7923. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7924. (looking-at "\\(\\*+\\)")
  7925. (setq stars (match-string 1)
  7926. re (concat "^" (regexp-quote stars) " +")
  7927. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7928. txt (buffer-substring beg end))
  7929. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7930. (when (and (not (equal stars "*")) (string-match re2 txt))
  7931. (user-error "Region to sort contains a level above the first entry"))
  7932. (unless sorting-type
  7933. (message
  7934. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7935. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7936. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7937. what)
  7938. (setq sorting-type (read-char-exclusive)))
  7939. (unless getkey-func
  7940. (and (= (downcase sorting-type) ?f)
  7941. (setq getkey-func
  7942. (or (and interactive?
  7943. (org-read-function
  7944. "Function for extracting keys: "))
  7945. (error "Missing key extractor")))))
  7946. (and (= (downcase sorting-type) ?r)
  7947. (not property)
  7948. (setq property
  7949. (completing-read "Property: "
  7950. (mapcar #'list (org-buffer-property-keys t))
  7951. nil t)))
  7952. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7953. (message "Sorting entries...")
  7954. (save-restriction
  7955. (narrow-to-region start end)
  7956. (let ((restore-clock?
  7957. ;; The clock marker is lost when using `sort-subr'; mark
  7958. ;; the clock with temporary `:org-clock-marker-backup'
  7959. ;; text property.
  7960. (when (and (eq (org-clock-is-active) (current-buffer))
  7961. (<= start (marker-position org-clock-marker))
  7962. (>= end (marker-position org-clock-marker)))
  7963. (org-with-silent-modifications
  7964. (put-text-property (1- org-clock-marker) org-clock-marker
  7965. :org-clock-marker-backup t))
  7966. t))
  7967. (dcst (downcase sorting-type))
  7968. (case-fold-search nil)
  7969. (now (current-time)))
  7970. (sort-subr
  7971. (/= dcst sorting-type)
  7972. ;; This function moves to the beginning character of the "record" to
  7973. ;; be sorted.
  7974. (lambda nil
  7975. (if (re-search-forward re nil t)
  7976. (goto-char (match-beginning 0))
  7977. (goto-char (point-max))))
  7978. ;; This function moves to the last character of the "record" being
  7979. ;; sorted.
  7980. (lambda nil
  7981. (save-match-data
  7982. (condition-case nil
  7983. (outline-forward-same-level 1)
  7984. (error
  7985. (goto-char (point-max))))))
  7986. ;; This function returns the value that gets sorted against.
  7987. (lambda nil
  7988. (cond
  7989. ((= dcst ?n)
  7990. (if (looking-at org-complex-heading-regexp)
  7991. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7992. nil))
  7993. ((= dcst ?a)
  7994. (if (looking-at org-complex-heading-regexp)
  7995. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7996. nil))
  7997. ((= dcst ?k)
  7998. (or (get-text-property (point) :org-clock-minutes) 0))
  7999. ((= dcst ?t)
  8000. (let ((end (save-excursion (outline-next-heading) (point))))
  8001. (if (or (re-search-forward org-ts-regexp end t)
  8002. (re-search-forward org-ts-regexp-both end t))
  8003. (org-time-string-to-seconds (match-string 0))
  8004. (float-time now))))
  8005. ((= dcst ?c)
  8006. (let ((end (save-excursion (outline-next-heading) (point))))
  8007. (if (re-search-forward
  8008. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8009. end t)
  8010. (org-time-string-to-seconds (match-string 0))
  8011. (float-time now))))
  8012. ((= dcst ?s)
  8013. (let ((end (save-excursion (outline-next-heading) (point))))
  8014. (if (re-search-forward org-scheduled-time-regexp end t)
  8015. (org-time-string-to-seconds (match-string 1))
  8016. (float-time now))))
  8017. ((= dcst ?d)
  8018. (let ((end (save-excursion (outline-next-heading) (point))))
  8019. (if (re-search-forward org-deadline-time-regexp end t)
  8020. (org-time-string-to-seconds (match-string 1))
  8021. (float-time now))))
  8022. ((= dcst ?p)
  8023. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8024. (string-to-char (match-string 2))
  8025. org-default-priority))
  8026. ((= dcst ?r)
  8027. (or (org-entry-get nil property) ""))
  8028. ((= dcst ?o)
  8029. (when (looking-at org-complex-heading-regexp)
  8030. (let* ((m (match-string 2))
  8031. (s (if (member m org-done-keywords) '- '+)))
  8032. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8033. ((= dcst ?f)
  8034. (if getkey-func
  8035. (progn
  8036. (setq tmp (funcall getkey-func))
  8037. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8038. tmp)
  8039. (error "Invalid key function `%s'" getkey-func)))
  8040. (t (error "Invalid sorting type `%c'" sorting-type))))
  8041. nil
  8042. (cond
  8043. ((= dcst ?a) 'string<)
  8044. ((= dcst ?f)
  8045. (or compare-func
  8046. (and interactive?
  8047. (org-read-function
  8048. (concat "Function for comparing keys "
  8049. "(empty for default `sort-subr' predicate): ")
  8050. 'allow-empty))))
  8051. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  8052. (when restore-clock?
  8053. (move-marker org-clock-marker
  8054. (1+ (next-single-property-change
  8055. start :org-clock-marker-backup)))
  8056. (remove-text-properties (1- org-clock-marker) org-clock-marker
  8057. '(:org-clock-marker-backup t)))))
  8058. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8059. (message "Sorting entries...done")))
  8060. ;;; The orgstruct minor mode
  8061. ;; Define a minor mode which can be used in other modes in order to
  8062. ;; integrate the Org mode structure editing commands.
  8063. ;; This is really a hack, because the Org mode structure commands use
  8064. ;; keys which normally belong to the major mode. Here is how it
  8065. ;; works: The minor mode defines all the keys necessary to operate the
  8066. ;; structure commands, but wraps the commands into a function which
  8067. ;; tests if the cursor is currently at a headline or a plain list
  8068. ;; item. If that is the case, the structure command is used,
  8069. ;; temporarily setting many Org mode variables like regular
  8070. ;; expressions for filling etc. However, when any of those keys is
  8071. ;; used at a different location, function uses `key-binding' to look
  8072. ;; up if the key has an associated command in another currently active
  8073. ;; keymap (minor modes, major mode, global), and executes that
  8074. ;; command. There might be problems if any of the keys is otherwise
  8075. ;; used as a prefix key.
  8076. (defcustom orgstruct-heading-prefix-regexp ""
  8077. "Regexp that matches the custom prefix of Org headlines in
  8078. orgstruct(++)-mode."
  8079. :group 'org
  8080. :version "26.1"
  8081. :package-version '(Org . "8.3")
  8082. :type 'regexp)
  8083. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8084. (defcustom orgstruct-setup-hook nil
  8085. "Hook run after orgstruct-mode-map is filled."
  8086. :group 'org
  8087. :version "24.4"
  8088. :package-version '(Org . "8.0")
  8089. :type 'hook)
  8090. (defvar orgstruct-initialized nil)
  8091. (defvar org-local-vars nil
  8092. "List of local variables, for use by `orgstruct-mode'.")
  8093. ;;;###autoload
  8094. (define-minor-mode orgstruct-mode
  8095. "Toggle the minor mode `orgstruct-mode'.
  8096. This mode is for using Org mode structure commands in other
  8097. modes. The following keys behave as if Org mode were active, if
  8098. the cursor is on a headline, or on a plain list item (both as
  8099. defined by Org mode)."
  8100. nil " OrgStruct" (make-sparse-keymap)
  8101. (funcall (if orgstruct-mode
  8102. 'add-to-invisibility-spec
  8103. 'remove-from-invisibility-spec)
  8104. '(outline . t))
  8105. (when orgstruct-mode
  8106. (org-load-modules-maybe)
  8107. (unless orgstruct-initialized
  8108. (orgstruct-setup)
  8109. (setq orgstruct-initialized t))))
  8110. ;;;###autoload
  8111. (defun turn-on-orgstruct ()
  8112. "Unconditionally turn on `orgstruct-mode'."
  8113. (orgstruct-mode 1))
  8114. (defvar-local orgstruct-is-++ nil
  8115. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8116. (defvar-local org-fb-vars nil)
  8117. (defun orgstruct++-mode (&optional arg)
  8118. "Toggle `orgstruct-mode', the enhanced version of it.
  8119. In addition to setting orgstruct-mode, this also exports all
  8120. indentation and autofilling variables from Org mode into the
  8121. buffer. It will also recognize item context in multiline items."
  8122. (interactive "P")
  8123. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8124. (if (< arg 1)
  8125. (progn (orgstruct-mode -1)
  8126. (dolist (v org-fb-vars)
  8127. (set (make-local-variable (car v))
  8128. (if (eq (car-safe (cadr v)) 'quote)
  8129. (cl-cadadr v)
  8130. (nth 1 v)))))
  8131. (orgstruct-mode 1)
  8132. (setq org-fb-vars nil)
  8133. (unless org-local-vars
  8134. (setq org-local-vars (org-get-local-variables)))
  8135. (let (var val)
  8136. (dolist (x org-local-vars)
  8137. (when (string-match
  8138. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8139. \\|fill-prefix\\|indent-\\)"
  8140. (symbol-name (car x)))
  8141. (setq var (car x) val (nth 1 x))
  8142. (push (list var `(quote ,(eval var))) org-fb-vars)
  8143. (set (make-local-variable var)
  8144. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8145. (setq-local orgstruct-is-++ t))))
  8146. ;;;###autoload
  8147. (defun turn-on-orgstruct++ ()
  8148. "Unconditionally turn on `orgstruct++-mode'."
  8149. (orgstruct++-mode 1))
  8150. (defun orgstruct-error ()
  8151. "Error when there is no default binding for a structure key."
  8152. (interactive)
  8153. (funcall (if (fboundp 'user-error)
  8154. 'user-error
  8155. 'error)
  8156. "This key has no function outside structure elements"))
  8157. (defun orgstruct-setup ()
  8158. "Setup orgstruct keymap."
  8159. (dolist (cell '((org-demote . t)
  8160. (org-metaleft . t)
  8161. (org-metaright . t)
  8162. (org-promote . t)
  8163. (org-shiftmetaleft . t)
  8164. (org-shiftmetaright . t)
  8165. org-backward-element
  8166. org-backward-heading-same-level
  8167. org-ctrl-c-ret
  8168. org-ctrl-c-minus
  8169. org-ctrl-c-star
  8170. org-cycle
  8171. org-force-cycle-archived
  8172. org-forward-heading-same-level
  8173. org-insert-heading
  8174. org-insert-heading-respect-content
  8175. org-kill-note-or-show-branches
  8176. org-mark-subtree
  8177. org-meta-return
  8178. org-metadown
  8179. org-metaup
  8180. org-narrow-to-subtree
  8181. org-promote-subtree
  8182. org-reveal
  8183. org-shiftdown
  8184. org-shiftleft
  8185. org-shiftmetadown
  8186. org-shiftmetaup
  8187. org-shiftright
  8188. org-shifttab
  8189. org-shifttab
  8190. org-shiftup
  8191. org-show-children
  8192. org-show-subtree
  8193. org-sort
  8194. org-up-element
  8195. outline-demote
  8196. outline-next-visible-heading
  8197. outline-previous-visible-heading
  8198. outline-promote
  8199. outline-up-heading))
  8200. (let ((f (or (car-safe cell) cell))
  8201. (disable-when-heading-prefix (cdr-safe cell)))
  8202. (when (fboundp f)
  8203. (let ((new-bindings))
  8204. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8205. (where-is-internal f outline-mode-map)))
  8206. (push binding new-bindings)
  8207. ;; TODO use local-function-key-map
  8208. (dolist (rep '(("<tab>" . "TAB")
  8209. ("<return>" . "RET")
  8210. ("<escape>" . "ESC")
  8211. ("<delete>" . "DEL")))
  8212. (setq binding (read-kbd-macro
  8213. (let ((case-fold-search))
  8214. (replace-regexp-in-string
  8215. (regexp-quote (cdr rep))
  8216. (car rep)
  8217. (key-description binding)))))
  8218. (cl-pushnew binding new-bindings :test 'equal)))
  8219. (dolist (binding new-bindings)
  8220. (let ((key (lookup-key orgstruct-mode-map binding)))
  8221. (when (or (not key) (numberp key))
  8222. (ignore-errors
  8223. (org-defkey orgstruct-mode-map
  8224. binding
  8225. (orgstruct-make-binding
  8226. f binding disable-when-heading-prefix))))))))))
  8227. (run-hooks 'orgstruct-setup-hook))
  8228. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8229. "Create a function for binding in the structure minor mode.
  8230. FUN is the command to call inside a table. KEY is the key that
  8231. should be checked in for a command to execute outside of tables.
  8232. Non-nil `disable-when-heading-prefix' means to disable the command
  8233. if `orgstruct-heading-prefix-regexp' is not empty."
  8234. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8235. (let ((nname name)
  8236. (i 0))
  8237. (while (fboundp (intern nname))
  8238. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8239. (setq name (intern nname)))
  8240. (eval
  8241. (let ((bindings '((org-heading-regexp
  8242. (concat "^"
  8243. orgstruct-heading-prefix-regexp
  8244. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8245. (org-outline-regexp
  8246. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8247. (org-outline-regexp-bol
  8248. (concat "^" org-outline-regexp))
  8249. (outline-regexp org-outline-regexp)
  8250. (outline-heading-end-regexp "\n")
  8251. (outline-level 'org-outline-level)
  8252. (outline-heading-alist))))
  8253. `(defun ,name (arg)
  8254. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8255. "Outside of structure, run the binding of `"
  8256. (key-description key) "'."
  8257. (when disable-when-heading-prefix
  8258. (concat
  8259. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8260. "back to the default binding due to limitations of Org's implementation of\n"
  8261. "`" (symbol-name fun) "'.")))
  8262. (interactive "p")
  8263. (let* ((disable
  8264. ,(and disable-when-heading-prefix
  8265. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8266. (fallback
  8267. (or disable
  8268. (not
  8269. (let* ,bindings
  8270. (org-context-p 'headline 'item
  8271. ,(when (memq fun
  8272. '(org-insert-heading
  8273. org-insert-heading-respect-content
  8274. org-meta-return))
  8275. '(when orgstruct-is-++
  8276. 'item-body))))))))
  8277. (if fallback
  8278. (let* ((orgstruct-mode)
  8279. (binding
  8280. (let ((key ,key))
  8281. (catch 'exit
  8282. (dolist
  8283. (rep
  8284. '(nil
  8285. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8286. ("<\\([^>]*\\)return>" . "\\1RET")
  8287. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8288. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8289. nil)
  8290. (when rep
  8291. (setq key (read-kbd-macro
  8292. (let ((case-fold-search))
  8293. (replace-regexp-in-string
  8294. (car rep)
  8295. (cdr rep)
  8296. (key-description key))))))
  8297. (when (key-binding key)
  8298. (throw 'exit (key-binding key))))))))
  8299. (if (keymapp binding)
  8300. (org-set-transient-map binding)
  8301. (let ((func (or binding
  8302. (unless disable
  8303. 'orgstruct-error))))
  8304. (when func
  8305. (call-interactively func)))))
  8306. (org-run-like-in-org-mode
  8307. (lambda ()
  8308. (interactive)
  8309. (let* ,bindings
  8310. (call-interactively ',fun)))))))))
  8311. name))
  8312. (defun org-contextualize-keys (alist contexts)
  8313. "Return valid elements in ALIST depending on CONTEXTS.
  8314. `org-agenda-custom-commands' or `org-capture-templates' are the
  8315. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8316. or `org-capture-templates-contexts' are the associated contexts
  8317. definitions."
  8318. (let ((contexts
  8319. ;; normalize contexts
  8320. (mapcar
  8321. (lambda(c) (cond ((listp (cadr c))
  8322. (list (car c) (car c) (nth 1 c)))
  8323. ((string= "" (cadr c))
  8324. (list (car c) (car c) (nth 2 c)))
  8325. (t c)))
  8326. contexts))
  8327. (a alist) r s)
  8328. ;; loop over all commands or templates
  8329. (dolist (c a)
  8330. (let (vrules repl)
  8331. (cond
  8332. ((not (assoc (car c) contexts))
  8333. (push c r))
  8334. ((and (assoc (car c) contexts)
  8335. (setq vrules (org-contextualize-validate-key
  8336. (car c) contexts)))
  8337. (mapc (lambda (vr)
  8338. (unless (equal (car vr) (cadr vr))
  8339. (setq repl vr)))
  8340. vrules)
  8341. (if (not repl) (push c r)
  8342. (push (cadr repl) s)
  8343. (push
  8344. (cons (car c)
  8345. (cdr (or (assoc (cadr repl) alist)
  8346. (error "Undefined key `%s' as contextual replacement for `%s'"
  8347. (cadr repl) (car c)))))
  8348. r))))))
  8349. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8350. (delq
  8351. nil
  8352. (delete-dups
  8353. (mapcar (lambda (x)
  8354. (let ((tpl (car x)))
  8355. (unless (delq
  8356. nil
  8357. (mapcar (lambda (y)
  8358. (equal y tpl))
  8359. s))
  8360. x)))
  8361. (reverse r))))))
  8362. (defun org-contextualize-validate-key (key contexts)
  8363. "Check CONTEXTS for agenda or capture KEY."
  8364. (let (res)
  8365. (dolist (r contexts)
  8366. (dolist (rr (car (last r)))
  8367. (when
  8368. (and (equal key (car r))
  8369. (if (functionp rr) (funcall rr)
  8370. (or (and (eq (car rr) 'in-file)
  8371. (buffer-file-name)
  8372. (string-match (cdr rr) (buffer-file-name)))
  8373. (and (eq (car rr) 'in-mode)
  8374. (string-match (cdr rr) (symbol-name major-mode)))
  8375. (and (eq (car rr) 'in-buffer)
  8376. (string-match (cdr rr) (buffer-name)))
  8377. (when (and (eq (car rr) 'not-in-file)
  8378. (buffer-file-name))
  8379. (not (string-match (cdr rr) (buffer-file-name))))
  8380. (when (eq (car rr) 'not-in-mode)
  8381. (not (string-match (cdr rr) (symbol-name major-mode))))
  8382. (when (eq (car rr) 'not-in-buffer)
  8383. (not (string-match (cdr rr) (buffer-name)))))))
  8384. (push r res))))
  8385. (delete-dups (delq nil res))))
  8386. (defun org-context-p (&rest contexts)
  8387. "Check if local context is any of CONTEXTS.
  8388. Possible values in the list of contexts are `table', `headline', and `item'."
  8389. (let ((pos (point)))
  8390. (goto-char (point-at-bol))
  8391. (prog1 (or (and (memq 'table contexts)
  8392. (looking-at "[ \t]*|"))
  8393. (and (memq 'headline contexts)
  8394. (looking-at org-outline-regexp))
  8395. (and (memq 'item contexts)
  8396. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8397. (and (memq 'item-body contexts)
  8398. (org-in-item-p)))
  8399. (goto-char pos))))
  8400. ;;;###autoload
  8401. (defun org-run-like-in-org-mode (cmd)
  8402. "Run a command, pretending that the current buffer is in Org mode.
  8403. This will temporarily bind local variables that are typically bound in
  8404. Org mode to the values they have in Org mode, and then interactively
  8405. call CMD."
  8406. (org-load-modules-maybe)
  8407. (unless org-local-vars
  8408. (setq org-local-vars (org-get-local-variables)))
  8409. (let (binds)
  8410. (dolist (var org-local-vars)
  8411. (when (or (not (boundp (car var)))
  8412. (eq (symbol-value (car var))
  8413. (default-value (car var))))
  8414. (push (list (car var) `(quote ,(cadr var))) binds)))
  8415. (eval `(let ,binds
  8416. (call-interactively (quote ,cmd))))))
  8417. (defun org-get-category (&optional pos force-refresh)
  8418. "Get the category applying to position POS."
  8419. (save-match-data
  8420. (when force-refresh (org-refresh-category-properties))
  8421. (let ((pos (or pos (point))))
  8422. (or (get-text-property pos 'org-category)
  8423. (progn (org-refresh-category-properties)
  8424. (get-text-property pos 'org-category))))))
  8425. ;;; Refresh properties
  8426. (defun org-refresh-properties (dprop tprop)
  8427. "Refresh buffer text properties.
  8428. DPROP is the drawer property and TPROP is either the
  8429. corresponding text property to set, or an alist with each element
  8430. being a text property (as a symbol) and a function to apply to
  8431. the value of the drawer property."
  8432. (let* ((case-fold-search t)
  8433. (inhibit-read-only t)
  8434. (inherit? (org-property-inherit-p dprop))
  8435. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8436. (global (and inherit? (org--property-global-value dprop nil))))
  8437. (org-with-silent-modifications
  8438. (org-with-point-at 1
  8439. ;; Set global values (e.g., values defined through
  8440. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8441. (when global (put-text-property (point-min) (point-max) tprop global))
  8442. ;; Set local values.
  8443. (while (re-search-forward property-re nil t)
  8444. (when (org-at-property-p)
  8445. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8446. (outline-next-heading))))))
  8447. (defun org-refresh-property (tprop p &optional inherit)
  8448. "Refresh the buffer text property TPROP from the drawer property P.
  8449. The refresh happens only for the current headline, or the whole
  8450. sub-tree if optional argument INHERIT is non-nil."
  8451. (unless (org-before-first-heading-p)
  8452. (save-excursion
  8453. (org-back-to-heading t)
  8454. (let ((start (point))
  8455. (end (save-excursion
  8456. (if inherit (org-end-of-subtree t t)
  8457. (or (outline-next-heading) (point-max))))))
  8458. (if (symbolp tprop)
  8459. ;; TPROP is a text property symbol.
  8460. (put-text-property start end tprop p)
  8461. ;; TPROP is an alist with (property . function) elements.
  8462. (pcase-dolist (`(,prop . ,f) tprop)
  8463. (put-text-property start end prop (funcall f p))))))))
  8464. (defun org-refresh-category-properties ()
  8465. "Refresh category text properties in the buffer."
  8466. (let ((case-fold-search t)
  8467. (inhibit-read-only t)
  8468. (default-category
  8469. (cond ((null org-category)
  8470. (if buffer-file-name
  8471. (file-name-sans-extension
  8472. (file-name-nondirectory buffer-file-name))
  8473. "???"))
  8474. ((symbolp org-category) (symbol-name org-category))
  8475. (t org-category))))
  8476. (org-with-silent-modifications
  8477. (org-with-wide-buffer
  8478. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8479. ;; This is the default category for the buffer. If none is
  8480. ;; found, fall-back to `org-category' or buffer file name.
  8481. (put-text-property
  8482. (point-min) (point-max)
  8483. 'org-category
  8484. (catch 'buffer-category
  8485. (goto-char (point-max))
  8486. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8487. (let ((element (org-element-at-point)))
  8488. (when (eq (org-element-type element) 'keyword)
  8489. (throw 'buffer-category
  8490. (org-element-property :value element)))))
  8491. default-category))
  8492. ;; Set sub-tree specific categories.
  8493. (goto-char (point-min))
  8494. (let ((regexp (org-re-property "CATEGORY")))
  8495. (while (re-search-forward regexp nil t)
  8496. (let ((value (match-string-no-properties 3)))
  8497. (when (org-at-property-p)
  8498. (put-text-property
  8499. (save-excursion (org-back-to-heading t) (point))
  8500. (save-excursion (org-end-of-subtree t t) (point))
  8501. 'org-category
  8502. value)))))))))
  8503. (defun org-refresh-stats-properties ()
  8504. "Refresh stats text properties in the buffer."
  8505. (org-with-silent-modifications
  8506. (org-with-point-at 1
  8507. (let ((regexp (concat org-outline-regexp-bol
  8508. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8509. (while (re-search-forward regexp nil t)
  8510. (let* ((numerator (string-to-number (match-string 1)))
  8511. (denominator (and (match-end 2)
  8512. (string-to-number (match-string 2))))
  8513. (stats (cond ((not denominator) numerator) ;percent
  8514. ((= denominator 0) 0)
  8515. (t (/ (* numerator 100) denominator)))))
  8516. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8517. 'org-stats stats)))))))
  8518. (defun org-refresh-effort-properties ()
  8519. "Refresh effort properties"
  8520. (org-refresh-properties
  8521. org-effort-property
  8522. '((effort . identity)
  8523. (effort-minutes . org-duration-to-minutes))))
  8524. ;;;; Link Stuff
  8525. ;;; Link abbreviations
  8526. (defun org-link-expand-abbrev (link)
  8527. "Apply replacements as defined in `org-link-abbrev-alist'."
  8528. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8529. (let* ((key (match-string 1 link))
  8530. (as (or (assoc key org-link-abbrev-alist-local)
  8531. (assoc key org-link-abbrev-alist)))
  8532. (tag (and (match-end 2) (match-string 3 link)))
  8533. rpl)
  8534. (if (not as)
  8535. link
  8536. (setq rpl (cdr as))
  8537. (cond
  8538. ((symbolp rpl) (funcall rpl tag))
  8539. ((string-match "%(\\([^)]+\\))" rpl)
  8540. (replace-match
  8541. (save-match-data
  8542. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8543. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8544. ((string-match "%h" rpl)
  8545. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8546. (t (concat rpl tag)))))
  8547. link))
  8548. ;;; Storing and inserting links
  8549. (defvar org-insert-link-history nil
  8550. "Minibuffer history for links inserted with `org-insert-link'.")
  8551. (defvar org-stored-links nil
  8552. "Contains the links stored with `org-store-link'.")
  8553. (defvar org-store-link-plist nil
  8554. "Plist with info about the most recently link created with `org-store-link'.")
  8555. (defun org-store-link-functions ()
  8556. "Return a list of functions that are called to create and store a link.
  8557. The functions defined in the :store property of
  8558. `org-link-parameters'.
  8559. Each function will be called in turn until one returns a non-nil
  8560. value. Each function should check if it is responsible for
  8561. creating this link (for example by looking at the major mode).
  8562. If not, it must exit and return nil. If yes, it should return
  8563. a non-nil value after calling `org-store-link-props' with a list
  8564. of properties and values. Special properties are:
  8565. :type The link prefix, like \"http\". This must be given.
  8566. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8567. This is obligatory as well.
  8568. :description Optional default description for the second pair
  8569. of brackets in an Org mode link. The user can still change
  8570. this when inserting this link into an Org mode buffer.
  8571. In addition to these, any additional properties can be specified
  8572. and then used in capture templates."
  8573. (cl-loop for link in org-link-parameters
  8574. with store-func
  8575. do (setq store-func (org-link-get-parameter (car link) :store))
  8576. if store-func
  8577. collect store-func))
  8578. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8579. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8580. ;;;###autoload
  8581. (defun org-store-link (arg)
  8582. "Store an org-link to the current location.
  8583. \\<org-mode-map>
  8584. This link is added to `org-stored-links' and can later be inserted
  8585. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8586. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8587. A single
  8588. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8589. `org-gnus-prefer-web-links' for links to Usenet articles.
  8590. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8591. skipping storing functions that are not
  8592. part of Org core.
  8593. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8594. prefix ARG forces storing a link for each line in the
  8595. active region."
  8596. (interactive "P")
  8597. (org-load-modules-maybe)
  8598. (if (and (equal arg '(64)) (org-region-active-p))
  8599. (save-excursion
  8600. (let ((end (region-end)))
  8601. (goto-char (region-beginning))
  8602. (set-mark (point))
  8603. (while (< (point-at-eol) end)
  8604. (move-end-of-line 1) (activate-mark)
  8605. (let (current-prefix-arg)
  8606. (call-interactively 'org-store-link))
  8607. (move-beginning-of-line 2)
  8608. (set-mark (point)))))
  8609. (setq org-store-link-plist nil)
  8610. (let (link cpltxt desc description search
  8611. txt custom-id agenda-link sfuns sfunsn)
  8612. (cond
  8613. ;; Store a link using an external link type
  8614. ((and (not (equal arg '(16)))
  8615. (setq sfuns
  8616. (delq
  8617. nil (mapcar (lambda (f)
  8618. (let (fs) (if (funcall f) (push f fs))))
  8619. (org-store-link-functions)))
  8620. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8621. (or (and (cdr sfuns)
  8622. (funcall (intern
  8623. (completing-read
  8624. "Which function for creating the link? "
  8625. sfunsn nil t (car sfunsn)))))
  8626. (funcall (caar sfuns)))
  8627. (setq link (plist-get org-store-link-plist :link)
  8628. desc (or (plist-get org-store-link-plist
  8629. :description)
  8630. link))))
  8631. ;; Store a link from a source code buffer.
  8632. ((org-src-edit-buffer-p)
  8633. (let ((coderef-format (org-src-coderef-format)))
  8634. (cond ((save-excursion
  8635. (beginning-of-line)
  8636. (looking-at (org-src-coderef-regexp coderef-format)))
  8637. (setq link (format "(%s)" (match-string-no-properties 3))))
  8638. ((called-interactively-p 'any)
  8639. (let ((label (read-string "Code line label: ")))
  8640. (end-of-line)
  8641. (setq link (format coderef-format label))
  8642. (let ((gc (- 79 (length link))))
  8643. (if (< (current-column) gc)
  8644. (org-move-to-column gc t)
  8645. (insert " ")))
  8646. (insert link)
  8647. (setq link (concat "(" label ")"))
  8648. (setq desc nil)))
  8649. (t (setq link nil)))))
  8650. ;; We are in the agenda, link to referenced location
  8651. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8652. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8653. (get-text-property (point) 'org-marker))))
  8654. (when m
  8655. (org-with-point-at m
  8656. (setq agenda-link
  8657. (if (called-interactively-p 'any)
  8658. (call-interactively 'org-store-link)
  8659. (org-store-link nil)))))))
  8660. ((eq major-mode 'calendar-mode)
  8661. (let ((cd (calendar-cursor-to-date)))
  8662. (setq link
  8663. (format-time-string
  8664. (car org-time-stamp-formats)
  8665. (apply 'encode-time
  8666. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8667. nil nil nil))))
  8668. (org-store-link-props :type "calendar" :date cd)))
  8669. ((eq major-mode 'help-mode)
  8670. (setq link (concat "help:" (save-excursion
  8671. (goto-char (point-min))
  8672. (looking-at "^[^ ]+")
  8673. (match-string 0))))
  8674. (org-store-link-props :type "help"))
  8675. ((eq major-mode 'w3-mode)
  8676. (setq cpltxt (if (and (buffer-name)
  8677. (not (string-match "Untitled" (buffer-name))))
  8678. (buffer-name)
  8679. (url-view-url t))
  8680. link (url-view-url t))
  8681. (org-store-link-props :type "w3" :url (url-view-url t)))
  8682. ((eq major-mode 'image-mode)
  8683. (setq cpltxt (concat "file:"
  8684. (abbreviate-file-name buffer-file-name))
  8685. link cpltxt)
  8686. (org-store-link-props :type "image" :file buffer-file-name))
  8687. ;; In dired, store a link to the file of the current line
  8688. ((derived-mode-p 'dired-mode)
  8689. (let ((file (dired-get-filename nil t)))
  8690. (setq file (if file
  8691. (abbreviate-file-name
  8692. (expand-file-name (dired-get-filename nil t)))
  8693. ;; otherwise, no file so use current directory.
  8694. default-directory))
  8695. (setq cpltxt (concat "file:" file)
  8696. link cpltxt)))
  8697. ((setq search (run-hook-with-args-until-success
  8698. 'org-create-file-search-functions))
  8699. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8700. "::" search))
  8701. (setq cpltxt (or description link)))
  8702. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8703. (org-with-limited-levels
  8704. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8705. (cond
  8706. ;; Store a link using the target at point
  8707. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8708. (setq cpltxt
  8709. (concat "file:"
  8710. (abbreviate-file-name
  8711. (buffer-file-name (buffer-base-buffer)))
  8712. "::" (match-string 1))
  8713. link cpltxt))
  8714. ((and (featurep 'org-id)
  8715. (or (eq org-id-link-to-org-use-id t)
  8716. (and (called-interactively-p 'any)
  8717. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8718. (and (eq org-id-link-to-org-use-id
  8719. 'create-if-interactive-and-no-custom-id)
  8720. (not custom-id))))
  8721. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8722. ;; Store a link using the ID at point
  8723. (setq link (condition-case nil
  8724. (prog1 (org-id-store-link)
  8725. (setq desc (or (plist-get org-store-link-plist
  8726. :description)
  8727. "")))
  8728. (error
  8729. ;; Probably before first headline, link only to file
  8730. (concat "file:"
  8731. (abbreviate-file-name
  8732. (buffer-file-name (buffer-base-buffer))))))))
  8733. (t
  8734. ;; Just link to current headline
  8735. (setq cpltxt (concat "file:"
  8736. (abbreviate-file-name
  8737. (buffer-file-name (buffer-base-buffer)))))
  8738. ;; Add a context search string
  8739. (when (org-xor org-context-in-file-links
  8740. (equal arg '(4)))
  8741. (let* ((element (org-element-at-point))
  8742. (name (org-element-property :name element)))
  8743. (setq txt (cond
  8744. ((org-at-heading-p) nil)
  8745. (name)
  8746. ((org-region-active-p)
  8747. (buffer-substring (region-beginning) (region-end)))))
  8748. (when (or (null txt) (string-match "\\S-" txt))
  8749. (setq cpltxt
  8750. (concat cpltxt "::"
  8751. (condition-case nil
  8752. (org-make-org-heading-search-string txt)
  8753. (error "")))
  8754. desc (or name
  8755. (nth 4 (ignore-errors (org-heading-components)))
  8756. "NONE")))))
  8757. (when (string-match "::\\'" cpltxt)
  8758. (setq cpltxt (substring cpltxt 0 -2)))
  8759. (setq link cpltxt)))))
  8760. ((buffer-file-name (buffer-base-buffer))
  8761. ;; Just link to this file here.
  8762. (setq cpltxt (concat "file:"
  8763. (abbreviate-file-name
  8764. (buffer-file-name (buffer-base-buffer)))))
  8765. ;; Add a context string.
  8766. (when (org-xor org-context-in-file-links
  8767. (equal arg '(4)))
  8768. (setq txt (if (org-region-active-p)
  8769. (buffer-substring (region-beginning) (region-end))
  8770. (buffer-substring (point-at-bol) (point-at-eol))))
  8771. ;; Only use search option if there is some text.
  8772. (when (string-match "\\S-" txt)
  8773. (setq cpltxt
  8774. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8775. desc "NONE")))
  8776. (setq link cpltxt))
  8777. ((called-interactively-p 'interactive)
  8778. (user-error "No method for storing a link from this buffer"))
  8779. (t (setq link nil)))
  8780. ;; We're done setting link and desc, clean up
  8781. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8782. (setq link (or link cpltxt)
  8783. desc (or desc cpltxt))
  8784. (cond ((not desc))
  8785. ((equal desc "NONE") (setq desc nil))
  8786. (t (setq desc
  8787. (replace-regexp-in-string
  8788. org-bracket-link-analytic-regexp
  8789. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8790. desc))))
  8791. ;; Return the link
  8792. (if (not (and (or (called-interactively-p 'any)
  8793. executing-kbd-macro)
  8794. link))
  8795. (or agenda-link (and link (org-make-link-string link desc)))
  8796. (push (list link desc) org-stored-links)
  8797. (message "Stored: %s" (or desc link))
  8798. (when custom-id
  8799. (setq link (concat "file:" (abbreviate-file-name
  8800. (buffer-file-name)) "::#" custom-id))
  8801. (push (list link desc) org-stored-links))
  8802. (car org-stored-links)))))
  8803. (defun org-store-link-props (&rest plist)
  8804. "Store link properties.
  8805. The properties are pre-processed by extracting names, addresses
  8806. and dates."
  8807. (let ((x (plist-get plist :from)))
  8808. (when x
  8809. (let ((adr (mail-extract-address-components x)))
  8810. (setq plist (plist-put plist :fromname (car adr)))
  8811. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8812. (let ((x (plist-get plist :to)))
  8813. (when x
  8814. (let ((adr (mail-extract-address-components x)))
  8815. (setq plist (plist-put plist :toname (car adr)))
  8816. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8817. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8818. (when x
  8819. (setq plist (plist-put plist :date-timestamp
  8820. (format-time-string
  8821. (org-time-stamp-format t) x)))
  8822. (setq plist (plist-put plist :date-timestamp-inactive
  8823. (format-time-string
  8824. (org-time-stamp-format t t) x)))))
  8825. (let ((from (plist-get plist :from))
  8826. (to (plist-get plist :to)))
  8827. (when (and from to org-from-is-user-regexp)
  8828. (setq plist
  8829. (plist-put plist :fromto
  8830. (if (string-match org-from-is-user-regexp from)
  8831. (concat "to %t")
  8832. (concat "from %f"))))))
  8833. (setq org-store-link-plist plist))
  8834. (defun org-add-link-props (&rest plist)
  8835. "Add these properties to the link property list."
  8836. (let (key value)
  8837. (while plist
  8838. (setq key (pop plist) value (pop plist))
  8839. (setq org-store-link-plist
  8840. (plist-put org-store-link-plist key value)))))
  8841. (defun org-email-link-description (&optional fmt)
  8842. "Return the description part of an email link.
  8843. This takes information from `org-store-link-plist' and formats it
  8844. according to FMT (default from `org-email-link-description-format')."
  8845. (setq fmt (or fmt org-email-link-description-format))
  8846. (let* ((p org-store-link-plist)
  8847. (to (plist-get p :toaddress))
  8848. (from (plist-get p :fromaddress))
  8849. (table
  8850. (list
  8851. (cons "%c" (plist-get p :fromto))
  8852. (cons "%F" (plist-get p :from))
  8853. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8854. (cons "%T" (plist-get p :to))
  8855. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8856. (cons "%s" (plist-get p :subject))
  8857. (cons "%d" (plist-get p :date))
  8858. (cons "%m" (plist-get p :message-id)))))
  8859. (when (string-match "%c" fmt)
  8860. ;; Check if the user wrote this message
  8861. (if (and org-from-is-user-regexp from to
  8862. (save-match-data (string-match org-from-is-user-regexp from)))
  8863. (setq fmt (replace-match "to %t" t t fmt))
  8864. (setq fmt (replace-match "from %f" t t fmt))))
  8865. (org-replace-escapes fmt table)))
  8866. (defun org-make-org-heading-search-string (&optional string)
  8867. "Make search string for the current headline or STRING."
  8868. (let ((s (or string
  8869. (and (derived-mode-p 'org-mode)
  8870. (save-excursion
  8871. (org-back-to-heading t)
  8872. (org-element-property :raw-value (org-element-at-point))))))
  8873. (lines org-context-in-file-links))
  8874. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8875. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8876. (when (and string (integerp lines) (> lines 0))
  8877. (let ((slines (org-split-string s "\n")))
  8878. (when (< lines (length slines))
  8879. (setq s (mapconcat
  8880. 'identity
  8881. (reverse (nthcdr (- (length slines) lines)
  8882. (reverse slines))) "\n")))))
  8883. (mapconcat #'identity (split-string s) " ")))
  8884. (defun org-make-link-string (link &optional description)
  8885. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8886. (unless (org-string-nw-p link) (error "Empty link"))
  8887. (let ((uri (cond ((string-match org-link-types-re link)
  8888. (concat (match-string 1 link)
  8889. (org-link-escape (substring link (match-end 1)))))
  8890. ;; For readability, url-encode internal links only
  8891. ;; when absolutely needed (i.e, when they contain
  8892. ;; square brackets). File links however, are
  8893. ;; encoded since, e.g., spaces are significant.
  8894. ((or (file-name-absolute-p link)
  8895. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8896. (org-link-escape link))
  8897. (t link)))
  8898. (description
  8899. (and (org-string-nw-p description)
  8900. ;; Remove brackets from description, as they are fatal.
  8901. (replace-regexp-in-string
  8902. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8903. (org-trim description)))))
  8904. (format "[[%s]%s]"
  8905. uri
  8906. (if description (format "[%s]" description) ""))))
  8907. (defconst org-link-escape-chars
  8908. ;;%20 %5B %5D %25
  8909. '(?\s ?\[ ?\] ?%)
  8910. "List of characters that should be escaped in a link when stored to Org.
  8911. This is the list that is used for internal purposes.")
  8912. (defun org-link-escape (text &optional table merge)
  8913. "Return percent escaped representation of TEXT.
  8914. TEXT is a string with the text to escape.
  8915. Optional argument TABLE is a list with characters that should be
  8916. escaped. When nil, `org-link-escape-chars' is used.
  8917. If optional argument MERGE is set, merge TABLE into
  8918. `org-link-escape-chars'."
  8919. (let ((characters-to-encode
  8920. (cond ((null table) org-link-escape-chars)
  8921. (merge (append org-link-escape-chars table))
  8922. (t table))))
  8923. (mapconcat
  8924. (lambda (c)
  8925. (if (or (memq c characters-to-encode)
  8926. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8927. (mapconcat (lambda (e) (format "%%%.2X" e))
  8928. (or (encode-coding-char c 'utf-8)
  8929. (error "Unable to percent escape character: %c" c))
  8930. "")
  8931. (char-to-string c)))
  8932. text "")))
  8933. (defun org-link-unescape (str)
  8934. "Unhex hexified Unicode parts in string STR.
  8935. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8936. reciprocal of `org-link-escape', which see."
  8937. (if (org-string-nw-p str)
  8938. (replace-regexp-in-string
  8939. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8940. str))
  8941. (defun org-link-unescape-compound (hex)
  8942. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8943. Note: this function also decodes single byte encodings like
  8944. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8945. (save-match-data
  8946. (let* ((bytes (cdr (split-string hex "%")))
  8947. (ret "")
  8948. (eat 0)
  8949. (sum 0))
  8950. (while bytes
  8951. (let* ((val (string-to-number (pop bytes) 16))
  8952. (shift-xor
  8953. (if (= 0 eat)
  8954. (cond
  8955. ((>= val 252) (cons 6 252))
  8956. ((>= val 248) (cons 5 248))
  8957. ((>= val 240) (cons 4 240))
  8958. ((>= val 224) (cons 3 224))
  8959. ((>= val 192) (cons 2 192))
  8960. (t (cons 0 0)))
  8961. (cons 6 128))))
  8962. (when (>= val 192) (setq eat (car shift-xor)))
  8963. (setq val (logxor val (cdr shift-xor)))
  8964. (setq sum (+ (lsh sum (car shift-xor)) val))
  8965. (when (> eat 0) (setq eat (- eat 1)))
  8966. (cond
  8967. ((= 0 eat) ;multi byte
  8968. (setq ret (concat ret (char-to-string sum)))
  8969. (setq sum 0))
  8970. ((not bytes) ; single byte(s)
  8971. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8972. ret)))
  8973. (defun org-link-unescape-single-byte-sequence (hex)
  8974. "Unhexify hex-encoded single byte character sequences."
  8975. (mapconcat (lambda (byte)
  8976. (char-to-string (string-to-number byte 16)))
  8977. (cdr (split-string hex "%")) ""))
  8978. (defun org-xor (a b)
  8979. "Exclusive or."
  8980. (if a (not b) b))
  8981. (defun org-fixup-message-id-for-http (s)
  8982. "Replace special characters in a message id, so it can be used in an http query."
  8983. (when (string-match "%" s)
  8984. (setq s (mapconcat (lambda (c)
  8985. (if (eq c ?%)
  8986. "%25"
  8987. (char-to-string c)))
  8988. s "")))
  8989. (while (string-match "<" s)
  8990. (setq s (replace-match "%3C" t t s)))
  8991. (while (string-match ">" s)
  8992. (setq s (replace-match "%3E" t t s)))
  8993. (while (string-match "@" s)
  8994. (setq s (replace-match "%40" t t s)))
  8995. s)
  8996. (defun org-link-prettify (link)
  8997. "Return a human-readable representation of LINK.
  8998. The car of LINK must be a raw link.
  8999. The cdr of LINK must be either a link description or nil."
  9000. (let ((desc (or (cadr link) "<no description>")))
  9001. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9002. "<" (car link) ">")))
  9003. ;;;###autoload
  9004. (defun org-insert-link-global ()
  9005. "Insert a link like Org mode does.
  9006. This command can be called in any mode to insert a link in Org syntax."
  9007. (interactive)
  9008. (org-load-modules-maybe)
  9009. (org-run-like-in-org-mode 'org-insert-link))
  9010. (defun org-insert-all-links (arg &optional pre post)
  9011. "Insert all links in `org-stored-links'.
  9012. When a universal prefix, do not delete the links from `org-stored-links'.
  9013. When `ARG' is a number, insert the last N link(s).
  9014. `PRE' and `POST' are optional arguments to define a string to
  9015. prepend or to append."
  9016. (interactive "P")
  9017. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9018. (links (copy-sequence org-stored-links))
  9019. (pr (or pre "- "))
  9020. (po (or post "\n"))
  9021. (cnt 1) l)
  9022. (if (null org-stored-links)
  9023. (message "No link to insert")
  9024. (while (and (or (listp arg) (>= arg cnt))
  9025. (setq l (if (listp arg)
  9026. (pop links)
  9027. (pop org-stored-links))))
  9028. (setq cnt (1+ cnt))
  9029. (insert pr)
  9030. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9031. (insert po)))))
  9032. (defun org-insert-last-stored-link (arg)
  9033. "Insert the last link stored in `org-stored-links'."
  9034. (interactive "p")
  9035. (org-insert-all-links arg "" "\n"))
  9036. (defun org-link-fontify-links-to-this-file ()
  9037. "Fontify links to the current file in `org-stored-links'."
  9038. (let ((f (buffer-file-name)) a b)
  9039. (setq a (mapcar (lambda(l)
  9040. (let ((ll (car l)))
  9041. (when (and (string-match "^file:\\(.+\\)::" ll)
  9042. (equal f (expand-file-name (match-string 1 ll))))
  9043. ll)))
  9044. org-stored-links))
  9045. (when (featurep 'org-id)
  9046. (setq b (mapcar (lambda(l)
  9047. (let ((ll (car l)))
  9048. (when (and (string-match "^id:\\(.+\\)$" ll)
  9049. (equal f (expand-file-name
  9050. (or (org-id-find-id-file
  9051. (match-string 1 ll)) ""))))
  9052. ll)))
  9053. org-stored-links)))
  9054. (mapcar (lambda(l)
  9055. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9056. (delq nil (append a b)))))
  9057. (defvar org--links-history nil)
  9058. (defun org-insert-link (&optional complete-file link-location default-description)
  9059. "Insert a link. At the prompt, enter the link.
  9060. Completion can be used to insert any of the link protocol prefixes in use.
  9061. The history can be used to select a link previously stored with
  9062. `org-store-link'. When the empty string is entered (i.e. if you just
  9063. press `RET' at the prompt), the link defaults to the most recently
  9064. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9065. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9066. You will also be prompted for a description, and if one is given, it will
  9067. be displayed in the buffer instead of the link.
  9068. If there is already a link at point, this command will allow you to edit
  9069. link and description parts.
  9070. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9071. file name can be
  9072. selected using completion. The path to the file will be relative to the
  9073. current directory if the file is in the current directory or a subdirectory.
  9074. Otherwise, the link will be the absolute path as completed in the minibuffer
  9075. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9076. option `org-link-file-path-type'.
  9077. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9078. absolute path even if the file is in
  9079. the current directory or below.
  9080. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9081. prefix negates `org-keep-stored-link-after-insertion'.
  9082. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9083. the link location instead of reading one interactively.
  9084. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9085. be used as the default description. Otherwise, if
  9086. `org-make-link-description-function' is non-nil, this function
  9087. will be called with the link target, and the result will be the
  9088. default link description."
  9089. (interactive "P")
  9090. (let* ((wcf (current-window-configuration))
  9091. (origbuf (current-buffer))
  9092. (region (when (org-region-active-p)
  9093. (buffer-substring (region-beginning) (region-end))))
  9094. (remove (and region (list (region-beginning) (region-end))))
  9095. (desc region)
  9096. (link link-location)
  9097. (abbrevs org-link-abbrev-alist-local)
  9098. entry all-prefixes auto-desc)
  9099. (cond
  9100. (link-location) ; specified by arg, just use it.
  9101. ((org-in-regexp org-bracket-link-regexp 1)
  9102. ;; We do have a link at point, and we are going to edit it.
  9103. (setq remove (list (match-beginning 0) (match-end 0)))
  9104. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9105. (setq link (read-string "Link: "
  9106. (org-link-unescape
  9107. (match-string-no-properties 1)))))
  9108. ((or (org-in-regexp org-angle-link-re)
  9109. (org-in-regexp org-plain-link-re))
  9110. ;; Convert to bracket link
  9111. (setq remove (list (match-beginning 0) (match-end 0))
  9112. link (read-string "Link: "
  9113. (org-unbracket-string "<" ">" (match-string 0)))))
  9114. ((member complete-file '((4) (16)))
  9115. ;; Completing read for file names.
  9116. (setq link (org-file-complete-link complete-file)))
  9117. (t
  9118. ;; Read link, with completion for stored links.
  9119. (org-link-fontify-links-to-this-file)
  9120. (org-switch-to-buffer-other-window "*Org Links*")
  9121. (with-current-buffer "*Org Links*"
  9122. (erase-buffer)
  9123. (insert "Insert a link.
  9124. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9125. (when org-stored-links
  9126. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9127. (insert (mapconcat 'org-link-prettify
  9128. (reverse org-stored-links) "\n")))
  9129. (goto-char (point-min)))
  9130. (let ((cw (selected-window)))
  9131. (select-window (get-buffer-window "*Org Links*" 'visible))
  9132. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9133. (unless (pos-visible-in-window-p (point-max))
  9134. (org-fit-window-to-buffer))
  9135. (and (window-live-p cw) (select-window cw)))
  9136. (setq all-prefixes (append (mapcar 'car abbrevs)
  9137. (mapcar 'car org-link-abbrev-alist)
  9138. (org-link-types)))
  9139. (unwind-protect
  9140. ;; Fake a link history, containing the stored links.
  9141. (let ((org--links-history
  9142. (append (mapcar #'car org-stored-links)
  9143. org-insert-link-history)))
  9144. (setq link
  9145. (org-completing-read
  9146. "Link: "
  9147. (append
  9148. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9149. (mapcar #'car org-stored-links))
  9150. nil nil nil
  9151. 'org--links-history
  9152. (caar org-stored-links)))
  9153. (unless (org-string-nw-p link) (user-error "No link selected"))
  9154. (dolist (l org-stored-links)
  9155. (when (equal link (cadr l))
  9156. (setq link (car l))
  9157. (setq auto-desc t)))
  9158. (when (or (member link all-prefixes)
  9159. (and (equal ":" (substring link -1))
  9160. (member (substring link 0 -1) all-prefixes)
  9161. (setq link (substring link 0 -1))))
  9162. (setq link (with-current-buffer origbuf
  9163. (org-link-try-special-completion link)))))
  9164. (set-window-configuration wcf)
  9165. (kill-buffer "*Org Links*"))
  9166. (setq entry (assoc link org-stored-links))
  9167. (or entry (push link org-insert-link-history))
  9168. (setq desc (or desc (nth 1 entry)))))
  9169. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9170. (not org-keep-stored-link-after-insertion))
  9171. (setq org-stored-links (delq (assoc link org-stored-links)
  9172. org-stored-links)))
  9173. (when (and (string-match org-plain-link-re link)
  9174. (not (string-match org-ts-regexp link)))
  9175. ;; URL-like link, normalize the use of angular brackets.
  9176. (setq link (org-unbracket-string "<" ">" link)))
  9177. ;; Check if we are linking to the current file with a search
  9178. ;; option If yes, simplify the link by using only the search
  9179. ;; option.
  9180. (when (and buffer-file-name
  9181. (let ((case-fold-search nil))
  9182. (string-match "\\`file:\\(.+?\\)::" link)))
  9183. (let ((path (match-string-no-properties 1 link))
  9184. (search (substring-no-properties link (match-end 0))))
  9185. (save-match-data
  9186. (when (equal (file-truename buffer-file-name) (file-truename path))
  9187. ;; We are linking to this same file, with a search option
  9188. (setq link search)))))
  9189. ;; Check if we can/should use a relative path. If yes, simplify the link
  9190. (let ((case-fold-search nil))
  9191. (when (string-match "\\`\\(file\\|docview\\):" link)
  9192. (let* ((type (match-string-no-properties 0 link))
  9193. (path (substring-no-properties link (match-end 0)))
  9194. (origpath path))
  9195. (cond
  9196. ((or (eq org-link-file-path-type 'absolute)
  9197. (equal complete-file '(16)))
  9198. (setq path (abbreviate-file-name (expand-file-name path))))
  9199. ((eq org-link-file-path-type 'noabbrev)
  9200. (setq path (expand-file-name path)))
  9201. ((eq org-link-file-path-type 'relative)
  9202. (setq path (file-relative-name path)))
  9203. (t
  9204. (save-match-data
  9205. (if (string-match (concat "^" (regexp-quote
  9206. (expand-file-name
  9207. (file-name-as-directory
  9208. default-directory))))
  9209. (expand-file-name path))
  9210. ;; We are linking a file with relative path name.
  9211. (setq path (substring (expand-file-name path)
  9212. (match-end 0)))
  9213. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9214. (setq link (concat type path))
  9215. (when (equal desc origpath)
  9216. (setq desc path)))))
  9217. (unless auto-desc
  9218. (let ((initial-input
  9219. (cond
  9220. (default-description)
  9221. ((not org-make-link-description-function) desc)
  9222. (t (condition-case nil
  9223. (funcall org-make-link-description-function link desc)
  9224. (error
  9225. (message "Can't get link description from `%s'"
  9226. (symbol-name org-make-link-description-function))
  9227. (sit-for 2)
  9228. nil))))))
  9229. (setq desc (read-string "Description: " initial-input))))
  9230. (unless (string-match "\\S-" desc) (setq desc nil))
  9231. (when remove (apply 'delete-region remove))
  9232. (insert (org-make-link-string link desc))
  9233. ;; Redisplay so as the new link has proper invisible characters.
  9234. (sit-for 0)))
  9235. (defun org-link-try-special-completion (type)
  9236. "If there is completion support for link type TYPE, offer it."
  9237. (let ((fun (org-link-get-parameter type :complete)))
  9238. (if (functionp fun)
  9239. (funcall fun)
  9240. (read-string "Link (no completion support): " (concat type ":")))))
  9241. (defun org-file-complete-link (&optional arg)
  9242. "Create a file link using completion."
  9243. (let ((file (read-file-name "File: "))
  9244. (pwd (file-name-as-directory (expand-file-name ".")))
  9245. (pwd1 (file-name-as-directory (abbreviate-file-name
  9246. (expand-file-name ".")))))
  9247. (cond ((equal arg '(16))
  9248. (concat "file:"
  9249. (abbreviate-file-name (expand-file-name file))))
  9250. ((string-match
  9251. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9252. (concat "file:" (match-string 1 file)))
  9253. ((string-match
  9254. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9255. (expand-file-name file))
  9256. (concat "file:"
  9257. (match-string 1 (expand-file-name file))))
  9258. (t (concat "file:" file)))))
  9259. (defun org-completing-read (&rest args)
  9260. "Completing-read with SPACE being a normal character."
  9261. (let ((enable-recursive-minibuffers t)
  9262. (minibuffer-local-completion-map
  9263. (copy-keymap minibuffer-local-completion-map)))
  9264. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9265. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9266. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9267. 'org-time-stamp-inactive)
  9268. (apply #'completing-read args)))
  9269. ;;; Opening/following a link
  9270. (defvar org-link-search-failed nil)
  9271. (defvar org-open-link-functions nil
  9272. "Hook for functions finding a plain text link.
  9273. These functions must take a single argument, the link content.
  9274. They will be called for links that look like [[link text][description]]
  9275. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9276. like a filename (e.g. \"./blue.png\").
  9277. These functions will be called *before* Org attempts to resolve the
  9278. link by doing text searches in the current buffer - so if you want a
  9279. link \"[[target]]\" to still find \"<<target>>\", your function should
  9280. handle this as a special case.
  9281. When the function does handle the link, it must return a non-nil value.
  9282. If it decides that it is not responsible for this link, it must return
  9283. nil to indicate that that Org can continue with other options like
  9284. exact and fuzzy text search.")
  9285. (defun org-next-link (&optional search-backward)
  9286. "Move forward to the next link.
  9287. If the link is in hidden text, expose it."
  9288. (interactive "P")
  9289. (when (and org-link-search-failed (eq this-command last-command))
  9290. (goto-char (point-min))
  9291. (message "Link search wrapped back to beginning of buffer"))
  9292. (setq org-link-search-failed nil)
  9293. (let* ((pos (point))
  9294. (ct (org-context))
  9295. (a (assq :link ct))
  9296. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9297. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9298. ((looking-at org-any-link-re)
  9299. ;; Don't stay stuck at link without an org-link face
  9300. (forward-char (if search-backward -1 1))))
  9301. (if (funcall srch-fun org-any-link-re nil t)
  9302. (progn
  9303. (goto-char (match-beginning 0))
  9304. (when (org-invisible-p) (org-show-context)))
  9305. (goto-char pos)
  9306. (setq org-link-search-failed t)
  9307. (message "No further link found"))))
  9308. (defun org-previous-link ()
  9309. "Move backward to the previous link.
  9310. If the link is in hidden text, expose it."
  9311. (interactive)
  9312. (funcall 'org-next-link t))
  9313. (defun org-translate-link (s)
  9314. "Translate a link string if a translation function has been defined."
  9315. (with-temp-buffer
  9316. (insert (org-trim s))
  9317. (org-trim (org-element-interpret-data (org-element-context)))))
  9318. (defun org-translate-link-from-planner (type path)
  9319. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9320. This is still an experimental function, your mileage may vary."
  9321. (cond
  9322. ((member type '("http" "https" "news" "ftp"))
  9323. ;; standard Internet links are the same.
  9324. nil)
  9325. ((and (equal type "irc") (string-match "^//" path))
  9326. ;; Planner has two / at the beginning of an irc link, we have 1.
  9327. ;; We should have zero, actually....
  9328. (setq path (substring path 1)))
  9329. ((and (equal type "lisp") (string-match "^/" path))
  9330. ;; Planner has a slash, we do not.
  9331. (setq type "elisp" path (substring path 1)))
  9332. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9333. ;; A typical message link. Planner has the id after the final slash,
  9334. ;; we separate it with a hash mark
  9335. (setq path (concat (match-string 1 path) "#"
  9336. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9337. (cons type path))
  9338. (defun org-find-file-at-mouse (ev)
  9339. "Open file link or URL at mouse."
  9340. (interactive "e")
  9341. (mouse-set-point ev)
  9342. (org-open-at-point 'in-emacs))
  9343. (defun org-open-at-mouse (ev)
  9344. "Open file link or URL at mouse.
  9345. See the docstring of `org-open-file' for details."
  9346. (interactive "e")
  9347. (mouse-set-point ev)
  9348. (when (eq major-mode 'org-agenda-mode)
  9349. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9350. (org-open-at-point))
  9351. (defvar org-window-config-before-follow-link nil
  9352. "The window configuration before following a link.
  9353. This is saved in case the need arises to restore it.")
  9354. ;;;###autoload
  9355. (defun org-open-at-point-global ()
  9356. "Follow a link or time-stamp like Org mode does.
  9357. This command can be called in any mode to follow an external link
  9358. or a time-stamp that has Org mode syntax. Its behavior is
  9359. undefined when called on internal links (e.g., fuzzy links).
  9360. Raise an error when there is nothing to follow. "
  9361. (interactive)
  9362. (cond ((org-in-regexp org-any-link-re)
  9363. (org-open-link-from-string (match-string-no-properties 0)))
  9364. ((or (org-in-regexp org-ts-regexp-both nil t)
  9365. (org-in-regexp org-tsr-regexp-both nil t))
  9366. (org-follow-timestamp-link))
  9367. (t (user-error "No link found"))))
  9368. ;;;###autoload
  9369. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9370. "Open a link in the string S, as if it was in Org mode."
  9371. (interactive "sLink: \nP")
  9372. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9373. (with-temp-buffer
  9374. (let ((org-inhibit-startup (not reference-buffer)))
  9375. (org-mode)
  9376. (insert s)
  9377. (goto-char (point-min))
  9378. (when reference-buffer
  9379. (setq org-link-abbrev-alist-local
  9380. (with-current-buffer reference-buffer
  9381. org-link-abbrev-alist-local)))
  9382. (org-open-at-point arg reference-buffer)))))
  9383. (defvar org-open-at-point-functions nil
  9384. "Hook that is run when following a link at point.
  9385. Functions in this hook must return t if they identify and follow
  9386. a link at point. If they don't find anything interesting at point,
  9387. they must return nil.")
  9388. (defvar org-link-search-inhibit-query nil)
  9389. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9390. (defun org--open-doi-link (path)
  9391. "Open a \"doi\" type link.
  9392. PATH is a the path to search for, as a string."
  9393. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9394. (defun org--open-elisp-link (path)
  9395. "Open a \"elisp\" type link.
  9396. PATH is the sexp to evaluate, as a string."
  9397. (let ((cmd path))
  9398. (if (or (and (org-string-nw-p
  9399. org-confirm-elisp-link-not-regexp)
  9400. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9401. (not org-confirm-elisp-link-function)
  9402. (funcall org-confirm-elisp-link-function
  9403. (format "Execute \"%s\" as elisp? "
  9404. (org-add-props cmd nil 'face 'org-warning))))
  9405. (message "%s => %s" cmd
  9406. (if (eq (string-to-char cmd) ?\()
  9407. (eval (read cmd))
  9408. (call-interactively (read cmd))))
  9409. (user-error "Abort"))))
  9410. (defun org--open-help-link (path)
  9411. "Open a \"help\" type link.
  9412. PATH is a symbol name, as a string."
  9413. (pcase (intern path)
  9414. ((and (pred fboundp) variable) (describe-function variable))
  9415. ((and (pred boundp) function) (describe-variable function))
  9416. (name (user-error "Unknown function or variable: %s" name))))
  9417. (defun org--open-shell-link (path)
  9418. "Open a \"shell\" type link.
  9419. PATH is the command to execute, as a string."
  9420. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9421. (cmd path))
  9422. (if (or (and (org-string-nw-p
  9423. org-confirm-shell-link-not-regexp)
  9424. (string-match
  9425. org-confirm-shell-link-not-regexp cmd))
  9426. (not org-confirm-shell-link-function)
  9427. (funcall org-confirm-shell-link-function
  9428. (format "Execute \"%s\" in shell? "
  9429. (org-add-props cmd nil
  9430. 'face 'org-warning))))
  9431. (progn
  9432. (message "Executing %s" cmd)
  9433. (shell-command cmd buf)
  9434. (when (featurep 'midnight)
  9435. (setq clean-buffer-list-kill-buffer-names
  9436. (cons (buffer-name buf)
  9437. clean-buffer-list-kill-buffer-names))))
  9438. (user-error "Abort"))))
  9439. (defun org-open-at-point (&optional arg reference-buffer)
  9440. "Open link, timestamp, footnote or tags at point.
  9441. When point is on a link, follow it. Normally, files will be
  9442. opened by an appropriate application. If the optional prefix
  9443. argument ARG is non-nil, Emacs will visit the file. With
  9444. a double prefix argument, try to open outside of Emacs, in the
  9445. application the system uses for this file type.
  9446. When point is on a timestamp, open the agenda at the day
  9447. specified.
  9448. When point is a footnote definition, move to the first reference
  9449. found. If it is on a reference, move to the associated
  9450. definition.
  9451. When point is on a headline, display a list of every link in the
  9452. entry, so it is possible to pick one, or all, of them. If point
  9453. is on a tag, call `org-tags-view' instead.
  9454. When optional argument REFERENCE-BUFFER is non-nil, it should
  9455. specify a buffer from where the link search should happen. This
  9456. is used internally by `org-open-link-from-string'.
  9457. On top of syntactically correct links, this function will also
  9458. try to open links and time-stamps in comments, example
  9459. blocks... i.e., whenever point is on something looking like
  9460. a timestamp or a link."
  9461. (interactive "P")
  9462. ;; On a code block, open block's results.
  9463. (unless (call-interactively 'org-babel-open-src-block-result)
  9464. (org-load-modules-maybe)
  9465. (setq org-window-config-before-follow-link (current-window-configuration))
  9466. (org-remove-occur-highlights nil nil t)
  9467. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9468. (let* ((context
  9469. ;; Only consider supported types, even if they are not
  9470. ;; the closest one.
  9471. (org-element-lineage
  9472. (org-element-context)
  9473. '(clock footnote-definition footnote-reference headline
  9474. inlinetask link timestamp)
  9475. t))
  9476. (type (org-element-type context))
  9477. (value (org-element-property :value context)))
  9478. (cond
  9479. ;; On a headline or an inlinetask, but not on a timestamp,
  9480. ;; a link, a footnote reference.
  9481. ((memq type '(headline inlinetask))
  9482. (org-match-line org-complex-heading-regexp)
  9483. (if (and (match-beginning 5)
  9484. (>= (point) (match-beginning 5))
  9485. (< (point) (match-end 5)))
  9486. ;; On tags.
  9487. (org-tags-view arg (substring (match-string 5) 0 -1))
  9488. ;; Not on tags.
  9489. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9490. (`(nil . ,_)
  9491. (require 'org-attach)
  9492. (org-attach-reveal 'if-exists))
  9493. (`(,links . ,links-end)
  9494. (dolist (link (if (stringp links) (list links) links))
  9495. (search-forward link nil links-end)
  9496. (goto-char (match-beginning 0))
  9497. (org-open-at-point))))))
  9498. ;; On a footnote reference or at definition's label.
  9499. ((or (eq type 'footnote-reference)
  9500. (and (eq type 'footnote-definition)
  9501. (save-excursion
  9502. ;; Do not validate action when point is on the
  9503. ;; spaces right after the footnote label, in
  9504. ;; order to be on par with behaviour on links.
  9505. (skip-chars-forward " \t")
  9506. (let ((begin
  9507. (org-element-property :contents-begin context)))
  9508. (if begin (< (point) begin)
  9509. (= (org-element-property :post-affiliated context)
  9510. (line-beginning-position)))))))
  9511. (org-footnote-action))
  9512. ;; No valid context. Ignore catch-all types like `headline'.
  9513. ;; If point is on something looking like a link or
  9514. ;; a time-stamp, try opening it. It may be useful in
  9515. ;; comments, example blocks...
  9516. ((memq type '(footnote-definition headline inlinetask nil))
  9517. (call-interactively #'org-open-at-point-global))
  9518. ;; On a clock line, make sure point is on the timestamp
  9519. ;; before opening it.
  9520. ((and (eq type 'clock)
  9521. value
  9522. (>= (point) (org-element-property :begin value))
  9523. (<= (point) (org-element-property :end value)))
  9524. (org-follow-timestamp-link))
  9525. ;; Do nothing on white spaces after an object.
  9526. ((>= (point)
  9527. (save-excursion
  9528. (goto-char (org-element-property :end context))
  9529. (skip-chars-backward " \t")
  9530. (point)))
  9531. (user-error "No link found"))
  9532. ((eq type 'timestamp) (org-follow-timestamp-link))
  9533. ((eq type 'link)
  9534. (let ((type (org-element-property :type context))
  9535. (path (org-link-unescape (org-element-property :path context))))
  9536. ;; Switch back to REFERENCE-BUFFER needed when called in
  9537. ;; a temporary buffer through `org-open-link-from-string'.
  9538. (with-current-buffer (or reference-buffer (current-buffer))
  9539. (cond
  9540. ((equal type "file")
  9541. (if (string-match "[*?{]" (file-name-nondirectory path))
  9542. (dired path)
  9543. ;; Look into `org-link-parameters' in order to find
  9544. ;; a DEDICATED-FUNCTION to open file. The function
  9545. ;; will be applied on raw link instead of parsed
  9546. ;; link due to the limitation in `org-add-link-type'
  9547. ;; ("open" function called with a single argument).
  9548. ;; If no such function is found, fallback to
  9549. ;; `org-open-file'.
  9550. (let* ((option (org-element-property :search-option context))
  9551. (app (org-element-property :application context))
  9552. (dedicated-function
  9553. (org-link-get-parameter
  9554. (if app (concat type "+" app) type)
  9555. :follow)))
  9556. (if dedicated-function
  9557. (funcall dedicated-function
  9558. (concat path
  9559. (and option (concat "::" option))))
  9560. (apply #'org-open-file
  9561. path
  9562. (cond (arg)
  9563. ((equal app "emacs") 'emacs)
  9564. ((equal app "sys") 'system))
  9565. (cond ((not option) nil)
  9566. ((string-match-p "\\`[0-9]+\\'" option)
  9567. (list (string-to-number option)))
  9568. (t (list nil
  9569. (org-link-unescape option)))))))))
  9570. ((functionp (org-link-get-parameter type :follow))
  9571. (funcall (org-link-get-parameter type :follow) path))
  9572. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9573. (unless (run-hook-with-args-until-success
  9574. 'org-open-link-functions path)
  9575. (if (not arg) (org-mark-ring-push)
  9576. (switch-to-buffer-other-window
  9577. (org-get-buffer-for-internal-link (current-buffer))))
  9578. (let ((destination
  9579. (org-with-wide-buffer
  9580. (if (equal type "radio")
  9581. (org-search-radio-target
  9582. (org-element-property :path context))
  9583. (org-link-search
  9584. (if (member type '("custom-id" "coderef"))
  9585. (org-element-property :raw-link context)
  9586. path)
  9587. ;; Prevent fuzzy links from matching
  9588. ;; themselves.
  9589. (and (equal type "fuzzy")
  9590. (+ 2 (org-element-property :begin context)))))
  9591. (point))))
  9592. (unless (and (<= (point-min) destination)
  9593. (>= (point-max) destination))
  9594. (widen))
  9595. (goto-char destination))))
  9596. (t (browse-url-at-point))))))
  9597. (t (user-error "No link found")))))
  9598. (run-hook-with-args 'org-follow-link-hook)))
  9599. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9600. "Offer links in the current entry and return the selected link.
  9601. If there is only one link, return it.
  9602. If NTH is an integer, return the NTH link found.
  9603. If ZERO is a string, check also this string for a link, and if
  9604. there is one, return it."
  9605. (with-current-buffer buffer
  9606. (org-with-wide-buffer
  9607. (goto-char marker)
  9608. (let ((cnt ?0)
  9609. have-zero end links link c)
  9610. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9611. (push (match-string 0 zero) links)
  9612. (setq cnt (1- cnt) have-zero t))
  9613. (save-excursion
  9614. (org-back-to-heading t)
  9615. (setq end (save-excursion (outline-next-heading) (point)))
  9616. (while (re-search-forward org-any-link-re end t)
  9617. (push (match-string 0) links))
  9618. (setq links (org-uniquify (reverse links))))
  9619. (cond
  9620. ((null links)
  9621. (message "No links"))
  9622. ((equal (length links) 1)
  9623. (setq link (car links)))
  9624. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9625. (setq link (nth (if have-zero nth (1- nth)) links)))
  9626. (t ; we have to select a link
  9627. (save-excursion
  9628. (save-window-excursion
  9629. (delete-other-windows)
  9630. (with-output-to-temp-buffer "*Select Link*"
  9631. (dolist (l links)
  9632. (cond
  9633. ((not (string-match org-bracket-link-regexp l))
  9634. (princ (format "[%c] %s\n" (cl-incf cnt)
  9635. (org-unbracket-string "<" ">" l))))
  9636. ((match-end 3)
  9637. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9638. (match-string 3 l) (match-string 1 l))))
  9639. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9640. (match-string 1 l)))))))
  9641. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9642. (message "Select link to open, RET to open all:")
  9643. (setq c (read-char-exclusive))
  9644. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9645. (when (equal c ?q) (user-error "Abort"))
  9646. (if (equal c ?\C-m)
  9647. (setq link links)
  9648. (setq nth (- c ?0))
  9649. (when have-zero (setq nth (1+ nth)))
  9650. (unless (and (integerp nth) (>= (length links) nth))
  9651. (user-error "Invalid link selection"))
  9652. (setq link (nth (1- nth) links)))))
  9653. (cons link end)))))
  9654. ;; TODO: These functions are deprecated since `org-open-at-point'
  9655. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9656. (defun org-open-file-with-system (path)
  9657. "Open file at PATH using the system way of opening it."
  9658. (org-open-file path 'system))
  9659. (defun org-open-file-with-emacs (path)
  9660. "Open file at PATH in Emacs."
  9661. (org-open-file path 'emacs))
  9662. ;;; File search
  9663. (defvar org-create-file-search-functions nil
  9664. "List of functions to construct the right search string for a file link.
  9665. These functions are called in turn with point at the location to
  9666. which the link should point.
  9667. A function in the hook should first test if it would like to
  9668. handle this file type, for example by checking the `major-mode'
  9669. or the file extension. If it decides not to handle this file, it
  9670. should just return nil to give other functions a chance. If it
  9671. does handle the file, it must return the search string to be used
  9672. when following the link. The search string will be part of the
  9673. file link, given after a double colon, and `org-open-at-point'
  9674. will automatically search for it. If special measures must be
  9675. taken to make the search successful, another function should be
  9676. added to the companion hook `org-execute-file-search-functions',
  9677. which see.
  9678. A function in this hook may also use `setq' to set the variable
  9679. `description' to provide a suggestion for the descriptive text to
  9680. be used for this link when it gets inserted into an Org buffer
  9681. with \\[org-insert-link].")
  9682. (defvar org-execute-file-search-functions nil
  9683. "List of functions to execute a file search triggered by a link.
  9684. Functions added to this hook must accept a single argument, the
  9685. search string that was part of the file link, the part after the
  9686. double colon. The function must first check if it would like to
  9687. handle this search, for example by checking the `major-mode' or
  9688. the file extension. If it decides not to handle this search, it
  9689. should just return nil to give other functions a chance. If it
  9690. does handle the search, it must return a non-nil value to keep
  9691. other functions from trying.
  9692. Each function can access the current prefix argument through the
  9693. variable `current-prefix-arg'. Note that a single prefix is used
  9694. to force opening a link in Emacs, so it may be good to only use a
  9695. numeric or double prefix to guide the search function.
  9696. In case this is needed, a function in this hook can also restore
  9697. the window configuration before `org-open-at-point' was called using:
  9698. (set-window-configuration org-window-config-before-follow-link)")
  9699. (defun org-search-radio-target (target)
  9700. "Search a radio target matching TARGET in current buffer.
  9701. White spaces are not significant."
  9702. (let ((re (format "<<<%s>>>"
  9703. (mapconcat #'regexp-quote
  9704. (split-string target)
  9705. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9706. (origin (point)))
  9707. (goto-char (point-min))
  9708. (catch :radio-match
  9709. (while (re-search-forward re nil t)
  9710. (backward-char)
  9711. (let ((object (org-element-context)))
  9712. (when (eq (org-element-type object) 'radio-target)
  9713. (goto-char (org-element-property :begin object))
  9714. (org-show-context 'link-search)
  9715. (throw :radio-match nil))))
  9716. (goto-char origin)
  9717. (user-error "No match for radio target: %s" target))))
  9718. (defun org-link-search (s &optional avoid-pos stealth)
  9719. "Search for a search string S.
  9720. If S starts with \"#\", it triggers a custom ID search.
  9721. If S is enclosed within parenthesis, it initiates a coderef
  9722. search.
  9723. If S is surrounded by forward slashes, it is interpreted as
  9724. a regular expression. In Org mode files, this will create an
  9725. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9726. to list matches. If the current buffer is in `dired-mode', grep
  9727. will be used to search in all files.
  9728. When AVOID-POS is given, ignore matches near that position.
  9729. When optional argument STEALTH is non-nil, do not modify
  9730. visibility around point, thus ignoring `org-show-context-detail'
  9731. variable.
  9732. Search is case-insensitive and ignores white spaces. Return type
  9733. of matched result, which is either `dedicated' or `fuzzy'."
  9734. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9735. (let* ((case-fold-search t)
  9736. (origin (point))
  9737. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9738. (starred (eq (string-to-char normalized) ?*))
  9739. (words (split-string (if starred (substring s 1) s)))
  9740. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9741. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9742. type)
  9743. (cond
  9744. ;; Check if there are any special search functions.
  9745. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9746. ((eq (string-to-char s) ?#)
  9747. ;; Look for a custom ID S if S starts with "#".
  9748. (let* ((id (substring normalized 1))
  9749. (match (org-find-property "CUSTOM_ID" id)))
  9750. (if match (progn (goto-char match) (setf type 'dedicated))
  9751. (error "No match for custom ID: %s" id))))
  9752. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9753. ;; Look for coderef targets if S is enclosed within parenthesis.
  9754. (let ((coderef (match-string-no-properties 1 normalized))
  9755. (re (substring s-single-re 1 -1)))
  9756. (goto-char (point-min))
  9757. (catch :coderef-match
  9758. (while (re-search-forward re nil t)
  9759. (let ((element (org-element-at-point)))
  9760. (when (and (memq (org-element-type element)
  9761. '(example-block src-block))
  9762. ;; Build proper regexp according to current
  9763. ;; block's label format.
  9764. (let ((label-fmt
  9765. (regexp-quote
  9766. (or (org-element-property :label-fmt element)
  9767. org-coderef-label-format))))
  9768. (save-excursion
  9769. (beginning-of-line)
  9770. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9771. (format label-fmt coderef))))))
  9772. (setq type 'dedicated)
  9773. (goto-char (match-beginning 1))
  9774. (throw :coderef-match nil))))
  9775. (goto-char origin)
  9776. (error "No match for coderef: %s" coderef))))
  9777. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9778. ;; Look for a regular expression.
  9779. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9780. (match-string 1 s)))
  9781. ;; From here, we handle fuzzy links.
  9782. ;;
  9783. ;; Look for targets, only if not in a headline search.
  9784. ((and (not starred)
  9785. (let ((target (format "<<%s>>" s-multi-re)))
  9786. (catch :target-match
  9787. (goto-char (point-min))
  9788. (while (re-search-forward target nil t)
  9789. (backward-char)
  9790. (let ((context (org-element-context)))
  9791. (when (eq (org-element-type context) 'target)
  9792. (setq type 'dedicated)
  9793. (goto-char (org-element-property :begin context))
  9794. (throw :target-match t))))
  9795. nil))))
  9796. ;; Look for elements named after S, only if not in a headline
  9797. ;; search.
  9798. ((and (not starred)
  9799. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9800. (catch :name-match
  9801. (goto-char (point-min))
  9802. (while (re-search-forward name nil t)
  9803. (let ((element (org-element-at-point)))
  9804. (when (equal words
  9805. (split-string
  9806. (org-element-property :name element)))
  9807. (setq type 'dedicated)
  9808. (beginning-of-line)
  9809. (throw :name-match t))))
  9810. nil))))
  9811. ;; Regular text search. Prefer headlines in Org mode buffers.
  9812. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9813. ;; statistics cookies and tags.
  9814. ((and (derived-mode-p 'org-mode)
  9815. (let ((title-re
  9816. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9817. org-outline-regexp-bol
  9818. org-comment-string
  9819. (mapconcat #'regexp-quote words ".+")))
  9820. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9821. (comment-re (eval-when-compile
  9822. (format "\\`%s[ \t]+" org-comment-string))))
  9823. (goto-char (point-min))
  9824. (catch :found
  9825. (while (re-search-forward title-re nil t)
  9826. (when (equal words
  9827. (split-string
  9828. (replace-regexp-in-string
  9829. cookie-re ""
  9830. (replace-regexp-in-string
  9831. comment-re "" (org-get-heading t t t)))))
  9832. (throw :found t)))
  9833. nil)))
  9834. (beginning-of-line)
  9835. (setq type 'dedicated))
  9836. ;; Offer to create non-existent headline depending on
  9837. ;; `org-link-search-must-match-exact-headline'.
  9838. ((and (derived-mode-p 'org-mode)
  9839. (not org-link-search-inhibit-query)
  9840. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9841. (yes-or-no-p "No match - create this as a new heading? "))
  9842. (goto-char (point-max))
  9843. (unless (bolp) (newline))
  9844. (org-insert-heading nil t t)
  9845. (insert s "\n")
  9846. (beginning-of-line 0))
  9847. ;; Only headlines are looked after. No need to process
  9848. ;; further: throw an error.
  9849. ((and (derived-mode-p 'org-mode)
  9850. (or starred org-link-search-must-match-exact-headline))
  9851. (goto-char origin)
  9852. (error "No match for fuzzy expression: %s" normalized))
  9853. ;; Regular text search.
  9854. ((catch :fuzzy-match
  9855. (goto-char (point-min))
  9856. (while (re-search-forward s-multi-re nil t)
  9857. ;; Skip match if it contains AVOID-POS or it is included in
  9858. ;; a link with a description but outside the description.
  9859. (unless (or (and avoid-pos
  9860. (<= (match-beginning 0) avoid-pos)
  9861. (> (match-end 0) avoid-pos))
  9862. (and (save-match-data
  9863. (org-in-regexp org-bracket-link-regexp))
  9864. (match-beginning 3)
  9865. (or (> (match-beginning 3) (point))
  9866. (<= (match-end 3) (point)))
  9867. (org-element-lineage
  9868. (save-match-data (org-element-context))
  9869. '(link) t)))
  9870. (goto-char (match-beginning 0))
  9871. (setq type 'fuzzy)
  9872. (throw :fuzzy-match t)))
  9873. nil))
  9874. ;; All failed. Throw an error.
  9875. (t (goto-char origin)
  9876. (error "No match for fuzzy expression: %s" normalized)))
  9877. ;; Disclose surroundings of match, if appropriate.
  9878. (when (and (derived-mode-p 'org-mode) (not stealth))
  9879. (org-show-context 'link-search))
  9880. type))
  9881. (defun org-get-buffer-for-internal-link (buffer)
  9882. "Return a buffer to be used for displaying the link target of internal links."
  9883. (cond
  9884. ((not org-display-internal-link-with-indirect-buffer)
  9885. buffer)
  9886. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9887. (message "Buffer is already a clone, not making another one")
  9888. ;; we also do not modify visibility in this case
  9889. buffer)
  9890. (t ; make a new indirect buffer for displaying the link
  9891. (let* ((bn (buffer-name buffer))
  9892. (ibn (concat bn "(Clone)"))
  9893. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9894. (with-current-buffer ib (org-overview))
  9895. ib))))
  9896. (defun org-do-occur (regexp &optional cleanup)
  9897. "Call the Emacs command `occur'.
  9898. If CLEANUP is non-nil, remove the printout of the regular expression
  9899. in the *Occur* buffer. This is useful if the regex is long and not useful
  9900. to read."
  9901. (occur regexp)
  9902. (when cleanup
  9903. (let ((cwin (selected-window)) win beg end)
  9904. (when (setq win (get-buffer-window "*Occur*"))
  9905. (select-window win))
  9906. (goto-char (point-min))
  9907. (when (re-search-forward "match[a-z]+" nil t)
  9908. (setq beg (match-end 0))
  9909. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9910. (setq end (1- (match-beginning 0)))))
  9911. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9912. (goto-char (point-min))
  9913. (select-window cwin))))
  9914. ;;; The mark ring for links jumps
  9915. (defvar org-mark-ring nil
  9916. "Mark ring for positions before jumps in Org mode.")
  9917. (defvar org-mark-ring-last-goto nil
  9918. "Last position in the mark ring used to go back.")
  9919. ;; Fill and close the ring
  9920. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9921. (dotimes (_ org-mark-ring-length)
  9922. (push (make-marker) org-mark-ring))
  9923. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9924. org-mark-ring)
  9925. (defun org-mark-ring-push (&optional pos buffer)
  9926. "Put the current position or POS into the mark ring and rotate it."
  9927. (interactive)
  9928. (setq pos (or pos (point)))
  9929. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9930. (move-marker (car org-mark-ring)
  9931. (or pos (point))
  9932. (or buffer (current-buffer)))
  9933. (message "%s"
  9934. (substitute-command-keys
  9935. "Position saved to mark ring, go back with \
  9936. `\\[org-mark-ring-goto]'.")))
  9937. (defun org-mark-ring-goto (&optional n)
  9938. "Jump to the previous position in the mark ring.
  9939. With prefix arg N, jump back that many stored positions. When
  9940. called several times in succession, walk through the entire ring.
  9941. Org mode commands jumping to a different position in the current file,
  9942. or to another Org file, automatically push the old position onto the ring."
  9943. (interactive "p")
  9944. (let (p m)
  9945. (if (eq last-command this-command)
  9946. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9947. (setq p org-mark-ring))
  9948. (setq org-mark-ring-last-goto p)
  9949. (setq m (car p))
  9950. (pop-to-buffer-same-window (marker-buffer m))
  9951. (goto-char m)
  9952. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9953. (defun org-add-angle-brackets (s)
  9954. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9955. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9956. s)
  9957. ;;; Following specific links
  9958. (defvar org-agenda-buffer-tmp-name)
  9959. (defvar org-agenda-start-on-weekday)
  9960. (defun org-follow-timestamp-link ()
  9961. "Open an agenda view for the time-stamp date/range at point."
  9962. (cond
  9963. ((org-at-date-range-p t)
  9964. (let ((org-agenda-start-on-weekday)
  9965. (t1 (match-string 1))
  9966. (t2 (match-string 2)) tt1 tt2)
  9967. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9968. tt2 (time-to-days (org-time-string-to-time t2)))
  9969. (let ((org-agenda-buffer-tmp-name
  9970. (format "*Org Agenda(a:%s)"
  9971. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9972. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9973. ((org-at-timestamp-p 'lax)
  9974. (let ((org-agenda-buffer-tmp-name
  9975. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9976. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9977. (substring (match-string 1) 0 10)))
  9978. 1)))
  9979. (t (error "This should not happen"))))
  9980. ;;; Following file links
  9981. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9982. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9983. (declare-function mailcap-mime-info
  9984. "mailcap" (string &optional request no-decode))
  9985. (defvar org-wait nil)
  9986. (defun org-open-file (path &optional in-emacs line search)
  9987. "Open the file at PATH.
  9988. First, this expands any special file name abbreviations. Then the
  9989. configuration variable `org-file-apps' is checked if it contains an
  9990. entry for this file type, and if yes, the corresponding command is launched.
  9991. If no application is found, Emacs simply visits the file.
  9992. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9993. With a double \\[universal-argument] \\[universal-argument] \
  9994. prefix arg, Org tries to avoid opening in Emacs
  9995. and to use an external application to visit the file.
  9996. Optional LINE specifies a line to go to, optional SEARCH a string
  9997. to search for. If LINE or SEARCH is given, the file will be
  9998. opened in Emacs, unless an entry from org-file-apps that makes
  9999. use of groups in a regexp matches.
  10000. If you want to change the way frames are used when following a
  10001. link, please customize `org-link-frame-setup'.
  10002. If the file does not exist, an error is thrown."
  10003. (let* ((file (if (equal path "")
  10004. buffer-file-name
  10005. (substitute-in-file-name (expand-file-name path))))
  10006. (file-apps (append org-file-apps (org-default-apps)))
  10007. (apps (cl-remove-if
  10008. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10009. (apps-dlink (cl-remove-if-not
  10010. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10011. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10012. (dirp (unless remp (file-directory-p file)))
  10013. (file (if (and dirp org-open-directory-means-index-dot-org)
  10014. (concat (file-name-as-directory file) "index.org")
  10015. file))
  10016. (a-m-a-p (assq 'auto-mode apps))
  10017. (dfile (downcase file))
  10018. ;; Reconstruct the original link from the PATH, LINE and
  10019. ;; SEARCH args.
  10020. (link (cond (line (concat file "::" (number-to-string line)))
  10021. (search (concat file "::" search))
  10022. (t file)))
  10023. (dlink (downcase link))
  10024. (ext
  10025. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10026. (match-string 1 dfile)))
  10027. (save-position-maybe
  10028. (let ((old-buffer (current-buffer))
  10029. (old-pos (point))
  10030. (old-mode major-mode))
  10031. (lambda ()
  10032. (and (derived-mode-p 'org-mode)
  10033. (eq old-mode 'org-mode)
  10034. (or (not (eq old-buffer (current-buffer)))
  10035. (not (eq old-pos (point))))
  10036. (org-mark-ring-push old-pos old-buffer)))))
  10037. cmd link-match-data)
  10038. (cond
  10039. ((member in-emacs '((16) system))
  10040. (setq cmd (cdr (assq 'system apps))))
  10041. (in-emacs (setq cmd 'emacs))
  10042. (t
  10043. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10044. (and dirp (cdr (assq 'directory apps)))
  10045. ;; First, try matching against apps-dlink if we
  10046. ;; get a match here, store the match data for
  10047. ;; later.
  10048. (let ((match (assoc-default dlink apps-dlink
  10049. 'string-match)))
  10050. (if match
  10051. (progn (setq link-match-data (match-data))
  10052. match)
  10053. (progn (setq in-emacs (or in-emacs line search))
  10054. nil))) ; if we have no match in apps-dlink,
  10055. ; always open the file in emacs if line or search
  10056. ; is given (for backwards compatibility)
  10057. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10058. 'string-match)
  10059. (cdr (assoc ext apps))
  10060. (cdr (assq t apps))))))
  10061. (when (eq cmd 'system)
  10062. (setq cmd (cdr (assq 'system apps))))
  10063. (when (eq cmd 'default)
  10064. (setq cmd (cdr (assoc t apps))))
  10065. (when (eq cmd 'mailcap)
  10066. (require 'mailcap)
  10067. (mailcap-parse-mailcaps)
  10068. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10069. (command (mailcap-mime-info mime-type)))
  10070. (if (stringp command)
  10071. (setq cmd command)
  10072. (setq cmd 'emacs))))
  10073. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10074. (not (file-exists-p file))
  10075. (not org-open-non-existing-files))
  10076. (user-error "No such file: %s" file))
  10077. (cond
  10078. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10079. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10080. (while (string-match "['\"]%s['\"]" cmd)
  10081. (setq cmd (replace-match "%s" t t cmd)))
  10082. (setq cmd (replace-regexp-in-string
  10083. "%s"
  10084. (shell-quote-argument (convert-standard-filename file))
  10085. cmd
  10086. nil t))
  10087. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10088. (save-match-data
  10089. (let ((match-index 1)
  10090. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10091. (set-match-data link-match-data)
  10092. (while (<= match-index number-of-groups)
  10093. (let ((regex (concat "%" (number-to-string match-index)))
  10094. (replace-with (match-string match-index dlink)))
  10095. (while (string-match regex cmd)
  10096. (setq cmd (replace-match replace-with t t cmd))))
  10097. (setq match-index (+ match-index 1)))))
  10098. (save-window-excursion
  10099. (message "Running %s...done" cmd)
  10100. (start-process-shell-command cmd nil cmd)
  10101. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10102. ((or (stringp cmd)
  10103. (eq cmd 'emacs))
  10104. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10105. (widen)
  10106. (cond (line (org-goto-line line)
  10107. (when (derived-mode-p 'org-mode) (org-reveal)))
  10108. (search (condition-case err
  10109. (org-link-search search)
  10110. ;; Save position before error-ing out so user
  10111. ;; can easily move back to the original buffer.
  10112. (error (funcall save-position-maybe)
  10113. (error (nth 1 err)))))))
  10114. ((functionp cmd)
  10115. (save-match-data
  10116. (set-match-data link-match-data)
  10117. (condition-case nil
  10118. (funcall cmd file link)
  10119. ;; FIXME: Remove this check when most default installations
  10120. ;; of Emacs have at least Org 9.0.
  10121. ((debug wrong-number-of-arguments wrong-type-argument
  10122. invalid-function)
  10123. (user-error "Please see Org News for version 9.0 about \
  10124. `org-file-apps'--Lisp error: %S" cmd)))))
  10125. ((consp cmd)
  10126. ;; FIXME: Remove this check when most default installations of
  10127. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10128. ;; fall back to `org-link-frame-setup' for an old usage of
  10129. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10130. (user-error "Please see Org News for version 9.0 about \
  10131. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10132. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10133. (funcall save-position-maybe)))
  10134. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10135. "This function returns non-nil if `entry' uses a regular
  10136. expression which should be matched against the whole link by
  10137. org-open-file.
  10138. It assumes that is the case when the entry uses a regular
  10139. expression which has at least one grouping construct and the
  10140. action is either a lisp form or a command string containing
  10141. `%1', i.e. using at least one subexpression match as a
  10142. parameter."
  10143. (let ((selector (car entry))
  10144. (action (cdr entry)))
  10145. (if (stringp selector)
  10146. (and (> (regexp-opt-depth selector) 0)
  10147. (or (and (stringp action)
  10148. (string-match "%[0-9]" action))
  10149. (consp action)))
  10150. nil)))
  10151. (defun org-default-apps ()
  10152. "Return the default applications for this operating system."
  10153. (cond
  10154. ((eq system-type 'darwin)
  10155. org-file-apps-defaults-macosx)
  10156. ((eq system-type 'windows-nt)
  10157. org-file-apps-defaults-windowsnt)
  10158. (t org-file-apps-defaults-gnu)))
  10159. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10160. "Convert extensions to regular expressions in the cars of LIST.
  10161. Also, weed out any non-string entries, because the return value is used
  10162. only for regexp matching.
  10163. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10164. point to the symbol `emacs', indicating that the file should
  10165. be opened in Emacs."
  10166. (append
  10167. (delq nil
  10168. (mapcar (lambda (x)
  10169. (unless (not (stringp (car x)))
  10170. (if (string-match "\\W" (car x))
  10171. x
  10172. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10173. list))
  10174. (when add-auto-mode
  10175. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10176. (defvar ange-ftp-name-format)
  10177. (defun org-file-remote-p (file)
  10178. "Test whether FILE specifies a location on a remote system.
  10179. Return non-nil if the location is indeed remote.
  10180. For example, the filename \"/user@host:/foo\" specifies a location
  10181. on the system \"/user@host:\"."
  10182. (cond ((fboundp 'file-remote-p)
  10183. (file-remote-p file))
  10184. ((fboundp 'tramp-handle-file-remote-p)
  10185. (tramp-handle-file-remote-p file))
  10186. ((and (boundp 'ange-ftp-name-format)
  10187. (string-match (car ange-ftp-name-format) file))
  10188. t)))
  10189. ;;;; Refiling
  10190. (defun org-get-org-file ()
  10191. "Read a filename, with default directory `org-directory'."
  10192. (let ((default (or org-default-notes-file remember-data-file)))
  10193. (read-file-name (format "File name [%s]: " default)
  10194. (file-name-as-directory org-directory)
  10195. default)))
  10196. (defun org-notes-order-reversed-p ()
  10197. "Check if the current file should receive notes in reversed order."
  10198. (cond
  10199. ((not org-reverse-note-order) nil)
  10200. ((eq t org-reverse-note-order) t)
  10201. ((not (listp org-reverse-note-order)) nil)
  10202. (t (catch 'exit
  10203. (dolist (entry org-reverse-note-order)
  10204. (when (string-match (car entry) buffer-file-name)
  10205. (throw 'exit (cdr entry))))))))
  10206. (defvar org-refile-target-table nil
  10207. "The list of refile targets, created by `org-refile'.")
  10208. (defvar org-agenda-new-buffers nil
  10209. "Buffers created to visit agenda files.")
  10210. (defvar org-refile-cache nil
  10211. "Cache for refile targets.")
  10212. (defvar org-refile-markers nil
  10213. "All the markers used for caching refile locations.")
  10214. (defun org-refile-marker (pos)
  10215. "Get a new refile marker, but only if caching is in use."
  10216. (if (not org-refile-use-cache)
  10217. pos
  10218. (let ((m (make-marker)))
  10219. (move-marker m pos)
  10220. (push m org-refile-markers)
  10221. m)))
  10222. (defun org-refile-cache-clear ()
  10223. "Clear the refile cache and disable all the markers."
  10224. (dolist (m org-refile-markers) (move-marker m nil))
  10225. (setq org-refile-markers nil)
  10226. (setq org-refile-cache nil)
  10227. (message "Refile cache has been cleared"))
  10228. (defun org-refile-cache-check-set (set)
  10229. "Check if all the markers in the cache still have live buffers."
  10230. (let (marker)
  10231. (catch 'exit
  10232. (while (and set (setq marker (nth 3 (pop set))))
  10233. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10234. (when (and marker (null (marker-buffer marker)))
  10235. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10236. (sit-for 3)
  10237. (throw 'exit nil)))
  10238. t)))
  10239. (defun org-refile-cache-put (set &rest identifiers)
  10240. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10241. (let* ((key (sha1 (prin1-to-string identifiers)))
  10242. (entry (assoc key org-refile-cache)))
  10243. (if entry
  10244. (setcdr entry set)
  10245. (push (cons key set) org-refile-cache))))
  10246. (defun org-refile-cache-get (&rest identifiers)
  10247. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10248. (cond
  10249. ((not org-refile-cache) nil)
  10250. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10251. (t
  10252. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10253. org-refile-cache))))
  10254. (and set (org-refile-cache-check-set set) set)))))
  10255. (defvar org-outline-path-cache nil
  10256. "Alist between buffer positions and outline paths.
  10257. It value is an alist (POSITION . PATH) where POSITION is the
  10258. buffer position at the beginning of an entry and PATH is a list
  10259. of strings describing the outline path for that entry, in reverse
  10260. order.")
  10261. (defun org-refile-get-targets (&optional default-buffer)
  10262. "Produce a table with refile targets."
  10263. (let ((case-fold-search nil)
  10264. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10265. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10266. targets tgs files desc descre)
  10267. (message "Getting targets...")
  10268. (with-current-buffer (or default-buffer (current-buffer))
  10269. (dolist (entry entries)
  10270. (setq files (car entry) desc (cdr entry))
  10271. (cond
  10272. ((null files) (setq files (list (current-buffer))))
  10273. ((eq files 'org-agenda-files)
  10274. (setq files (org-agenda-files 'unrestricted)))
  10275. ((and (symbolp files) (fboundp files))
  10276. (setq files (funcall files)))
  10277. ((and (symbolp files) (boundp files))
  10278. (setq files (symbol-value files))))
  10279. (when (stringp files) (setq files (list files)))
  10280. (cond
  10281. ((eq (car desc) :tag)
  10282. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10283. ((eq (car desc) :todo)
  10284. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10285. ((eq (car desc) :regexp)
  10286. (setq descre (cdr desc)))
  10287. ((eq (car desc) :level)
  10288. (setq descre (concat "^\\*\\{" (number-to-string
  10289. (if org-odd-levels-only
  10290. (1- (* 2 (cdr desc)))
  10291. (cdr desc)))
  10292. "\\}[ \t]")))
  10293. ((eq (car desc) :maxlevel)
  10294. (setq descre (concat "^\\*\\{1," (number-to-string
  10295. (if org-odd-levels-only
  10296. (1- (* 2 (cdr desc)))
  10297. (cdr desc)))
  10298. "\\}[ \t]")))
  10299. (t (error "Bad refiling target description %s" desc)))
  10300. (dolist (f files)
  10301. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10302. (or
  10303. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10304. (progn
  10305. (when (bufferp f)
  10306. (setq f (buffer-file-name (buffer-base-buffer f))))
  10307. (setq f (and f (expand-file-name f)))
  10308. (when (eq org-refile-use-outline-path 'file)
  10309. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10310. (when (eq org-refile-use-outline-path 'buffer-name)
  10311. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10312. (when (eq org-refile-use-outline-path 'full-file-path)
  10313. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10314. (org-with-wide-buffer
  10315. (goto-char (point-min))
  10316. (setq org-outline-path-cache nil)
  10317. (while (re-search-forward descre nil t)
  10318. (beginning-of-line)
  10319. (let ((case-fold-search nil))
  10320. (looking-at org-complex-heading-regexp))
  10321. (let ((begin (point))
  10322. (heading (match-string-no-properties 4)))
  10323. (unless (or (and
  10324. org-refile-target-verify-function
  10325. (not
  10326. (funcall org-refile-target-verify-function)))
  10327. (not heading))
  10328. (let ((re (format org-complex-heading-regexp-format
  10329. (regexp-quote heading)))
  10330. (target
  10331. (if (not org-refile-use-outline-path) heading
  10332. (mapconcat
  10333. #'identity
  10334. (append
  10335. (pcase org-refile-use-outline-path
  10336. (`file (list (file-name-nondirectory
  10337. (buffer-file-name
  10338. (buffer-base-buffer)))))
  10339. (`full-file-path
  10340. (list (buffer-file-name
  10341. (buffer-base-buffer))))
  10342. (`buffer-name
  10343. (list (buffer-name
  10344. (buffer-base-buffer))))
  10345. (_ nil))
  10346. (mapcar (lambda (s) (replace-regexp-in-string
  10347. "/" "\\/" s nil t))
  10348. (org-get-outline-path t t)))
  10349. "/"))))
  10350. (push (list target f re (org-refile-marker (point)))
  10351. tgs)))
  10352. (when (= (point) begin)
  10353. ;; Verification function has not moved point.
  10354. (end-of-line)))))))
  10355. (when org-refile-use-cache
  10356. (org-refile-cache-put tgs (buffer-file-name) descre))
  10357. (setq targets (append tgs targets))))))
  10358. (message "Getting targets...done")
  10359. (delete-dups (nreverse targets))))
  10360. (defun org--get-outline-path-1 (&optional use-cache)
  10361. "Return outline path to current headline.
  10362. Outline path is a list of strings, in reverse order. When
  10363. optional argument USE-CACHE is non-nil, make use of a cache. See
  10364. `org-get-outline-path' for details.
  10365. Assume buffer is widened and point is on a headline."
  10366. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10367. (let ((p (point))
  10368. (heading (let ((case-fold-search nil))
  10369. (looking-at org-complex-heading-regexp)
  10370. (if (not (match-end 4)) ""
  10371. ;; Remove statistics cookies.
  10372. (org-trim
  10373. (org-link-display-format
  10374. (replace-regexp-in-string
  10375. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10376. (match-string-no-properties 4))))))))
  10377. (if (org-up-heading-safe)
  10378. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10379. (when use-cache
  10380. (push (cons p path) org-outline-path-cache))
  10381. path)
  10382. ;; This is a new root node. Since we assume we are moving
  10383. ;; forward, we can drop previous cache so as to limit number
  10384. ;; of associations there.
  10385. (let ((path (list heading)))
  10386. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10387. path)))))
  10388. (defun org-get-outline-path (&optional with-self use-cache)
  10389. "Return the outline path to the current entry.
  10390. An outline path is a list of ancestors for current headline, as
  10391. a list of strings. Statistics cookies are removed and links are
  10392. replaced with their description, if any, or their path otherwise.
  10393. When optional argument WITH-SELF is non-nil, the path also
  10394. includes the current headline.
  10395. When optional argument USE-CACHE is non-nil, cache outline paths
  10396. between calls to this function so as to avoid backtracking. This
  10397. argument is useful when planning to find more than one outline
  10398. path in the same document. In that case, there are two
  10399. conditions to satisfy:
  10400. - `org-outline-path-cache' is set to nil before starting the
  10401. process;
  10402. - outline paths are computed by increasing buffer positions."
  10403. (org-with-wide-buffer
  10404. (and (or (and with-self (org-back-to-heading t))
  10405. (org-up-heading-safe))
  10406. (reverse (org--get-outline-path-1 use-cache)))))
  10407. (defun org-format-outline-path (path &optional width prefix separator)
  10408. "Format the outline path PATH for display.
  10409. WIDTH is the maximum number of characters that is available.
  10410. PREFIX is a prefix to be included in the returned string,
  10411. such as the file name.
  10412. SEPARATOR is inserted between the different parts of the path,
  10413. the default is \"/\"."
  10414. (setq width (or width 79))
  10415. (setq path (delq nil path))
  10416. (unless (> width 0)
  10417. (user-error "Argument `width' must be positive"))
  10418. (setq separator (or separator "/"))
  10419. (let* ((org-odd-levels-only nil)
  10420. (fpath (concat
  10421. prefix (and prefix path separator)
  10422. (mapconcat
  10423. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10424. (cl-loop for head in path
  10425. for n from 0
  10426. collect (org-add-props
  10427. head nil 'face
  10428. (nth (% n org-n-level-faces) org-level-faces)))
  10429. separator))))
  10430. (when (> (length fpath) width)
  10431. (if (< width 7)
  10432. ;; It's unlikely that `width' will be this small, but don't
  10433. ;; waste characters by adding ".." if it is.
  10434. (setq fpath (substring fpath 0 width))
  10435. (setf (substring fpath (- width 2)) "..")))
  10436. fpath))
  10437. (defun org-display-outline-path (&optional file current separator just-return-string)
  10438. "Display the current outline path in the echo area.
  10439. If FILE is non-nil, prepend the output with the file name.
  10440. If CURRENT is non-nil, append the current heading to the output.
  10441. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10442. the different parts of the path and defaults to \"/\".
  10443. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10444. (interactive "P")
  10445. (let* (case-fold-search
  10446. (bfn (buffer-file-name (buffer-base-buffer)))
  10447. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10448. res)
  10449. (when current (setq path (append path
  10450. (save-excursion
  10451. (org-back-to-heading t)
  10452. (when (looking-at org-complex-heading-regexp)
  10453. (list (match-string 4)))))))
  10454. (setq res
  10455. (org-format-outline-path
  10456. path
  10457. (1- (frame-width))
  10458. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10459. separator))
  10460. (if just-return-string
  10461. (org-no-properties res)
  10462. (org-unlogged-message "%s" res))))
  10463. (defvar org-refile-history nil
  10464. "History for refiling operations.")
  10465. (defvar org-after-refile-insert-hook nil
  10466. "Hook run after `org-refile' has inserted its stuff at the new location.
  10467. Note that this is still *before* the stuff will be removed from
  10468. the *old* location.")
  10469. (defvar org-capture-last-stored-marker)
  10470. (defvar org-refile-keep nil
  10471. "Non-nil means `org-refile' will copy instead of refile.")
  10472. (defun org-copy ()
  10473. "Like `org-refile', but copy."
  10474. (interactive)
  10475. (let ((org-refile-keep t))
  10476. (funcall 'org-refile nil nil nil "Copy")))
  10477. (defun org-refile (&optional arg default-buffer rfloc msg)
  10478. "Move the entry or entries at point to another heading.
  10479. The list of target headings is compiled using the information in
  10480. `org-refile-targets', which see.
  10481. At the target location, the entry is filed as a subitem of the
  10482. target heading. Depending on `org-reverse-note-order', the new
  10483. subitem will either be the first or the last subitem.
  10484. If there is an active region, all entries in that region will be
  10485. refiled. However, the region must fulfill the requirement that
  10486. the first heading sets the top-level of the moved text.
  10487. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10488. location
  10489. and not actually move anything.
  10490. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10491. location where the last
  10492. refiling operation has put the subtree.
  10493. With a numeric prefix argument of `2', refile to the running clock.
  10494. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10495. being set to t and copy to the target location, don't move it.
  10496. Beware that keeping refiled entries may result in duplicated ID
  10497. properties.
  10498. RFLOC can be a refile location obtained in a different way.
  10499. MSG is a string to replace \"Refile\" in the default prompt with
  10500. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10501. See also `org-refile-use-outline-path'.
  10502. If you are using target caching (see `org-refile-use-cache'), you
  10503. have to clear the target cache in order to find new targets.
  10504. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10505. prefix argument (`C-u C-u C-u C-c C-w')."
  10506. (interactive "P")
  10507. (if (member arg '(0 (64)))
  10508. (org-refile-cache-clear)
  10509. (let* ((actionmsg (cond (msg msg)
  10510. ((equal arg 3) "Refile (and keep)")
  10511. (t "Refile")))
  10512. (regionp (org-region-active-p))
  10513. (region-start (and regionp (region-beginning)))
  10514. (region-end (and regionp (region-end)))
  10515. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10516. pos it nbuf file level reversed)
  10517. (setq last-command nil)
  10518. (when regionp
  10519. (goto-char region-start)
  10520. (or (bolp) (goto-char (point-at-bol)))
  10521. (setq region-start (point))
  10522. (unless (or (org-kill-is-subtree-p
  10523. (buffer-substring region-start region-end))
  10524. (prog1 org-refile-active-region-within-subtree
  10525. (let ((s (point-at-eol)))
  10526. (org-toggle-heading)
  10527. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10528. (user-error "The region is not a (sequence of) subtree(s)")))
  10529. (if (equal arg '(16))
  10530. (org-refile-goto-last-stored)
  10531. (when (or
  10532. (and (equal arg 2)
  10533. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10534. (prog1
  10535. (setq it (list (or org-clock-heading "running clock")
  10536. (buffer-file-name
  10537. (marker-buffer org-clock-hd-marker))
  10538. ""
  10539. (marker-position org-clock-hd-marker)))
  10540. (setq arg nil)))
  10541. (setq it
  10542. (or rfloc
  10543. (let (heading-text)
  10544. (save-excursion
  10545. (unless (and arg (listp arg))
  10546. (org-back-to-heading t)
  10547. (setq heading-text
  10548. (replace-regexp-in-string
  10549. org-bracket-link-regexp
  10550. "\\3"
  10551. (or (nth 4 (org-heading-components))
  10552. ""))))
  10553. (org-refile-get-location
  10554. (cond ((and arg (listp arg)) "Goto")
  10555. (regionp (concat actionmsg " region to"))
  10556. (t (concat actionmsg " subtree \""
  10557. heading-text "\" to")))
  10558. default-buffer
  10559. (and (not (equal '(4) arg))
  10560. org-refile-allow-creating-parent-nodes)))))))
  10561. (setq file (nth 1 it)
  10562. pos (nth 3 it))
  10563. (when (and (not arg)
  10564. pos
  10565. (equal (buffer-file-name) file)
  10566. (if regionp
  10567. (and (>= pos region-start)
  10568. (<= pos region-end))
  10569. (and (>= pos (point))
  10570. (< pos (save-excursion
  10571. (org-end-of-subtree t t))))))
  10572. (error "Cannot refile to position inside the tree or region"))
  10573. (setq nbuf (or (find-buffer-visiting file)
  10574. (find-file-noselect file)))
  10575. (if (and arg (not (equal arg 3)))
  10576. (progn
  10577. (pop-to-buffer-same-window nbuf)
  10578. (goto-char (cond (pos)
  10579. ((org-notes-order-reversed-p) (point-min))
  10580. (t (point-max))))
  10581. (org-show-context 'org-goto))
  10582. (if regionp
  10583. (progn
  10584. (org-kill-new (buffer-substring region-start region-end))
  10585. (org-save-markers-in-region region-start region-end))
  10586. (org-copy-subtree 1 nil t))
  10587. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10588. (find-file-noselect file)))
  10589. (setq reversed (org-notes-order-reversed-p))
  10590. (org-with-wide-buffer
  10591. (if pos
  10592. (progn
  10593. (goto-char pos)
  10594. (setq level (org-get-valid-level (funcall outline-level) 1))
  10595. (goto-char
  10596. (if reversed
  10597. (or (outline-next-heading) (point-max))
  10598. (or (save-excursion (org-get-next-sibling))
  10599. (org-end-of-subtree t t)
  10600. (point-max)))))
  10601. (setq level 1)
  10602. (if (not reversed)
  10603. (goto-char (point-max))
  10604. (goto-char (point-min))
  10605. (or (outline-next-heading) (goto-char (point-max)))))
  10606. (unless (bolp) (newline))
  10607. (org-paste-subtree level nil nil t)
  10608. (when org-log-refile
  10609. (org-add-log-setup 'refile nil nil org-log-refile)
  10610. (unless (eq org-log-refile 'note)
  10611. (save-excursion (org-add-log-note))))
  10612. (and org-auto-align-tags
  10613. (let ((org-loop-over-headlines-in-active-region nil))
  10614. (org-set-tags nil t)))
  10615. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10616. :last-refile)))
  10617. (when bookmark-name
  10618. (with-demoted-errors
  10619. (bookmark-set bookmark-name))))
  10620. ;; If we are refiling for capture, make sure that the
  10621. ;; last-capture pointers point here
  10622. (when (bound-and-true-p org-capture-is-refiling)
  10623. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10624. :last-capture-marker)))
  10625. (when bookmark-name
  10626. (with-demoted-errors
  10627. (bookmark-set bookmark-name))))
  10628. (move-marker org-capture-last-stored-marker (point)))
  10629. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10630. (run-hooks 'org-after-refile-insert-hook)))
  10631. (unless org-refile-keep
  10632. (if regionp
  10633. (delete-region (point) (+ (point) (- region-end region-start)))
  10634. (delete-region
  10635. (and (org-back-to-heading t) (point))
  10636. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10637. (when (featurep 'org-inlinetask)
  10638. (org-inlinetask-remove-END-maybe))
  10639. (setq org-markers-to-move nil)
  10640. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10641. (defun org-refile-goto-last-stored ()
  10642. "Go to the location where the last refile was stored."
  10643. (interactive)
  10644. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10645. (message "This is the location of the last refile"))
  10646. (defun org-refile--get-location (refloc tbl)
  10647. "When user refile to REFLOC, find the associated target in TBL.
  10648. Also check `org-refile-target-table'."
  10649. (car (delq
  10650. nil
  10651. (mapcar
  10652. (lambda (r) (or (assoc r tbl)
  10653. (assoc r org-refile-target-table)))
  10654. (list (replace-regexp-in-string "/$" "" refloc)
  10655. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10656. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10657. "Prompt the user for a refile location, using PROMPT.
  10658. PROMPT should not be suffixed with a colon and a space, because
  10659. this function appends the default value from
  10660. `org-refile-history' automatically, if that is not empty."
  10661. (let ((org-refile-targets org-refile-targets)
  10662. (org-refile-use-outline-path org-refile-use-outline-path))
  10663. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10664. (unless org-refile-target-table
  10665. (user-error "No refile targets"))
  10666. (let* ((cbuf (current-buffer))
  10667. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10668. (cfunc (if (and org-refile-use-outline-path
  10669. org-outline-path-complete-in-steps)
  10670. #'org-olpath-completing-read
  10671. #'completing-read))
  10672. (extra (if org-refile-use-outline-path "/" ""))
  10673. (cbnex (concat (buffer-name) extra))
  10674. (filename (and cfn (expand-file-name cfn)))
  10675. (tbl (mapcar
  10676. (lambda (x)
  10677. (if (and (not (member org-refile-use-outline-path
  10678. '(file full-file-path)))
  10679. (not (equal filename (nth 1 x))))
  10680. (cons (concat (car x) extra " ("
  10681. (file-name-nondirectory (nth 1 x)) ")")
  10682. (cdr x))
  10683. (cons (concat (car x) extra) (cdr x))))
  10684. org-refile-target-table))
  10685. (completion-ignore-case t)
  10686. cdef
  10687. (prompt (concat prompt
  10688. (or (and (car org-refile-history)
  10689. (concat " (default " (car org-refile-history) ")"))
  10690. (and (assoc cbnex tbl) (setq cdef cbnex)
  10691. (concat " (default " cbnex ")"))) ": "))
  10692. pa answ parent-target child parent old-hist)
  10693. (setq old-hist org-refile-history)
  10694. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10695. nil 'org-refile-history (or cdef (car org-refile-history))))
  10696. (if (setq pa (org-refile--get-location answ tbl))
  10697. (progn
  10698. (org-refile-check-position pa)
  10699. (when (or (not org-refile-history)
  10700. (not (eq old-hist org-refile-history))
  10701. (not (equal (car pa) (car org-refile-history))))
  10702. (setq org-refile-history
  10703. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10704. org-refile-history
  10705. (cdr org-refile-history))))
  10706. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10707. (pop org-refile-history)))
  10708. pa)
  10709. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10710. (progn
  10711. (setq parent (match-string 1 answ)
  10712. child (match-string 2 answ))
  10713. (setq parent-target (org-refile--get-location parent tbl))
  10714. (when (and parent-target
  10715. (or (eq new-nodes t)
  10716. (and (eq new-nodes 'confirm)
  10717. (y-or-n-p (format "Create new node \"%s\"? "
  10718. child)))))
  10719. (org-refile-new-child parent-target child)))
  10720. (user-error "Invalid target location")))))
  10721. (declare-function org-string-nw-p "org-macs" (s))
  10722. (defun org-refile-check-position (refile-pointer)
  10723. "Check if the refile pointer matches the headline to which it points."
  10724. (let* ((file (nth 1 refile-pointer))
  10725. (re (nth 2 refile-pointer))
  10726. (pos (nth 3 refile-pointer))
  10727. buffer)
  10728. (if (and (not (markerp pos)) (not file))
  10729. (user-error "Please indicate a target file in the refile path")
  10730. (when (org-string-nw-p re)
  10731. (setq buffer (if (markerp pos)
  10732. (marker-buffer pos)
  10733. (or (find-buffer-visiting file)
  10734. (find-file-noselect file))))
  10735. (with-current-buffer buffer
  10736. (org-with-wide-buffer
  10737. (goto-char pos)
  10738. (beginning-of-line 1)
  10739. (unless (looking-at-p re)
  10740. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10741. (defun org-refile-new-child (parent-target child)
  10742. "Use refile target PARENT-TARGET to add new CHILD below it."
  10743. (unless parent-target
  10744. (error "Cannot find parent for new node"))
  10745. (let ((file (nth 1 parent-target))
  10746. (pos (nth 3 parent-target))
  10747. level)
  10748. (with-current-buffer (or (find-buffer-visiting file)
  10749. (find-file-noselect file))
  10750. (org-with-wide-buffer
  10751. (if pos
  10752. (goto-char pos)
  10753. (goto-char (point-max))
  10754. (unless (bolp) (newline)))
  10755. (when (looking-at org-outline-regexp)
  10756. (setq level (funcall outline-level))
  10757. (org-end-of-subtree t t))
  10758. (org-back-over-empty-lines)
  10759. (insert "\n" (make-string
  10760. (if pos (org-get-valid-level level 1) 1) ?*)
  10761. " " child "\n")
  10762. (beginning-of-line 0)
  10763. (list (concat (car parent-target) "/" child) file "" (point))))))
  10764. (defun org-olpath-completing-read (prompt collection &rest args)
  10765. "Read an outline path like a file name."
  10766. (let ((thetable collection))
  10767. (apply #'completing-read
  10768. prompt
  10769. (lambda (string predicate &optional flag)
  10770. (cond
  10771. ((eq flag nil) (try-completion string thetable))
  10772. ((eq flag t)
  10773. (let ((l (length string)))
  10774. (mapcar (lambda (x)
  10775. (let ((r (substring x l))
  10776. (f (if (string-match " ([^)]*)$" x)
  10777. (match-string 0 x)
  10778. "")))
  10779. (if (string-match "/" r)
  10780. (concat string (substring r 0 (match-end 0)) f)
  10781. x)))
  10782. (all-completions string thetable predicate))))
  10783. ;; Exact match?
  10784. ((eq flag 'lambda) (assoc string thetable))))
  10785. args)))
  10786. ;;;; Dynamic blocks
  10787. (defun org-find-dblock (name)
  10788. "Find the first dynamic block with name NAME in the buffer.
  10789. If not found, stay at current position and return nil."
  10790. (let ((case-fold-search t) pos)
  10791. (save-excursion
  10792. (goto-char (point-min))
  10793. (setq pos (and (re-search-forward
  10794. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10795. (match-beginning 0))))
  10796. (when pos (goto-char pos))
  10797. pos))
  10798. (defun org-create-dblock (plist)
  10799. "Create a dynamic block section, with parameters taken from PLIST.
  10800. PLIST must contain a :name entry which is used as the name of the block."
  10801. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10802. (end-of-line 1)
  10803. (newline))
  10804. (let ((col (current-column))
  10805. (name (plist-get plist :name)))
  10806. (insert "#+BEGIN: " name)
  10807. (while plist
  10808. (if (eq (car plist) :name)
  10809. (setq plist (cddr plist))
  10810. (insert " " (prin1-to-string (pop plist)))))
  10811. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10812. (beginning-of-line -2)))
  10813. (defun org-prepare-dblock ()
  10814. "Prepare dynamic block for refresh.
  10815. This empties the block, puts the cursor at the insert position and returns
  10816. the property list including an extra property :name with the block name."
  10817. (unless (looking-at org-dblock-start-re)
  10818. (user-error "Not at a dynamic block"))
  10819. (let* ((begdel (1+ (match-end 0)))
  10820. (name (org-no-properties (match-string 1)))
  10821. (params (append (list :name name)
  10822. (read (concat "(" (match-string 3) ")")))))
  10823. (save-excursion
  10824. (beginning-of-line 1)
  10825. (skip-chars-forward " \t")
  10826. (setq params (plist-put params :indentation-column (current-column))))
  10827. (unless (re-search-forward org-dblock-end-re nil t)
  10828. (error "Dynamic block not terminated"))
  10829. (setq params
  10830. (append params
  10831. (list :content (buffer-substring
  10832. begdel (match-beginning 0)))))
  10833. (delete-region begdel (match-beginning 0))
  10834. (goto-char begdel)
  10835. (open-line 1)
  10836. params))
  10837. (defun org-map-dblocks (&optional command)
  10838. "Apply COMMAND to all dynamic blocks in the current buffer.
  10839. If COMMAND is not given, use `org-update-dblock'."
  10840. (let ((cmd (or command 'org-update-dblock)))
  10841. (save-excursion
  10842. (goto-char (point-min))
  10843. (while (re-search-forward org-dblock-start-re nil t)
  10844. (goto-char (match-beginning 0))
  10845. (save-excursion
  10846. (condition-case nil
  10847. (funcall cmd)
  10848. (error (message "Error during update of dynamic block"))))
  10849. (unless (re-search-forward org-dblock-end-re nil t)
  10850. (error "Dynamic block not terminated"))))))
  10851. (defun org-dblock-update (&optional arg)
  10852. "User command for updating dynamic blocks.
  10853. Update the dynamic block at point. With prefix ARG, update all dynamic
  10854. blocks in the buffer."
  10855. (interactive "P")
  10856. (if arg
  10857. (org-update-all-dblocks)
  10858. (or (looking-at org-dblock-start-re)
  10859. (org-beginning-of-dblock))
  10860. (org-update-dblock)))
  10861. (defun org-update-dblock ()
  10862. "Update the dynamic block at point.
  10863. This means to empty the block, parse for parameters and then call
  10864. the correct writing function."
  10865. (interactive)
  10866. (save-excursion
  10867. (let* ((win (selected-window))
  10868. (pos (point))
  10869. (line (org-current-line))
  10870. (params (org-prepare-dblock))
  10871. (name (plist-get params :name))
  10872. (indent (plist-get params :indentation-column))
  10873. (cmd (intern (concat "org-dblock-write:" name))))
  10874. (message "Updating dynamic block `%s' at line %d..." name line)
  10875. (funcall cmd params)
  10876. (message "Updating dynamic block `%s' at line %d...done" name line)
  10877. (goto-char pos)
  10878. (when (and indent (> indent 0))
  10879. (setq indent (make-string indent ?\ ))
  10880. (save-excursion
  10881. (select-window win)
  10882. (org-beginning-of-dblock)
  10883. (forward-line 1)
  10884. (while (not (looking-at org-dblock-end-re))
  10885. (insert indent)
  10886. (beginning-of-line 2))
  10887. (when (looking-at org-dblock-end-re)
  10888. (and (looking-at "[ \t]+")
  10889. (replace-match ""))
  10890. (insert indent)))))))
  10891. (defun org-beginning-of-dblock ()
  10892. "Find the beginning of the dynamic block at point.
  10893. Error if there is no such block at point."
  10894. (let ((pos (point))
  10895. beg)
  10896. (end-of-line 1)
  10897. (if (and (re-search-backward org-dblock-start-re nil t)
  10898. (setq beg (match-beginning 0))
  10899. (re-search-forward org-dblock-end-re nil t)
  10900. (> (match-end 0) pos))
  10901. (goto-char beg)
  10902. (goto-char pos)
  10903. (error "Not in a dynamic block"))))
  10904. (defun org-update-all-dblocks ()
  10905. "Update all dynamic blocks in the buffer.
  10906. This function can be used in a hook."
  10907. (interactive)
  10908. (when (derived-mode-p 'org-mode)
  10909. (org-map-dblocks 'org-update-dblock)))
  10910. ;;;; Completion
  10911. (declare-function org-export-backend-options "ox" (cl-x) t)
  10912. (defun org-get-export-keywords ()
  10913. "Return a list of all currently understood export keywords.
  10914. Export keywords include options, block names, attributes and
  10915. keywords relative to each registered export back-end."
  10916. (let (keywords)
  10917. (dolist (backend
  10918. (bound-and-true-p org-export-registered-backends)
  10919. (delq nil keywords))
  10920. ;; Back-end name (for keywords, like #+LATEX:)
  10921. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10922. (dolist (option-entry (org-export-backend-options backend))
  10923. ;; Back-end options.
  10924. (push (nth 1 option-entry) keywords)))))
  10925. (defconst org-options-keywords
  10926. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10927. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10928. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10929. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10930. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10931. (defcustom org-structure-template-alist
  10932. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10933. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10934. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10935. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10936. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10937. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10938. ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
  10939. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10940. ("L" "#+LaTeX: ")
  10941. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10942. ("H" "#+HTML: ")
  10943. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10944. ("A" "#+ASCII: ")
  10945. ("i" "#+INDEX: ?")
  10946. ("I" "#+INCLUDE: %file ?"))
  10947. "Structure completion elements.
  10948. This is a list of abbreviation keys and values. The value gets inserted
  10949. if you type `<' followed by the key and then press the completion key,
  10950. usually `TAB'. %file will be replaced by a file name after prompting
  10951. for the file using completion. The cursor will be placed at the position
  10952. of the `?' in the template.
  10953. There are two templates for each key, the first uses the original Org syntax,
  10954. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10955. the default when the /org-mtags.el/ module has been loaded. See also the
  10956. variable `org-mtags-prefer-muse-templates'."
  10957. :group 'org-completion
  10958. :type '(repeat
  10959. (list
  10960. (string :tag "Key")
  10961. (string :tag "Template")))
  10962. :version "26.1"
  10963. :package-version '(Org . "8.3"))
  10964. (defun org-try-structure-completion ()
  10965. "Try to complete a structure template before point.
  10966. This looks for strings like \"<e\" on an otherwise empty line and
  10967. expands them."
  10968. (let ((l (buffer-substring (point-at-bol) (point)))
  10969. a)
  10970. (when (and (looking-at "[ \t]*$")
  10971. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10972. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10973. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10974. (match-beginning 1)) a)
  10975. t)))
  10976. (defun org-complete-expand-structure-template (start cell)
  10977. "Expand a structure template."
  10978. (let ((rpl (nth 1 cell))
  10979. (ind ""))
  10980. (delete-region start (point))
  10981. (when (string-match "\\`[ \t]*#\\+" rpl)
  10982. (cond
  10983. ((bolp))
  10984. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  10985. (setq ind (buffer-substring (point-at-bol) (point))))
  10986. (t (newline))))
  10987. (setq start (point))
  10988. (when (string-match "%file" rpl)
  10989. (setq rpl (replace-match
  10990. (concat
  10991. "\""
  10992. (save-match-data
  10993. (abbreviate-file-name (read-file-name "Include file: ")))
  10994. "\"")
  10995. t t rpl)))
  10996. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  10997. (concat "\n" ind)))
  10998. (insert rpl)
  10999. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11000. ;;;; TODO, DEADLINE, Comments
  11001. (defun org-toggle-comment ()
  11002. "Change the COMMENT state of an entry."
  11003. (interactive)
  11004. (save-excursion
  11005. (org-back-to-heading)
  11006. (let ((case-fold-search nil))
  11007. (looking-at org-complex-heading-regexp))
  11008. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11009. (skip-chars-forward " \t")
  11010. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11011. (if (org-in-commented-heading-p t)
  11012. (delete-region (point)
  11013. (progn (search-forward " " (line-end-position) 'move)
  11014. (skip-chars-forward " \t")
  11015. (point)))
  11016. (insert org-comment-string)
  11017. (unless (eolp) (insert " ")))))
  11018. (defvar org-last-todo-state-is-todo nil
  11019. "This is non-nil when the last TODO state change led to a TODO state.
  11020. If the last change removed the TODO tag or switched to DONE, then
  11021. this is nil.")
  11022. (defvar org-setting-tags nil) ; dynamically skipped
  11023. (defvar org-todo-setup-filter-hook nil
  11024. "Hook for functions that pre-filter todo specs.
  11025. Each function takes a todo spec and returns either nil or the spec
  11026. transformed into canonical form." )
  11027. (defvar org-todo-get-default-hook nil
  11028. "Hook for functions that get a default item for todo.
  11029. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11030. nil or a string to be used for the todo mark." )
  11031. (defvar org-agenda-headline-snapshot-before-repeat)
  11032. (defun org-current-effective-time ()
  11033. "Return current time adjusted for `org-extend-today-until' variable."
  11034. (let* ((ct (org-current-time))
  11035. (dct (decode-time ct))
  11036. (ct1
  11037. (cond
  11038. (org-use-last-clock-out-time-as-effective-time
  11039. (or (org-clock-get-last-clock-out-time) ct))
  11040. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11041. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11042. (t ct))))
  11043. ct1))
  11044. (defun org-todo-yesterday (&optional arg)
  11045. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11046. (interactive "P")
  11047. (if (eq major-mode 'org-agenda-mode)
  11048. (apply 'org-agenda-todo-yesterday arg)
  11049. (let* ((org-use-effective-time t)
  11050. (hour (nth 2 (decode-time (org-current-time))))
  11051. (org-extend-today-until (1+ hour)))
  11052. (org-todo arg))))
  11053. (defvar org-block-entry-blocking ""
  11054. "First entry preventing the TODO state change.")
  11055. (defun org-cancel-repeater ()
  11056. "Cancel a repeater by setting its numeric value to zero."
  11057. (interactive)
  11058. (save-excursion
  11059. (org-back-to-heading t)
  11060. (let ((bound1 (point))
  11061. (bound0 (save-excursion (outline-next-heading) (point))))
  11062. (when (and (re-search-forward
  11063. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11064. org-deadline-time-regexp "\\)\\|\\("
  11065. org-ts-regexp "\\)")
  11066. bound0 t)
  11067. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11068. bound1 t))
  11069. (replace-match "0" t nil nil 1)))))
  11070. (defvar org-state)
  11071. (defvar org-blocked-by-checkboxes)
  11072. (defun org-todo (&optional arg)
  11073. "Change the TODO state of an item.
  11074. The state of an item is given by a keyword at the start of the heading,
  11075. like
  11076. *** TODO Write paper
  11077. *** DONE Call mom
  11078. The different keywords are specified in the variable `org-todo-keywords'.
  11079. By default the available states are \"TODO\" and \"DONE\". So, for this
  11080. example: when the item starts with TODO, it is changed to DONE.
  11081. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11082. DONE are present, add TODO at the beginning of the heading.
  11083. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11084. state.
  11085. With numeric prefix ARG, switch to that state.
  11086. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11087. next set of TODO \
  11088. keywords (nextset).
  11089. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11090. prefix, circumvent any state blocking.
  11091. With a numeric prefix arg of 0, inhibit note taking for the change.
  11092. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11093. When called through ELisp, arg is also interpreted in the following way:
  11094. `none' -> empty state
  11095. \"\" -> switch to empty state
  11096. `done' -> switch to DONE
  11097. `nextset' -> switch to the next set of keywords
  11098. `previousset' -> switch to the previous set of keywords
  11099. \"WAITING\" -> switch to the specified keyword, but only if it
  11100. really is a member of `org-todo-keywords'."
  11101. (interactive "P")
  11102. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11103. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11104. 'region-start-level 'region))
  11105. org-loop-over-headlines-in-active-region)
  11106. (org-map-entries
  11107. `(org-todo ,arg)
  11108. org-loop-over-headlines-in-active-region
  11109. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11110. (when (equal arg '(16)) (setq arg 'nextset))
  11111. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11112. (let ((org-blocker-hook org-blocker-hook)
  11113. commentp
  11114. case-fold-search)
  11115. (when (equal arg '(64))
  11116. (setq arg nil org-blocker-hook nil))
  11117. (when (and org-blocker-hook
  11118. (or org-inhibit-blocking
  11119. (org-entry-get nil "NOBLOCKING")))
  11120. (setq org-blocker-hook nil))
  11121. (save-excursion
  11122. (catch 'exit
  11123. (org-back-to-heading t)
  11124. (when (org-in-commented-heading-p t)
  11125. (org-toggle-comment)
  11126. (setq commentp t))
  11127. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11128. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11129. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11130. (let* ((match-data (match-data))
  11131. (startpos (point-at-bol))
  11132. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11133. (org-log-done org-log-done)
  11134. (org-log-repeat org-log-repeat)
  11135. (org-todo-log-states org-todo-log-states)
  11136. (org-inhibit-logging
  11137. (if (equal arg 0)
  11138. (progn (setq arg nil) 'note) org-inhibit-logging))
  11139. (this (match-string 1))
  11140. (hl-pos (match-beginning 0))
  11141. (head (org-get-todo-sequence-head this))
  11142. (ass (assoc head org-todo-kwd-alist))
  11143. (interpret (nth 1 ass))
  11144. (done-word (nth 3 ass))
  11145. (final-done-word (nth 4 ass))
  11146. (org-last-state (or this ""))
  11147. (completion-ignore-case t)
  11148. (member (member this org-todo-keywords-1))
  11149. (tail (cdr member))
  11150. (org-state (cond
  11151. ((and org-todo-key-trigger
  11152. (or (and (equal arg '(4))
  11153. (eq org-use-fast-todo-selection 'prefix))
  11154. (and (not arg) org-use-fast-todo-selection
  11155. (not (eq org-use-fast-todo-selection
  11156. 'prefix)))))
  11157. ;; Use fast selection.
  11158. (org-fast-todo-selection))
  11159. ((and (equal arg '(4))
  11160. (or (not org-use-fast-todo-selection)
  11161. (not org-todo-key-trigger)))
  11162. ;; Read a state with completion.
  11163. (completing-read
  11164. "State: " (mapcar #'list org-todo-keywords-1)
  11165. nil t))
  11166. ((eq arg 'right)
  11167. (if this
  11168. (if tail (car tail) nil)
  11169. (car org-todo-keywords-1)))
  11170. ((eq arg 'left)
  11171. (unless (equal member org-todo-keywords-1)
  11172. (if this
  11173. (nth (- (length org-todo-keywords-1)
  11174. (length tail) 2)
  11175. org-todo-keywords-1)
  11176. (org-last org-todo-keywords-1))))
  11177. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11178. (setq arg nil))) ;hack to fall back to cycling
  11179. (arg
  11180. ;; User or caller requests a specific state.
  11181. (cond
  11182. ((equal arg "") nil)
  11183. ((eq arg 'none) nil)
  11184. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11185. ((eq arg 'nextset)
  11186. (or (car (cdr (member head org-todo-heads)))
  11187. (car org-todo-heads)))
  11188. ((eq arg 'previousset)
  11189. (let ((org-todo-heads (reverse org-todo-heads)))
  11190. (or (car (cdr (member head org-todo-heads)))
  11191. (car org-todo-heads))))
  11192. ((car (member arg org-todo-keywords-1)))
  11193. ((stringp arg)
  11194. (user-error "State `%s' not valid in this file" arg))
  11195. ((nth (1- (prefix-numeric-value arg))
  11196. org-todo-keywords-1))))
  11197. ((null member) (or head (car org-todo-keywords-1)))
  11198. ((equal this final-done-word) nil) ;-> make empty
  11199. ((null tail) nil) ;-> first entry
  11200. ((memq interpret '(type priority))
  11201. (if (eq this-command last-command)
  11202. (car tail)
  11203. (if (> (length tail) 0)
  11204. (or done-word (car org-done-keywords))
  11205. nil)))
  11206. (t
  11207. (car tail))))
  11208. (org-state (or
  11209. (run-hook-with-args-until-success
  11210. 'org-todo-get-default-hook org-state org-last-state)
  11211. org-state))
  11212. (next (if org-state (concat " " org-state " ") " "))
  11213. (change-plist (list :type 'todo-state-change :from this :to org-state
  11214. :position startpos))
  11215. dolog now-done-p)
  11216. (when org-blocker-hook
  11217. (let (org-blocked-by-checkboxes block-reason)
  11218. (setq org-last-todo-state-is-todo
  11219. (not (member this org-done-keywords)))
  11220. (unless (save-excursion
  11221. (save-match-data
  11222. (org-with-wide-buffer
  11223. (run-hook-with-args-until-failure
  11224. 'org-blocker-hook change-plist))))
  11225. (setq block-reason (if org-blocked-by-checkboxes
  11226. "contained checkboxes"
  11227. (format "\"%s\"" org-block-entry-blocking)))
  11228. (if (called-interactively-p 'interactive)
  11229. (user-error "TODO state change from %s to %s blocked (by %s)"
  11230. this org-state block-reason)
  11231. ;; Fail silently.
  11232. (message "TODO state change from %s to %s blocked (by %s)"
  11233. this org-state block-reason)
  11234. (throw 'exit nil)))))
  11235. (store-match-data match-data)
  11236. (replace-match next t t)
  11237. (cond ((equal this org-state)
  11238. (message "TODO state was already %s" (org-trim next)))
  11239. ((not (pos-visible-in-window-p hl-pos))
  11240. (message "TODO state changed to %s" (org-trim next))))
  11241. (unless head
  11242. (setq head (org-get-todo-sequence-head org-state)
  11243. ass (assoc head org-todo-kwd-alist)
  11244. interpret (nth 1 ass)
  11245. done-word (nth 3 ass)
  11246. final-done-word (nth 4 ass)))
  11247. (when (memq arg '(nextset previousset))
  11248. (message "Keyword-Set %d/%d: %s"
  11249. (- (length org-todo-sets) -1
  11250. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11251. (length org-todo-sets)
  11252. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11253. (setq org-last-todo-state-is-todo
  11254. (not (member org-state org-done-keywords)))
  11255. (setq now-done-p (and (member org-state org-done-keywords)
  11256. (not (member this org-done-keywords))))
  11257. (and logging (org-local-logging logging))
  11258. (when (and (or org-todo-log-states org-log-done)
  11259. (not (eq org-inhibit-logging t))
  11260. (not (memq arg '(nextset previousset))))
  11261. ;; We need to look at recording a time and note.
  11262. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11263. (nth 2 (assoc this org-todo-log-states))))
  11264. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11265. (setq dolog 'time))
  11266. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11267. (and org-state
  11268. (member org-state org-not-done-keywords)
  11269. (not (member this org-not-done-keywords))))
  11270. ;; This is now a todo state and was not one before
  11271. ;; If there was a CLOSED time stamp, get rid of it.
  11272. (org-add-planning-info nil nil 'closed))
  11273. (when (and now-done-p org-log-done)
  11274. ;; It is now done, and it was not done before.
  11275. (org-add-planning-info 'closed (org-current-effective-time))
  11276. (when (and (not dolog) (eq 'note org-log-done))
  11277. (org-add-log-setup 'done org-state this 'note)))
  11278. (when (and org-state dolog)
  11279. ;; This is a non-nil state, and we need to log it.
  11280. (org-add-log-setup 'state org-state this dolog)))
  11281. ;; Fixup tag positioning.
  11282. (org-todo-trigger-tag-changes org-state)
  11283. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11284. (when org-provide-todo-statistics
  11285. (org-update-parent-todo-statistics))
  11286. (run-hooks 'org-after-todo-state-change-hook)
  11287. (when (and arg (not (member org-state org-done-keywords)))
  11288. (setq head (org-get-todo-sequence-head org-state)))
  11289. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11290. ;; Do we need to trigger a repeat?
  11291. (when now-done-p
  11292. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11293. ;; This is for the agenda, take a snapshot of the headline.
  11294. (save-match-data
  11295. (setq org-agenda-headline-snapshot-before-repeat
  11296. (org-get-heading))))
  11297. (org-auto-repeat-maybe org-state))
  11298. ;; Fixup cursor location if close to the keyword.
  11299. (when (and (outline-on-heading-p)
  11300. (not (bolp))
  11301. (save-excursion (beginning-of-line 1)
  11302. (looking-at org-todo-line-regexp))
  11303. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11304. (goto-char (or (match-end 2) (match-end 1)))
  11305. (and (looking-at " ") (just-one-space)))
  11306. (when org-trigger-hook
  11307. (save-excursion
  11308. (run-hook-with-args 'org-trigger-hook change-plist)))
  11309. (when commentp (org-toggle-comment))))))))
  11310. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11311. "Block turning an entry into a TODO, using the hierarchy.
  11312. This checks whether the current task should be blocked from state
  11313. changes. Such blocking occurs when:
  11314. 1. The task has children which are not all in a completed state.
  11315. 2. A task has a parent with the property :ORDERED:, and there
  11316. are siblings prior to the current task with incomplete
  11317. status.
  11318. 3. The parent of the task is blocked because it has siblings that should
  11319. be done first, or is child of a block grandparent TODO entry."
  11320. (if (not org-enforce-todo-dependencies)
  11321. t ; if locally turned off don't block
  11322. (catch 'dont-block
  11323. ;; If this is not a todo state change, or if this entry is already DONE,
  11324. ;; do not block
  11325. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11326. (member (plist-get change-plist :from)
  11327. (cons 'done org-done-keywords))
  11328. (member (plist-get change-plist :to)
  11329. (cons 'todo org-not-done-keywords))
  11330. (not (plist-get change-plist :to)))
  11331. (throw 'dont-block t))
  11332. ;; If this task has children, and any are undone, it's blocked
  11333. (save-excursion
  11334. (org-back-to-heading t)
  11335. (let ((this-level (funcall outline-level)))
  11336. (outline-next-heading)
  11337. (let ((child-level (funcall outline-level)))
  11338. (while (and (not (eobp))
  11339. (> child-level this-level))
  11340. ;; this todo has children, check whether they are all
  11341. ;; completed
  11342. (when (and (not (org-entry-is-done-p))
  11343. (org-entry-is-todo-p))
  11344. (setq org-block-entry-blocking (org-get-heading))
  11345. (throw 'dont-block nil))
  11346. (outline-next-heading)
  11347. (setq child-level (funcall outline-level))))))
  11348. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11349. ;; any previous siblings are undone, it's blocked
  11350. (save-excursion
  11351. (org-back-to-heading t)
  11352. (let* ((pos (point))
  11353. (parent-pos (and (org-up-heading-safe) (point)))
  11354. (case-fold-search nil))
  11355. (unless parent-pos (throw 'dont-block t)) ; no parent
  11356. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11357. (forward-line 1)
  11358. (re-search-forward org-not-done-heading-regexp pos t))
  11359. (setq org-block-entry-blocking (match-string 0))
  11360. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11361. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11362. (while t
  11363. (goto-char parent-pos)
  11364. (unless (looking-at org-not-done-heading-regexp)
  11365. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11366. (setq pos (point))
  11367. (setq parent-pos (and (org-up-heading-safe) (point)))
  11368. (unless parent-pos (throw 'dont-block t)) ; no parent
  11369. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11370. (forward-line 1)
  11371. (re-search-forward org-not-done-heading-regexp pos t)
  11372. (setq org-block-entry-blocking (org-get-heading)))
  11373. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11374. (defcustom org-track-ordered-property-with-tag nil
  11375. "Should the ORDERED property also be shown as a tag?
  11376. The ORDERED property decides if an entry should require subtasks to be
  11377. completed in sequence. Since a property is not very visible, setting
  11378. this option means that toggling the ORDERED property with the command
  11379. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11380. not relevant for the behavior, but it makes things more visible.
  11381. Note that toggling the tag with tags commands will not change the property
  11382. and therefore not influence behavior!
  11383. This can be t, meaning the tag ORDERED should be used, It can also be a
  11384. string to select a different tag for this task."
  11385. :group 'org-todo
  11386. :type '(choice
  11387. (const :tag "No tracking" nil)
  11388. (const :tag "Track with ORDERED tag" t)
  11389. (string :tag "Use other tag")))
  11390. (defun org-toggle-ordered-property ()
  11391. "Toggle the ORDERED property of the current entry.
  11392. For better visibility, you can track the value of this property with a tag.
  11393. See variable `org-track-ordered-property-with-tag'."
  11394. (interactive)
  11395. (let* ((t1 org-track-ordered-property-with-tag)
  11396. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11397. (save-excursion
  11398. (org-back-to-heading)
  11399. (if (org-entry-get nil "ORDERED")
  11400. (progn
  11401. (org-delete-property "ORDERED")
  11402. (and tag (org-toggle-tag tag 'off))
  11403. (message "Subtasks can be completed in arbitrary order"))
  11404. (org-entry-put nil "ORDERED" "t")
  11405. (and tag (org-toggle-tag tag 'on))
  11406. (message "Subtasks must be completed in sequence")))))
  11407. (defun org-block-todo-from-checkboxes (change-plist)
  11408. "Block turning an entry into a TODO, using checkboxes.
  11409. This checks whether the current task should be blocked from state
  11410. changes because there are unchecked boxes in this entry."
  11411. (if (not org-enforce-todo-checkbox-dependencies)
  11412. t ; if locally turned off don't block
  11413. (catch 'dont-block
  11414. ;; If this is not a todo state change, or if this entry is already DONE,
  11415. ;; do not block
  11416. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11417. (member (plist-get change-plist :from)
  11418. (cons 'done org-done-keywords))
  11419. (member (plist-get change-plist :to)
  11420. (cons 'todo org-not-done-keywords))
  11421. (not (plist-get change-plist :to)))
  11422. (throw 'dont-block t))
  11423. ;; If this task has checkboxes that are not checked, it's blocked
  11424. (save-excursion
  11425. (org-back-to-heading t)
  11426. (let ((beg (point)) end)
  11427. (outline-next-heading)
  11428. (setq end (point))
  11429. (goto-char beg)
  11430. (when (org-list-search-forward
  11431. (concat (org-item-beginning-re)
  11432. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11433. "\\[[- ]\\]")
  11434. end t)
  11435. (when (boundp 'org-blocked-by-checkboxes)
  11436. (setq org-blocked-by-checkboxes t))
  11437. (throw 'dont-block nil))))
  11438. t))) ; do not block
  11439. (defun org-entry-blocked-p ()
  11440. "Non-nil if entry at point is blocked."
  11441. (and (not (org-entry-get nil "NOBLOCKING"))
  11442. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11443. (not (run-hook-with-args-until-failure
  11444. 'org-blocker-hook
  11445. (list :type 'todo-state-change
  11446. :position (point)
  11447. :from 'todo
  11448. :to 'done)))))
  11449. (defun org-update-statistics-cookies (all)
  11450. "Update the statistics cookie, either from TODO or from checkboxes.
  11451. This should be called with the cursor in a line with a statistics
  11452. cookie. When called with a \\[universal-argument] prefix, update
  11453. all statistics cookies in the buffer."
  11454. (interactive "P")
  11455. (if all
  11456. (progn
  11457. (org-update-checkbox-count 'all)
  11458. (org-map-entries 'org-update-parent-todo-statistics))
  11459. (if (not (org-at-heading-p))
  11460. (org-update-checkbox-count)
  11461. (let ((pos (point-marker))
  11462. end l1 l2)
  11463. (ignore-errors (org-back-to-heading t))
  11464. (if (not (org-at-heading-p))
  11465. (org-update-checkbox-count)
  11466. (setq l1 (org-outline-level))
  11467. (setq end (save-excursion
  11468. (outline-next-heading)
  11469. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11470. (point)))
  11471. (if (and (save-excursion
  11472. (re-search-forward
  11473. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11474. (not (save-excursion (re-search-forward
  11475. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11476. (org-update-checkbox-count)
  11477. (if (and l2 (> l2 l1))
  11478. (progn
  11479. (goto-char end)
  11480. (org-update-parent-todo-statistics))
  11481. (goto-char pos)
  11482. (beginning-of-line 1)
  11483. (while (re-search-forward
  11484. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11485. (point-at-eol) t)
  11486. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11487. (goto-char pos)
  11488. (move-marker pos nil)))))
  11489. (defvar org-entry-property-inherited-from) ;; defined below
  11490. (defun org-update-parent-todo-statistics ()
  11491. "Update any statistics cookie in the parent of the current headline.
  11492. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11493. the entire subtree and this will travel up the hierarchy and update
  11494. statistics everywhere."
  11495. (let* ((prop (save-excursion (org-up-heading-safe)
  11496. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11497. (recursive (or (not org-hierarchical-todo-statistics)
  11498. (and prop (string-match "\\<recursive\\>" prop))))
  11499. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11500. 0))
  11501. (first t)
  11502. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11503. level ltoggle l1 new ndel
  11504. (cnt-all 0) (cnt-done 0) is-percent kwd
  11505. checkbox-beg cookie-present)
  11506. (catch 'exit
  11507. (save-excursion
  11508. (beginning-of-line 1)
  11509. (setq ltoggle (funcall outline-level))
  11510. ;; Three situations are to consider:
  11511. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11512. ;; to the top-level ancestor on the headline;
  11513. ;; 2. If parent has "recursive" property, repeat up to the
  11514. ;; headline setting that property, taking inheritance into
  11515. ;; account;
  11516. ;; 3. Else, move up to direct parent and proceed only once.
  11517. (while (and (setq level (org-up-heading-safe))
  11518. (or recursive first)
  11519. (>= (point) lim))
  11520. (setq first nil cookie-present nil)
  11521. (unless (and level
  11522. (not (string-match
  11523. "\\<checkbox\\>"
  11524. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11525. "")))))
  11526. (throw 'exit nil))
  11527. (while (re-search-forward box-re (point-at-eol) t)
  11528. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11529. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11530. (save-match-data
  11531. (unless (outline-next-heading) (throw 'exit nil))
  11532. (while (and (looking-at org-complex-heading-regexp)
  11533. (> (setq l1 (length (match-string 1))) level))
  11534. (setq kwd (and (or recursive (= l1 ltoggle))
  11535. (match-string 2)))
  11536. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11537. (and (eq org-provide-todo-statistics t)
  11538. (or (member kwd org-done-keywords)))
  11539. (and (listp org-provide-todo-statistics)
  11540. (stringp (car org-provide-todo-statistics))
  11541. (or (member kwd org-provide-todo-statistics)
  11542. (member kwd org-done-keywords)))
  11543. (and (listp org-provide-todo-statistics)
  11544. (listp (car org-provide-todo-statistics))
  11545. (or (member kwd (car org-provide-todo-statistics))
  11546. (and (member kwd org-done-keywords)
  11547. (member kwd (cadr org-provide-todo-statistics))))))
  11548. (setq cnt-all (1+ cnt-all))
  11549. (and (eq org-provide-todo-statistics t)
  11550. kwd
  11551. (setq cnt-all (1+ cnt-all))))
  11552. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11553. (member kwd org-done-keywords))
  11554. (and (listp org-provide-todo-statistics)
  11555. (listp (car org-provide-todo-statistics))
  11556. (member kwd org-done-keywords)
  11557. (member kwd (cadr org-provide-todo-statistics)))
  11558. (and (listp org-provide-todo-statistics)
  11559. (stringp (car org-provide-todo-statistics))
  11560. (member kwd org-done-keywords)))
  11561. (setq cnt-done (1+ cnt-done)))
  11562. (outline-next-heading)))
  11563. (setq new
  11564. (if is-percent
  11565. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11566. (max 1 cnt-all)))
  11567. (format "[%d/%d]" cnt-done cnt-all))
  11568. ndel (- (match-end 0) checkbox-beg))
  11569. (goto-char checkbox-beg)
  11570. (insert new)
  11571. (delete-region (point) (+ (point) ndel))
  11572. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11573. (when cookie-present
  11574. (run-hook-with-args 'org-after-todo-statistics-hook
  11575. cnt-done (- cnt-all cnt-done))))))
  11576. (run-hooks 'org-todo-statistics-hook)))
  11577. (defvar org-after-todo-statistics-hook nil
  11578. "Hook that is called after a TODO statistics cookie has been updated.
  11579. Each function is called with two arguments: the number of not-done entries
  11580. and the number of done entries.
  11581. For example, the following function, when added to this hook, will switch
  11582. an entry to DONE when all children are done, and back to TODO when new
  11583. entries are set to a TODO status. Note that this hook is only called
  11584. when there is a statistics cookie in the headline!
  11585. (defun org-summary-todo (n-done n-not-done)
  11586. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11587. (let (org-log-done org-log-states) ; turn off logging
  11588. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11589. ")
  11590. (defvar org-todo-statistics-hook nil
  11591. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11592. This hook runs even if there is no statistics cookie present, in which case
  11593. `org-after-todo-statistics-hook' would not run.")
  11594. (defun org-todo-trigger-tag-changes (state)
  11595. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11596. (let ((l org-todo-state-tags-triggers)
  11597. changes)
  11598. (when (or (not state) (equal state ""))
  11599. (setq changes (append changes (cdr (assoc "" l)))))
  11600. (when (and (stringp state) (> (length state) 0))
  11601. (setq changes (append changes (cdr (assoc state l)))))
  11602. (when (member state org-not-done-keywords)
  11603. (setq changes (append changes (cdr (assq 'todo l)))))
  11604. (when (member state org-done-keywords)
  11605. (setq changes (append changes (cdr (assq 'done l)))))
  11606. (dolist (c changes)
  11607. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11608. (defun org-local-logging (value)
  11609. "Get logging settings from a property VALUE."
  11610. ;; Directly set the variables, they are already local.
  11611. (setq org-log-done nil
  11612. org-log-repeat nil
  11613. org-todo-log-states nil)
  11614. (dolist (w (split-string value))
  11615. (let (a)
  11616. (cond
  11617. ((setq a (assoc w org-startup-options))
  11618. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11619. (set (nth 1 a) (nth 2 a))))
  11620. ((setq a (org-extract-log-state-settings w))
  11621. (and (member (car a) org-todo-keywords-1)
  11622. (push a org-todo-log-states)))))))
  11623. (defun org-get-todo-sequence-head (kwd)
  11624. "Return the head of the TODO sequence to which KWD belongs.
  11625. If KWD is not set, check if there is a text property remembering the
  11626. right sequence."
  11627. (let (p)
  11628. (cond
  11629. ((not kwd)
  11630. (or (get-text-property (point-at-bol) 'org-todo-head)
  11631. (progn
  11632. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11633. nil (point-at-eol)))
  11634. (get-text-property p 'org-todo-head))))
  11635. ((not (member kwd org-todo-keywords-1))
  11636. (car org-todo-keywords-1))
  11637. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11638. (defun org-fast-todo-selection ()
  11639. "Fast TODO keyword selection with single keys.
  11640. Returns the new TODO keyword, or nil if no state change should occur."
  11641. (let* ((fulltable org-todo-key-alist)
  11642. (done-keywords org-done-keywords) ;; needed for the faces.
  11643. (maxlen (apply 'max (mapcar
  11644. (lambda (x)
  11645. (if (stringp (car x)) (string-width (car x)) 0))
  11646. fulltable)))
  11647. (expert nil)
  11648. (fwidth (+ maxlen 3 1 3))
  11649. (ncol (/ (- (window-width) 4) fwidth))
  11650. tg cnt e c tbl
  11651. groups ingroup)
  11652. (save-excursion
  11653. (save-window-excursion
  11654. (if expert
  11655. (set-buffer (get-buffer-create " *Org todo*"))
  11656. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11657. (erase-buffer)
  11658. (setq-local org-done-keywords done-keywords)
  11659. (setq tbl fulltable cnt 0)
  11660. (while (setq e (pop tbl))
  11661. (cond
  11662. ((equal e '(:startgroup))
  11663. (push '() groups) (setq ingroup t)
  11664. (unless (= cnt 0)
  11665. (setq cnt 0)
  11666. (insert "\n"))
  11667. (insert "{ "))
  11668. ((equal e '(:endgroup))
  11669. (setq ingroup nil cnt 0)
  11670. (insert "}\n"))
  11671. ((equal e '(:newline))
  11672. (unless (= cnt 0)
  11673. (setq cnt 0)
  11674. (insert "\n")
  11675. (setq e (car tbl))
  11676. (while (equal (car tbl) '(:newline))
  11677. (insert "\n")
  11678. (setq tbl (cdr tbl)))))
  11679. (t
  11680. (setq tg (car e) c (cdr e))
  11681. (when ingroup (push tg (car groups)))
  11682. (setq tg (org-add-props tg nil 'face
  11683. (org-get-todo-face tg)))
  11684. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11685. (insert "[" c "] " tg (make-string
  11686. (- fwidth 4 (length tg)) ?\ ))
  11687. (when (= (setq cnt (1+ cnt)) ncol)
  11688. (insert "\n")
  11689. (when ingroup (insert " "))
  11690. (setq cnt 0)))))
  11691. (insert "\n")
  11692. (goto-char (point-min))
  11693. (unless expert (org-fit-window-to-buffer))
  11694. (message "[a-z..]:Set [SPC]:clear")
  11695. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11696. (cond
  11697. ((or (= c ?\C-g)
  11698. (and (= c ?q) (not (rassoc c fulltable))))
  11699. (setq quit-flag t))
  11700. ((= c ?\ ) nil)
  11701. ((setq e (rassoc c fulltable) tg (car e))
  11702. tg)
  11703. (t (setq quit-flag t)))))))
  11704. (defun org-entry-is-todo-p ()
  11705. (member (org-get-todo-state) org-not-done-keywords))
  11706. (defun org-entry-is-done-p ()
  11707. (member (org-get-todo-state) org-done-keywords))
  11708. (defun org-get-todo-state ()
  11709. "Return the TODO keyword of the current subtree."
  11710. (save-excursion
  11711. (org-back-to-heading t)
  11712. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11713. (match-end 2)
  11714. (match-string 2))))
  11715. (defun org-at-date-range-p (&optional inactive-ok)
  11716. "Non-nil if point is inside a date range.
  11717. When optional argument INACTIVE-OK is non-nil, also consider
  11718. inactive time ranges.
  11719. When this function returns a non-nil value, match data is set
  11720. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11721. on INACTIVE-OK."
  11722. (interactive)
  11723. (save-excursion
  11724. (catch 'exit
  11725. (let ((pos (point)))
  11726. (skip-chars-backward "^[<\r\n")
  11727. (skip-chars-backward "<[")
  11728. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11729. (>= (match-end 0) pos)
  11730. (throw 'exit t))
  11731. (skip-chars-backward "^<[\r\n")
  11732. (skip-chars-backward "<[")
  11733. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11734. (>= (match-end 0) pos)
  11735. (throw 'exit t)))
  11736. nil)))
  11737. (defun org-get-repeat (&optional timestamp)
  11738. "Check if there is a time-stamp with repeater in this entry.
  11739. Return the repeater, as a string, or nil. Also return nil when
  11740. this function is called before first heading.
  11741. When optional argument TIMESTAMP is a string, extract the
  11742. repeater from there instead."
  11743. (save-match-data
  11744. (cond (timestamp
  11745. (and (string-match org-repeat-re timestamp)
  11746. (match-string-no-properties 1 timestamp)))
  11747. ((org-before-first-heading-p) nil)
  11748. (t
  11749. (save-excursion
  11750. (org-back-to-heading t)
  11751. (let ((end (org-entry-end-position)))
  11752. (catch :repeat
  11753. (while (re-search-forward org-repeat-re end t)
  11754. (when (save-match-data (org-at-timestamp-p 'agenda))
  11755. (throw :repeat (match-string-no-properties 1)))))))))))
  11756. (defvar org-last-changed-timestamp)
  11757. (defvar org-last-inserted-timestamp)
  11758. (defvar org-log-post-message)
  11759. (defvar org-log-note-purpose)
  11760. (defvar org-log-note-how nil)
  11761. (defvar org-log-note-extra)
  11762. (defun org-auto-repeat-maybe (done-word)
  11763. "Check if the current headline contains a repeated time-stamp.
  11764. If yes, set TODO state back to what it was and change the base date
  11765. of repeating deadline/scheduled time stamps to new date.
  11766. This function is run automatically after each state change to a DONE state."
  11767. (let* ((repeat (org-get-repeat))
  11768. (aa (assoc org-last-state org-todo-kwd-alist))
  11769. (interpret (nth 1 aa))
  11770. (head (nth 2 aa))
  11771. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11772. (msg "Entry repeats: ")
  11773. (org-log-done nil)
  11774. (org-todo-log-states nil)
  11775. (end (copy-marker (org-entry-end-position))))
  11776. (unwind-protect
  11777. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11778. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11779. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11780. org-todo-repeat-to-state)))
  11781. (org-todo (cond
  11782. ((and to-state (member to-state org-todo-keywords-1))
  11783. to-state)
  11784. ((eq interpret 'type) org-last-state)
  11785. (head)
  11786. (t 'none))))
  11787. (org-back-to-heading t)
  11788. (org-add-planning-info nil nil 'closed)
  11789. ;; When `org-log-repeat' is non-nil or entry contains
  11790. ;; a clock, set LAST_REPEAT property.
  11791. (when (or org-log-repeat
  11792. (catch :clock
  11793. (save-excursion
  11794. (while (re-search-forward org-clock-line-re end t)
  11795. (when (org-at-clock-log-p) (throw :clock t))))))
  11796. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11797. (org-time-stamp-format t t)
  11798. (current-time))))
  11799. (when org-log-repeat
  11800. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11801. (memq 'org-add-log-note post-command-hook))
  11802. ;; We are already setup for some record.
  11803. (when (eq org-log-repeat 'note)
  11804. ;; Make sure we take a note, not only a time stamp.
  11805. (setq org-log-note-how 'note))
  11806. ;; Set up for taking a record.
  11807. (org-add-log-setup 'state
  11808. (or done-word (car org-done-keywords))
  11809. org-last-state
  11810. org-log-repeat)))
  11811. (let ((planning-re (regexp-opt
  11812. (list org-scheduled-string org-deadline-string))))
  11813. (while (re-search-forward org-ts-regexp end t)
  11814. (let* ((ts (match-string 0))
  11815. (planning? (org-at-planning-p))
  11816. (type (if (not planning?) "Plain:"
  11817. (save-excursion
  11818. (re-search-backward
  11819. planning-re (line-beginning-position) t)
  11820. (match-string 0)))))
  11821. (cond
  11822. ;; Ignore fake time-stamps (e.g., within comments).
  11823. ((not (org-at-timestamp-p 'agenda)))
  11824. ;; Time-stamps without a repeater are usually
  11825. ;; skipped. However, a SCHEDULED time-stamp without
  11826. ;; one is removed, as they are no longer relevant.
  11827. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11828. ts))
  11829. (when (equal type org-scheduled-string)
  11830. (org-remove-timestamp-with-keyword type)))
  11831. (t
  11832. (let ((n (string-to-number (match-string 2 ts)))
  11833. (what (match-string 3 ts)))
  11834. (when (equal what "w") (setq n (* n 7) what "d"))
  11835. (when (and (equal what "h")
  11836. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11837. ts)))
  11838. (user-error
  11839. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11840. has been set"
  11841. n))
  11842. ;; Preparation, see if we need to modify the start
  11843. ;; date for the change.
  11844. (when (match-end 1)
  11845. (let ((time (save-match-data
  11846. (org-time-string-to-time ts))))
  11847. (cond
  11848. ((equal (match-string 1 ts) ".")
  11849. ;; Shift starting date to today
  11850. (org-timestamp-change
  11851. (- (org-today) (time-to-days time))
  11852. 'day))
  11853. ((equal (match-string 1 ts) "+")
  11854. (let ((nshiftmax 10)
  11855. (nshift 0))
  11856. (while (or (= nshift 0)
  11857. (not (time-less-p (current-time) time)))
  11858. (when (= (cl-incf nshift) nshiftmax)
  11859. (or (y-or-n-p
  11860. (format "%d repeater intervals were not \
  11861. enough to shift date past today. Continue? "
  11862. nshift))
  11863. (user-error "Abort")))
  11864. (org-timestamp-change n (cdr (assoc what whata)))
  11865. (org-in-regexp org-ts-regexp3)
  11866. (setq ts (match-string 1))
  11867. (setq time
  11868. (save-match-data
  11869. (org-time-string-to-time ts)))))
  11870. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11871. ;; Rematch, so that we have everything in place
  11872. ;; for the real shift.
  11873. (org-in-regexp org-ts-regexp3)
  11874. (setq ts (match-string 1))
  11875. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11876. ts)))))
  11877. (save-excursion
  11878. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11879. (setq msg
  11880. (concat
  11881. msg type " " org-last-changed-timestamp " "))))))))
  11882. (setq org-log-post-message msg)
  11883. (message "%s" msg))
  11884. (set-marker end nil))))
  11885. (defun org-show-todo-tree (arg)
  11886. "Make a compact tree which shows all headlines marked with TODO.
  11887. The tree will show the lines where the regexp matches, and all higher
  11888. headlines above the match.
  11889. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11890. With a numeric prefix N, construct a sparse tree for the Nth element
  11891. of `org-todo-keywords-1'."
  11892. (interactive "P")
  11893. (let ((case-fold-search nil)
  11894. (kwd-re
  11895. (cond ((null arg) org-not-done-regexp)
  11896. ((equal arg '(4))
  11897. (let ((kwd
  11898. (completing-read "Keyword (or KWD1|KWD2|...): "
  11899. (mapcar #'list org-todo-keywords-1))))
  11900. (concat "\\("
  11901. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11902. "\\)\\>")))
  11903. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11904. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11905. org-todo-keywords-1)))
  11906. (t (user-error "Invalid prefix argument: %s" arg)))))
  11907. (message "%d TODO entries found"
  11908. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11909. (defun org--deadline-or-schedule (arg type time)
  11910. "Insert DEADLINE or SCHEDULE information in current entry.
  11911. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11912. `org-schedule' for information about ARG and TIME arguments."
  11913. (let* ((deadline? (eq type 'deadline))
  11914. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11915. (log (if deadline? org-log-redeadline org-log-reschedule))
  11916. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11917. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11918. ;; Save repeater cookie from either TIME or current scheduled
  11919. ;; time stamp. We are going to insert it back at the end of
  11920. ;; the process.
  11921. (repeater (or (and (org-string-nw-p time)
  11922. ;; We use `org-repeat-re' because we need
  11923. ;; to tell the difference between a real
  11924. ;; repeater and a time delta, e.g. "+2d".
  11925. (string-match org-repeat-re time)
  11926. (match-string 1 time))
  11927. (and (org-string-nw-p old-date)
  11928. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11929. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11930. old-date)
  11931. (match-string 1 old-date)))))
  11932. (pcase arg
  11933. (`(4)
  11934. (when (and old-date log)
  11935. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11936. nil old-date log))
  11937. (org-remove-timestamp-with-keyword keyword)
  11938. (message (if deadline? "Item no longer has a deadline."
  11939. "Item is no longer scheduled.")))
  11940. (`(16)
  11941. (save-excursion
  11942. (org-back-to-heading t)
  11943. (let ((regexp (if deadline? org-deadline-time-regexp
  11944. org-scheduled-time-regexp)))
  11945. (if (not (re-search-forward regexp (line-end-position 2) t))
  11946. (user-error (if deadline? "No deadline information to update"
  11947. "No scheduled information to update"))
  11948. (let* ((rpl0 (match-string 1))
  11949. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11950. (msg (if deadline? "Warn starting from" "Delay until")))
  11951. (replace-match
  11952. (concat keyword
  11953. " <" rpl
  11954. (format " -%dd"
  11955. (abs (- (time-to-days
  11956. (save-match-data
  11957. (org-read-date
  11958. nil t nil msg old-date-time)))
  11959. (time-to-days old-date-time))))
  11960. ">") t t))))))
  11961. (_
  11962. (org-add-planning-info type time 'closed)
  11963. (when (and old-date
  11964. log
  11965. (not (equal old-date org-last-inserted-timestamp)))
  11966. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11967. org-last-inserted-timestamp
  11968. old-date
  11969. log))
  11970. (when repeater
  11971. (save-excursion
  11972. (org-back-to-heading t)
  11973. (when (re-search-forward
  11974. (concat keyword " " org-last-inserted-timestamp)
  11975. (line-end-position 2)
  11976. t)
  11977. (goto-char (1- (match-end 0)))
  11978. (insert " " repeater)
  11979. (setq org-last-inserted-timestamp
  11980. (concat (substring org-last-inserted-timestamp 0 -1)
  11981. " " repeater
  11982. (substring org-last-inserted-timestamp -1))))))
  11983. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11984. org-last-inserted-timestamp)))))
  11985. (defun org-deadline (arg &optional time)
  11986. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11987. With one universal prefix argument, remove any deadline from the item.
  11988. With two universal prefix arguments, prompt for a warning delay.
  11989. With argument TIME, set the deadline at the corresponding date. TIME
  11990. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11991. (interactive "P")
  11992. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11993. (org-map-entries
  11994. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11995. nil
  11996. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11997. 'region-start-level
  11998. 'region)
  11999. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12000. (org--deadline-or-schedule arg 'deadline time)))
  12001. (defun org-schedule (arg &optional time)
  12002. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12003. With one universal prefix argument, remove any scheduling date from the item.
  12004. With two universal prefix arguments, prompt for a delay cookie.
  12005. With argument TIME, scheduled at the corresponding date. TIME can
  12006. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12007. (interactive "P")
  12008. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12009. (org-map-entries
  12010. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12011. nil
  12012. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12013. 'region-start-level
  12014. 'region)
  12015. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12016. (org--deadline-or-schedule arg 'scheduled time)))
  12017. (defun org-get-scheduled-time (pom &optional inherit)
  12018. "Get the scheduled time as a time tuple, of a format suitable
  12019. for calling org-schedule with, or if there is no scheduling,
  12020. returns nil."
  12021. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12022. (when time
  12023. (apply 'encode-time (org-parse-time-string time)))))
  12024. (defun org-get-deadline-time (pom &optional inherit)
  12025. "Get the deadline as a time tuple, of a format suitable for
  12026. calling org-deadline with, or if there is no scheduling, returns
  12027. nil."
  12028. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12029. (when time
  12030. (apply 'encode-time (org-parse-time-string time)))))
  12031. (defun org-remove-timestamp-with-keyword (keyword)
  12032. "Remove all time stamps with KEYWORD in the current entry."
  12033. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12034. beg)
  12035. (save-excursion
  12036. (org-back-to-heading t)
  12037. (setq beg (point))
  12038. (outline-next-heading)
  12039. (while (re-search-backward re beg t)
  12040. (replace-match "")
  12041. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12042. (equal (char-before) ?\ ))
  12043. (backward-delete-char 1)
  12044. (when (string-match "^[ \t]*$" (buffer-substring
  12045. (point-at-bol) (point-at-eol)))
  12046. (delete-region (point-at-bol)
  12047. (min (point-max) (1+ (point-at-eol))))))))))
  12048. (defvar org-time-was-given) ; dynamically scoped parameter
  12049. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12050. (defun org-at-planning-p ()
  12051. "Non-nil when point is on a planning info line."
  12052. ;; This is as accurate and faster than `org-element-at-point' since
  12053. ;; planning info location is fixed in the section.
  12054. (org-with-wide-buffer
  12055. (beginning-of-line)
  12056. (and (looking-at-p org-planning-line-re)
  12057. (eq (point)
  12058. (ignore-errors
  12059. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12060. (org-back-to-heading t)
  12061. (org-with-limited-levels (org-back-to-heading t)))
  12062. (line-beginning-position 2))))))
  12063. (defun org-add-planning-info (what &optional time &rest remove)
  12064. "Insert new timestamp with keyword in the planning line.
  12065. WHAT indicates what kind of time stamp to add. It is a symbol
  12066. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12067. the time to use. If none is given, the user is prompted for
  12068. a date. REMOVE indicates what kind of entries to remove. An old
  12069. WHAT entry will also be removed."
  12070. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12071. (catch 'exit
  12072. (when (and (memq what '(scheduled deadline))
  12073. (or (not time)
  12074. (and (stringp time)
  12075. (string-match "^[-+]+[0-9]" time))))
  12076. ;; Try to get a default date/time from existing timestamp
  12077. (save-excursion
  12078. (org-back-to-heading t)
  12079. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12080. (when (re-search-forward (if (eq what 'scheduled)
  12081. org-scheduled-time-regexp
  12082. org-deadline-time-regexp)
  12083. end t)
  12084. (setq ts (match-string 1)
  12085. default-time (apply 'encode-time (org-parse-time-string ts))
  12086. default-input (and ts (org-get-compact-tod ts)))))))
  12087. (when what
  12088. (setq time
  12089. (if (stringp time)
  12090. ;; This is a string (relative or absolute), set
  12091. ;; proper date.
  12092. (apply #'encode-time
  12093. (org-read-date-analyze
  12094. time default-time (decode-time default-time)))
  12095. ;; If necessary, get the time from the user
  12096. (or time (org-read-date nil 'to-time nil nil
  12097. default-time default-input)))))
  12098. (org-with-wide-buffer
  12099. (org-back-to-heading t)
  12100. (forward-line)
  12101. (unless (bolp) (insert "\n"))
  12102. (cond ((looking-at-p org-planning-line-re)
  12103. ;; Move to current indentation.
  12104. (skip-chars-forward " \t")
  12105. ;; Check if we have to remove something.
  12106. (dolist (type (if what (cons what remove) remove))
  12107. (save-excursion
  12108. (when (re-search-forward
  12109. (cl-case type
  12110. (closed org-closed-time-regexp)
  12111. (deadline org-deadline-time-regexp)
  12112. (scheduled org-scheduled-time-regexp)
  12113. (otherwise
  12114. (error "Invalid planning type: %s" type)))
  12115. (line-end-position) t)
  12116. ;; Delete until next keyword or end of line.
  12117. (delete-region
  12118. (match-beginning 0)
  12119. (if (re-search-forward org-keyword-time-not-clock-regexp
  12120. (line-end-position)
  12121. t)
  12122. (match-beginning 0)
  12123. (line-end-position))))))
  12124. ;; If there is nothing more to add and no more keyword
  12125. ;; is left, remove the line completely.
  12126. (if (and (looking-at-p "[ \t]*$") (not what))
  12127. (delete-region (line-beginning-position)
  12128. (line-beginning-position 2))
  12129. ;; If we removed last keyword, do not leave trailing
  12130. ;; white space at the end of line.
  12131. (let ((p (point)))
  12132. (save-excursion
  12133. (end-of-line)
  12134. (unless (= (skip-chars-backward " \t" p) 0)
  12135. (delete-region (point) (line-end-position)))))))
  12136. ((not what) (throw 'exit nil)) ; Nothing to do.
  12137. (t (insert-before-markers "\n")
  12138. (backward-char 1)
  12139. (when org-adapt-indentation
  12140. (indent-to-column (1+ (org-outline-level))))))
  12141. (when what
  12142. ;; Insert planning keyword.
  12143. (insert (cl-case what
  12144. (closed org-closed-string)
  12145. (deadline org-deadline-string)
  12146. (scheduled org-scheduled-string)
  12147. (otherwise (error "Invalid planning type: %s" what)))
  12148. " ")
  12149. ;; Insert associated timestamp.
  12150. (let ((ts (org-insert-time-stamp
  12151. time
  12152. (or org-time-was-given
  12153. (and (eq what 'closed) org-log-done-with-time))
  12154. (eq what 'closed)
  12155. nil nil (list org-end-time-was-given))))
  12156. (unless (eolp) (insert " "))
  12157. ts))))))
  12158. (defvar org-log-note-marker (make-marker)
  12159. "Marker pointing at the entry where the note is to be inserted.")
  12160. (defvar org-log-note-purpose nil)
  12161. (defvar org-log-note-state nil)
  12162. (defvar org-log-note-previous-state nil)
  12163. (defvar org-log-note-extra nil)
  12164. (defvar org-log-note-window-configuration nil)
  12165. (defvar org-log-note-return-to (make-marker))
  12166. (defvar org-log-note-effective-time nil
  12167. "Remembered current time so that dynamically scoped
  12168. `org-extend-today-until' affects timestamps in state change log")
  12169. (defvar org-log-post-message nil
  12170. "Message to be displayed after a log note has been stored.
  12171. The auto-repeater uses this.")
  12172. (defun org-add-note ()
  12173. "Add a note to the current entry.
  12174. This is done in the same way as adding a state change note."
  12175. (interactive)
  12176. (org-add-log-setup 'note))
  12177. (defun org-log-beginning (&optional create)
  12178. "Return expected start of log notes in current entry.
  12179. When optional argument CREATE is non-nil, the function creates
  12180. a drawer to store notes, if necessary. Returned position ignores
  12181. narrowing."
  12182. (org-with-wide-buffer
  12183. (let ((drawer (org-log-into-drawer)))
  12184. (cond
  12185. (drawer
  12186. (org-end-of-meta-data)
  12187. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12188. (end (if (org-at-heading-p) (point)
  12189. (save-excursion (outline-next-heading) (point))))
  12190. (case-fold-search t))
  12191. (catch 'exit
  12192. ;; Try to find existing drawer.
  12193. (while (re-search-forward regexp end t)
  12194. (let ((element (org-element-at-point)))
  12195. (when (eq (org-element-type element) 'drawer)
  12196. (let ((cend (org-element-property :contents-end element)))
  12197. (when (and (not org-log-states-order-reversed) cend)
  12198. (goto-char cend)))
  12199. (throw 'exit nil))))
  12200. ;; No drawer found. Create one, if permitted.
  12201. (when create
  12202. (unless (bolp) (insert "\n"))
  12203. (let ((beg (point)))
  12204. (insert ":" drawer ":\n:END:\n")
  12205. (org-indent-region beg (point)))
  12206. (end-of-line -1)))))
  12207. (t
  12208. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12209. (skip-chars-forward " \t\n")
  12210. (beginning-of-line)
  12211. (unless org-log-states-order-reversed
  12212. (org-skip-over-state-notes)
  12213. (skip-chars-backward " \t\n")
  12214. (forward-line)))))
  12215. (if (bolp) (point) (line-beginning-position 2))))
  12216. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12217. "Set up the post command hook to take a note.
  12218. If this is about to TODO state change, the new state is expected in STATE.
  12219. HOW is an indicator what kind of note should be created.
  12220. EXTRA is additional text that will be inserted into the notes buffer."
  12221. (move-marker org-log-note-marker (point))
  12222. (setq org-log-note-purpose purpose
  12223. org-log-note-state state
  12224. org-log-note-previous-state prev-state
  12225. org-log-note-how how
  12226. org-log-note-extra extra
  12227. org-log-note-effective-time (org-current-effective-time))
  12228. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12229. (defun org-skip-over-state-notes ()
  12230. "Skip past the list of State notes in an entry."
  12231. (when (ignore-errors (goto-char (org-in-item-p)))
  12232. (let* ((struct (org-list-struct))
  12233. (prevs (org-list-prevs-alist struct))
  12234. (regexp
  12235. (concat "[ \t]*- +"
  12236. (replace-regexp-in-string
  12237. " +" " +"
  12238. (org-replace-escapes
  12239. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12240. `(("%d" . ,org-ts-regexp-inactive)
  12241. ("%D" . ,org-ts-regexp)
  12242. ("%s" . "\"\\S-+\"")
  12243. ("%S" . "\"\\S-+\"")
  12244. ("%t" . ,org-ts-regexp-inactive)
  12245. ("%T" . ,org-ts-regexp)
  12246. ("%u" . ".*?")
  12247. ("%U" . ".*?")))))))
  12248. (while (looking-at-p regexp)
  12249. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12250. (org-list-get-item-end (point) struct)))))))
  12251. (defun org-add-log-note (&optional _purpose)
  12252. "Pop up a window for taking a note, and add this note later."
  12253. (remove-hook 'post-command-hook 'org-add-log-note)
  12254. (setq org-log-note-window-configuration (current-window-configuration))
  12255. (delete-other-windows)
  12256. (move-marker org-log-note-return-to (point))
  12257. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12258. (goto-char org-log-note-marker)
  12259. (org-switch-to-buffer-other-window "*Org Note*")
  12260. (erase-buffer)
  12261. (if (memq org-log-note-how '(time state))
  12262. (org-store-log-note)
  12263. (let ((org-inhibit-startup t)) (org-mode))
  12264. (insert (format "# Insert note for %s.
  12265. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12266. (cond
  12267. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12268. ((eq org-log-note-purpose 'done) "closed todo item")
  12269. ((eq org-log-note-purpose 'state)
  12270. (format "state change from \"%s\" to \"%s\""
  12271. (or org-log-note-previous-state "")
  12272. (or org-log-note-state "")))
  12273. ((eq org-log-note-purpose 'reschedule)
  12274. "rescheduling")
  12275. ((eq org-log-note-purpose 'delschedule)
  12276. "no longer scheduled")
  12277. ((eq org-log-note-purpose 'redeadline)
  12278. "changing deadline")
  12279. ((eq org-log-note-purpose 'deldeadline)
  12280. "removing deadline")
  12281. ((eq org-log-note-purpose 'refile)
  12282. "refiling")
  12283. ((eq org-log-note-purpose 'note)
  12284. "this entry")
  12285. (t (error "This should not happen")))))
  12286. (when org-log-note-extra (insert org-log-note-extra))
  12287. (setq-local org-finish-function 'org-store-log-note)
  12288. (run-hooks 'org-log-buffer-setup-hook)))
  12289. (defvar org-note-abort nil) ; dynamically scoped
  12290. (defun org-store-log-note ()
  12291. "Finish taking a log note, and insert it to where it belongs."
  12292. (let ((txt (prog1 (buffer-string)
  12293. (kill-buffer)))
  12294. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12295. lines)
  12296. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12297. (setq txt (replace-match "" t t txt)))
  12298. (when (string-match "\\s-+\\'" txt)
  12299. (setq txt (replace-match "" t t txt)))
  12300. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12301. (when (org-string-nw-p note)
  12302. (setq note
  12303. (org-replace-escapes
  12304. note
  12305. (list (cons "%u" (user-login-name))
  12306. (cons "%U" user-full-name)
  12307. (cons "%t" (format-time-string
  12308. (org-time-stamp-format 'long 'inactive)
  12309. org-log-note-effective-time))
  12310. (cons "%T" (format-time-string
  12311. (org-time-stamp-format 'long nil)
  12312. org-log-note-effective-time))
  12313. (cons "%d" (format-time-string
  12314. (org-time-stamp-format nil 'inactive)
  12315. org-log-note-effective-time))
  12316. (cons "%D" (format-time-string
  12317. (org-time-stamp-format nil nil)
  12318. org-log-note-effective-time))
  12319. (cons "%s" (cond
  12320. ((not org-log-note-state) "")
  12321. ((string-match-p org-ts-regexp
  12322. org-log-note-state)
  12323. (format "\"[%s]\""
  12324. (substring org-log-note-state 1 -1)))
  12325. (t (format "\"%s\"" org-log-note-state))))
  12326. (cons "%S"
  12327. (cond
  12328. ((not org-log-note-previous-state) "")
  12329. ((string-match-p org-ts-regexp
  12330. org-log-note-previous-state)
  12331. (format "\"[%s]\""
  12332. (substring
  12333. org-log-note-previous-state 1 -1)))
  12334. (t (format "\"%s\""
  12335. org-log-note-previous-state)))))))
  12336. (when lines (setq note (concat note " \\\\")))
  12337. (push note lines))
  12338. (when (and lines (not org-note-abort))
  12339. (with-current-buffer (marker-buffer org-log-note-marker)
  12340. (org-with-wide-buffer
  12341. ;; Find location for the new note.
  12342. (goto-char org-log-note-marker)
  12343. (set-marker org-log-note-marker nil)
  12344. ;; Note associated to a clock is to be located right after
  12345. ;; the clock. Do not move point.
  12346. (unless (eq org-log-note-purpose 'clock-out)
  12347. (goto-char (org-log-beginning t)))
  12348. ;; Make sure point is at the beginning of an empty line.
  12349. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12350. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12351. ;; In an existing list, add a new item at the top level.
  12352. ;; Otherwise, indent line like a regular one.
  12353. (let ((itemp (org-in-item-p)))
  12354. (if itemp
  12355. (indent-line-to
  12356. (let ((struct (save-excursion
  12357. (goto-char itemp) (org-list-struct))))
  12358. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12359. (org-indent-line)))
  12360. (insert (org-list-bullet-string "-") (pop lines))
  12361. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12362. (dolist (line lines)
  12363. (insert "\n")
  12364. (indent-line-to ind)
  12365. (insert line)))
  12366. (message "Note stored")
  12367. (org-back-to-heading t)
  12368. (org-cycle-hide-drawers 'children))
  12369. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12370. ;; from within `org-add-log-note' because `buffer-undo-list'
  12371. ;; is then modified outside of `org-with-remote-undo'.
  12372. (when (eq this-command 'org-agenda-todo)
  12373. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12374. ;; Don't add undo information when called from `org-agenda-todo'.
  12375. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12376. (set-window-configuration org-log-note-window-configuration)
  12377. (with-current-buffer (marker-buffer org-log-note-return-to)
  12378. (goto-char org-log-note-return-to))
  12379. (move-marker org-log-note-return-to nil)
  12380. (when org-log-post-message (message "%s" org-log-post-message))))
  12381. (defun org-remove-empty-drawer-at (pos)
  12382. "Remove an empty drawer at position POS.
  12383. POS may also be a marker."
  12384. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12385. (org-with-wide-buffer
  12386. (goto-char pos)
  12387. (let ((drawer (org-element-at-point)))
  12388. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12389. (not (org-element-property :contents-begin drawer)))
  12390. (delete-region (org-element-property :begin drawer)
  12391. (progn (goto-char (org-element-property :end drawer))
  12392. (skip-chars-backward " \r\t\n")
  12393. (forward-line)
  12394. (point))))))))
  12395. (defvar org-ts-type nil)
  12396. (defun org-sparse-tree (&optional arg type)
  12397. "Create a sparse tree, prompt for the details.
  12398. This command can create sparse trees. You first need to select the type
  12399. of match used to create the tree:
  12400. t Show all TODO entries.
  12401. T Show entries with a specific TODO keyword.
  12402. m Show entries selected by a tags/property match.
  12403. p Enter a property name and its value (both with completion on existing
  12404. names/values) and show entries with that property.
  12405. r Show entries matching a regular expression (`/' can be used as well).
  12406. b Show deadlines and scheduled items before a date.
  12407. a Show deadlines and scheduled items after a date.
  12408. d Show deadlines due within `org-deadline-warning-days'.
  12409. D Show deadlines and scheduled items between a date range."
  12410. (interactive "P")
  12411. (setq type (or type org-sparse-tree-default-date-type))
  12412. (setq org-ts-type type)
  12413. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12414. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12415. \[c]ycle through date types: %s"
  12416. (cl-case type
  12417. (all "all timestamps")
  12418. (scheduled "only scheduled")
  12419. (deadline "only deadline")
  12420. (active "only active timestamps")
  12421. (inactive "only inactive timestamps")
  12422. (closed "with a closed time-stamp")
  12423. (otherwise "scheduled/deadline")))
  12424. (let ((answer (read-char-exclusive)))
  12425. (cl-case answer
  12426. (?c
  12427. (org-sparse-tree
  12428. arg
  12429. (cadr
  12430. (memq type '(nil all scheduled deadline active inactive closed)))))
  12431. (?d (call-interactively 'org-check-deadlines))
  12432. (?b (call-interactively 'org-check-before-date))
  12433. (?a (call-interactively 'org-check-after-date))
  12434. (?D (call-interactively 'org-check-dates-range))
  12435. (?t (call-interactively 'org-show-todo-tree))
  12436. (?T (org-show-todo-tree '(4)))
  12437. (?m (call-interactively 'org-match-sparse-tree))
  12438. ((?p ?P)
  12439. (let* ((kwd (completing-read
  12440. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12441. (value (completing-read
  12442. "Value: " (mapcar #'list (org-property-values kwd)))))
  12443. (unless (string-match "\\`{.*}\\'" value)
  12444. (setq value (concat "\"" value "\"")))
  12445. (org-match-sparse-tree arg (concat kwd "=" value))))
  12446. ((?r ?R ?/) (call-interactively 'org-occur))
  12447. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12448. (defvar-local org-occur-highlights nil
  12449. "List of overlays used for occur matches.")
  12450. (defvar-local org-occur-parameters nil
  12451. "Parameters of the active org-occur calls.
  12452. This is a list, each call to org-occur pushes as cons cell,
  12453. containing the regular expression and the callback, onto the list.
  12454. The list can contain several entries if `org-occur' has been called
  12455. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12456. will only contain one set of parameters. When the highlights are
  12457. removed (for example with `C-c C-c', or with the next edit (depending
  12458. on `org-remove-highlights-with-change'), this variable is emptied
  12459. as well.")
  12460. (defun org-occur (regexp &optional keep-previous callback)
  12461. "Make a compact tree which shows all matches of REGEXP.
  12462. The tree will show the lines where the regexp matches, and any other context
  12463. defined in `org-show-context-detail', which see.
  12464. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12465. done by a previous call to `org-occur' will be kept, to allow stacking of
  12466. calls to this command.
  12467. Optional argument CALLBACK can be a function of no argument. In this case,
  12468. it is called with point at the end of the match, match data being set
  12469. accordingly. Current match is shown only if the return value is non-nil.
  12470. The function must neither move point nor alter narrowing."
  12471. (interactive "sRegexp: \nP")
  12472. (when (equal regexp "")
  12473. (user-error "Regexp cannot be empty"))
  12474. (unless keep-previous
  12475. (org-remove-occur-highlights nil nil t))
  12476. (push (cons regexp callback) org-occur-parameters)
  12477. (let ((cnt 0))
  12478. (save-excursion
  12479. (goto-char (point-min))
  12480. (when (or (not keep-previous) ; do not want to keep
  12481. (not org-occur-highlights)) ; no previous matches
  12482. ;; hide everything
  12483. (org-overview))
  12484. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12485. (isearch-no-upper-case-p regexp t)
  12486. org-occur-case-fold-search)))
  12487. (while (re-search-forward regexp nil t)
  12488. (when (or (not callback)
  12489. (save-match-data (funcall callback)))
  12490. (setq cnt (1+ cnt))
  12491. (when org-highlight-sparse-tree-matches
  12492. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12493. (org-show-context 'occur-tree)))))
  12494. (when org-remove-highlights-with-change
  12495. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12496. nil 'local))
  12497. (unless org-sparse-tree-open-archived-trees
  12498. (org-hide-archived-subtrees (point-min) (point-max)))
  12499. (run-hooks 'org-occur-hook)
  12500. (when (called-interactively-p 'interactive)
  12501. (message "%d match(es) for regexp %s" cnt regexp))
  12502. cnt))
  12503. (defun org-occur-next-match (&optional n _reset)
  12504. "Function for `next-error-function' to find sparse tree matches.
  12505. N is the number of matches to move, when negative move backwards.
  12506. This function always goes back to the starting point when no
  12507. match is found."
  12508. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12509. (search-func (if (< n 0)
  12510. 'previous-single-char-property-change
  12511. 'next-single-char-property-change))
  12512. (n (abs n))
  12513. (pos (point))
  12514. p1)
  12515. (catch 'exit
  12516. (while (setq p1 (funcall search-func (point) 'org-type))
  12517. (when (equal p1 limit)
  12518. (goto-char pos)
  12519. (user-error "No more matches"))
  12520. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12521. (setq n (1- n))
  12522. (when (= n 0)
  12523. (goto-char p1)
  12524. (throw 'exit (point))))
  12525. (goto-char p1))
  12526. (goto-char p1)
  12527. (user-error "No more matches"))))
  12528. (defun org-show-context (&optional key)
  12529. "Make sure point and context are visible.
  12530. Optional argument KEY, when non-nil, is a symbol. See
  12531. `org-show-context-detail' for allowed values and how much is to
  12532. be shown."
  12533. (org-show-set-visibility
  12534. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12535. ((cdr (assq key org-show-context-detail)))
  12536. (t (cdr (assq 'default org-show-context-detail))))))
  12537. (defun org-show-set-visibility (detail)
  12538. "Set visibility around point according to DETAIL.
  12539. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12540. `tree', `canonical' or t. See `org-show-context-detail' for more
  12541. information."
  12542. ;; Show current heading and possibly its entry, following headline
  12543. ;; or all children.
  12544. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12545. (org-flag-heading nil)
  12546. (org-show-entry)
  12547. ;; If point is hidden within a drawer or a block, make sure to
  12548. ;; expose it.
  12549. (dolist (o (overlays-at (point)))
  12550. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12551. (delete-overlay o)))
  12552. (unless (org-before-first-heading-p)
  12553. (org-with-limited-levels
  12554. (cl-case detail
  12555. ((tree canonical t) (org-show-children))
  12556. ((nil minimal ancestors))
  12557. (t (save-excursion
  12558. (outline-next-heading)
  12559. (org-flag-heading nil)))))))
  12560. ;; Show all siblings.
  12561. (when (eq detail 'lineage) (org-show-siblings))
  12562. ;; Show ancestors, possibly with their children.
  12563. (when (memq detail '(ancestors lineage tree canonical t))
  12564. (save-excursion
  12565. (while (org-up-heading-safe)
  12566. (org-flag-heading nil)
  12567. (when (memq detail '(canonical t)) (org-show-entry))
  12568. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12569. (defvar org-reveal-start-hook nil
  12570. "Hook run before revealing a location.")
  12571. (defun org-reveal (&optional siblings)
  12572. "Show current entry, hierarchy above it, and the following headline.
  12573. This can be used to show a consistent set of context around
  12574. locations exposed with `org-show-context'.
  12575. With optional argument SIBLINGS, on each level of the hierarchy all
  12576. siblings are shown. This repairs the tree structure to what it would
  12577. look like when opened with hierarchical calls to `org-cycle'.
  12578. With a \\[universal-argument] \\[universal-argument] prefix, \
  12579. go to the parent and show the entire tree."
  12580. (interactive "P")
  12581. (run-hooks 'org-reveal-start-hook)
  12582. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12583. ((equal siblings '(16))
  12584. (save-excursion
  12585. (when (org-up-heading-safe)
  12586. (org-show-subtree)
  12587. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12588. (t (org-show-set-visibility 'lineage))))
  12589. (defun org-highlight-new-match (beg end)
  12590. "Highlight from BEG to END and mark the highlight is an occur headline."
  12591. (let ((ov (make-overlay beg end)))
  12592. (overlay-put ov 'face 'secondary-selection)
  12593. (overlay-put ov 'org-type 'org-occur)
  12594. (push ov org-occur-highlights)))
  12595. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12596. "Remove the occur highlights from the buffer.
  12597. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12598. from the `before-change-functions' in the current buffer."
  12599. (interactive)
  12600. (unless org-inhibit-highlight-removal
  12601. (mapc #'delete-overlay org-occur-highlights)
  12602. (setq org-occur-highlights nil)
  12603. (setq org-occur-parameters nil)
  12604. (unless noremove
  12605. (remove-hook 'before-change-functions
  12606. 'org-remove-occur-highlights 'local))))
  12607. ;;;; Priorities
  12608. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12609. "Regular expression matching the priority indicator.")
  12610. (defvar org-remove-priority-next-time nil)
  12611. (defun org-priority-up ()
  12612. "Increase the priority of the current item."
  12613. (interactive)
  12614. (org-priority 'up))
  12615. (defun org-priority-down ()
  12616. "Decrease the priority of the current item."
  12617. (interactive)
  12618. (org-priority 'down))
  12619. (defun org-priority (&optional action _show)
  12620. "Change the priority of an item.
  12621. ACTION can be `set', `up', `down', or a character."
  12622. (interactive "P")
  12623. (if (equal action '(4))
  12624. (org-show-priority)
  12625. (unless org-enable-priority-commands
  12626. (user-error "Priority commands are disabled"))
  12627. (setq action (or action 'set))
  12628. (let (current new news have remove)
  12629. (save-excursion
  12630. (org-back-to-heading t)
  12631. (when (looking-at org-priority-regexp)
  12632. (setq current (string-to-char (match-string 2))
  12633. have t))
  12634. (cond
  12635. ((eq action 'remove)
  12636. (setq remove t new ?\ ))
  12637. ((or (eq action 'set)
  12638. (integerp action))
  12639. (if (not (eq action 'set))
  12640. (setq new action)
  12641. (message "Priority %c-%c, SPC to remove: "
  12642. org-highest-priority org-lowest-priority)
  12643. (save-match-data
  12644. (setq new (read-char-exclusive))))
  12645. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12646. (= (upcase org-lowest-priority) org-lowest-priority))
  12647. (setq new (upcase new)))
  12648. (cond ((equal new ?\ ) (setq remove t))
  12649. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12650. (user-error "Priority must be between `%c' and `%c'"
  12651. org-highest-priority org-lowest-priority))))
  12652. ((eq action 'up)
  12653. (setq new (if have
  12654. (1- current) ; normal cycling
  12655. ;; last priority was empty
  12656. (if (eq last-command this-command)
  12657. org-lowest-priority ; wrap around empty to lowest
  12658. ;; default
  12659. (if org-priority-start-cycle-with-default
  12660. org-default-priority
  12661. (1- org-default-priority))))))
  12662. ((eq action 'down)
  12663. (setq new (if have
  12664. (1+ current) ; normal cycling
  12665. ;; last priority was empty
  12666. (if (eq last-command this-command)
  12667. org-highest-priority ; wrap around empty to highest
  12668. ;; default
  12669. (if org-priority-start-cycle-with-default
  12670. org-default-priority
  12671. (1+ org-default-priority))))))
  12672. (t (user-error "Invalid action")))
  12673. (when (or (< (upcase new) org-highest-priority)
  12674. (> (upcase new) org-lowest-priority))
  12675. (if (and (memq action '(up down))
  12676. (not have) (not (eq last-command this-command)))
  12677. ;; `new' is from default priority
  12678. (error
  12679. "The default can not be set, see `org-default-priority' why")
  12680. ;; normal cycling: `new' is beyond highest/lowest priority
  12681. ;; and is wrapped around to the empty priority
  12682. (setq remove t)))
  12683. (setq news (format "%c" new))
  12684. (if have
  12685. (if remove
  12686. (replace-match "" t t nil 1)
  12687. (replace-match news t t nil 2))
  12688. (if remove
  12689. (user-error "No priority cookie found in line")
  12690. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12691. (if (match-end 2)
  12692. (progn
  12693. (goto-char (match-end 2))
  12694. (insert " [#" news "]"))
  12695. (goto-char (match-beginning 3))
  12696. (insert "[#" news "] "))))
  12697. (org-set-tags nil 'align))
  12698. (if remove
  12699. (message "Priority removed")
  12700. (message "Priority of current item set to %s" news)))))
  12701. (defun org-show-priority ()
  12702. "Show the priority of the current item.
  12703. This priority is composed of the main priority given with the [#A] cookies,
  12704. and by additional input from the age of a schedules or deadline entry."
  12705. (interactive)
  12706. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12707. (org-get-at-bol 'priority)
  12708. (save-excursion
  12709. (save-match-data
  12710. (beginning-of-line)
  12711. (and (looking-at org-heading-regexp)
  12712. (org-get-priority (match-string 0))))))))
  12713. (message "Priority is %d" (if pri pri -1000))))
  12714. (defun org-get-priority (s)
  12715. "Find priority cookie and return priority."
  12716. (save-match-data
  12717. (if (functionp org-get-priority-function)
  12718. (funcall org-get-priority-function)
  12719. (if (not (string-match org-priority-regexp s))
  12720. (* 1000 (- org-lowest-priority org-default-priority))
  12721. (* 1000 (- org-lowest-priority
  12722. (string-to-char (match-string 2 s))))))))
  12723. ;;;; Tags
  12724. (defvar org-agenda-archives-mode)
  12725. (defvar org-map-continue-from nil
  12726. "Position from where mapping should continue.
  12727. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12728. (defvar org-scanner-tags nil
  12729. "The current tag list while the tags scanner is running.")
  12730. (defvar org-trust-scanner-tags nil
  12731. "Should `org-get-tags-at' use the tags for the scanner.
  12732. This is for internal dynamical scoping only.
  12733. When this is non-nil, the function `org-get-tags-at' will return the value
  12734. of `org-scanner-tags' instead of building the list by itself. This
  12735. can lead to large speed-ups when the tags scanner is used in a file with
  12736. many entries, and when the list of tags is retrieved, for example to
  12737. obtain a list of properties. Building the tags list for each entry in such
  12738. a file becomes an N^2 operation - but with this variable set, it scales
  12739. as N.")
  12740. (defvar org--matcher-tags-todo-only nil)
  12741. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12742. "Scan headline tags with inheritance and produce output ACTION.
  12743. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12744. or `agenda' to produce an entry list for an agenda view. It can also be
  12745. a Lisp form or a function that should be called at each matched headline, in
  12746. this case the return value is a list of all return values from these calls.
  12747. MATCHER is a function accepting three arguments, returning
  12748. a non-nil value whenever a given set of tags qualifies a headline
  12749. for inclusion. See `org-make-tags-matcher' for more information.
  12750. As a special case, it can also be set to t (respectively nil) in
  12751. order to match all (respectively none) headline.
  12752. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12753. included in the output.
  12754. START-LEVEL can be a string with asterisks, reducing the scope to
  12755. headlines matching this string."
  12756. (require 'org-agenda)
  12757. (let* ((re (concat "^"
  12758. (if start-level
  12759. ;; Get the correct level to match
  12760. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12761. org-outline-regexp)
  12762. " *\\(\\<\\("
  12763. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12764. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12765. (props (list 'face 'default
  12766. 'done-face 'org-agenda-done
  12767. 'undone-face 'default
  12768. 'mouse-face 'highlight
  12769. 'org-not-done-regexp org-not-done-regexp
  12770. 'org-todo-regexp org-todo-regexp
  12771. 'org-complex-heading-regexp org-complex-heading-regexp
  12772. 'help-echo
  12773. (format "mouse-2 or RET jump to org file %s"
  12774. (abbreviate-file-name
  12775. (or (buffer-file-name (buffer-base-buffer))
  12776. (buffer-name (buffer-base-buffer)))))))
  12777. (org-map-continue-from nil)
  12778. lspos tags tags-list
  12779. (tags-alist (list (cons 0 org-file-tags)))
  12780. (llast 0) rtn rtn1 level category i txt
  12781. todo marker entry priority
  12782. ts-date ts-date-type ts-date-pair)
  12783. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12784. (setq action (list 'lambda nil action)))
  12785. (save-excursion
  12786. (goto-char (point-min))
  12787. (when (eq action 'sparse-tree)
  12788. (org-overview)
  12789. (org-remove-occur-highlights))
  12790. (while (let (case-fold-search)
  12791. (re-search-forward re nil t))
  12792. (setq org-map-continue-from nil)
  12793. (catch :skip
  12794. (setq todo
  12795. ;; TODO: is the 1-2 difference a bug?
  12796. (when (match-end 1) (match-string-no-properties 2))
  12797. tags (when (match-end 4) (match-string-no-properties 4)))
  12798. (goto-char (setq lspos (match-beginning 0)))
  12799. (setq level (org-reduced-level (org-outline-level))
  12800. category (org-get-category))
  12801. (when (eq action 'agenda)
  12802. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12803. ts-date (car ts-date-pair)
  12804. ts-date-type (cdr ts-date-pair)))
  12805. (setq i llast llast level)
  12806. ;; remove tag lists from same and sublevels
  12807. (while (>= i level)
  12808. (when (setq entry (assoc i tags-alist))
  12809. (setq tags-alist (delete entry tags-alist)))
  12810. (setq i (1- i)))
  12811. ;; add the next tags
  12812. (when tags
  12813. (setq tags (org-split-string tags ":")
  12814. tags-alist
  12815. (cons (cons level tags) tags-alist)))
  12816. ;; compile tags for current headline
  12817. (setq tags-list
  12818. (if org-use-tag-inheritance
  12819. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12820. tags)
  12821. org-scanner-tags tags-list)
  12822. (when org-use-tag-inheritance
  12823. (setcdr (car tags-alist)
  12824. (mapcar (lambda (x)
  12825. (setq x (copy-sequence x))
  12826. (org-add-prop-inherited x))
  12827. (cdar tags-alist))))
  12828. (when (and tags org-use-tag-inheritance
  12829. (or (not (eq t org-use-tag-inheritance))
  12830. org-tags-exclude-from-inheritance))
  12831. ;; Selective inheritance, remove uninherited ones.
  12832. (setcdr (car tags-alist)
  12833. (org-remove-uninherited-tags (cdar tags-alist))))
  12834. (when (and
  12835. ;; eval matcher only when the todo condition is OK
  12836. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12837. (if (functionp matcher)
  12838. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12839. (funcall matcher todo tags-list level))
  12840. matcher))
  12841. ;; Call the skipper, but return t if it does not
  12842. ;; skip, so that the `and' form continues evaluating.
  12843. (progn
  12844. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12845. t)
  12846. ;; Check if timestamps are deselecting this entry
  12847. (or (not todo-only)
  12848. (and (member todo org-todo-keywords-1)
  12849. (or (not org-agenda-tags-todo-honor-ignore-options)
  12850. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12851. ;; select this headline
  12852. (cond
  12853. ((eq action 'sparse-tree)
  12854. (and org-highlight-sparse-tree-matches
  12855. (org-get-heading) (match-end 0)
  12856. (org-highlight-new-match
  12857. (match-beginning 1) (match-end 1)))
  12858. (org-show-context 'tags-tree))
  12859. ((eq action 'agenda)
  12860. (setq txt (org-agenda-format-item
  12861. ""
  12862. (concat
  12863. (if (eq org-tags-match-list-sublevels 'indented)
  12864. (make-string (1- level) ?.) "")
  12865. (org-get-heading))
  12866. (make-string level ?\s)
  12867. category
  12868. tags-list)
  12869. priority (org-get-priority txt))
  12870. (goto-char lspos)
  12871. (setq marker (org-agenda-new-marker))
  12872. (org-add-props txt props
  12873. 'org-marker marker 'org-hd-marker marker 'org-category category
  12874. 'todo-state todo
  12875. 'ts-date ts-date
  12876. 'priority priority
  12877. 'type (concat "tagsmatch" ts-date-type))
  12878. (push txt rtn))
  12879. ((functionp action)
  12880. (setq org-map-continue-from nil)
  12881. (save-excursion
  12882. (setq rtn1 (funcall action))
  12883. (push rtn1 rtn)))
  12884. (t (user-error "Invalid action")))
  12885. ;; if we are to skip sublevels, jump to end of subtree
  12886. (unless org-tags-match-list-sublevels
  12887. (org-end-of-subtree t)
  12888. (backward-char 1))))
  12889. ;; Get the correct position from where to continue
  12890. (if org-map-continue-from
  12891. (goto-char org-map-continue-from)
  12892. (and (= (point) lspos) (end-of-line 1)))))
  12893. (when (and (eq action 'sparse-tree)
  12894. (not org-sparse-tree-open-archived-trees))
  12895. (org-hide-archived-subtrees (point-min) (point-max)))
  12896. (nreverse rtn)))
  12897. (defun org-remove-uninherited-tags (tags)
  12898. "Remove all tags that are not inherited from the list TAGS."
  12899. (cond
  12900. ((eq org-use-tag-inheritance t)
  12901. (if org-tags-exclude-from-inheritance
  12902. (org-delete-all org-tags-exclude-from-inheritance tags)
  12903. tags))
  12904. ((not org-use-tag-inheritance) nil)
  12905. ((stringp org-use-tag-inheritance)
  12906. (delq nil (mapcar
  12907. (lambda (x)
  12908. (if (and (string-match org-use-tag-inheritance x)
  12909. (not (member x org-tags-exclude-from-inheritance)))
  12910. x nil))
  12911. tags)))
  12912. ((listp org-use-tag-inheritance)
  12913. (delq nil (mapcar
  12914. (lambda (x)
  12915. (if (member x org-use-tag-inheritance) x nil))
  12916. tags)))))
  12917. (defun org-match-sparse-tree (&optional todo-only match)
  12918. "Create a sparse tree according to tags string MATCH.
  12919. MATCH is a string with match syntax. It can contain a selection
  12920. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12921. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12922. those. See the manual for details.
  12923. If optional argument TODO-ONLY is non-nil, only select lines that
  12924. are also TODO tasks."
  12925. (interactive "P")
  12926. (org-agenda-prepare-buffers (list (current-buffer)))
  12927. (let ((org--matcher-tags-todo-only todo-only))
  12928. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12929. org--matcher-tags-todo-only)))
  12930. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12931. (defvar org-cached-props nil)
  12932. (defun org-cached-entry-get (pom property)
  12933. (if (or (eq t org-use-property-inheritance)
  12934. (and (stringp org-use-property-inheritance)
  12935. (let ((case-fold-search t))
  12936. (string-match-p org-use-property-inheritance property)))
  12937. (and (listp org-use-property-inheritance)
  12938. (member-ignore-case property org-use-property-inheritance)))
  12939. ;; Caching is not possible, check it directly.
  12940. (org-entry-get pom property 'inherit)
  12941. ;; Get all properties, so we can do complicated checks easily.
  12942. (cdr (assoc-string property
  12943. (or org-cached-props
  12944. (setq org-cached-props (org-entry-properties pom)))
  12945. t))))
  12946. (defun org-global-tags-completion-table (&optional files)
  12947. "Return the list of all tags in all agenda buffer/files.
  12948. Optional FILES argument is a list of files which can be used
  12949. instead of the agenda files."
  12950. (save-excursion
  12951. (org-uniquify
  12952. (delq nil
  12953. (apply #'append
  12954. (mapcar
  12955. (lambda (file)
  12956. (set-buffer (find-file-noselect file))
  12957. (mapcar (lambda (x)
  12958. (and (stringp (car-safe x))
  12959. (list (car-safe x))))
  12960. (or org-current-tag-alist (org-get-buffer-tags))))
  12961. (if (car-safe files) files
  12962. (org-agenda-files))))))))
  12963. (defun org-make-tags-matcher (match)
  12964. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12965. Returns a cons of the selection string MATCH and a function
  12966. implementing the matcher.
  12967. The matcher is to be called at an Org entry, with point on the
  12968. headline, and returns non-nil if the entry matches the selection
  12969. string MATCH. It must be called with three arguments: the TODO
  12970. keyword at the entry (or nil if none), the list of all tags at
  12971. the entry including inherited ones and the reduced level of the
  12972. headline. Additionally, the category of the entry, if any, must
  12973. be specified as the text property `org-category' on the headline.
  12974. This function sets the variable `org--matcher-tags-todo-only' to
  12975. a non-nil value if the matcher restricts matching to TODO
  12976. entries, otherwise it is not touched.
  12977. See also `org-scan-tags'."
  12978. (unless match
  12979. ;; Get a new match request, with completion against the global
  12980. ;; tags table and the local tags in current buffer.
  12981. (let ((org-last-tags-completion-table
  12982. (org-uniquify
  12983. (delq nil (append (org-get-buffer-tags)
  12984. (org-global-tags-completion-table))))))
  12985. (setq match
  12986. (completing-read
  12987. "Match: "
  12988. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12989. (let ((match0 match)
  12990. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12991. (start 0)
  12992. tagsmatch todomatch tagsmatcher todomatcher)
  12993. ;; Expand group tags.
  12994. (setq match (org-tags-expand match))
  12995. ;; Check if there is a TODO part of this match, which would be the
  12996. ;; part after a "/". To make sure that this slash is not part of
  12997. ;; a property value to be matched against, we also check that
  12998. ;; there is no / after that slash. First, find the last slash.
  12999. (let ((s 0))
  13000. (while (string-match "/+" match s)
  13001. (setq start (match-beginning 0))
  13002. (setq s (match-end 0))))
  13003. (if (and (string-match "/+" match start)
  13004. (not (string-match-p "\"" match start)))
  13005. ;; Match contains also a TODO-matching request.
  13006. (progn
  13007. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13008. (setq todomatch (substring match (match-end 0)))
  13009. (when (string-prefix-p "!" todomatch)
  13010. (setq org--matcher-tags-todo-only t)
  13011. (setq todomatch (substring todomatch 1)))
  13012. (when (string-match "\\`\\s-*\\'" todomatch)
  13013. (setq todomatch nil)))
  13014. ;; Only matching tags.
  13015. (setq tagsmatch match)
  13016. (setq todomatch nil))
  13017. ;; Make the tags matcher.
  13018. (when (org-string-nw-p tagsmatch)
  13019. (let ((orlist nil)
  13020. (orterms (org-split-string tagsmatch "|"))
  13021. term)
  13022. (while (setq term (pop orterms))
  13023. (while (and (equal (substring term -1) "\\") orterms)
  13024. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13025. (while (string-match re term)
  13026. (let* ((rest (substring term (match-end 0)))
  13027. (minus (and (match-end 1)
  13028. (equal (match-string 1 term) "-")))
  13029. (tag (save-match-data
  13030. (replace-regexp-in-string
  13031. "\\\\-" "-" (match-string 2 term))))
  13032. (regexp (eq (string-to-char tag) ?{))
  13033. (levelp (match-end 4))
  13034. (propp (match-end 5))
  13035. (mm
  13036. (cond
  13037. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13038. (levelp
  13039. `(,(org-op-to-function (match-string 3 term))
  13040. level
  13041. ,(string-to-number (match-string 4 term))))
  13042. (propp
  13043. (let* ((gv (pcase (upcase (match-string 5 term))
  13044. ("CATEGORY"
  13045. '(get-text-property (point) 'org-category))
  13046. ("TODO" 'todo)
  13047. (p `(org-cached-entry-get nil ,p))))
  13048. (pv (match-string 7 term))
  13049. (regexp (eq (string-to-char pv) ?{))
  13050. (strp (eq (string-to-char pv) ?\"))
  13051. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13052. (po (org-op-to-function (match-string 6 term)
  13053. (if timep 'time strp))))
  13054. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13055. (when timep (setq pv (org-matcher-time pv)))
  13056. (cond ((and regexp (eq po 'org<>))
  13057. `(not (string-match ,pv (or ,gv ""))))
  13058. (regexp `(string-match ,pv (or ,gv "")))
  13059. (strp `(,po (or ,gv "") ,pv))
  13060. (t
  13061. `(,po
  13062. (string-to-number (or ,gv ""))
  13063. ,(string-to-number pv))))))
  13064. (t `(member ,tag tags-list)))))
  13065. (push (if minus `(not ,mm) mm) tagsmatcher)
  13066. (setq term rest)))
  13067. (push `(and ,@tagsmatcher) orlist)
  13068. (setq tagsmatcher nil))
  13069. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13070. ;; Make the TODO matcher.
  13071. (when (org-string-nw-p todomatch)
  13072. (let ((orlist nil))
  13073. (dolist (term (org-split-string todomatch "|"))
  13074. (while (string-match re term)
  13075. (let* ((minus (and (match-end 1)
  13076. (equal (match-string 1 term) "-")))
  13077. (kwd (match-string 2 term))
  13078. (regexp (eq (string-to-char kwd) ?{))
  13079. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13080. `(equal todo ,kwd))))
  13081. (push (if minus `(not ,mm) mm) todomatcher))
  13082. (setq term (substring term (match-end 0))))
  13083. (push (if (> (length todomatcher) 1)
  13084. (cons 'and todomatcher)
  13085. (car todomatcher))
  13086. orlist)
  13087. (setq todomatcher nil))
  13088. (setq todomatcher (cons 'or orlist))))
  13089. ;; Return the string and function of the matcher. If no
  13090. ;; tags-specific or todo-specific matcher exists, match
  13091. ;; everything.
  13092. (let ((matcher (if (and tagsmatcher todomatcher)
  13093. `(and ,tagsmatcher ,todomatcher)
  13094. (or tagsmatcher todomatcher t))))
  13095. (when org--matcher-tags-todo-only
  13096. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13097. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13098. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13099. "Expand group tags in MATCH.
  13100. This replaces every group tag in MATCH with a regexp tag search.
  13101. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13102. will be replaced like this:
  13103. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13104. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13105. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13106. Replacing by a regexp preserves the structure of the match.
  13107. E.g., this expansion
  13108. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13109. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13110. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13111. A group tag in MATCH can contain regular expressions of its own.
  13112. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13113. will be replaced like this:
  13114. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13115. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13116. assumed to be a single group tag, and the function will return
  13117. the list of tags in this group.
  13118. When DOWNCASE is non-nil, expand downcased TAGS."
  13119. (if org-group-tags
  13120. (let* ((case-fold-search t)
  13121. (stable org-mode-syntax-table)
  13122. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13123. (taggroups (if downcased
  13124. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13125. taggroups)
  13126. taggroups))
  13127. (taggroups-keys (mapcar #'car taggroups))
  13128. (return-match (if downcased (downcase match) match))
  13129. (count 0)
  13130. (work-already-expanded tags-already-expanded)
  13131. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13132. ;; @ and _ are allowed as word-components in tags.
  13133. (modify-syntax-entry ?@ "w" stable)
  13134. (modify-syntax-entry ?_ "w" stable)
  13135. ;; Temporarily replace regexp-expressions in the match-expression.
  13136. (while (string-match "{.+?}" return-match)
  13137. (cl-incf count)
  13138. (push (match-string 0 return-match) regexps-in-match)
  13139. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13140. (while (and taggroups-keys
  13141. (with-syntax-table stable
  13142. (string-match
  13143. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13144. (regexp-opt taggroups-keys) "\\>\\)")
  13145. return-match)))
  13146. (let* ((dir (match-string 1 return-match))
  13147. (tag (match-string 2 return-match))
  13148. (tag (if downcased (downcase tag) tag)))
  13149. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13150. (member tag work-already-expanded))
  13151. (setq tags-in-group (assoc tag taggroups))
  13152. (push tag work-already-expanded)
  13153. ;; Recursively expand each tag in the group, if the tag hasn't
  13154. ;; already been expanded. Restore the match-data after all recursive calls.
  13155. (save-match-data
  13156. (let (tags-expanded)
  13157. (dolist (x (cdr tags-in-group))
  13158. (if (and (member x taggroups-keys)
  13159. (not (member x work-already-expanded)))
  13160. (setq tags-expanded
  13161. (delete-dups
  13162. (append
  13163. (org-tags-expand x t downcased
  13164. work-already-expanded)
  13165. tags-expanded)))
  13166. (setq tags-expanded
  13167. (append (list x) tags-expanded)))
  13168. (setq work-already-expanded
  13169. (delete-dups
  13170. (append tags-expanded
  13171. work-already-expanded))))
  13172. (setq tags-in-group
  13173. (delete-dups (cons (car tags-in-group)
  13174. tags-expanded)))))
  13175. ;; Filter tag-regexps from tags.
  13176. (setq regexp-in-group-escaped
  13177. (delq nil (mapcar (lambda (x)
  13178. (if (stringp x)
  13179. (and (equal "{" (substring x 0 1))
  13180. (equal "}" (substring x -1))
  13181. x)
  13182. x))
  13183. tags-in-group))
  13184. regexp-in-group
  13185. (mapcar (lambda (x)
  13186. (substring x 1 -1))
  13187. regexp-in-group-escaped)
  13188. tags-in-group
  13189. (delq nil (mapcar (lambda (x)
  13190. (if (stringp x)
  13191. (and (not (equal "{" (substring x 0 1)))
  13192. (not (equal "}" (substring x -1)))
  13193. x)
  13194. x))
  13195. tags-in-group)))
  13196. ;; If single-as-list, do no more in the while-loop.
  13197. (if (not single-as-list)
  13198. (progn
  13199. (when regexp-in-group
  13200. (setq regexp-in-group
  13201. (concat "\\|"
  13202. (mapconcat 'identity regexp-in-group
  13203. "\\|"))))
  13204. (setq tags-in-group
  13205. (concat dir
  13206. "{\\<"
  13207. (regexp-opt tags-in-group)
  13208. "\\>"
  13209. regexp-in-group
  13210. "}"))
  13211. (when (stringp tags-in-group)
  13212. (org-add-props tags-in-group '(grouptag t)))
  13213. (setq return-match
  13214. (replace-match tags-in-group t t return-match)))
  13215. (setq tags-in-group
  13216. (append regexp-in-group-escaped tags-in-group))))
  13217. (setq taggroups-keys (delete tag taggroups-keys))))
  13218. ;; Add the regular expressions back into the match-expression again.
  13219. (while regexps-in-match
  13220. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13221. (pop regexps-in-match)
  13222. return-match t t))
  13223. (cl-decf count))
  13224. (if single-as-list
  13225. (if tags-in-group tags-in-group (list return-match))
  13226. return-match))
  13227. (if single-as-list
  13228. (list (if downcased (downcase match) match))
  13229. match)))
  13230. (defun org-op-to-function (op &optional stringp)
  13231. "Turn an operator into the appropriate function."
  13232. (setq op
  13233. (cond
  13234. ((equal op "<" ) '(< string< org-time<))
  13235. ((equal op ">" ) '(> org-string> org-time>))
  13236. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13237. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13238. ((member op '("=" "==")) '(= string= org-time=))
  13239. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13240. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13241. (defun org<> (a b) (not (= a b)))
  13242. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13243. (defun org-string>= (a b) (not (string< a b)))
  13244. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13245. (defun org-string<> (a b) (not (string= a b)))
  13246. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13247. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13248. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13249. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13250. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13251. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13252. (defun org-2ft (s)
  13253. "Convert S to a floating point time.
  13254. If S is already a number, just return it. If it is a string, parse
  13255. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13256. (cond
  13257. ((numberp s) s)
  13258. ((stringp s)
  13259. (condition-case nil
  13260. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13261. (error 0.)))
  13262. (t 0.)))
  13263. (defun org-time-today ()
  13264. "Time in seconds today at 0:00.
  13265. Returns the float number of seconds since the beginning of the
  13266. epoch to the beginning of today (00:00)."
  13267. (float-time (apply 'encode-time
  13268. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13269. (defun org-matcher-time (s)
  13270. "Interpret a time comparison value."
  13271. (save-match-data
  13272. (cond
  13273. ((string= s "<now>") (float-time))
  13274. ((string= s "<today>") (org-time-today))
  13275. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13276. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13277. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13278. (+ (org-time-today)
  13279. (* (string-to-number (match-string 1 s))
  13280. (cdr (assoc (match-string 2 s)
  13281. '(("d" . 86400.0) ("w" . 604800.0)
  13282. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13283. (t (org-2ft s)))))
  13284. (defun org-match-any-p (re list)
  13285. "Does re match any element of list?"
  13286. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13287. (delq nil list))
  13288. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13289. (defvar org-tags-overlay (make-overlay 1 1))
  13290. (delete-overlay org-tags-overlay)
  13291. (defun org-get-local-tags-at (&optional pos)
  13292. "Get a list of tags defined in the current headline."
  13293. (org-get-tags-at pos 'local))
  13294. (defun org-get-local-tags ()
  13295. "Get a list of tags defined in the current headline."
  13296. (org-get-tags-at nil 'local))
  13297. (defun org-get-tags-at (&optional pos local)
  13298. "Get a list of all headline tags applicable at POS.
  13299. POS defaults to point. If tags are inherited, the list contains
  13300. the targets in the same sequence as the headlines appear, i.e.
  13301. the tags of the current headline come last.
  13302. When LOCAL is non-nil, only return tags from the current headline,
  13303. ignore inherited ones."
  13304. (interactive)
  13305. (if (and org-trust-scanner-tags
  13306. (or (not pos) (equal pos (point)))
  13307. (not local))
  13308. org-scanner-tags
  13309. (let (tags ltags lastpos parent)
  13310. (save-excursion
  13311. (save-restriction
  13312. (widen)
  13313. (goto-char (or pos (point)))
  13314. (save-match-data
  13315. (catch 'done
  13316. (condition-case nil
  13317. (progn
  13318. (org-back-to-heading t)
  13319. (while (not (equal lastpos (point)))
  13320. (setq lastpos (point))
  13321. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13322. (setq ltags (org-split-string
  13323. (match-string-no-properties 1) ":"))
  13324. (when parent
  13325. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13326. (setq tags (append
  13327. (if parent
  13328. (org-remove-uninherited-tags ltags)
  13329. ltags)
  13330. tags)))
  13331. (or org-use-tag-inheritance (throw 'done t))
  13332. (when local (throw 'done t))
  13333. (or (org-up-heading-safe) (error nil))
  13334. (setq parent t)))
  13335. (error nil)))))
  13336. (if local
  13337. tags
  13338. (reverse (delete-dups
  13339. (reverse (append
  13340. (org-remove-uninherited-tags
  13341. org-file-tags)
  13342. tags)))))))))
  13343. (defun org-add-prop-inherited (s)
  13344. (add-text-properties 0 (length s) '(inherited t) s)
  13345. s)
  13346. (defun org-toggle-tag (tag &optional onoff)
  13347. "Toggle the tag TAG for the current line.
  13348. If ONOFF is `on' or `off', don't toggle but set to this state."
  13349. (save-excursion
  13350. (org-back-to-heading t)
  13351. (let ((current
  13352. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13353. (line-end-position) t)
  13354. (let ((tags (match-string 1)))
  13355. ;; Clear current tags.
  13356. (replace-match "")
  13357. ;; Reverse the tags list so any new tag is appended to
  13358. ;; the current list of tags.
  13359. (nreverse (org-split-string tags ":")))))
  13360. res)
  13361. (pcase onoff
  13362. (`off (setq current (delete tag current)))
  13363. ((or `on (guard (not (member tag current))))
  13364. (setq res t)
  13365. (cl-pushnew tag current :test #'equal))
  13366. (_ (setq current (delete tag current))))
  13367. (end-of-line)
  13368. (if current
  13369. (progn
  13370. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13371. (org-set-tags nil t))
  13372. (delete-horizontal-space))
  13373. (run-hooks 'org-after-tags-change-hook)
  13374. res)))
  13375. (defun org--align-tags-here (to-col)
  13376. "Align tags on the current headline to TO-COL.
  13377. Assume point is on a headline."
  13378. (let ((pos (point)))
  13379. (beginning-of-line)
  13380. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13381. (>= pos (match-beginning 2)))
  13382. ;; No tags or point within tags: do not align.
  13383. (goto-char pos)
  13384. (goto-char (match-beginning 1))
  13385. (let ((shift (max (- (if (>= to-col 0) to-col
  13386. (- (abs to-col) (string-width (match-string 2))))
  13387. (current-column))
  13388. 1)))
  13389. (replace-match (make-string shift ?\s) nil nil nil 1)
  13390. ;; Preserve initial position, if possible. In any case, stop
  13391. ;; before tags.
  13392. (when (< pos (point)) (goto-char pos))))))
  13393. (defun org-set-tags-command (&optional arg just-align)
  13394. "Call the set-tags command for the current entry."
  13395. (interactive "P")
  13396. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13397. (org-set-tags arg just-align)
  13398. (save-excursion
  13399. (unless (and (org-region-active-p)
  13400. org-loop-over-headlines-in-active-region)
  13401. (org-back-to-heading t))
  13402. (org-set-tags arg just-align))))
  13403. (defun org-set-tags-to (data)
  13404. "Set the tags of the current entry to DATA, replacing the current tags.
  13405. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13406. If DATA is nil or the empty string, any tags will be removed."
  13407. (interactive "sTags: ")
  13408. (setq data
  13409. (cond
  13410. ((eq data nil) "")
  13411. ((equal data "") "")
  13412. ((stringp data)
  13413. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13414. ":"))
  13415. ((listp data)
  13416. (concat ":" (mapconcat 'identity data ":") ":"))))
  13417. (when data
  13418. (save-excursion
  13419. (org-back-to-heading t)
  13420. (when (let ((case-fold-search nil))
  13421. (looking-at org-complex-heading-regexp))
  13422. (if (match-end 5)
  13423. (progn
  13424. (goto-char (match-beginning 5))
  13425. (insert data)
  13426. (delete-region (point) (point-at-eol))
  13427. (org-set-tags nil 'align))
  13428. (goto-char (point-at-eol))
  13429. (insert " " data)
  13430. (org-set-tags nil 'align)))
  13431. (beginning-of-line 1)
  13432. (when (looking-at ".*?\\([ \t]+\\)$")
  13433. (delete-region (match-beginning 1) (match-end 1))))))
  13434. (defun org-align-all-tags ()
  13435. "Align the tags in all headings."
  13436. (interactive)
  13437. (save-excursion
  13438. (or (ignore-errors (org-back-to-heading t))
  13439. (outline-next-heading))
  13440. (if (org-at-heading-p)
  13441. (org-set-tags t)
  13442. (message "No headings"))))
  13443. (defvar org-indent-indentation-per-level)
  13444. (defun org-set-tags (&optional arg just-align)
  13445. "Set the tags for the current headline.
  13446. With prefix ARG, realign all tags in headings in the current buffer.
  13447. When JUST-ALIGN is non-nil, only align tags."
  13448. (interactive "P")
  13449. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13450. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13451. 'region-start-level
  13452. 'region))
  13453. org-loop-over-headlines-in-active-region)
  13454. (org-map-entries
  13455. ;; We don't use ARG and JUST-ALIGN here because these args
  13456. ;; are not useful when looping over headlines.
  13457. #'org-set-tags
  13458. org-loop-over-headlines-in-active-region
  13459. cl
  13460. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13461. (let ((org-setting-tags t))
  13462. (if arg
  13463. (save-excursion
  13464. (goto-char (point-min))
  13465. (while (re-search-forward org-outline-regexp-bol nil t)
  13466. (org-set-tags nil t)
  13467. (end-of-line))
  13468. (message "All tags realigned to column %d" org-tags-column))
  13469. (let* ((current (org-get-tags-string))
  13470. (tags
  13471. (if just-align current
  13472. ;; Get a new set of tags from the user.
  13473. (save-excursion
  13474. (let* ((seen)
  13475. (table
  13476. (setq
  13477. org-last-tags-completion-table
  13478. ;; Uniquify tags in alists, yet preserve
  13479. ;; structure (i.e., keywords).
  13480. (delq nil
  13481. (mapcar
  13482. (lambda (pair)
  13483. (let ((head (car pair)))
  13484. (cond ((symbolp head) pair)
  13485. ((member head seen) nil)
  13486. (t (push head seen)
  13487. pair))))
  13488. (append
  13489. (or org-current-tag-alist
  13490. (org-get-buffer-tags))
  13491. (and
  13492. org-complete-tags-always-offer-all-agenda-tags
  13493. (org-global-tags-completion-table
  13494. (org-agenda-files))))))))
  13495. (current-tags (org-split-string current ":"))
  13496. (inherited-tags
  13497. (nreverse (nthcdr (length current-tags)
  13498. (nreverse (org-get-tags-at))))))
  13499. (replace-regexp-in-string
  13500. "\\([-+&]+\\|,\\)"
  13501. ":"
  13502. (if (or (eq t org-use-fast-tag-selection)
  13503. (and org-use-fast-tag-selection
  13504. (delq nil (mapcar #'cdr table))))
  13505. (org-fast-tag-selection
  13506. current-tags inherited-tags table
  13507. (and org-fast-tag-selection-include-todo
  13508. org-todo-key-alist))
  13509. (let ((org-add-colon-after-tag-completion
  13510. (< 1 (length table))))
  13511. (org-trim
  13512. (completing-read
  13513. "Tags: "
  13514. #'org-tags-completion-function
  13515. nil nil current 'org-tags-history))))))))))
  13516. (when org-tags-sort-function
  13517. (setq tags
  13518. (mapconcat
  13519. #'identity
  13520. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13521. org-tags-sort-function)
  13522. ":")))
  13523. (if (or (string= ":" tags)
  13524. (string= "::" tags))
  13525. (setq tags ""))
  13526. (if (not (org-string-nw-p tags)) (setq tags "")
  13527. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13528. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13529. ;; Insert new tags at the correct column.
  13530. (unless (equal current tags)
  13531. (save-excursion
  13532. (beginning-of-line)
  13533. (let ((case-fold-search nil))
  13534. (looking-at org-complex-heading-regexp))
  13535. ;; Remove current tags, if any.
  13536. (when (match-end 5) (replace-match "" nil nil nil 5))
  13537. ;; Insert new tags, if any. Otherwise, remove trailing
  13538. ;; white spaces.
  13539. (end-of-line)
  13540. (if (not (equal tags ""))
  13541. ;; When text is being inserted on an invisible
  13542. ;; region boundary, it can be inadvertently sucked
  13543. ;; into invisibility.
  13544. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13545. (skip-chars-backward " \t")
  13546. (delete-region (point) (line-end-position)))))
  13547. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13548. ;; is on.
  13549. (unless (equal tags "")
  13550. (let* ((level (save-excursion
  13551. (beginning-of-line)
  13552. (skip-chars-forward "\\*")))
  13553. (offset (if (bound-and-true-p org-indent-mode)
  13554. (* (1- org-indent-indentation-per-level)
  13555. (1- level))
  13556. 0))
  13557. (tags-column
  13558. (+ org-tags-column
  13559. (if (> org-tags-column 0) (- offset) offset))))
  13560. (org--align-tags-here tags-column))))
  13561. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13562. (defun org-change-tag-in-region (beg end tag off)
  13563. "Add or remove TAG for each entry in the region.
  13564. This works in the agenda, and also in an Org buffer."
  13565. (interactive
  13566. (list (region-beginning) (region-end)
  13567. (let ((org-last-tags-completion-table
  13568. (if (derived-mode-p 'org-mode)
  13569. (org-uniquify
  13570. (delq nil (append (org-get-buffer-tags)
  13571. (org-global-tags-completion-table))))
  13572. (org-global-tags-completion-table))))
  13573. (completing-read
  13574. "Tag: " 'org-tags-completion-function nil nil nil
  13575. 'org-tags-history))
  13576. (progn
  13577. (message "[s]et or [r]emove? ")
  13578. (equal (read-char-exclusive) ?r))))
  13579. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13580. (let ((agendap (equal major-mode 'org-agenda-mode))
  13581. l1 l2 m buf pos newhead (cnt 0))
  13582. (goto-char end)
  13583. (setq l2 (1- (org-current-line)))
  13584. (goto-char beg)
  13585. (setq l1 (org-current-line))
  13586. (cl-loop for l from l1 to l2 do
  13587. (org-goto-line l)
  13588. (setq m (get-text-property (point) 'org-hd-marker))
  13589. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13590. (and agendap m))
  13591. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13592. pos (if agendap m (point)))
  13593. (with-current-buffer buf
  13594. (save-excursion
  13595. (save-restriction
  13596. (goto-char pos)
  13597. (setq cnt (1+ cnt))
  13598. (org-toggle-tag tag (if off 'off 'on))
  13599. (setq newhead (org-get-heading)))))
  13600. (and agendap (org-agenda-change-all-lines newhead m))))
  13601. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13602. (defun org-tags-completion-function (string _predicate &optional flag)
  13603. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13604. (confirm (lambda (x) (stringp (car x)))))
  13605. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13606. (setq s1 (match-string 1 string)
  13607. s2 (match-string 2 string))
  13608. (setq s1 "" s2 string))
  13609. (cond
  13610. ((eq flag nil)
  13611. ;; try completion
  13612. (setq rtn (try-completion s2 ctable confirm))
  13613. (when (stringp rtn)
  13614. (setq rtn
  13615. (concat s1 s2 (substring rtn (length s2))
  13616. (if (and org-add-colon-after-tag-completion
  13617. (assoc rtn ctable))
  13618. ":" ""))))
  13619. rtn)
  13620. ((eq flag t)
  13621. ;; all-completions
  13622. (all-completions s2 ctable confirm))
  13623. ((eq flag 'lambda)
  13624. ;; exact match?
  13625. (assoc s2 ctable)))))
  13626. (defun org-fast-tag-insert (kwd tags face &optional end)
  13627. "Insert KDW, and the TAGS, the latter with face FACE.
  13628. Also insert END."
  13629. (insert (format "%-12s" (concat kwd ":"))
  13630. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13631. (or end "")))
  13632. (defun org-fast-tag-show-exit (flag)
  13633. (save-excursion
  13634. (org-goto-line 3)
  13635. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13636. (replace-match ""))
  13637. (when flag
  13638. (end-of-line 1)
  13639. (org-move-to-column (- (window-width) 19) t)
  13640. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13641. (defun org-set-current-tags-overlay (current prefix)
  13642. "Add an overlay to CURRENT tag with PREFIX."
  13643. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13644. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13645. (org-overlay-display org-tags-overlay (concat prefix s))))
  13646. (defvar org-last-tag-selection-key nil)
  13647. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13648. "Fast tag selection with single keys.
  13649. CURRENT is the current list of tags in the headline, INHERITED is the
  13650. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13651. possibly with grouping information. TODO-TABLE is a similar table with
  13652. TODO keywords, should these have keys assigned to them.
  13653. If the keys are nil, a-z are automatically assigned.
  13654. Returns the new tags string, or nil to not change the current settings."
  13655. (let* ((fulltable (append table todo-table))
  13656. (maxlen (apply 'max (mapcar
  13657. (lambda (x)
  13658. (if (stringp (car x)) (string-width (car x)) 0))
  13659. fulltable)))
  13660. (buf (current-buffer))
  13661. (expert (eq org-fast-tag-selection-single-key 'expert))
  13662. (buffer-tags nil)
  13663. (fwidth (+ maxlen 3 1 3))
  13664. (ncol (/ (- (window-width) 4) fwidth))
  13665. (i-face 'org-done)
  13666. (c-face 'org-todo)
  13667. tg cnt e c char c1 c2 ntable tbl rtn
  13668. ov-start ov-end ov-prefix
  13669. (exit-after-next org-fast-tag-selection-single-key)
  13670. (done-keywords org-done-keywords)
  13671. groups ingroup intaggroup)
  13672. (save-excursion
  13673. (beginning-of-line 1)
  13674. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13675. (setq ov-start (match-beginning 1)
  13676. ov-end (match-end 1)
  13677. ov-prefix "")
  13678. (setq ov-start (1- (point-at-eol))
  13679. ov-end (1+ ov-start))
  13680. (skip-chars-forward "^\n\r")
  13681. (setq ov-prefix
  13682. (concat
  13683. (buffer-substring (1- (point)) (point))
  13684. (if (> (current-column) org-tags-column)
  13685. " "
  13686. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13687. (move-overlay org-tags-overlay ov-start ov-end)
  13688. (save-window-excursion
  13689. (if expert
  13690. (set-buffer (get-buffer-create " *Org tags*"))
  13691. (delete-other-windows)
  13692. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13693. (org-switch-to-buffer-other-window " *Org tags*"))
  13694. (erase-buffer)
  13695. (setq-local org-done-keywords done-keywords)
  13696. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13697. (org-fast-tag-insert "Current" current c-face "\n\n")
  13698. (org-fast-tag-show-exit exit-after-next)
  13699. (org-set-current-tags-overlay current ov-prefix)
  13700. (setq tbl fulltable char ?a cnt 0)
  13701. (while (setq e (pop tbl))
  13702. (cond
  13703. ((eq (car e) :startgroup)
  13704. (push '() groups) (setq ingroup t)
  13705. (unless (zerop cnt)
  13706. (setq cnt 0)
  13707. (insert "\n"))
  13708. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13709. ((eq (car e) :endgroup)
  13710. (setq ingroup nil cnt 0)
  13711. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13712. ((eq (car e) :startgrouptag)
  13713. (setq intaggroup t)
  13714. (unless (zerop cnt)
  13715. (setq cnt 0)
  13716. (insert "\n"))
  13717. (insert "[ "))
  13718. ((eq (car e) :endgrouptag)
  13719. (setq intaggroup nil cnt 0)
  13720. (insert "]\n"))
  13721. ((equal e '(:newline))
  13722. (unless (zerop cnt)
  13723. (setq cnt 0)
  13724. (insert "\n")
  13725. (setq e (car tbl))
  13726. (while (equal (car tbl) '(:newline))
  13727. (insert "\n")
  13728. (setq tbl (cdr tbl)))))
  13729. ((equal e '(:grouptags)) (insert " : "))
  13730. (t
  13731. (setq tg (copy-sequence (car e)) c2 nil)
  13732. (if (cdr e)
  13733. (setq c (cdr e))
  13734. ;; automatically assign a character.
  13735. (setq c1 (string-to-char
  13736. (downcase (substring
  13737. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13738. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13739. (while (or (rassoc char ntable) (rassoc char table))
  13740. (setq char (1+ char)))
  13741. (setq c2 c1))
  13742. (setq c (or c2 char)))
  13743. (when ingroup (push tg (car groups)))
  13744. (setq tg (org-add-props tg nil 'face
  13745. (cond
  13746. ((not (assoc tg table))
  13747. (org-get-todo-face tg))
  13748. ((member tg current) c-face)
  13749. ((member tg inherited) i-face))))
  13750. (when (equal (caar tbl) :grouptags)
  13751. (org-add-props tg nil 'face 'org-tag-group))
  13752. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13753. (insert "[" c "] " tg (make-string
  13754. (- fwidth 4 (length tg)) ?\ ))
  13755. (push (cons tg c) ntable)
  13756. (when (= (cl-incf cnt) ncol)
  13757. (insert "\n")
  13758. (when (or ingroup intaggroup) (insert " "))
  13759. (setq cnt 0)))))
  13760. (setq ntable (nreverse ntable))
  13761. (insert "\n")
  13762. (goto-char (point-min))
  13763. (unless expert (org-fit-window-to-buffer))
  13764. (setq rtn
  13765. (catch 'exit
  13766. (while t
  13767. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13768. (if (not groups) "no " "")
  13769. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13770. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13771. (setq org-last-tag-selection-key c)
  13772. (cond
  13773. ((= c ?\r) (throw 'exit t))
  13774. ((= c ?!)
  13775. (setq groups (not groups))
  13776. (goto-char (point-min))
  13777. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13778. ((= c ?\C-c)
  13779. (if (not expert)
  13780. (org-fast-tag-show-exit
  13781. (setq exit-after-next (not exit-after-next)))
  13782. (setq expert nil)
  13783. (delete-other-windows)
  13784. (set-window-buffer (split-window-vertically) " *Org tags*")
  13785. (org-switch-to-buffer-other-window " *Org tags*")
  13786. (org-fit-window-to-buffer)))
  13787. ((or (= c ?\C-g)
  13788. (and (= c ?q) (not (rassoc c ntable))))
  13789. (delete-overlay org-tags-overlay)
  13790. (setq quit-flag t))
  13791. ((= c ?\ )
  13792. (setq current nil)
  13793. (when exit-after-next (setq exit-after-next 'now)))
  13794. ((= c ?\t)
  13795. (condition-case nil
  13796. (setq tg (completing-read
  13797. "Tag: "
  13798. (or buffer-tags
  13799. (with-current-buffer buf
  13800. (setq buffer-tags
  13801. (org-get-buffer-tags))))))
  13802. (quit (setq tg "")))
  13803. (when (string-match "\\S-" tg)
  13804. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13805. (if (member tg current)
  13806. (setq current (delete tg current))
  13807. (push tg current)))
  13808. (when exit-after-next (setq exit-after-next 'now)))
  13809. ((setq e (rassoc c todo-table) tg (car e))
  13810. (with-current-buffer buf
  13811. (save-excursion (org-todo tg)))
  13812. (when exit-after-next (setq exit-after-next 'now)))
  13813. ((setq e (rassoc c ntable) tg (car e))
  13814. (if (member tg current)
  13815. (setq current (delete tg current))
  13816. (cl-loop for g in groups do
  13817. (when (member tg g)
  13818. (dolist (x g) (setq current (delete x current)))))
  13819. (push tg current))
  13820. (when exit-after-next (setq exit-after-next 'now))))
  13821. ;; Create a sorted list
  13822. (setq current
  13823. (sort current
  13824. (lambda (a b)
  13825. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13826. (when (eq exit-after-next 'now) (throw 'exit t))
  13827. (goto-char (point-min))
  13828. (beginning-of-line 2)
  13829. (delete-region (point) (point-at-eol))
  13830. (org-fast-tag-insert "Current" current c-face)
  13831. (org-set-current-tags-overlay current ov-prefix)
  13832. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13833. (setq tg (match-string 1))
  13834. (add-text-properties
  13835. (match-beginning 1) (match-end 1)
  13836. (list 'face
  13837. (cond
  13838. ((member tg current) c-face)
  13839. ((member tg inherited) i-face)
  13840. (t (get-text-property (match-beginning 1) 'face))))))
  13841. (goto-char (point-min)))))
  13842. (delete-overlay org-tags-overlay)
  13843. (if rtn
  13844. (mapconcat 'identity current ":")
  13845. nil))))
  13846. (defun org-get-tags-string ()
  13847. "Get the TAGS string in the current headline."
  13848. (unless (org-at-heading-p t)
  13849. (user-error "Not on a heading"))
  13850. (save-excursion
  13851. (beginning-of-line 1)
  13852. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13853. (match-string-no-properties 1)
  13854. "")))
  13855. (defun org-get-tags ()
  13856. "Get the list of tags specified in the current headline."
  13857. (org-split-string (org-get-tags-string) ":"))
  13858. (defun org-get-buffer-tags ()
  13859. "Get a table of all tags used in the buffer, for completion."
  13860. (org-with-wide-buffer
  13861. (goto-char (point-min))
  13862. (let ((tag-re (concat org-outline-regexp-bol
  13863. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13864. tags)
  13865. (while (re-search-forward tag-re nil t)
  13866. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13867. (push tag tags)))
  13868. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13869. ;;;; The mapping API
  13870. (defvar org-agenda-skip-comment-trees)
  13871. (defvar org-agenda-skip-function)
  13872. (defun org-map-entries (func &optional match scope &rest skip)
  13873. "Call FUNC at each headline selected by MATCH in SCOPE.
  13874. FUNC is a function or a lisp form. The function will be called without
  13875. arguments, with the cursor positioned at the beginning of the headline.
  13876. The return values of all calls to the function will be collected and
  13877. returned as a list.
  13878. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13879. does not need to preserve point. After evaluation, the cursor will be
  13880. moved to the end of the line (presumably of the headline of the
  13881. processed entry) and search continues from there. Under some
  13882. circumstances, this may not produce the wanted results. For example,
  13883. if you have removed (e.g. archived) the current (sub)tree it could
  13884. mean that the next entry will be skipped entirely. In such cases, you
  13885. can specify the position from where search should continue by making
  13886. FUNC set the variable `org-map-continue-from' to the desired buffer
  13887. position.
  13888. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13889. Only headlines that are matched by this query will be considered during
  13890. the iteration. When MATCH is nil or t, all headlines will be
  13891. visited by the iteration.
  13892. SCOPE determines the scope of this command. It can be any of:
  13893. nil The current buffer, respecting the restriction if any
  13894. tree The subtree started with the entry at point
  13895. region The entries within the active region, if any
  13896. region-start-level
  13897. The entries within the active region, but only those at
  13898. the same level than the first one.
  13899. file The current buffer, without restriction
  13900. file-with-archives
  13901. The current buffer, and any archives associated with it
  13902. agenda All agenda files
  13903. agenda-with-archives
  13904. All agenda files with any archive files associated with them
  13905. \(file1 file2 ...)
  13906. If this is a list, all files in the list will be scanned
  13907. The remaining args are treated as settings for the skipping facilities of
  13908. the scanner. The following items can be given here:
  13909. archive skip trees with the archive tag
  13910. comment skip trees with the COMMENT keyword
  13911. function or Emacs Lisp form:
  13912. will be used as value for `org-agenda-skip-function', so
  13913. whenever the function returns a position, FUNC will not be
  13914. called for that entry and search will continue from the
  13915. position returned
  13916. If your function needs to retrieve the tags including inherited tags
  13917. at the *current* entry, you can use the value of the variable
  13918. `org-scanner-tags' which will be much faster than getting the value
  13919. with `org-get-tags-at'. If your function gets properties with
  13920. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13921. to t around the call to `org-entry-properties' to get the same speedup.
  13922. Note that if your function moves around to retrieve tags and properties at
  13923. a *different* entry, you cannot use these techniques."
  13924. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13925. (not (org-region-active-p)))
  13926. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13927. (org-agenda-skip-archived-trees (memq 'archive skip))
  13928. (org-agenda-skip-comment-trees (memq 'comment skip))
  13929. (org-agenda-skip-function
  13930. (car (org-delete-all '(comment archive) skip)))
  13931. (org-tags-match-list-sublevels t)
  13932. (start-level (eq scope 'region-start-level))
  13933. matcher res
  13934. org-todo-keywords-for-agenda
  13935. org-done-keywords-for-agenda
  13936. org-todo-keyword-alist-for-agenda
  13937. org-tag-alist-for-agenda
  13938. org--matcher-tags-todo-only)
  13939. (cond
  13940. ((eq match t) (setq matcher t))
  13941. ((eq match nil) (setq matcher t))
  13942. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13943. (save-excursion
  13944. (save-restriction
  13945. (cond ((eq scope 'tree)
  13946. (org-back-to-heading t)
  13947. (org-narrow-to-subtree)
  13948. (setq scope nil))
  13949. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13950. (org-region-active-p))
  13951. ;; If needed, set start-level to a string like "2"
  13952. (when start-level
  13953. (save-excursion
  13954. (goto-char (region-beginning))
  13955. (unless (org-at-heading-p) (outline-next-heading))
  13956. (setq start-level (org-current-level))))
  13957. (narrow-to-region (region-beginning)
  13958. (save-excursion
  13959. (goto-char (region-end))
  13960. (unless (and (bolp) (org-at-heading-p))
  13961. (outline-next-heading))
  13962. (point)))
  13963. (setq scope nil)))
  13964. (if (not scope)
  13965. (progn
  13966. (org-agenda-prepare-buffers
  13967. (and buffer-file-name (list buffer-file-name)))
  13968. (setq res
  13969. (org-scan-tags
  13970. func matcher org--matcher-tags-todo-only start-level)))
  13971. ;; Get the right scope
  13972. (cond
  13973. ((and scope (listp scope) (symbolp (car scope)))
  13974. (setq scope (eval scope)))
  13975. ((eq scope 'agenda)
  13976. (setq scope (org-agenda-files t)))
  13977. ((eq scope 'agenda-with-archives)
  13978. (setq scope (org-agenda-files t))
  13979. (setq scope (org-add-archive-files scope)))
  13980. ((eq scope 'file)
  13981. (setq scope (and buffer-file-name (list buffer-file-name))))
  13982. ((eq scope 'file-with-archives)
  13983. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13984. (org-agenda-prepare-buffers scope)
  13985. (dolist (file scope)
  13986. (with-current-buffer (org-find-base-buffer-visiting file)
  13987. (org-with-wide-buffer
  13988. (goto-char (point-min))
  13989. (setq res
  13990. (append
  13991. res
  13992. (org-scan-tags
  13993. func matcher org--matcher-tags-todo-only)))))))))
  13994. res)))
  13995. ;;; Properties API
  13996. (defconst org-special-properties
  13997. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13998. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13999. "The special properties valid in Org mode.
  14000. These are properties that are not defined in the property drawer,
  14001. but in some other way.")
  14002. (defconst org-default-properties
  14003. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14004. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14005. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14006. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14007. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14008. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14009. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14010. "Some properties that are used by Org mode for various purposes.
  14011. Being in this list makes sure that they are offered for completion.")
  14012. (defun org--valid-property-p (property)
  14013. "Non nil when string PROPERTY is a valid property name."
  14014. (not
  14015. (or (equal property "")
  14016. (string-match-p "\\s-" property))))
  14017. (defun org--update-property-plist (key val props)
  14018. "Associate KEY to VAL in alist PROPS.
  14019. Modifications are made by side-effect. Return new alist."
  14020. (let* ((appending (string= (substring key -1) "+"))
  14021. (key (if appending (substring key 0 -1) key))
  14022. (old (assoc-string key props t)))
  14023. (if (not old) (cons (cons key val) props)
  14024. (setcdr old (if appending (concat (cdr old) " " val) val))
  14025. props)))
  14026. (defun org-get-property-block (&optional beg force)
  14027. "Return the (beg . end) range of the body of the property drawer.
  14028. BEG is the beginning of the current subtree, or of the part
  14029. before the first headline. If it is not given, it will be found.
  14030. If the drawer does not exist, create it if FORCE is non-nil, or
  14031. return nil."
  14032. (org-with-wide-buffer
  14033. (when beg (goto-char beg))
  14034. (unless (org-before-first-heading-p)
  14035. (let ((beg (cond (beg)
  14036. ((or (not (featurep 'org-inlinetask))
  14037. (org-inlinetask-in-task-p))
  14038. (org-back-to-heading t))
  14039. (t (org-with-limited-levels (org-back-to-heading t))))))
  14040. (forward-line)
  14041. (when (looking-at-p org-planning-line-re) (forward-line))
  14042. (cond ((looking-at org-property-drawer-re)
  14043. (forward-line)
  14044. (cons (point) (progn (goto-char (match-end 0))
  14045. (line-beginning-position))))
  14046. (force
  14047. (goto-char beg)
  14048. (org-insert-property-drawer)
  14049. (let ((pos (save-excursion (search-forward ":END:")
  14050. (line-beginning-position))))
  14051. (cons pos pos))))))))
  14052. (defun org-at-property-p ()
  14053. "Non-nil when point is inside a property drawer.
  14054. See `org-property-re' for match data, if applicable."
  14055. (save-excursion
  14056. (beginning-of-line)
  14057. (and (looking-at org-property-re)
  14058. (let ((property-drawer (save-match-data (org-get-property-block))))
  14059. (and property-drawer
  14060. (>= (point) (car property-drawer))
  14061. (< (point) (cdr property-drawer)))))))
  14062. (defun org-property-action ()
  14063. "Do an action on properties."
  14064. (interactive)
  14065. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14066. (let ((c (read-char-exclusive)))
  14067. (cl-case c
  14068. (?s (call-interactively #'org-set-property))
  14069. (?d (call-interactively #'org-delete-property))
  14070. (?D (call-interactively #'org-delete-property-globally))
  14071. (?c (call-interactively #'org-compute-property-at-point))
  14072. (otherwise (user-error "No such property action %c" c)))))
  14073. (defun org-inc-effort ()
  14074. "Increment the value of the effort property in the current entry."
  14075. (interactive)
  14076. (org-set-effort nil t))
  14077. (defvar org-clock-effort) ; Defined in org-clock.el.
  14078. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14079. (defun org-set-effort (&optional value increment)
  14080. "Set the effort property of the current entry.
  14081. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14082. 10th allowed value.
  14083. When INCREMENT is non-nil, set the property to the next allowed value."
  14084. (interactive "P")
  14085. (when (equal value 0) (setq value 10))
  14086. (let* ((completion-ignore-case t)
  14087. (prop org-effort-property)
  14088. (cur (org-entry-get nil prop))
  14089. (allowed (org-property-get-allowed-values nil prop 'table))
  14090. (existing (mapcar 'list (org-property-values prop)))
  14091. (heading (nth 4 (org-heading-components)))
  14092. rpl
  14093. (val (cond
  14094. ((stringp value) value)
  14095. ((and allowed (integerp value))
  14096. (or (car (nth (1- value) allowed))
  14097. (car (org-last allowed))))
  14098. ((and allowed increment)
  14099. (or (cl-caadr (member (list cur) allowed))
  14100. (user-error "Allowed effort values are not set")))
  14101. (allowed
  14102. (message "Select 1-9,0, [RET%s]: %s"
  14103. (if cur (concat "=" cur) "")
  14104. (mapconcat 'car allowed " "))
  14105. (setq rpl (read-char-exclusive))
  14106. (if (equal rpl ?\r)
  14107. cur
  14108. (setq rpl (- rpl ?0))
  14109. (when (equal rpl 0) (setq rpl 10))
  14110. (if (and (> rpl 0) (<= rpl (length allowed)))
  14111. (car (nth (1- rpl) allowed))
  14112. (org-completing-read "Effort: " allowed nil))))
  14113. (t
  14114. (org-completing-read
  14115. (concat "Effort" (and cur (string-match "\\S-" cur)
  14116. (concat " [" cur "]"))
  14117. ": ")
  14118. existing nil nil "" nil cur)))))
  14119. (unless (equal (org-entry-get nil prop) val)
  14120. (org-entry-put nil prop val))
  14121. (org-refresh-property
  14122. '((effort . identity)
  14123. (effort-minutes . org-duration-to-minutes))
  14124. val)
  14125. (when (equal heading (bound-and-true-p org-clock-current-task))
  14126. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14127. (org-clock-update-mode-line))
  14128. (message "%s is now %s" prop val)))
  14129. (defun org-entry-properties (&optional pom which)
  14130. "Get all properties of the current entry.
  14131. When POM is a buffer position, get all properties from the entry
  14132. there instead.
  14133. This includes the TODO keyword, the tags, time strings for
  14134. deadline, scheduled, and clocking, and any additional properties
  14135. defined in the entry.
  14136. If WHICH is nil or `all', get all properties. If WHICH is
  14137. `special' or `standard', only get that subclass. If WHICH is
  14138. a string, only get that property.
  14139. Return value is an alist. Keys are properties, as upcased
  14140. strings."
  14141. (org-with-point-at pom
  14142. (when (and (derived-mode-p 'org-mode)
  14143. (ignore-errors (org-back-to-heading t)))
  14144. (catch 'exit
  14145. (let* ((beg (point))
  14146. (specific (and (stringp which) (upcase which)))
  14147. (which (cond ((not specific) which)
  14148. ((member specific org-special-properties) 'special)
  14149. (t 'standard)))
  14150. props)
  14151. ;; Get the special properties, like TODO and TAGS.
  14152. (when (memq which '(nil all special))
  14153. (when (or (not specific) (string= specific "CLOCKSUM"))
  14154. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14155. (when clocksum
  14156. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14157. props)))
  14158. (when specific (throw 'exit props)))
  14159. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14160. (let ((clocksumt (get-text-property (point)
  14161. :org-clock-minutes-today)))
  14162. (when clocksumt
  14163. (push (cons "CLOCKSUM_T"
  14164. (org-duration-from-minutes clocksumt))
  14165. props)))
  14166. (when specific (throw 'exit props)))
  14167. (when (or (not specific) (string= specific "ITEM"))
  14168. (let ((case-fold-search nil))
  14169. (when (looking-at org-complex-heading-regexp)
  14170. (push (cons "ITEM"
  14171. (let ((title (match-string-no-properties 4)))
  14172. (if (org-string-nw-p title)
  14173. (org-remove-tabs title)
  14174. "")))
  14175. props)))
  14176. (when specific (throw 'exit props)))
  14177. (when (or (not specific) (string= specific "TODO"))
  14178. (let ((case-fold-search nil))
  14179. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14180. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14181. (when specific (throw 'exit props)))
  14182. (when (or (not specific) (string= specific "PRIORITY"))
  14183. (push (cons "PRIORITY"
  14184. (if (looking-at org-priority-regexp)
  14185. (match-string-no-properties 2)
  14186. (char-to-string org-default-priority)))
  14187. props)
  14188. (when specific (throw 'exit props)))
  14189. (when (or (not specific) (string= specific "FILE"))
  14190. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14191. props)
  14192. (when specific (throw 'exit props)))
  14193. (when (or (not specific) (string= specific "TAGS"))
  14194. (let ((value (org-string-nw-p (org-get-tags-string))))
  14195. (when value (push (cons "TAGS" value) props)))
  14196. (when specific (throw 'exit props)))
  14197. (when (or (not specific) (string= specific "ALLTAGS"))
  14198. (let ((value (org-get-tags-at)))
  14199. (when value
  14200. (push (cons "ALLTAGS"
  14201. (format ":%s:" (mapconcat #'identity value ":")))
  14202. props)))
  14203. (when specific (throw 'exit props)))
  14204. (when (or (not specific) (string= specific "BLOCKED"))
  14205. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14206. (when specific (throw 'exit props)))
  14207. (when (or (not specific)
  14208. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14209. (forward-line)
  14210. (when (looking-at-p org-planning-line-re)
  14211. (end-of-line)
  14212. (let ((bol (line-beginning-position))
  14213. ;; Backward compatibility: time keywords used to
  14214. ;; be configurable (before 8.3). Make sure we
  14215. ;; get the correct keyword.
  14216. (key-assoc `(("CLOSED" . ,org-closed-string)
  14217. ("DEADLINE" . ,org-deadline-string)
  14218. ("SCHEDULED" . ,org-scheduled-string))))
  14219. (dolist (pair (if specific (list (assoc specific key-assoc))
  14220. key-assoc))
  14221. (save-excursion
  14222. (when (search-backward (cdr pair) bol t)
  14223. (goto-char (match-end 0))
  14224. (skip-chars-forward " \t")
  14225. (and (looking-at org-ts-regexp-both)
  14226. (push (cons (car pair)
  14227. (match-string-no-properties 0))
  14228. props)))))))
  14229. (when specific (throw 'exit props)))
  14230. (when (or (not specific)
  14231. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14232. (let ((find-ts
  14233. (lambda (end ts)
  14234. ;; Fix next time-stamp before END. TS is the
  14235. ;; list of time-stamps found so far.
  14236. (let ((ts ts)
  14237. (regexp (cond
  14238. ((string= specific "TIMESTAMP")
  14239. org-ts-regexp)
  14240. ((string= specific "TIMESTAMP_IA")
  14241. org-ts-regexp-inactive)
  14242. ((assoc "TIMESTAMP_IA" ts)
  14243. org-ts-regexp)
  14244. ((assoc "TIMESTAMP" ts)
  14245. org-ts-regexp-inactive)
  14246. (t org-ts-regexp-both))))
  14247. (catch 'next
  14248. (while (re-search-forward regexp end t)
  14249. (backward-char)
  14250. (let ((object (org-element-context)))
  14251. ;; Accept to match timestamps in node
  14252. ;; properties, too.
  14253. (when (memq (org-element-type object)
  14254. '(node-property timestamp))
  14255. (let ((type
  14256. (org-element-property :type object)))
  14257. (cond
  14258. ((and (memq type '(active active-range))
  14259. (not (equal specific "TIMESTAMP_IA")))
  14260. (unless (assoc "TIMESTAMP" ts)
  14261. (push (cons "TIMESTAMP"
  14262. (org-element-property
  14263. :raw-value object))
  14264. ts)
  14265. (when specific (throw 'exit ts))))
  14266. ((and (memq type '(inactive inactive-range))
  14267. (not (string= specific "TIMESTAMP")))
  14268. (unless (assoc "TIMESTAMP_IA" ts)
  14269. (push (cons "TIMESTAMP_IA"
  14270. (org-element-property
  14271. :raw-value object))
  14272. ts)
  14273. (when specific (throw 'exit ts))))))
  14274. ;; Both timestamp types are found,
  14275. ;; move to next part.
  14276. (when (= (length ts) 2) (throw 'next ts)))))
  14277. ts)))))
  14278. (goto-char beg)
  14279. ;; First look for timestamps within headline.
  14280. (let ((ts (funcall find-ts (line-end-position) nil)))
  14281. (if (= (length ts) 2) (setq props (nconc ts props))
  14282. ;; Then find timestamps in the section, skipping
  14283. ;; planning line.
  14284. (let ((end (save-excursion (outline-next-heading))))
  14285. (forward-line)
  14286. (when (looking-at-p org-planning-line-re) (forward-line))
  14287. (setq props (nconc (funcall find-ts end ts) props))))))))
  14288. ;; Get the standard properties, like :PROP:.
  14289. (when (memq which '(nil all standard))
  14290. ;; If we are looking after a specific property, delegate
  14291. ;; to `org-entry-get', which is faster. However, make an
  14292. ;; exception for "CATEGORY", since it can be also set
  14293. ;; through keywords (i.e. #+CATEGORY).
  14294. (if (and specific (not (equal specific "CATEGORY")))
  14295. (let ((value (org-entry-get beg specific nil t)))
  14296. (throw 'exit (and value (list (cons specific value)))))
  14297. (let ((range (org-get-property-block beg)))
  14298. (when range
  14299. (let ((end (cdr range)) seen-base)
  14300. (goto-char (car range))
  14301. ;; Unlike to `org--update-property-plist', we
  14302. ;; handle the case where base values is found
  14303. ;; after its extension. We also forbid standard
  14304. ;; properties to be named as special properties.
  14305. (while (re-search-forward org-property-re end t)
  14306. (let* ((key (upcase (match-string-no-properties 2)))
  14307. (extendp (string-match-p "\\+\\'" key))
  14308. (key-base (if extendp (substring key 0 -1) key))
  14309. (value (match-string-no-properties 3)))
  14310. (cond
  14311. ((member-ignore-case key-base org-special-properties))
  14312. (extendp
  14313. (setq props
  14314. (org--update-property-plist key value props)))
  14315. ((member key seen-base))
  14316. (t (push key seen-base)
  14317. (let ((p (assoc-string key props t)))
  14318. (if p (setcdr p (concat value " " (cdr p)))
  14319. (push (cons key value) props))))))))))))
  14320. (unless (assoc "CATEGORY" props)
  14321. (push (cons "CATEGORY" (org-get-category beg)) props)
  14322. (when (string= specific "CATEGORY") (throw 'exit props)))
  14323. ;; Return value.
  14324. props)))))
  14325. (defun org--property-local-values (property literal-nil)
  14326. "Return value for PROPERTY in current entry.
  14327. Value is a list whose car is the base value for PROPERTY and cdr
  14328. a list of accumulated values. Return nil if neither is found in
  14329. the entry. Also return nil when PROPERTY is set to \"nil\",
  14330. unless LITERAL-NIL is non-nil."
  14331. (let ((range (org-get-property-block)))
  14332. (when range
  14333. (goto-char (car range))
  14334. (let* ((case-fold-search t)
  14335. (end (cdr range))
  14336. (value
  14337. ;; Base value.
  14338. (save-excursion
  14339. (let ((v (and (re-search-forward
  14340. (org-re-property property nil t) end t)
  14341. (match-string-no-properties 3))))
  14342. (list (if literal-nil v (org-not-nil v)))))))
  14343. ;; Find additional values.
  14344. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14345. (while (re-search-forward property+ end t)
  14346. (push (match-string-no-properties 3) value)))
  14347. ;; Return final values.
  14348. (and (not (equal value '(nil))) (nreverse value))))))
  14349. (defun org--property-global-value (property literal-nil)
  14350. "Return value for PROPERTY in current buffer.
  14351. Return value is a string. Return nil if property is not set
  14352. globally. Also return nil when PROPERTY is set to \"nil\",
  14353. unless LITERAL-NIL is non-nil."
  14354. (let ((global
  14355. (cdr (or (assoc-string property org-file-properties t)
  14356. (assoc-string property org-global-properties t)
  14357. (assoc-string property org-global-properties-fixed t)))))
  14358. (if literal-nil global (org-not-nil global))))
  14359. (defun org-entry-get (pom property &optional inherit literal-nil)
  14360. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14361. If INHERIT is non-nil and the entry does not have the property,
  14362. then also check higher levels of the hierarchy. If INHERIT is
  14363. the symbol `selective', use inheritance only if the setting in
  14364. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14365. If the property is present but empty, the return value is the
  14366. empty string. If the property is not present at all, nil is
  14367. returned. In any other case, return the value as a string.
  14368. Search is case-insensitive.
  14369. If LITERAL-NIL is set, return the string value \"nil\" as
  14370. a string, do not interpret it as the list atom nil. This is used
  14371. for inheritance when a \"nil\" value can supersede a non-nil
  14372. value higher up the hierarchy."
  14373. (org-with-point-at pom
  14374. (cond
  14375. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14376. ;; We need a special property. Use `org-entry-properties' to
  14377. ;; retrieve it, but specify the wanted property.
  14378. (cdr (assoc-string property (org-entry-properties nil property))))
  14379. ((and inherit
  14380. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14381. (org-entry-get-with-inheritance property literal-nil))
  14382. (t
  14383. (let* ((local (org--property-local-values property literal-nil))
  14384. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14385. (if literal-nil value (org-not-nil value)))))))
  14386. (defun org-property-or-variable-value (var &optional inherit)
  14387. "Check if there is a property fixing the value of VAR.
  14388. If yes, return this value. If not, return the current value of the variable."
  14389. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14390. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14391. (read prop)
  14392. (symbol-value var))))
  14393. (defun org-entry-delete (pom property)
  14394. "Delete PROPERTY from entry at point-or-marker POM.
  14395. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14396. non-nil when a property was removed."
  14397. (org-with-point-at pom
  14398. (pcase (org-get-property-block)
  14399. (`(,begin . ,origin)
  14400. (let* ((end (copy-marker origin))
  14401. (re (org-re-property
  14402. (concat (regexp-quote property) "\\+?") t t)))
  14403. (goto-char begin)
  14404. (while (re-search-forward re end t)
  14405. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14406. ;; If drawer is empty, remove it altogether.
  14407. (when (= begin end)
  14408. (delete-region (line-beginning-position 0)
  14409. (line-beginning-position 2)))
  14410. ;; Return non-nil if some property was removed.
  14411. (prog1 (/= end origin) (set-marker end nil))))
  14412. (_ nil))))
  14413. ;; Multi-values properties are properties that contain multiple values
  14414. ;; These values are assumed to be single words, separated by whitespace.
  14415. (defun org-entry-add-to-multivalued-property (pom property value)
  14416. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14417. (let* ((old (org-entry-get pom property))
  14418. (values (and old (split-string old))))
  14419. (setq value (org-entry-protect-space value))
  14420. (unless (member value values)
  14421. (setq values (append values (list value)))
  14422. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14423. (defun org-entry-remove-from-multivalued-property (pom property value)
  14424. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14425. (let* ((old (org-entry-get pom property))
  14426. (values (and old (split-string old))))
  14427. (setq value (org-entry-protect-space value))
  14428. (when (member value values)
  14429. (setq values (delete value values))
  14430. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14431. (defun org-entry-member-in-multivalued-property (pom property value)
  14432. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14433. (let* ((old (org-entry-get pom property))
  14434. (values (and old (split-string old))))
  14435. (setq value (org-entry-protect-space value))
  14436. (member value values)))
  14437. (defun org-entry-get-multivalued-property (pom property)
  14438. "Return a list of values in a multivalued property."
  14439. (let* ((value (org-entry-get pom property))
  14440. (values (and value (split-string value))))
  14441. (mapcar #'org-entry-restore-space values)))
  14442. (defun org-entry-put-multivalued-property (pom property &rest values)
  14443. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14444. VALUES should be a list of strings. Spaces will be protected."
  14445. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14446. (let* ((value (org-entry-get pom property))
  14447. (values (and value (split-string value))))
  14448. (mapcar #'org-entry-restore-space values)))
  14449. (defun org-entry-protect-space (s)
  14450. "Protect spaces and newline in string S."
  14451. (while (string-match " " s)
  14452. (setq s (replace-match "%20" t t s)))
  14453. (while (string-match "\n" s)
  14454. (setq s (replace-match "%0A" t t s)))
  14455. s)
  14456. (defun org-entry-restore-space (s)
  14457. "Restore spaces and newline in string S."
  14458. (while (string-match "%20" s)
  14459. (setq s (replace-match " " t t s)))
  14460. (while (string-match "%0A" s)
  14461. (setq s (replace-match "\n" t t s)))
  14462. s)
  14463. (defvar org-entry-property-inherited-from (make-marker)
  14464. "Marker pointing to the entry from where a property was inherited.
  14465. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14466. location of the entry where the inheritance search matched. If there was
  14467. no match, the marker will point nowhere.
  14468. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14469. is set.")
  14470. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14471. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14472. The search will stop at the first ancestor which has the property defined.
  14473. If the value found is \"nil\", return nil to show that the property
  14474. should be considered as undefined (this is the meaning of nil here).
  14475. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14476. (move-marker org-entry-property-inherited-from nil)
  14477. (org-with-wide-buffer
  14478. (let (value)
  14479. (catch 'exit
  14480. (while t
  14481. (let ((v (org--property-local-values property literal-nil)))
  14482. (when v
  14483. (setq value
  14484. (concat (mapconcat #'identity (delq nil v) " ")
  14485. (and value " ")
  14486. value)))
  14487. (cond
  14488. ((car v)
  14489. (org-back-to-heading t)
  14490. (move-marker org-entry-property-inherited-from (point))
  14491. (throw 'exit nil))
  14492. ((org-up-heading-safe))
  14493. (t
  14494. (let ((global (org--property-global-value property literal-nil)))
  14495. (cond ((not global))
  14496. (value (setq value (concat global " " value)))
  14497. (t (setq value global))))
  14498. (throw 'exit nil))))))
  14499. (if literal-nil value (org-not-nil value)))))
  14500. (defvar org-property-changed-functions nil
  14501. "Hook called when the value of a property has changed.
  14502. Each hook function should accept two arguments, the name of the property
  14503. and the new value.")
  14504. (defun org-entry-put (pom property value)
  14505. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14506. If the value is nil, it is converted to the empty string. If it
  14507. is not a string, an error is raised. Also raise an error on
  14508. invalid property names.
  14509. PROPERTY can be any regular property (see
  14510. `org-special-properties'). It can also be \"TODO\",
  14511. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14512. For the last two properties, VALUE may have any of the special
  14513. values \"earlier\" and \"later\". The function then increases or
  14514. decreases scheduled or deadline date by one day."
  14515. (cond ((null value) (setq value ""))
  14516. ((not (stringp value)) (error "Properties values should be strings"))
  14517. ((not (org--valid-property-p property))
  14518. (user-error "Invalid property name: \"%s\"" property)))
  14519. (org-with-point-at pom
  14520. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14521. (org-back-to-heading t)
  14522. (org-with-limited-levels (org-back-to-heading t)))
  14523. (let ((beg (point)))
  14524. (cond
  14525. ((equal property "TODO")
  14526. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14527. ((not (member value org-todo-keywords-1))
  14528. (user-error "\"%s\" is not a valid TODO state" value)))
  14529. (org-todo value)
  14530. (org-set-tags nil 'align))
  14531. ((equal property "PRIORITY")
  14532. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14533. (org-set-tags nil 'align))
  14534. ((equal property "SCHEDULED")
  14535. (forward-line)
  14536. (if (and (looking-at-p org-planning-line-re)
  14537. (re-search-forward
  14538. org-scheduled-time-regexp (line-end-position) t))
  14539. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14540. ((string= value "later") (org-timestamp-change 1 'day))
  14541. ((string= value "") (org-schedule '(4)))
  14542. (t (org-schedule nil value)))
  14543. (if (member value '("earlier" "later" ""))
  14544. (call-interactively #'org-schedule)
  14545. (org-schedule nil value))))
  14546. ((equal property "DEADLINE")
  14547. (forward-line)
  14548. (if (and (looking-at-p org-planning-line-re)
  14549. (re-search-forward
  14550. org-deadline-time-regexp (line-end-position) t))
  14551. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14552. ((string= value "later") (org-timestamp-change 1 'day))
  14553. ((string= value "") (org-deadline '(4)))
  14554. (t (org-deadline nil value)))
  14555. (if (member value '("earlier" "later" ""))
  14556. (call-interactively #'org-deadline)
  14557. (org-deadline nil value))))
  14558. ((member property org-special-properties)
  14559. (error "The %s property cannot be set with `org-entry-put'" property))
  14560. (t
  14561. (let* ((range (org-get-property-block beg 'force))
  14562. (end (cdr range))
  14563. (case-fold-search t))
  14564. (goto-char (car range))
  14565. (if (re-search-forward (org-re-property property nil t) end t)
  14566. (progn (delete-region (match-beginning 0) (match-end 0))
  14567. (goto-char (match-beginning 0)))
  14568. (goto-char end)
  14569. (insert "\n")
  14570. (backward-char))
  14571. (insert ":" property ":")
  14572. (when value (insert " " value))
  14573. (org-indent-line)))))
  14574. (run-hook-with-args 'org-property-changed-functions property value)))
  14575. (defun org-buffer-property-keys
  14576. (&optional specials defaults columns ignore-malformed)
  14577. "Get all property keys in the current buffer.
  14578. When SPECIALS is non-nil, also list the special properties that
  14579. reflect things like tags and TODO state.
  14580. When DEFAULTS is non-nil, also include properties that has
  14581. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14582. DESCRIPTION, LOCATION, and LOGGING and others.
  14583. When COLUMNS in non-nil, also include property names given in
  14584. COLUMN formats in the current buffer.
  14585. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14586. automatically performed, such drawers will be silently ignored."
  14587. (let ((case-fold-search t)
  14588. (props (append
  14589. (and specials org-special-properties)
  14590. (and defaults (cons org-effort-property org-default-properties))
  14591. nil)))
  14592. (org-with-wide-buffer
  14593. (goto-char (point-min))
  14594. (while (re-search-forward org-property-start-re nil t)
  14595. (let ((range (org-get-property-block)))
  14596. (catch 'skip
  14597. (unless range
  14598. (when (and (not ignore-malformed)
  14599. (not (org-before-first-heading-p))
  14600. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14601. (line-beginning-position))))
  14602. (org-get-property-block nil t))
  14603. (throw 'skip nil))
  14604. (goto-char (car range))
  14605. (let ((begin (car range))
  14606. (end (cdr range)))
  14607. ;; Make sure that found property block is not located
  14608. ;; before current point, as it would generate an infloop.
  14609. ;; It can happen, for example, in the following
  14610. ;; situation:
  14611. ;;
  14612. ;; * Headline
  14613. ;; :PROPERTIES:
  14614. ;; ...
  14615. ;; :END:
  14616. ;; *************** Inlinetask
  14617. ;; #+BEGIN_EXAMPLE
  14618. ;; :PROPERTIES:
  14619. ;; #+END_EXAMPLE
  14620. ;;
  14621. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14622. (while (< (point) end)
  14623. (let ((p (progn (looking-at org-property-re)
  14624. (match-string-no-properties 2))))
  14625. ;; Only add true property name, not extension symbol.
  14626. (push (if (not (string-match-p "\\+\\'" p)) p
  14627. (substring p 0 -1))
  14628. props))
  14629. (forward-line))))
  14630. (outline-next-heading)))
  14631. (when columns
  14632. (goto-char (point-min))
  14633. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14634. (let ((element (org-element-at-point)))
  14635. (when (memq (org-element-type element) '(keyword node-property))
  14636. (let ((value (org-element-property :value element))
  14637. (start 0))
  14638. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14639. \\(?:{[^}]+}\\)?"
  14640. value start)
  14641. (setq start (match-end 0))
  14642. (let ((p (match-string-no-properties 1 value)))
  14643. (unless (member-ignore-case p org-special-properties)
  14644. (push p props))))))))))
  14645. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14646. (defun org-property-values (key)
  14647. "List all non-nil values of property KEY in current buffer."
  14648. (org-with-wide-buffer
  14649. (goto-char (point-min))
  14650. (let ((case-fold-search t)
  14651. (re (org-re-property key))
  14652. values)
  14653. (while (re-search-forward re nil t)
  14654. (push (org-entry-get (point) key) values))
  14655. (delete-dups values))))
  14656. (defun org-insert-property-drawer ()
  14657. "Insert a property drawer into the current entry."
  14658. (org-with-wide-buffer
  14659. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14660. (org-back-to-heading t)
  14661. (org-with-limited-levels (org-back-to-heading t)))
  14662. (forward-line)
  14663. (when (looking-at-p org-planning-line-re) (forward-line))
  14664. (unless (looking-at-p org-property-drawer-re)
  14665. ;; Make sure we start editing a line from current entry, not from
  14666. ;; next one. It prevents extending text properties or overlays
  14667. ;; belonging to the latter.
  14668. (when (bolp) (backward-char))
  14669. (let ((begin (1+ (point)))
  14670. (inhibit-read-only t))
  14671. (insert "\n:PROPERTIES:\n:END:")
  14672. (when (eobp) (insert "\n"))
  14673. (org-indent-region begin (point))))))
  14674. (defun org-insert-drawer (&optional arg drawer)
  14675. "Insert a drawer at point.
  14676. When optional argument ARG is non-nil, insert a property drawer.
  14677. Optional argument DRAWER, when non-nil, is a string representing
  14678. drawer's name. Otherwise, the user is prompted for a name.
  14679. If a region is active, insert the drawer around that region
  14680. instead.
  14681. Point is left between drawer's boundaries."
  14682. (interactive "P")
  14683. (let* ((drawer (if arg "PROPERTIES"
  14684. (or drawer (read-from-minibuffer "Drawer: ")))))
  14685. (cond
  14686. ;; With C-u, fall back on `org-insert-property-drawer'
  14687. (arg (org-insert-property-drawer))
  14688. ;; Check validity of suggested drawer's name.
  14689. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14690. (user-error "Invalid drawer name"))
  14691. ;; With an active region, insert a drawer at point.
  14692. ((not (org-region-active-p))
  14693. (progn
  14694. (unless (bolp) (insert "\n"))
  14695. (insert (format ":%s:\n\n:END:\n" drawer))
  14696. (forward-line -2)))
  14697. ;; Otherwise, insert the drawer at point
  14698. (t
  14699. (let ((rbeg (region-beginning))
  14700. (rend (copy-marker (region-end))))
  14701. (unwind-protect
  14702. (progn
  14703. (goto-char rbeg)
  14704. (beginning-of-line)
  14705. (when (save-excursion
  14706. (re-search-forward org-outline-regexp-bol rend t))
  14707. (user-error "Drawers cannot contain headlines"))
  14708. ;; Position point at the beginning of the first
  14709. ;; non-blank line in region. Insert drawer's opening
  14710. ;; there, then indent it.
  14711. (org-skip-whitespace)
  14712. (beginning-of-line)
  14713. (insert ":" drawer ":\n")
  14714. (forward-line -1)
  14715. (indent-for-tab-command)
  14716. ;; Move point to the beginning of the first blank line
  14717. ;; after the last non-blank line in region. Insert
  14718. ;; drawer's closing, then indent it.
  14719. (goto-char rend)
  14720. (skip-chars-backward " \r\t\n")
  14721. (insert "\n:END:")
  14722. (deactivate-mark t)
  14723. (indent-for-tab-command)
  14724. (unless (eolp) (insert "\n")))
  14725. ;; Clear marker, whatever the outcome of insertion is.
  14726. (set-marker rend nil)))))))
  14727. (defvar org-property-set-functions-alist nil
  14728. "Property set function alist.
  14729. Each entry should have the following format:
  14730. (PROPERTY . READ-FUNCTION)
  14731. The read function will be called with the same argument as
  14732. `org-completing-read'.")
  14733. (defun org-set-property-function (property)
  14734. "Get the function that should be used to set PROPERTY.
  14735. This is computed according to `org-property-set-functions-alist'."
  14736. (or (cdr (assoc property org-property-set-functions-alist))
  14737. 'org-completing-read))
  14738. (defun org-read-property-value (property)
  14739. "Read PROPERTY value from user."
  14740. (let* ((completion-ignore-case t)
  14741. (allowed (org-property-get-allowed-values nil property 'table))
  14742. (cur (org-entry-get nil property))
  14743. (prompt (concat property " value"
  14744. (if (and cur (string-match "\\S-" cur))
  14745. (concat " [" cur "]") "") ": "))
  14746. (set-function (org-set-property-function property))
  14747. (val (if allowed
  14748. (funcall set-function prompt allowed nil
  14749. (not (get-text-property 0 'org-unrestricted
  14750. (caar allowed))))
  14751. (funcall set-function prompt
  14752. (mapcar 'list (org-property-values property))
  14753. nil nil "" nil cur))))
  14754. (org-trim val)))
  14755. (defvar org-last-set-property nil)
  14756. (defvar org-last-set-property-value nil)
  14757. (defun org-read-property-name ()
  14758. "Read a property name."
  14759. (let ((completion-ignore-case t)
  14760. (default-prop (or (and (org-at-property-p)
  14761. (match-string-no-properties 2))
  14762. org-last-set-property)))
  14763. (org-completing-read
  14764. (concat "Property"
  14765. (if default-prop (concat " [" default-prop "]") "")
  14766. ": ")
  14767. (mapcar #'list (org-buffer-property-keys nil t t))
  14768. nil nil nil nil default-prop)))
  14769. (defun org-set-property-and-value (use-last)
  14770. "Allow to set [PROPERTY]: [value] direction from prompt.
  14771. When use-default, don't even ask, just use the last
  14772. \"[PROPERTY]: [value]\" string from the history."
  14773. (interactive "P")
  14774. (let* ((completion-ignore-case t)
  14775. (pv (or (and use-last org-last-set-property-value)
  14776. (org-completing-read
  14777. "Enter a \"[Property]: [value]\" pair: "
  14778. nil nil nil nil nil
  14779. org-last-set-property-value)))
  14780. prop val)
  14781. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14782. (setq prop (match-string 1 pv)
  14783. val (match-string 2 pv))
  14784. (org-set-property prop val))))
  14785. (defun org-set-property (property value)
  14786. "In the current entry, set PROPERTY to VALUE.
  14787. When called interactively, this will prompt for a property name, offering
  14788. completion on existing and default properties. And then it will prompt
  14789. for a value, offering completion either on allowed values (via an inherited
  14790. xxx_ALL property) or on existing values in other instances of this property
  14791. in the current file.
  14792. Throw an error when trying to set a property with an invalid name."
  14793. (interactive (list nil nil))
  14794. (let ((property (or property (org-read-property-name))))
  14795. ;; `org-entry-put' also makes the following check, but this one
  14796. ;; avoids polluting `org-last-set-property' and
  14797. ;; `org-last-set-property-value' needlessly.
  14798. (unless (org--valid-property-p property)
  14799. (user-error "Invalid property name: \"%s\"" property))
  14800. (let ((value (or value (org-read-property-value property)))
  14801. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14802. (setq org-last-set-property property)
  14803. (setq org-last-set-property-value (concat property ": " value))
  14804. ;; Possibly postprocess the inserted value:
  14805. (when fn (setq value (funcall fn value)))
  14806. (unless (equal (org-entry-get nil property) value)
  14807. (org-entry-put nil property value)))))
  14808. (defun org-find-property (property &optional value)
  14809. "Find first entry in buffer that sets PROPERTY.
  14810. When optional argument VALUE is non-nil, only consider an entry
  14811. if it contains PROPERTY set to this value. If PROPERTY should be
  14812. explicitly set to nil, use string \"nil\" for VALUE.
  14813. Return position where the entry begins, or nil if there is no
  14814. such entry. If narrowing is in effect, only search the visible
  14815. part of the buffer."
  14816. (save-excursion
  14817. (goto-char (point-min))
  14818. (let ((case-fold-search t)
  14819. (re (org-re-property property nil (not value) value)))
  14820. (catch 'exit
  14821. (while (re-search-forward re nil t)
  14822. (when (if value (org-at-property-p)
  14823. (org-entry-get (point) property nil t))
  14824. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14825. (defun org-delete-property (property)
  14826. "In the current entry, delete PROPERTY."
  14827. (interactive
  14828. (let* ((completion-ignore-case t)
  14829. (cat (org-entry-get (point) "CATEGORY"))
  14830. (props0 (org-entry-properties nil 'standard))
  14831. (props (if cat props0
  14832. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14833. (prop (if (< 1 (length props))
  14834. (completing-read "Property: " props nil t)
  14835. (caar props))))
  14836. (list prop)))
  14837. (if (not property)
  14838. (message "No property to delete in this entry")
  14839. (org-entry-delete nil property)
  14840. (message "Property \"%s\" deleted" property)))
  14841. (defun org-delete-property-globally (property)
  14842. "Remove PROPERTY globally, from all entries.
  14843. This function ignores narrowing, if any."
  14844. (interactive
  14845. (let* ((completion-ignore-case t)
  14846. (prop (completing-read
  14847. "Globally remove property: "
  14848. (mapcar #'list (org-buffer-property-keys)))))
  14849. (list prop)))
  14850. (org-with-wide-buffer
  14851. (goto-char (point-min))
  14852. (let ((count 0)
  14853. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14854. (while (re-search-forward re nil t)
  14855. (when (org-entry-delete (point) property) (cl-incf count)))
  14856. (message "Property \"%s\" removed from %d entries" property count))))
  14857. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14858. (defun org-compute-property-at-point ()
  14859. "Compute the property at point.
  14860. This looks for an enclosing column format, extracts the operator and
  14861. then applies it to the property in the column format's scope."
  14862. (interactive)
  14863. (unless (org-at-property-p)
  14864. (user-error "Not at a property"))
  14865. (let ((prop (match-string-no-properties 2)))
  14866. (org-columns-get-format-and-top-level)
  14867. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14868. (user-error "No operator defined for property %s" prop))
  14869. (org-columns-compute prop)))
  14870. (defvar org-property-allowed-value-functions nil
  14871. "Hook for functions supplying allowed values for a specific property.
  14872. The functions must take a single argument, the name of the property, and
  14873. return a flat list of allowed values. If \":ETC\" is one of
  14874. the values, this means that these values are intended as defaults for
  14875. completion, but that other values should be allowed too.
  14876. The functions must return nil if they are not responsible for this
  14877. property.")
  14878. (defun org-property-get-allowed-values (pom property &optional table)
  14879. "Get allowed values for the property PROPERTY.
  14880. When TABLE is non-nil, return an alist that can directly be used for
  14881. completion."
  14882. (let (vals)
  14883. (cond
  14884. ((equal property "TODO")
  14885. (setq vals (org-with-point-at pom
  14886. (append org-todo-keywords-1 '("")))))
  14887. ((equal property "PRIORITY")
  14888. (let ((n org-lowest-priority))
  14889. (while (>= n org-highest-priority)
  14890. (push (char-to-string n) vals)
  14891. (setq n (1- n)))))
  14892. ((equal property "CATEGORY"))
  14893. ((member property org-special-properties))
  14894. ((setq vals (run-hook-with-args-until-success
  14895. 'org-property-allowed-value-functions property)))
  14896. (t
  14897. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14898. (when (and vals (string-match "\\S-" vals))
  14899. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14900. (setq vals (mapcar (lambda (x)
  14901. (cond ((stringp x) x)
  14902. ((numberp x) (number-to-string x))
  14903. ((symbolp x) (symbol-name x))
  14904. (t "???")))
  14905. vals)))))
  14906. (when (member ":ETC" vals)
  14907. (setq vals (remove ":ETC" vals))
  14908. (org-add-props (car vals) '(org-unrestricted t)))
  14909. (if table (mapcar 'list vals) vals)))
  14910. (defun org-property-previous-allowed-value (&optional _previous)
  14911. "Switch to the next allowed value for this property."
  14912. (interactive)
  14913. (org-property-next-allowed-value t))
  14914. (defun org-property-next-allowed-value (&optional previous)
  14915. "Switch to the next allowed value for this property."
  14916. (interactive)
  14917. (unless (org-at-property-p)
  14918. (user-error "Not at a property"))
  14919. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14920. (key (match-string 2))
  14921. (value (match-string 3))
  14922. (allowed (or (org-property-get-allowed-values (point) key)
  14923. (and (member value '("[ ]" "[-]" "[X]"))
  14924. '("[ ]" "[X]"))))
  14925. (heading (save-match-data (nth 4 (org-heading-components))))
  14926. nval)
  14927. (unless allowed
  14928. (user-error "Allowed values for this property have not been defined"))
  14929. (when previous (setq allowed (reverse allowed)))
  14930. (when (member value allowed)
  14931. (setq nval (car (cdr (member value allowed)))))
  14932. (setq nval (or nval (car allowed)))
  14933. (when (equal nval value)
  14934. (user-error "Only one allowed value for this property"))
  14935. (org-at-property-p)
  14936. (replace-match (concat " :" key ": " nval) t t)
  14937. (org-indent-line)
  14938. (beginning-of-line 1)
  14939. (skip-chars-forward " \t")
  14940. (when (equal prop org-effort-property)
  14941. (org-refresh-property
  14942. '((effort . identity)
  14943. (effort-minutes . org-duration-to-minutes))
  14944. nval)
  14945. (when (string= org-clock-current-task heading)
  14946. (setq org-clock-effort nval)
  14947. (org-clock-update-mode-line)))
  14948. (run-hook-with-args 'org-property-changed-functions key nval)))
  14949. (defun org-find-olp (path &optional this-buffer)
  14950. "Return a marker pointing to the entry at outline path OLP.
  14951. If anything goes wrong, throw an error.
  14952. You can wrap this call to catch the error like this:
  14953. (condition-case msg
  14954. (org-mobile-locate-entry (match-string 4))
  14955. (error (nth 1 msg)))
  14956. The return value will then be either a string with the error message,
  14957. or a marker if everything is OK.
  14958. If THIS-BUFFER is set, the outline path does not contain a file,
  14959. only headings."
  14960. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14961. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14962. (level 1)
  14963. (lmin 1)
  14964. (lmax 1)
  14965. end found flevel)
  14966. (unless buffer (error "File not found :%s" file))
  14967. (with-current-buffer buffer
  14968. (unless (derived-mode-p 'org-mode)
  14969. (error "Buffer %s needs to be in Org mode" buffer))
  14970. (org-with-wide-buffer
  14971. (goto-char (point-min))
  14972. (dolist (heading path)
  14973. (let ((re (format org-complex-heading-regexp-format
  14974. (regexp-quote heading)))
  14975. (cnt 0))
  14976. (while (re-search-forward re end t)
  14977. (setq level (- (match-end 1) (match-beginning 1)))
  14978. (when (and (>= level lmin) (<= level lmax))
  14979. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14980. (when (= cnt 0)
  14981. (error "Heading not found on level %d: %s" lmax heading))
  14982. (when (> cnt 1)
  14983. (error "Heading not unique on level %d: %s" lmax heading))
  14984. (goto-char found)
  14985. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14986. (setq end (save-excursion (org-end-of-subtree t t)))))
  14987. (when (org-at-heading-p)
  14988. (point-marker))))))
  14989. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14990. "Find node HEADING in BUFFER.
  14991. Return a marker to the heading if it was found, or nil if not.
  14992. If POS-ONLY is set, return just the position instead of a marker.
  14993. The heading text must match exact, but it may have a TODO keyword,
  14994. a priority cookie and tags in the standard locations."
  14995. (with-current-buffer (or buffer (current-buffer))
  14996. (org-with-wide-buffer
  14997. (goto-char (point-min))
  14998. (let (case-fold-search)
  14999. (when (re-search-forward
  15000. (format org-complex-heading-regexp-format
  15001. (regexp-quote heading)) nil t)
  15002. (if pos-only
  15003. (match-beginning 0)
  15004. (move-marker (make-marker) (match-beginning 0))))))))
  15005. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15006. "Find Org node headline HEADING in all .org files in directory DIR.
  15007. When the target headline is found, return a marker to this location."
  15008. (let ((files (directory-files (or dir default-directory)
  15009. t "\\`[^.#].*\\.org\\'"))
  15010. visiting m buffer)
  15011. (catch 'found
  15012. (dolist (file files)
  15013. (message "trying %s" file)
  15014. (setq visiting (org-find-base-buffer-visiting file))
  15015. (setq buffer (or visiting (find-file-noselect file)))
  15016. (setq m (org-find-exact-headline-in-buffer
  15017. heading buffer))
  15018. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15019. (and m (throw 'found m))))))
  15020. (defun org-find-entry-with-id (ident)
  15021. "Locate the entry that contains the ID property with exact value IDENT.
  15022. IDENT can be a string, a symbol or a number, this function will search for
  15023. the string representation of it.
  15024. Return the position where this entry starts, or nil if there is no such entry."
  15025. (interactive "sID: ")
  15026. (let ((id (cond
  15027. ((stringp ident) ident)
  15028. ((symbolp ident) (symbol-name ident))
  15029. ((numberp ident) (number-to-string ident))
  15030. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15031. (org-with-wide-buffer (org-find-property "ID" id))))
  15032. ;;;; Timestamps
  15033. (defvar org-last-changed-timestamp nil)
  15034. (defvar org-last-inserted-timestamp nil
  15035. "The last time stamp inserted with `org-insert-time-stamp'.")
  15036. (defun org-time-stamp (arg &optional inactive)
  15037. "Prompt for a date/time and insert a time stamp.
  15038. If the user specifies a time like HH:MM or if this command is
  15039. called with at least one prefix argument, the time stamp contains
  15040. the date and the time. Otherwise, only the date is included.
  15041. All parts of a date not specified by the user are filled in from
  15042. the timestamp at point, if any, or the current date/time
  15043. otherwise.
  15044. If there is already a timestamp at the cursor, it is replaced.
  15045. With two universal prefix arguments, insert an active timestamp
  15046. with the current time without prompting the user.
  15047. When called from lisp, the timestamp is inactive if INACTIVE is
  15048. non-nil."
  15049. (interactive "P")
  15050. (let* ((ts (cond
  15051. ((org-at-date-range-p t)
  15052. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15053. ((org-at-timestamp-p 'lax) (match-string 0))))
  15054. ;; Default time is either the timestamp at point or today.
  15055. ;; When entering a range, only the range start is considered.
  15056. (default-time (if (not ts) (current-time)
  15057. (apply #'encode-time (org-parse-time-string ts))))
  15058. (default-input (and ts (org-get-compact-tod ts)))
  15059. (repeater (and ts
  15060. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15061. (match-string 0 ts)))
  15062. org-time-was-given
  15063. org-end-time-was-given
  15064. (time
  15065. (and (if (equal arg '(16)) (current-time)
  15066. ;; Preserve `this-command' and `last-command'.
  15067. (let ((this-command this-command)
  15068. (last-command last-command))
  15069. (org-read-date
  15070. arg 'totime nil nil default-time default-input
  15071. inactive))))))
  15072. (cond
  15073. ((and ts
  15074. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15075. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15076. (insert "--")
  15077. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15078. (ts
  15079. ;; Make sure we're on a timestamp. When in the middle of a date
  15080. ;; range, move arbitrarily to range end.
  15081. (unless (org-at-timestamp-p 'lax)
  15082. (skip-chars-forward "-")
  15083. (org-at-timestamp-p 'lax))
  15084. (replace-match "")
  15085. (setq org-last-changed-timestamp
  15086. (org-insert-time-stamp
  15087. time (or org-time-was-given arg)
  15088. inactive nil nil (list org-end-time-was-given)))
  15089. (when repeater
  15090. (backward-char)
  15091. (insert " " repeater)
  15092. (setq org-last-changed-timestamp
  15093. (concat (substring org-last-inserted-timestamp 0 -1)
  15094. " " repeater ">")))
  15095. (message "Timestamp updated"))
  15096. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15097. (t (org-insert-time-stamp
  15098. time (or org-time-was-given arg) inactive nil nil
  15099. (list org-end-time-was-given))))))
  15100. ;; FIXME: can we use this for something else, like computing time differences?
  15101. (defun org-get-compact-tod (s)
  15102. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15103. (let* ((t1 (match-string 1 s))
  15104. (h1 (string-to-number (match-string 2 s)))
  15105. (m1 (string-to-number (match-string 3 s)))
  15106. (t2 (and (match-end 4) (match-string 5 s)))
  15107. (h2 (and t2 (string-to-number (match-string 6 s))))
  15108. (m2 (and t2 (string-to-number (match-string 7 s))))
  15109. dh dm)
  15110. (if (not t2)
  15111. t1
  15112. (setq dh (- h2 h1) dm (- m2 m1))
  15113. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15114. (concat t1 "+" (number-to-string dh)
  15115. (and (/= 0 dm) (format ":%02d" dm)))))))
  15116. (defun org-time-stamp-inactive (&optional arg)
  15117. "Insert an inactive time stamp.
  15118. An inactive time stamp is enclosed in square brackets instead of angle
  15119. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15120. does not link to the calendar and cannot be changed with the S-cursor keys.
  15121. So these are more for recording a certain time/date."
  15122. (interactive "P")
  15123. (org-time-stamp arg 'inactive))
  15124. (defvar org-date-ovl (make-overlay 1 1))
  15125. (overlay-put org-date-ovl 'face 'org-date-selected)
  15126. (delete-overlay org-date-ovl)
  15127. (defvar org-ans1) ; dynamically scoped parameter
  15128. (defvar org-ans2) ; dynamically scoped parameter
  15129. (defvar org-plain-time-of-day-regexp) ; defined below
  15130. (defvar org-overriding-default-time nil) ; dynamically scoped
  15131. (defvar org-read-date-overlay nil)
  15132. (defvar org-dcst nil) ; dynamically scoped
  15133. (defvar org-read-date-history nil)
  15134. (defvar org-read-date-final-answer nil)
  15135. (defvar org-read-date-analyze-futurep nil)
  15136. (defvar org-read-date-analyze-forced-year nil)
  15137. (defvar org-read-date-inactive)
  15138. (defvar org-read-date-minibuffer-local-map
  15139. (let* ((map (make-sparse-keymap)))
  15140. (set-keymap-parent map minibuffer-local-map)
  15141. (org-defkey map (kbd ".")
  15142. (lambda () (interactive)
  15143. ;; Are we at the beginning of the prompt?
  15144. (if (looking-back "^[^:]+: "
  15145. (let ((inhibit-field-text-motion t))
  15146. (line-beginning-position)))
  15147. (org-eval-in-calendar '(calendar-goto-today))
  15148. (insert "."))))
  15149. (org-defkey map (kbd "C-.")
  15150. (lambda () (interactive)
  15151. (org-eval-in-calendar '(calendar-goto-today))))
  15152. (org-defkey map [(meta shift left)]
  15153. (lambda () (interactive)
  15154. (org-eval-in-calendar '(calendar-backward-month 1))))
  15155. (org-defkey map [(meta shift right)]
  15156. (lambda () (interactive)
  15157. (org-eval-in-calendar '(calendar-forward-month 1))))
  15158. (org-defkey map [(meta shift up)]
  15159. (lambda () (interactive)
  15160. (org-eval-in-calendar '(calendar-backward-year 1))))
  15161. (org-defkey map [(meta shift down)]
  15162. (lambda () (interactive)
  15163. (org-eval-in-calendar '(calendar-forward-year 1))))
  15164. (org-defkey map [?\e (shift left)]
  15165. (lambda () (interactive)
  15166. (org-eval-in-calendar '(calendar-backward-month 1))))
  15167. (org-defkey map [?\e (shift right)]
  15168. (lambda () (interactive)
  15169. (org-eval-in-calendar '(calendar-forward-month 1))))
  15170. (org-defkey map [?\e (shift up)]
  15171. (lambda () (interactive)
  15172. (org-eval-in-calendar '(calendar-backward-year 1))))
  15173. (org-defkey map [?\e (shift down)]
  15174. (lambda () (interactive)
  15175. (org-eval-in-calendar '(calendar-forward-year 1))))
  15176. (org-defkey map [(shift up)]
  15177. (lambda () (interactive)
  15178. (org-eval-in-calendar '(calendar-backward-week 1))))
  15179. (org-defkey map [(shift down)]
  15180. (lambda () (interactive)
  15181. (org-eval-in-calendar '(calendar-forward-week 1))))
  15182. (org-defkey map [(shift left)]
  15183. (lambda () (interactive)
  15184. (org-eval-in-calendar '(calendar-backward-day 1))))
  15185. (org-defkey map [(shift right)]
  15186. (lambda () (interactive)
  15187. (org-eval-in-calendar '(calendar-forward-day 1))))
  15188. (org-defkey map "!"
  15189. (lambda () (interactive)
  15190. (org-eval-in-calendar '(diary-view-entries))
  15191. (message "")))
  15192. (org-defkey map ">"
  15193. (lambda () (interactive)
  15194. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15195. (org-defkey map "<"
  15196. (lambda () (interactive)
  15197. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15198. (org-defkey map "\C-v"
  15199. (lambda () (interactive)
  15200. (org-eval-in-calendar
  15201. '(calendar-scroll-left-three-months 1))))
  15202. (org-defkey map "\M-v"
  15203. (lambda () (interactive)
  15204. (org-eval-in-calendar
  15205. '(calendar-scroll-right-three-months 1))))
  15206. map)
  15207. "Keymap for minibuffer commands when using `org-read-date'.")
  15208. (defvar org-def)
  15209. (defvar org-defdecode)
  15210. (defvar org-with-time)
  15211. (defvar calendar-setup) ; Dynamically scoped.
  15212. (defun org-read-date (&optional with-time to-time from-string prompt
  15213. default-time default-input inactive)
  15214. "Read a date, possibly a time, and make things smooth for the user.
  15215. The prompt will suggest to enter an ISO date, but you can also enter anything
  15216. which will at least partially be understood by `parse-time-string'.
  15217. Unrecognized parts of the date will default to the current day, month, year,
  15218. hour and minute. If this command is called to replace a timestamp at point,
  15219. or to enter the second timestamp of a range, the default time is taken
  15220. from the existing stamp. Furthermore, the command prefers the future,
  15221. so if you are giving a date where the year is not given, and the day-month
  15222. combination is already past in the current year, it will assume you
  15223. mean next year. For details, see the manual. A few examples:
  15224. 3-2-5 --> 2003-02-05
  15225. feb 15 --> currentyear-02-15
  15226. 2/15 --> currentyear-02-15
  15227. sep 12 9 --> 2009-09-12
  15228. 12:45 --> today 12:45
  15229. 22 sept 0:34 --> currentyear-09-22 0:34
  15230. 12 --> currentyear-currentmonth-12
  15231. Fri --> nearest Friday after today
  15232. -Tue --> last Tuesday
  15233. etc.
  15234. Furthermore you can specify a relative date by giving, as the *first* thing
  15235. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15236. change in days weeks, months, years.
  15237. With a single plus or minus, the date is relative to today. With a double
  15238. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15239. +4d --> four days from today
  15240. +4 --> same as above
  15241. +2w --> two weeks from today
  15242. ++5 --> five days from default date
  15243. The function understands only English month and weekday abbreviations.
  15244. While prompting, a calendar is popped up - you can also select the
  15245. date with the mouse (button 1). The calendar shows a period of three
  15246. months. To scroll it to other months, use the keys `>' and `<'.
  15247. If you don't like the calendar, turn it off with
  15248. (setq org-read-date-popup-calendar nil)
  15249. With optional argument TO-TIME, the date will immediately be converted
  15250. to an internal time.
  15251. With an optional argument WITH-TIME, the prompt will suggest to
  15252. also insert a time. Note that when WITH-TIME is not set, you can
  15253. still enter a time, and this function will inform the calling routine
  15254. about this change. The calling routine may then choose to change the
  15255. format used to insert the time stamp into the buffer to include the time.
  15256. With optional argument FROM-STRING, read from this string instead from
  15257. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15258. the time/date that is used for everything that is not specified by the
  15259. user."
  15260. (require 'parse-time)
  15261. (let* ((org-with-time with-time)
  15262. (org-time-stamp-rounding-minutes
  15263. (if (equal org-with-time '(16))
  15264. '(0 0)
  15265. org-time-stamp-rounding-minutes))
  15266. (org-dcst org-display-custom-times)
  15267. (ct (org-current-time))
  15268. (org-def (or org-overriding-default-time default-time ct))
  15269. (org-defdecode (decode-time org-def))
  15270. (cur-frame (selected-frame))
  15271. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15272. (calendar-setup
  15273. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15274. (calendar-move-hook nil)
  15275. (calendar-view-diary-initially-flag nil)
  15276. (calendar-view-holidays-initially-flag nil)
  15277. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15278. ;; Rationalize `org-def' and `org-defdecode', if required.
  15279. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15280. (setf (nth 2 org-defdecode) -1)
  15281. (setf (nth 1 org-defdecode) 59)
  15282. (setq org-def (apply #'encode-time org-defdecode))
  15283. (setq org-defdecode (decode-time org-def)))
  15284. (let* ((timestr (format-time-string
  15285. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15286. org-def))
  15287. (prompt (concat (if prompt (concat prompt " ") "")
  15288. (format "Date+time [%s]: " timestr))))
  15289. (cond
  15290. (from-string (setq ans from-string))
  15291. (org-read-date-popup-calendar
  15292. (save-excursion
  15293. (save-window-excursion
  15294. (calendar)
  15295. (when (eq calendar-setup 'calendar-only)
  15296. (setq cal-frame
  15297. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15298. (select-frame cal-frame))
  15299. (org-eval-in-calendar '(setq cursor-type nil) t)
  15300. (unwind-protect
  15301. (progn
  15302. (calendar-forward-day (- (time-to-days org-def)
  15303. (calendar-absolute-from-gregorian
  15304. (calendar-current-date))))
  15305. (org-eval-in-calendar nil t)
  15306. (let* ((old-map (current-local-map))
  15307. (map (copy-keymap calendar-mode-map))
  15308. (minibuffer-local-map
  15309. (copy-keymap org-read-date-minibuffer-local-map)))
  15310. (org-defkey map (kbd "RET") 'org-calendar-select)
  15311. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15312. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15313. (unwind-protect
  15314. (progn
  15315. (use-local-map map)
  15316. (setq org-read-date-inactive inactive)
  15317. (add-hook 'post-command-hook 'org-read-date-display)
  15318. (setq org-ans0
  15319. (read-string prompt
  15320. default-input
  15321. 'org-read-date-history
  15322. nil))
  15323. ;; org-ans0: from prompt
  15324. ;; org-ans1: from mouse click
  15325. ;; org-ans2: from calendar motion
  15326. (setq ans
  15327. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15328. (remove-hook 'post-command-hook 'org-read-date-display)
  15329. (use-local-map old-map)
  15330. (when org-read-date-overlay
  15331. (delete-overlay org-read-date-overlay)
  15332. (setq org-read-date-overlay nil)))))
  15333. (bury-buffer "*Calendar*")
  15334. (when cal-frame
  15335. (delete-frame cal-frame)
  15336. (select-frame-set-input-focus cur-frame))))))
  15337. (t ; Naked prompt only
  15338. (unwind-protect
  15339. (setq ans (read-string prompt default-input
  15340. 'org-read-date-history timestr))
  15341. (when org-read-date-overlay
  15342. (delete-overlay org-read-date-overlay)
  15343. (setq org-read-date-overlay nil))))))
  15344. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15345. (when org-read-date-analyze-forced-year
  15346. (message "Year was forced into %s"
  15347. (if org-read-date-force-compatible-dates
  15348. "compatible range (1970-2037)"
  15349. "range representable on this machine"))
  15350. (ding))
  15351. ;; One round trip to get rid of 34th of August and stuff like that....
  15352. (setq final (decode-time (apply 'encode-time final)))
  15353. (setq org-read-date-final-answer ans)
  15354. (if to-time
  15355. (apply 'encode-time final)
  15356. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15357. (format "%04d-%02d-%02d %02d:%02d"
  15358. (nth 5 final) (nth 4 final) (nth 3 final)
  15359. (nth 2 final) (nth 1 final))
  15360. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15361. (defun org-read-date-display ()
  15362. "Display the current date prompt interpretation in the minibuffer."
  15363. (when org-read-date-display-live
  15364. (when org-read-date-overlay
  15365. (delete-overlay org-read-date-overlay))
  15366. (when (minibufferp (current-buffer))
  15367. (save-excursion
  15368. (end-of-line 1)
  15369. (while (not (equal (buffer-substring
  15370. (max (point-min) (- (point) 4)) (point))
  15371. " "))
  15372. (insert " ")))
  15373. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15374. " " (or org-ans1 org-ans2)))
  15375. (org-end-time-was-given nil)
  15376. (f (org-read-date-analyze ans org-def org-defdecode))
  15377. (fmts (if org-dcst
  15378. org-time-stamp-custom-formats
  15379. org-time-stamp-formats))
  15380. (fmt (if (or org-with-time
  15381. (and (boundp 'org-time-was-given) org-time-was-given))
  15382. (cdr fmts)
  15383. (car fmts)))
  15384. (txt (format-time-string fmt (apply 'encode-time f)))
  15385. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15386. (txt (concat "=> " txt)))
  15387. (when (and org-end-time-was-given
  15388. (string-match org-plain-time-of-day-regexp txt))
  15389. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15390. org-end-time-was-given
  15391. (substring txt (match-end 0)))))
  15392. (when org-read-date-analyze-futurep
  15393. (setq txt (concat txt " (=>F)")))
  15394. (setq org-read-date-overlay
  15395. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15396. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15397. (defun org-read-date-analyze (ans def defdecode)
  15398. "Analyze the combined answer of the date prompt."
  15399. ;; FIXME: cleanup and comment
  15400. ;; Pass `current-time' result to `decode-time' (instead of calling
  15401. ;; without arguments) so that only `current-time' has to be
  15402. ;; overridden in tests.
  15403. (let ((org-def def)
  15404. (org-defdecode defdecode)
  15405. (nowdecode (decode-time (current-time)))
  15406. delta deltan deltaw deltadef year month day
  15407. hour minute second wday pm h2 m2 tl wday1
  15408. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15409. (setq org-read-date-analyze-futurep nil
  15410. org-read-date-analyze-forced-year nil)
  15411. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15412. (setq ans "+0"))
  15413. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15414. (setq ans (replace-match "" t t ans)
  15415. deltan (car delta)
  15416. deltaw (nth 1 delta)
  15417. deltadef (nth 2 delta)))
  15418. ;; Check if there is an iso week date in there. If yes, store the
  15419. ;; info and postpone interpreting it until the rest of the parsing
  15420. ;; is done.
  15421. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15422. (setq iso-year (when (match-end 1)
  15423. (org-small-year-to-year
  15424. (string-to-number (match-string 1 ans))))
  15425. iso-weekday (when (match-end 3)
  15426. (string-to-number (match-string 3 ans)))
  15427. iso-week (string-to-number (match-string 2 ans)))
  15428. (setq ans (replace-match "" t t ans)))
  15429. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15430. (when (string-match
  15431. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15432. (setq year (if (match-end 2)
  15433. (string-to-number (match-string 2 ans))
  15434. (progn (setq kill-year t)
  15435. (string-to-number (format-time-string "%Y"))))
  15436. month (string-to-number (match-string 3 ans))
  15437. day (string-to-number (match-string 4 ans)))
  15438. (setq year (org-small-year-to-year year))
  15439. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15440. t nil ans)))
  15441. ;; Help matching dotted european dates
  15442. (when (string-match
  15443. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15444. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15445. (setq kill-year t)
  15446. (string-to-number (format-time-string "%Y")))
  15447. day (string-to-number (match-string 1 ans))
  15448. month (string-to-number (match-string 2 ans))
  15449. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15450. t nil ans)))
  15451. ;; Help matching american dates, like 5/30 or 5/30/7
  15452. (when (string-match
  15453. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15454. (setq year (if (match-end 4)
  15455. (string-to-number (match-string 4 ans))
  15456. (progn (setq kill-year t)
  15457. (string-to-number (format-time-string "%Y"))))
  15458. month (string-to-number (match-string 1 ans))
  15459. day (string-to-number (match-string 2 ans)))
  15460. (setq year (org-small-year-to-year year))
  15461. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15462. t nil ans)))
  15463. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15464. ;; If there is a time with am/pm, and *no* time without it, we convert
  15465. ;; so that matching will be successful.
  15466. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15467. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15468. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15469. (setq hour (string-to-number (match-string 1 ans))
  15470. minute (if (match-end 3)
  15471. (string-to-number (match-string 3 ans))
  15472. 0)
  15473. pm (equal ?p
  15474. (string-to-char (downcase (match-string 4 ans)))))
  15475. (if (and (= hour 12) (not pm))
  15476. (setq hour 0)
  15477. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15478. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15479. t t ans))))
  15480. ;; Check if a time range is given as a duration
  15481. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15482. (setq hour (string-to-number (match-string 1 ans))
  15483. h2 (+ hour (string-to-number (match-string 3 ans)))
  15484. minute (string-to-number (match-string 2 ans))
  15485. m2 (+ minute (if (match-end 5) (string-to-number
  15486. (match-string 5 ans))0)))
  15487. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15488. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15489. t t ans)))
  15490. ;; Check if there is a time range
  15491. (when (boundp 'org-end-time-was-given)
  15492. (setq org-time-was-given nil)
  15493. (when (and (string-match org-plain-time-of-day-regexp ans)
  15494. (match-end 8))
  15495. (setq org-end-time-was-given (match-string 8 ans))
  15496. (setq ans (concat (substring ans 0 (match-beginning 7))
  15497. (substring ans (match-end 7))))))
  15498. (setq tl (parse-time-string ans)
  15499. day (or (nth 3 tl) (nth 3 org-defdecode))
  15500. month
  15501. (cond ((nth 4 tl))
  15502. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15503. ;; Day was specified. Make sure DAY+MONTH
  15504. ;; combination happens in the future.
  15505. ((nth 3 tl)
  15506. (setq futurep t)
  15507. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15508. (nth 4 nowdecode)))
  15509. (t (nth 4 org-defdecode)))
  15510. year
  15511. (cond ((and (not kill-year) (nth 5 tl)))
  15512. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15513. ;; Month was guessed in the future and is at least
  15514. ;; equal to NOWDECODE's. Fix year accordingly.
  15515. (futurep
  15516. (if (or (> month (nth 4 nowdecode))
  15517. (>= day (nth 3 nowdecode)))
  15518. (nth 5 nowdecode)
  15519. (1+ (nth 5 nowdecode))))
  15520. ;; Month was specified. Make sure MONTH+YEAR
  15521. ;; combination happens in the future.
  15522. ((nth 4 tl)
  15523. (setq futurep t)
  15524. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15525. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15526. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15527. (t (nth 5 nowdecode))))
  15528. (t (nth 5 org-defdecode)))
  15529. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15530. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15531. second (or (nth 0 tl) 0)
  15532. wday (nth 6 tl))
  15533. (when (and (eq org-read-date-prefer-future 'time)
  15534. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15535. (equal day (nth 3 nowdecode))
  15536. (equal month (nth 4 nowdecode))
  15537. (equal year (nth 5 nowdecode))
  15538. (nth 2 tl)
  15539. (or (< (nth 2 tl) (nth 2 nowdecode))
  15540. (and (= (nth 2 tl) (nth 2 nowdecode))
  15541. (nth 1 tl)
  15542. (< (nth 1 tl) (nth 1 nowdecode)))))
  15543. (setq day (1+ day)
  15544. futurep t))
  15545. ;; Special date definitions below
  15546. (cond
  15547. (iso-week
  15548. ;; There was an iso week
  15549. (require 'cal-iso)
  15550. (setq futurep nil)
  15551. (setq year (or iso-year year)
  15552. day (or iso-weekday wday 1)
  15553. wday nil ; to make sure that the trigger below does not match
  15554. iso-date (calendar-gregorian-from-absolute
  15555. (calendar-iso-to-absolute
  15556. (list iso-week day year))))
  15557. ; FIXME: Should we also push ISO weeks into the future?
  15558. ; (when (and org-read-date-prefer-future
  15559. ; (not iso-year)
  15560. ; (< (calendar-absolute-from-gregorian iso-date)
  15561. ; (time-to-days (current-time))))
  15562. ; (setq year (1+ year)
  15563. ; iso-date (calendar-gregorian-from-absolute
  15564. ; (calendar-iso-to-absolute
  15565. ; (list iso-week day year)))))
  15566. (setq month (car iso-date)
  15567. year (nth 2 iso-date)
  15568. day (nth 1 iso-date)))
  15569. (deltan
  15570. (setq futurep nil)
  15571. (unless deltadef
  15572. ;; Pass `current-time' result to `decode-time' (instead of
  15573. ;; calling without arguments) so that only `current-time' has
  15574. ;; to be overridden in tests.
  15575. (let ((now (decode-time (current-time))))
  15576. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15577. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15578. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15579. ((equal deltaw "m") (setq month (+ month deltan)))
  15580. ((equal deltaw "y") (setq year (+ year deltan)))))
  15581. ((and wday (not (nth 3 tl)))
  15582. ;; Weekday was given, but no day, so pick that day in the week
  15583. ;; on or after the derived date.
  15584. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15585. (unless (equal wday wday1)
  15586. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15587. (when (and (boundp 'org-time-was-given)
  15588. (nth 2 tl))
  15589. (setq org-time-was-given t))
  15590. (when (< year 100) (setq year (+ 2000 year)))
  15591. ;; Check of the date is representable
  15592. (if org-read-date-force-compatible-dates
  15593. (progn
  15594. (when (< year 1970)
  15595. (setq year 1970 org-read-date-analyze-forced-year t))
  15596. (when (> year 2037)
  15597. (setq year 2037 org-read-date-analyze-forced-year t)))
  15598. (condition-case nil
  15599. (ignore (encode-time second minute hour day month year))
  15600. (error
  15601. (setq year (nth 5 org-defdecode))
  15602. (setq org-read-date-analyze-forced-year t))))
  15603. (setq org-read-date-analyze-futurep futurep)
  15604. (list second minute hour day month year)))
  15605. (defvar parse-time-weekdays)
  15606. (defun org-read-date-get-relative (s today default)
  15607. "Check string S for special relative date string.
  15608. TODAY and DEFAULT are internal times, for today and for a default.
  15609. Return shift list (N what def-flag)
  15610. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15611. N is the number of WHATs to shift.
  15612. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15613. the DEFAULT date rather than TODAY."
  15614. (require 'parse-time)
  15615. (when (and
  15616. (string-match
  15617. (concat
  15618. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15619. "\\([0-9]+\\)?"
  15620. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15621. "\\([ \t]\\|$\\)") s)
  15622. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15623. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15624. (string-to-char (substring (match-string 1 s) -1))
  15625. ?+))
  15626. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15627. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15628. (what (if (match-end 3) (match-string 3 s) "d"))
  15629. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15630. (date (if rel default today))
  15631. (wday (nth 6 (decode-time date)))
  15632. delta)
  15633. (if wday1
  15634. (progn
  15635. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15636. (when (= delta 0) (setq delta 7))
  15637. (when (= dir ?-)
  15638. (setq delta (- delta 7))
  15639. (when (= delta 0) (setq delta -7)))
  15640. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15641. (list delta "d" rel))
  15642. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15643. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15644. "Turn a user-specified date into the internal representation.
  15645. The internal representation needed by the calendar is (month day year).
  15646. This is a wrapper to handle the brain-dead convention in calendar that
  15647. user function argument order change dependent on argument order."
  15648. (pcase calendar-date-style
  15649. (`american (list arg1 arg2 arg3))
  15650. (`european (list arg2 arg1 arg3))
  15651. (`iso (list arg2 arg3 arg1))))
  15652. (defun org-eval-in-calendar (form &optional keepdate)
  15653. "Eval FORM in the calendar window and return to current window.
  15654. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15655. (let ((sf (selected-frame))
  15656. (sw (selected-window)))
  15657. (select-window (get-buffer-window "*Calendar*" t))
  15658. (eval form)
  15659. (when (and (not keepdate) (calendar-cursor-to-date))
  15660. (let* ((date (calendar-cursor-to-date))
  15661. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15662. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15663. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15664. (select-window sw)
  15665. (select-frame-set-input-focus sf)))
  15666. (defun org-calendar-select ()
  15667. "Return to `org-read-date' with the date currently selected.
  15668. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15669. (interactive)
  15670. (when (calendar-cursor-to-date)
  15671. (let* ((date (calendar-cursor-to-date))
  15672. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15673. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15674. (when (active-minibuffer-window) (exit-minibuffer))))
  15675. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15676. "Insert a date stamp for the date given by the internal TIME.
  15677. See `format-time-string' for the format of TIME.
  15678. WITH-HM means use the stamp format that includes the time of the day.
  15679. INACTIVE means use square brackets instead of angular ones, so that the
  15680. stamp will not contribute to the agenda.
  15681. PRE and POST are optional strings to be inserted before and after the
  15682. stamp.
  15683. The command returns the inserted time stamp."
  15684. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15685. stamp)
  15686. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15687. (insert-before-markers (or pre ""))
  15688. (when (listp extra)
  15689. (setq extra (car extra))
  15690. (if (and (stringp extra)
  15691. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15692. (setq extra (format "-%02d:%02d"
  15693. (string-to-number (match-string 1 extra))
  15694. (string-to-number (match-string 2 extra))))
  15695. (setq extra nil)))
  15696. (when extra
  15697. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15698. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15699. (insert-before-markers (or post ""))
  15700. (setq org-last-inserted-timestamp stamp)))
  15701. (defun org-toggle-time-stamp-overlays ()
  15702. "Toggle the use of custom time stamp formats."
  15703. (interactive)
  15704. (setq org-display-custom-times (not org-display-custom-times))
  15705. (unless org-display-custom-times
  15706. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15707. (while (setq p (next-single-property-change p 'display))
  15708. (when (and (get-text-property p 'display)
  15709. (eq (get-text-property p 'face) 'org-date))
  15710. (remove-text-properties
  15711. p (setq p (next-single-property-change p 'display))
  15712. '(display t))))
  15713. (set-buffer-modified-p bmp)))
  15714. (org-restart-font-lock)
  15715. (setq org-table-may-need-update t)
  15716. (if org-display-custom-times
  15717. (message "Time stamps are overlaid with custom format")
  15718. (message "Time stamp overlays removed")))
  15719. (defun org-display-custom-time (beg end)
  15720. "Overlay modified time stamp format over timestamp between BEG and END."
  15721. (let* ((ts (buffer-substring beg end))
  15722. t1 with-hm tf time str (off 0))
  15723. (save-match-data
  15724. (setq t1 (org-parse-time-string ts t))
  15725. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15726. (setq off (- (match-end 0) (match-beginning 0)))))
  15727. (setq end (- end off))
  15728. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15729. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15730. time (org-fix-decoded-time t1)
  15731. str (org-add-props
  15732. (format-time-string
  15733. (substring tf 1 -1) (apply 'encode-time time))
  15734. nil 'mouse-face 'highlight))
  15735. (put-text-property beg end 'display str)))
  15736. (defun org-fix-decoded-time (time)
  15737. "Set 0 instead of nil for the first 6 elements of time.
  15738. Don't touch the rest."
  15739. (let ((n 0))
  15740. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15741. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15742. "Difference between TIMESTAMP-STRING and now in days.
  15743. If SECONDS is non-nil, return the difference in seconds."
  15744. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15745. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15746. (funcall fdiff (current-time)))))
  15747. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15748. "Is the time in TIMESTAMP-STRING close to the current date?"
  15749. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15750. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15751. (not (org-entry-is-done-p))))
  15752. (defun org-get-wdays (ts &optional delay zero-delay)
  15753. "Get the deadline lead time appropriate for timestring TS.
  15754. When DELAY is non-nil, get the delay time for scheduled items
  15755. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15756. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15757. don't try to find the delay cookie in the scheduled timestamp."
  15758. (let ((tv (if delay org-scheduled-delay-days
  15759. org-deadline-warning-days)))
  15760. (cond
  15761. ((or (and delay (< tv 0))
  15762. (and delay zero-delay (<= tv 0))
  15763. (and (not delay) (<= tv 0)))
  15764. ;; Enforce this value no matter what
  15765. (- tv))
  15766. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15767. ;; lead time is specified.
  15768. (floor (* (string-to-number (match-string 1 ts))
  15769. (cdr (assoc (match-string 2 ts)
  15770. '(("d" . 1) ("w" . 7)
  15771. ("m" . 30.4) ("y" . 365.25)
  15772. ("h" . 0.041667)))))))
  15773. ;; go for the default.
  15774. (t tv))))
  15775. (defun org-calendar-select-mouse (ev)
  15776. "Return to `org-read-date' with the date currently selected.
  15777. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15778. (interactive "e")
  15779. (mouse-set-point ev)
  15780. (when (calendar-cursor-to-date)
  15781. (let* ((date (calendar-cursor-to-date))
  15782. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15783. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15784. (when (active-minibuffer-window) (exit-minibuffer))))
  15785. (defun org-check-deadlines (ndays)
  15786. "Check if there are any deadlines due or past due.
  15787. A deadline is considered due if it happens within `org-deadline-warning-days'
  15788. days from today's date. If the deadline appears in an entry marked DONE,
  15789. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15790. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15791. are shown."
  15792. (interactive "P")
  15793. (let* ((org-warn-days
  15794. (cond
  15795. ((equal ndays '(4)) 100000)
  15796. (ndays (prefix-numeric-value ndays))
  15797. (t (abs org-deadline-warning-days))))
  15798. (case-fold-search nil)
  15799. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15800. (callback
  15801. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15802. (message "%d deadlines past-due or due within %d days"
  15803. (org-occur regexp nil callback)
  15804. org-warn-days)))
  15805. (defsubst org-re-timestamp (type)
  15806. "Return a regexp for timestamp TYPE.
  15807. Allowed values for TYPE are:
  15808. all: all timestamps
  15809. active: only active timestamps (<...>)
  15810. inactive: only inactive timestamps ([...])
  15811. scheduled: only scheduled timestamps
  15812. deadline: only deadline timestamps
  15813. closed: only closed time-stamps
  15814. When TYPE is nil, fall back on returning a regexp that matches
  15815. both scheduled and deadline timestamps."
  15816. (cl-case type
  15817. (all org-ts-regexp-both)
  15818. (active org-ts-regexp)
  15819. (inactive org-ts-regexp-inactive)
  15820. (scheduled org-scheduled-time-regexp)
  15821. (deadline org-deadline-time-regexp)
  15822. (closed org-closed-time-regexp)
  15823. (otherwise
  15824. (concat "\\<"
  15825. (regexp-opt (list org-deadline-string org-scheduled-string))
  15826. " *<\\([^>]+\\)>"))))
  15827. (defun org-check-before-date (d)
  15828. "Check if there are deadlines or scheduled entries before date D."
  15829. (interactive (list (org-read-date)))
  15830. (let* ((case-fold-search nil)
  15831. (regexp (org-re-timestamp org-ts-type))
  15832. (ts-type org-ts-type)
  15833. (callback
  15834. (lambda ()
  15835. (let ((match (match-string 1)))
  15836. (and (if (memq ts-type '(active inactive all))
  15837. (eq (org-element-type (save-excursion
  15838. (backward-char)
  15839. (org-element-context)))
  15840. 'timestamp)
  15841. (org-at-planning-p))
  15842. (time-less-p
  15843. (org-time-string-to-time match t)
  15844. (org-time-string-to-time d t)))))))
  15845. (message "%d entries before %s"
  15846. (org-occur regexp nil callback)
  15847. d)))
  15848. (defun org-check-after-date (d)
  15849. "Check if there are deadlines or scheduled entries after date D."
  15850. (interactive (list (org-read-date)))
  15851. (let* ((case-fold-search nil)
  15852. (regexp (org-re-timestamp org-ts-type))
  15853. (ts-type org-ts-type)
  15854. (callback
  15855. (lambda ()
  15856. (let ((match (match-string 1)))
  15857. (and (if (memq ts-type '(active inactive all))
  15858. (eq (org-element-type (save-excursion
  15859. (backward-char)
  15860. (org-element-context)))
  15861. 'timestamp)
  15862. (org-at-planning-p))
  15863. (not (time-less-p
  15864. (org-time-string-to-time match t)
  15865. (org-time-string-to-time d t))))))))
  15866. (message "%d entries after %s"
  15867. (org-occur regexp nil callback)
  15868. d)))
  15869. (defun org-check-dates-range (start-date end-date)
  15870. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15871. (interactive (list (org-read-date nil nil nil "Range starts")
  15872. (org-read-date nil nil nil "Range end")))
  15873. (let ((case-fold-search nil)
  15874. (regexp (org-re-timestamp org-ts-type))
  15875. (callback
  15876. (let ((type org-ts-type))
  15877. (lambda ()
  15878. (let ((match (match-string 1)))
  15879. (and
  15880. (if (memq type '(active inactive all))
  15881. (eq (org-element-type (save-excursion
  15882. (backward-char)
  15883. (org-element-context)))
  15884. 'timestamp)
  15885. (org-at-planning-p))
  15886. (not (time-less-p
  15887. (org-time-string-to-time match t)
  15888. (org-time-string-to-time start-date t)))
  15889. (time-less-p
  15890. (org-time-string-to-time match t)
  15891. (org-time-string-to-time end-date t))))))))
  15892. (message "%d entries between %s and %s"
  15893. (org-occur regexp nil callback) start-date end-date)))
  15894. (defun org-evaluate-time-range (&optional to-buffer)
  15895. "Evaluate a time range by computing the difference between start and end.
  15896. Normally the result is just printed in the echo area, but with prefix arg
  15897. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15898. If the time range is actually in a table, the result is inserted into the
  15899. next column.
  15900. For time difference computation, a year is assumed to be exactly 365
  15901. days in order to avoid rounding problems."
  15902. (interactive "P")
  15903. (or
  15904. (org-clock-update-time-maybe)
  15905. (save-excursion
  15906. (unless (org-at-date-range-p t)
  15907. (goto-char (point-at-bol))
  15908. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15909. (unless (org-at-date-range-p t)
  15910. (user-error "Not at a time-stamp range, and none found in current line")))
  15911. (let* ((ts1 (match-string 1))
  15912. (ts2 (match-string 2))
  15913. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15914. (match-end (match-end 0))
  15915. (time1 (org-time-string-to-time ts1))
  15916. (time2 (org-time-string-to-time ts2))
  15917. (t1 (float-time time1))
  15918. (t2 (float-time time2))
  15919. (diff (abs (- t2 t1)))
  15920. (negative (< (- t2 t1) 0))
  15921. ;; (ys (floor (* 365 24 60 60)))
  15922. (ds (* 24 60 60))
  15923. (hs (* 60 60))
  15924. (fy "%dy %dd %02d:%02d")
  15925. (fy1 "%dy %dd")
  15926. (fd "%dd %02d:%02d")
  15927. (fd1 "%dd")
  15928. (fh "%02d:%02d")
  15929. y d h m align)
  15930. (if havetime
  15931. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15932. y 0
  15933. d (floor (/ diff ds)) diff (mod diff ds)
  15934. h (floor (/ diff hs)) diff (mod diff hs)
  15935. m (floor (/ diff 60)))
  15936. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15937. y 0
  15938. d (floor (+ (/ diff ds) 0.5))
  15939. h 0 m 0))
  15940. (if (not to-buffer)
  15941. (message "%s" (org-make-tdiff-string y d h m))
  15942. (if (org-at-table-p)
  15943. (progn
  15944. (goto-char match-end)
  15945. (setq align t)
  15946. (and (looking-at " *|") (goto-char (match-end 0))))
  15947. (goto-char match-end))
  15948. (when (looking-at
  15949. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15950. (replace-match ""))
  15951. (when negative (insert " -"))
  15952. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15953. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15954. (insert " " (format fh h m))))
  15955. (when align (org-table-align))
  15956. (message "Time difference inserted")))))
  15957. (defun org-make-tdiff-string (y d h m)
  15958. (let ((fmt "")
  15959. (l nil))
  15960. (when (> y 0)
  15961. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15962. (push y l))
  15963. (when (> d 0)
  15964. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15965. (push d l))
  15966. (when (> h 0)
  15967. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15968. (push h l))
  15969. (when (> m 0)
  15970. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15971. (push m l))
  15972. (apply 'format fmt (nreverse l))))
  15973. (defun org-time-string-to-time (s &optional zone)
  15974. "Convert timestamp string S into internal time.
  15975. The optional ZONE is omitted or nil for Emacs local time, t for
  15976. Universal Time, ‘wall’ for system wall clock time, or a string as
  15977. in the TZ environment variable."
  15978. (apply #'encode-time (org-parse-time-string s nil zone)))
  15979. (defun org-time-string-to-seconds (s &optional zone)
  15980. "Convert a timestamp string S into a number of seconds.
  15981. The optional ZONE is omitted or nil for Emacs local time, t for
  15982. Universal Time, ‘wall’ for system wall clock time, or a string as
  15983. in the TZ environment variable."
  15984. (float-time (org-time-string-to-time s zone)))
  15985. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15986. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15987. "Convert time stamp S to an absolute day number.
  15988. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15989. stamp, get the closest date to DAYNR. If PREFER is
  15990. `past' (respectively `future') return a date past (respectively
  15991. after) or equal to DAYNR.
  15992. POS is the location of time stamp S, as a buffer position in
  15993. BUFFER.
  15994. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15995. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15996. signaled."
  15997. (cond
  15998. ((string-match "\\`%%\\((.*)\\)" s)
  15999. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16000. ;; only able to match individual dates. If it fails, raise an
  16001. ;; error.
  16002. (if (and daynr
  16003. (org-diary-sexp-entry
  16004. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16005. daynr
  16006. (signal 'org-diary-sexp-no-match (list s))))
  16007. (daynr (org-closest-date s daynr prefer))
  16008. (t (time-to-days
  16009. (condition-case errdata
  16010. (apply #'encode-time (org-parse-time-string s))
  16011. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16012. s
  16013. (if (not (and buffer pos)) ""
  16014. (format-message " at %d in buffer `%s'" pos buffer))
  16015. (cdr errdata))))))))
  16016. (defun org-days-to-iso-week (days)
  16017. "Return the iso week number."
  16018. (require 'cal-iso)
  16019. (car (calendar-iso-from-absolute days)))
  16020. (defun org-small-year-to-year (year)
  16021. "Convert 2-digit years into 4-digit years.
  16022. YEAR is expanded into one of the 30 next years, if possible, or
  16023. into a past one. Any year larger than 99 is returned unchanged."
  16024. (if (>= year 100) year
  16025. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16026. (century (/ current 100))
  16027. (offset (- year (% current 100))))
  16028. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16029. ((> offset -70) (+ (* century 100) year))
  16030. (t (+ (* (1+ century) 100) year))))))
  16031. (defun org-time-from-absolute (d)
  16032. "Return the time corresponding to date D.
  16033. D may be an absolute day number, or a calendar-type list (month day year)."
  16034. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16035. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16036. (defvar org-agenda-current-date)
  16037. (defun org-calendar-holiday ()
  16038. "List of holidays, for Diary display in Org mode."
  16039. (require 'holidays)
  16040. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16041. (and hl (mapconcat #'identity hl "; "))))
  16042. (defun org-diary-sexp-entry (sexp entry d)
  16043. "Process a SEXP diary ENTRY for date D."
  16044. (require 'diary-lib)
  16045. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16046. ;; dynamically.
  16047. (let* ((sexp `(let ((entry ,entry)
  16048. (date ',d))
  16049. ,(car (read-from-string sexp))))
  16050. (result (if calendar-debug-sexp (eval sexp)
  16051. (condition-case nil
  16052. (eval sexp)
  16053. (error
  16054. (beep)
  16055. (message "Bad sexp at line %d in %s: %s"
  16056. (org-current-line)
  16057. (buffer-file-name) sexp)
  16058. (sleep-for 2))))))
  16059. (cond ((stringp result) (split-string result "; "))
  16060. ((and (consp result)
  16061. (not (consp (cdr result)))
  16062. (stringp (cdr result))) (cdr result))
  16063. ((and (consp result)
  16064. (stringp (car result))) result)
  16065. (result entry))))
  16066. (defun org-diary-to-ical-string (frombuf)
  16067. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16068. This uses the icalendar.el library."
  16069. (let* ((tmpdir temporary-file-directory)
  16070. (tmpfile (make-temp-name
  16071. (expand-file-name "orgics" tmpdir)))
  16072. buf rtn b e)
  16073. (with-current-buffer frombuf
  16074. (icalendar-export-region (point-min) (point-max) tmpfile)
  16075. (setq buf (find-buffer-visiting tmpfile))
  16076. (set-buffer buf)
  16077. (goto-char (point-min))
  16078. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16079. (setq b (match-beginning 0)))
  16080. (goto-char (point-max))
  16081. (when (re-search-backward "^END:VEVENT" nil t)
  16082. (setq e (match-end 0)))
  16083. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16084. (kill-buffer buf)
  16085. (delete-file tmpfile)
  16086. rtn))
  16087. (defun org-closest-date (start current prefer)
  16088. "Return closest date to CURRENT starting from START.
  16089. CURRENT and START are both time stamps.
  16090. When PREFER is `past', return a date that is either CURRENT or
  16091. past. When PREFER is `future', return a date that is either
  16092. CURRENT or future.
  16093. Only time stamps with a repeater are modified. Any other time
  16094. stamp stay unchanged. In any case, return value is an absolute
  16095. day number."
  16096. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16097. ;; No repeater. Do not shift time stamp.
  16098. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16099. (let ((value (string-to-number (match-string 1 start)))
  16100. (type (match-string 2 start)))
  16101. (if (= 0 value)
  16102. ;; Repeater with a 0-value is considered as void.
  16103. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16104. (let* ((base (org-date-to-gregorian start))
  16105. (target (org-date-to-gregorian current))
  16106. (sday (calendar-absolute-from-gregorian base))
  16107. (cday (calendar-absolute-from-gregorian target))
  16108. n1 n2)
  16109. ;; If START is already past CURRENT, just return START.
  16110. (if (<= cday sday) sday
  16111. ;; Compute closest date before (N1) and closest date past
  16112. ;; (N2) CURRENT.
  16113. (pcase type
  16114. ("h"
  16115. (let ((missing-hours
  16116. (mod (+ (- (* 24 (- cday sday))
  16117. (nth 2 (org-parse-time-string start)))
  16118. org-extend-today-until)
  16119. value)))
  16120. (setf n1 (if (= missing-hours 0) cday
  16121. (- cday (1+ (/ missing-hours 24)))))
  16122. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16123. ((or "d" "w")
  16124. (let ((value (if (equal type "w") (* 7 value) value)))
  16125. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16126. (setf n2 (+ n1 value))))
  16127. ("m"
  16128. (let* ((add-months
  16129. (lambda (d n)
  16130. ;; Add N months to gregorian date D, i.e.,
  16131. ;; a list (MONTH DAY YEAR). Return a valid
  16132. ;; gregorian date.
  16133. (let ((m (+ (nth 0 d) n)))
  16134. (list (mod m 12)
  16135. (nth 1 d)
  16136. (+ (/ m 12) (nth 2 d))))))
  16137. (months ; Complete months to TARGET.
  16138. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16139. (- (nth 0 target) (nth 0 base))
  16140. ;; If START's day is greater than
  16141. ;; TARGET's, remove incomplete month.
  16142. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16143. value)
  16144. value))
  16145. (before (funcall add-months base months)))
  16146. (setf n1 (calendar-absolute-from-gregorian before))
  16147. (setf n2
  16148. (calendar-absolute-from-gregorian
  16149. (funcall add-months before value)))))
  16150. (_
  16151. (let* ((d (nth 1 base))
  16152. (m (nth 0 base))
  16153. (y (nth 2 base))
  16154. (years ; Complete years to TARGET.
  16155. (* (/ (- (nth 2 target)
  16156. y
  16157. ;; If START's month and day are
  16158. ;; greater than TARGET's, remove
  16159. ;; incomplete year.
  16160. (if (or (> (nth 0 target) m)
  16161. (and (= (nth 0 target) m)
  16162. (> (nth 1 target) d)))
  16163. 0
  16164. 1))
  16165. value)
  16166. value))
  16167. (before (list m d (+ y years))))
  16168. (setf n1 (calendar-absolute-from-gregorian before))
  16169. (setf n2 (calendar-absolute-from-gregorian
  16170. (list m d (+ (nth 2 before) value)))))))
  16171. ;; Handle PREFER parameter, if any.
  16172. (cond
  16173. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16174. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16175. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16176. (defun org-date-to-gregorian (d)
  16177. "Turn any specification of date D into a Gregorian date for the calendar."
  16178. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16179. ((and (listp d) (= (length d) 3)) d)
  16180. ((stringp d)
  16181. (let ((d (org-parse-time-string d)))
  16182. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16183. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16184. (defun org-parse-time-string (s &optional nodefault zone)
  16185. "Parse the standard Org time string.
  16186. This should be a lot faster than the normal `parse-time-string'.
  16187. If time is not given, defaults to 0:00. However, with optional
  16188. NODEFAULT, hour and minute fields will be nil if not given.
  16189. The optional ZONE is omitted or nil for Emacs local time, t for
  16190. Universal Time, ‘wall’ for system wall clock time, or a string as
  16191. in the TZ environment variable."
  16192. (cond ((string-match org-ts-regexp0 s)
  16193. (list 0
  16194. (when (or (match-beginning 8) (not nodefault))
  16195. (string-to-number (or (match-string 8 s) "0")))
  16196. (when (or (match-beginning 7) (not nodefault))
  16197. (string-to-number (or (match-string 7 s) "0")))
  16198. (string-to-number (match-string 4 s))
  16199. (string-to-number (match-string 3 s))
  16200. (string-to-number (match-string 2 s))
  16201. nil nil zone))
  16202. ((string-match "^<[^>]+>$" s)
  16203. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16204. ;; second argument. However, this requires at least Emacs
  16205. ;; 25.1. We can do it when we switch to this version as our
  16206. ;; minimal requirement.
  16207. (decode-time (seconds-to-time (org-matcher-time s))))
  16208. (t (error "Not a standard Org time string: %s" s))))
  16209. (defun org-timestamp-up (&optional arg)
  16210. "Increase the date item at the cursor by one.
  16211. If the cursor is on the year, change the year. If it is on the month,
  16212. the day or the time, change that.
  16213. With prefix ARG, change by that many units."
  16214. (interactive "p")
  16215. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16216. (defun org-timestamp-down (&optional arg)
  16217. "Decrease the date item at the cursor by one.
  16218. If the cursor is on the year, change the year. If it is on the month,
  16219. the day or the time, change that.
  16220. With prefix ARG, change by that many units."
  16221. (interactive "p")
  16222. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16223. (defun org-timestamp-up-day (&optional arg)
  16224. "Increase the date in the time stamp by one day.
  16225. With prefix ARG, change that many days."
  16226. (interactive "p")
  16227. (if (and (not (org-at-timestamp-p 'lax))
  16228. (org-at-heading-p))
  16229. (org-todo 'up)
  16230. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16231. (defun org-timestamp-down-day (&optional arg)
  16232. "Decrease the date in the time stamp by one day.
  16233. With prefix ARG, change that many days."
  16234. (interactive "p")
  16235. (if (and (not (org-at-timestamp-p 'lax))
  16236. (org-at-heading-p))
  16237. (org-todo 'down)
  16238. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16239. (defun org-at-timestamp-p (&optional extended)
  16240. "Non-nil if point is inside a timestamp.
  16241. By default, the function only consider syntactically valid active
  16242. timestamps. However, the caller may have a broader definition
  16243. for timestamps. As a consequence, optional argument EXTENDED can
  16244. be set to the following values
  16245. `inactive'
  16246. Include also syntactically valid inactive timestamps.
  16247. `agenda'
  16248. Include timestamps allowed in Agenda, i.e., those in
  16249. properties drawers, planning lines and clock lines.
  16250. `lax'
  16251. Ignore context. The function matches any part of the
  16252. document looking like a timestamp. This includes comments,
  16253. example blocks...
  16254. For backward-compatibility with Org 9.0, every other non-nil
  16255. value is equivalent to `inactive'.
  16256. When at a timestamp, return the position of the point as a symbol
  16257. among `bracket', `after', `year', `month', `hour', `minute',
  16258. `day' or a number of character from the last know part of the
  16259. time stamp.
  16260. When matching, the match groups are the following:
  16261. group 1: year
  16262. group 2: month
  16263. group 3: day number
  16264. group 4: day name
  16265. group 5: hours, if any
  16266. group 6: minutes, if any"
  16267. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16268. (pos (point))
  16269. (match?
  16270. (let ((boundaries (org-in-regexp regexp)))
  16271. (save-match-data
  16272. (cond ((null boundaries) nil)
  16273. ((eq extended 'lax) t)
  16274. (t
  16275. (or (and (eq extended 'agenda)
  16276. (or (org-at-planning-p)
  16277. (org-at-property-p)
  16278. (and (bound-and-true-p
  16279. org-agenda-include-inactive-timestamps)
  16280. (org-at-clock-log-p))))
  16281. (eq 'timestamp
  16282. (save-excursion
  16283. (when (= pos (cdr boundaries)) (forward-char -1))
  16284. (org-element-type (org-element-context)))))))))))
  16285. (cond
  16286. ((not match?) nil)
  16287. ((= pos (match-beginning 0)) 'bracket)
  16288. ;; Distinguish location right before the closing bracket from
  16289. ;; right after it.
  16290. ((= pos (1- (match-end 0))) 'bracket)
  16291. ((= pos (match-end 0)) 'after)
  16292. ((org-pos-in-match-range pos 2) 'year)
  16293. ((org-pos-in-match-range pos 3) 'month)
  16294. ((org-pos-in-match-range pos 7) 'hour)
  16295. ((org-pos-in-match-range pos 8) 'minute)
  16296. ((or (org-pos-in-match-range pos 4)
  16297. (org-pos-in-match-range pos 5)) 'day)
  16298. ((and (> pos (or (match-end 8) (match-end 5)))
  16299. (< pos (match-end 0)))
  16300. (- pos (or (match-end 8) (match-end 5))))
  16301. (t 'day))))
  16302. (defun org-toggle-timestamp-type ()
  16303. "Toggle the type (<active> or [inactive]) of a time stamp."
  16304. (interactive)
  16305. (when (org-at-timestamp-p 'lax)
  16306. (let ((beg (match-beginning 0)) (end (match-end 0))
  16307. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16308. (save-excursion
  16309. (goto-char beg)
  16310. (while (re-search-forward "[][<>]" end t)
  16311. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16312. t t)))
  16313. (message "Timestamp is now %sactive"
  16314. (if (equal (char-after beg) ?<) "" "in")))))
  16315. (defun org-at-clock-log-p ()
  16316. "Non-nil if point is on a clock log line."
  16317. (and (org-match-line org-clock-line-re)
  16318. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16319. (defvar org-clock-history) ; defined in org-clock.el
  16320. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16321. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16322. "Change the date in the time stamp at point.
  16323. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16324. `year', `minute', `second'. If WHAT is not given, the cursor position
  16325. in the timestamp determines what will be changed.
  16326. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16327. (let ((origin (point))
  16328. (timestamp? (org-at-timestamp-p 'lax))
  16329. origin-cat
  16330. with-hm inactive
  16331. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16332. extra rem
  16333. ts time time0 fixnext clrgx)
  16334. (unless timestamp? (user-error "Not at a timestamp"))
  16335. (if (and (not what) (eq timestamp? 'bracket))
  16336. (org-toggle-timestamp-type)
  16337. ;; Point isn't on brackets. Remember the part of the time-stamp
  16338. ;; the point was in. Indeed, size of time-stamps may change,
  16339. ;; but point must be kept in the same category nonetheless.
  16340. (setq origin-cat timestamp?)
  16341. (when (and (not what) (not (eq timestamp? 'day))
  16342. org-display-custom-times
  16343. (get-text-property (point) 'display)
  16344. (not (get-text-property (1- (point)) 'display)))
  16345. (setq timestamp? 'day))
  16346. (setq timestamp? (or what timestamp?)
  16347. inactive (= (char-after (match-beginning 0)) ?\[)
  16348. ts (match-string 0))
  16349. (replace-match "")
  16350. (when (string-match
  16351. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16352. ts)
  16353. (setq extra (match-string 1 ts))
  16354. (when suppress-tmp-delay
  16355. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16356. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16357. (setq with-hm t))
  16358. (setq time0 (org-parse-time-string ts))
  16359. (when (and updown
  16360. (eq timestamp? 'minute)
  16361. (not current-prefix-arg))
  16362. ;; This looks like s-up and s-down. Change by one rounding step.
  16363. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16364. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16365. (setcar (cdr time0) (+ (nth 1 time0)
  16366. (if (> n 0) (- rem) (- dm rem))))))
  16367. (setq time
  16368. (apply #'encode-time
  16369. (or (car time0) 0)
  16370. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16371. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16372. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16373. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16374. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16375. (nthcdr 6 time0)))
  16376. (when (and (memq timestamp? '(hour minute))
  16377. extra
  16378. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16379. (setq extra (org-modify-ts-extra
  16380. extra
  16381. (if (eq timestamp? 'hour) 2 5)
  16382. n dm)))
  16383. (when (integerp timestamp?)
  16384. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16385. (when (eq what 'calendar)
  16386. (let ((cal-date (org-get-date-from-calendar)))
  16387. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16388. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16389. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16390. (setcar time0 (or (car time0) 0))
  16391. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16392. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16393. (setq time (apply 'encode-time time0))))
  16394. ;; Insert the new time-stamp, and ensure point stays in the same
  16395. ;; category as before (i.e. not after the last position in that
  16396. ;; category).
  16397. (let ((pos (point)))
  16398. ;; Stay before inserted string. `save-excursion' is of no use.
  16399. (setq org-last-changed-timestamp
  16400. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16401. (goto-char pos))
  16402. (save-match-data
  16403. (looking-at org-ts-regexp3)
  16404. (goto-char
  16405. (pcase origin-cat
  16406. ;; `day' category ends before `hour' if any, or at the end
  16407. ;; of the day name.
  16408. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16409. (`hour (min (match-end 7) origin))
  16410. (`minute (min (1- (match-end 8)) origin))
  16411. ((pred integerp) (min (1- (match-end 0)) origin))
  16412. ;; Point was right after the time-stamp. However, the
  16413. ;; time-stamp length might have changed, so refer to
  16414. ;; (match-end 0) instead.
  16415. (`after (match-end 0))
  16416. ;; `year' and `month' have both fixed size: point couldn't
  16417. ;; have moved into another part.
  16418. (_ origin))))
  16419. ;; Update clock if on a CLOCK line.
  16420. (org-clock-update-time-maybe)
  16421. ;; Maybe adjust the closest clock in `org-clock-history'
  16422. (when org-clock-adjust-closest
  16423. (if (not (and (org-at-clock-log-p)
  16424. (< 1 (length (delq nil (mapcar 'marker-position
  16425. org-clock-history))))))
  16426. (message "No clock to adjust")
  16427. (cond ((save-excursion ; fix previous clock?
  16428. (re-search-backward org-ts-regexp0 nil t)
  16429. (looking-back (concat org-clock-string " \\[")
  16430. (line-beginning-position)))
  16431. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16432. ((save-excursion ; fix next clock?
  16433. (re-search-backward org-ts-regexp0 nil t)
  16434. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16435. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16436. (save-window-excursion
  16437. ;; Find closest clock to point, adjust the previous/next one in history
  16438. (let* ((p (save-excursion (org-back-to-heading t)))
  16439. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16440. (clfixnth
  16441. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16442. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16443. (if (not clfixpos)
  16444. (message "No clock to adjust")
  16445. (save-excursion
  16446. (org-goto-marker-or-bmk clfixpos)
  16447. (org-show-subtree)
  16448. (when (re-search-forward clrgx nil t)
  16449. (goto-char (match-beginning 1))
  16450. (let (org-clock-adjust-closest)
  16451. (org-timestamp-change n timestamp? updown))
  16452. (message "Clock adjusted in %s for heading: %s"
  16453. (file-name-nondirectory (buffer-file-name))
  16454. (org-get-heading t t)))))))))
  16455. ;; Try to recenter the calendar window, if any.
  16456. (when (and org-calendar-follow-timestamp-change
  16457. (get-buffer-window "*Calendar*" t)
  16458. (memq timestamp? '(day month year)))
  16459. (org-recenter-calendar (time-to-days time))))))
  16460. (defun org-modify-ts-extra (s pos n dm)
  16461. "Change the different parts of the lead-time and repeat fields in timestamp."
  16462. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16463. ng h m new rem)
  16464. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16465. (cond
  16466. ((or (org-pos-in-match-range pos 2)
  16467. (org-pos-in-match-range pos 3))
  16468. (setq m (string-to-number (match-string 3 s))
  16469. h (string-to-number (match-string 2 s)))
  16470. (if (org-pos-in-match-range pos 2)
  16471. (setq h (+ h n))
  16472. (setq n (* dm (with-no-warnings (signum n))))
  16473. (unless (= 0 (setq rem (% m dm)))
  16474. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16475. (setq m (+ m n)))
  16476. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16477. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16478. (setq h (mod h 24))
  16479. (setq ng 1 new (format "-%02d:%02d" h m)))
  16480. ((org-pos-in-match-range pos 6)
  16481. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16482. ((org-pos-in-match-range pos 5)
  16483. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16484. ((org-pos-in-match-range pos 9)
  16485. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16486. ((org-pos-in-match-range pos 8)
  16487. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16488. (when ng
  16489. (setq s (concat
  16490. (substring s 0 (match-beginning ng))
  16491. new
  16492. (substring s (match-end ng))))))
  16493. s))
  16494. (defun org-recenter-calendar (d)
  16495. "If the calendar is visible, recenter it to date D."
  16496. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16497. (when cwin
  16498. (let ((calendar-move-hook nil))
  16499. (with-selected-window cwin
  16500. (calendar-goto-date
  16501. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16502. (defun org-goto-calendar (&optional arg)
  16503. "Go to the Emacs calendar at the current date.
  16504. If there is a time stamp in the current line, go to that date.
  16505. A prefix ARG can be used to force the current date."
  16506. (interactive "P")
  16507. (let ((calendar-move-hook nil)
  16508. (calendar-view-holidays-initially-flag nil)
  16509. (calendar-view-diary-initially-flag nil)
  16510. diff)
  16511. (when (or (org-at-timestamp-p 'lax)
  16512. (org-match-line (concat ".*" org-ts-regexp)))
  16513. (let ((d1 (time-to-days (current-time)))
  16514. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16515. (setq diff (- d2 d1))))
  16516. (calendar)
  16517. (calendar-goto-today)
  16518. (when (and diff (not arg)) (calendar-forward-day diff))))
  16519. (defun org-get-date-from-calendar ()
  16520. "Return a list (month day year) of date at point in calendar."
  16521. (with-current-buffer "*Calendar*"
  16522. (save-match-data
  16523. (calendar-cursor-to-date))))
  16524. (defun org-date-from-calendar ()
  16525. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16526. If there is already a time stamp at the cursor position, update it."
  16527. (interactive)
  16528. (if (org-at-timestamp-p 'lax)
  16529. (org-timestamp-change 0 'calendar)
  16530. (let ((cal-date (org-get-date-from-calendar)))
  16531. (org-insert-time-stamp
  16532. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16533. (defcustom org-effort-durations
  16534. `(("min" . 1)
  16535. ("h" . 60)
  16536. ("d" . ,(* 60 8))
  16537. ("w" . ,(* 60 8 5))
  16538. ("m" . ,(* 60 8 5 4))
  16539. ("y" . ,(* 60 8 5 40)))
  16540. "Conversion factor to minutes for an effort modifier.
  16541. Each entry has the form (MODIFIER . MINUTES).
  16542. In an effort string, a number followed by MODIFIER is multiplied
  16543. by the specified number of MINUTES to obtain an effort in
  16544. minutes.
  16545. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16546. effort string \"2hours\" is equivalent to 120 minutes."
  16547. :group 'org-agenda
  16548. :version "26.1"
  16549. :package-version '(Org . "8.3")
  16550. :type '(alist :key-type (string :tag "Modifier")
  16551. :value-type (number :tag "Minutes")))
  16552. (defcustom org-image-actual-width t
  16553. "Should we use the actual width of images when inlining them?
  16554. When set to t, always use the image width.
  16555. When set to a number, use imagemagick (when available) to set
  16556. the image's width to this value.
  16557. When set to a number in a list, try to get the width from any
  16558. #+ATTR.* keyword if it matches a width specification like
  16559. #+ATTR_HTML: :width 300px
  16560. and fall back on that number if none is found.
  16561. When set to nil, try to get the width from an #+ATTR.* keyword
  16562. and fall back on the original width if none is found.
  16563. This requires Emacs >= 24.1, build with imagemagick support."
  16564. :group 'org-appearance
  16565. :version "24.4"
  16566. :package-version '(Org . "8.0")
  16567. :type '(choice
  16568. (const :tag "Use the image width" t)
  16569. (integer :tag "Use a number of pixels")
  16570. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16571. (const :tag "Use #+ATTR* or don't resize" nil)))
  16572. (defcustom org-agenda-inhibit-startup nil
  16573. "Inhibit startup when preparing agenda buffers.
  16574. When this variable is t, the initialization of the Org agenda
  16575. buffers is inhibited: e.g. the visibility state is not set, the
  16576. tables are not re-aligned, etc."
  16577. :type 'boolean
  16578. :version "24.3"
  16579. :group 'org-agenda)
  16580. (defcustom org-agenda-ignore-properties nil
  16581. "Avoid updating text properties when building the agenda.
  16582. Properties are used to prepare buffers for effort estimates,
  16583. appointments, statistics and subtree-local categories.
  16584. If you don't use these in the agenda, you can add them to this
  16585. list and agenda building will be a bit faster.
  16586. The value is a list, with zero or more of the symbols `effort', `appt',
  16587. `stats' or `category'."
  16588. :type '(set :greedy t
  16589. (const effort)
  16590. (const appt)
  16591. (const stats)
  16592. (const category))
  16593. :version "26.1"
  16594. :package-version '(Org . "8.3")
  16595. :group 'org-agenda)
  16596. ;;;; Files
  16597. (defun org-save-all-org-buffers ()
  16598. "Save all Org buffers without user confirmation."
  16599. (interactive)
  16600. (message "Saving all Org buffers...")
  16601. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16602. (when (featurep 'org-id) (org-id-locations-save))
  16603. (message "Saving all Org buffers... done"))
  16604. (defun org-revert-all-org-buffers ()
  16605. "Revert all Org buffers.
  16606. Prompt for confirmation when there are unsaved changes.
  16607. Be sure you know what you are doing before letting this function
  16608. overwrite your changes.
  16609. This function is useful in a setup where one tracks org files
  16610. with a version control system, to revert on one machine after pulling
  16611. changes from another. I believe the procedure must be like this:
  16612. 1. M-x org-save-all-org-buffers
  16613. 2. Pull changes from the other machine, resolve conflicts
  16614. 3. M-x org-revert-all-org-buffers"
  16615. (interactive)
  16616. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16617. (user-error "Abort"))
  16618. (save-excursion
  16619. (save-window-excursion
  16620. (dolist (b (buffer-list))
  16621. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16622. (with-current-buffer b buffer-file-name))
  16623. (pop-to-buffer-same-window b)
  16624. (revert-buffer t 'no-confirm)))
  16625. (when (and (featurep 'org-id) org-id-track-globally)
  16626. (org-id-locations-load)))))
  16627. ;;;; Agenda files
  16628. ;;;###autoload
  16629. (defun org-switchb (&optional arg)
  16630. "Switch between Org buffers.
  16631. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16632. With `\\[universal-argument] \\[universal-argument]' \
  16633. prefix, restrict available buffers to agenda files."
  16634. (interactive "P")
  16635. (let ((blist (org-buffer-list
  16636. (cond ((equal arg '(4)) 'files)
  16637. ((equal arg '(16)) 'agenda)))))
  16638. (pop-to-buffer-same-window
  16639. (completing-read "Org buffer: "
  16640. (mapcar #'list (mapcar #'buffer-name blist))
  16641. nil t))))
  16642. (defun org-buffer-list (&optional predicate exclude-tmp)
  16643. "Return a list of Org buffers.
  16644. PREDICATE can be `export', `files' or `agenda'.
  16645. export restrict the list to Export buffers.
  16646. files restrict the list to buffers visiting Org files.
  16647. agenda restrict the list to buffers visiting agenda files.
  16648. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16649. (let* ((bfn nil)
  16650. (agenda-files (and (eq predicate 'agenda)
  16651. (mapcar 'file-truename (org-agenda-files t))))
  16652. (filter
  16653. (cond
  16654. ((eq predicate 'files)
  16655. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16656. ((eq predicate 'export)
  16657. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16658. ((eq predicate 'agenda)
  16659. (lambda (b)
  16660. (with-current-buffer b
  16661. (and (derived-mode-p 'org-mode)
  16662. (setq bfn (buffer-file-name b))
  16663. (member (file-truename bfn) agenda-files)))))
  16664. (t (lambda (b) (with-current-buffer b
  16665. (or (derived-mode-p 'org-mode)
  16666. (string-match "\\*Org .*Export"
  16667. (buffer-name b)))))))))
  16668. (delq nil
  16669. (mapcar
  16670. (lambda(b)
  16671. (if (and (funcall filter b)
  16672. (or (not exclude-tmp)
  16673. (not (string-match "tmp" (buffer-name b)))))
  16674. b
  16675. nil))
  16676. (buffer-list)))))
  16677. (defun org-agenda-files (&optional unrestricted archives)
  16678. "Get the list of agenda files.
  16679. Optional UNRESTRICTED means return the full list even if a restriction
  16680. is currently in place.
  16681. When ARCHIVES is t, include all archive files that are really being
  16682. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16683. `org-agenda-archives-mode' is t."
  16684. (let ((files
  16685. (cond
  16686. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16687. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16688. ((listp org-agenda-files) org-agenda-files)
  16689. (t (error "Invalid value of `org-agenda-files'")))))
  16690. (setq files (apply 'append
  16691. (mapcar (lambda (f)
  16692. (if (file-directory-p f)
  16693. (directory-files
  16694. f t org-agenda-file-regexp)
  16695. (list f)))
  16696. files)))
  16697. (when org-agenda-skip-unavailable-files
  16698. (setq files (delq nil
  16699. (mapcar (function
  16700. (lambda (file)
  16701. (and (file-readable-p file) file)))
  16702. files))))
  16703. (when (or (eq archives t)
  16704. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16705. (setq files (org-add-archive-files files)))
  16706. files))
  16707. (defun org-agenda-file-p (&optional file)
  16708. "Return non-nil, if FILE is an agenda file.
  16709. If FILE is omitted, use the file associated with the current
  16710. buffer."
  16711. (let ((fname (or file (buffer-file-name))))
  16712. (and fname
  16713. (member (file-truename fname)
  16714. (mapcar #'file-truename (org-agenda-files t))))))
  16715. (defun org-edit-agenda-file-list ()
  16716. "Edit the list of agenda files.
  16717. Depending on setup, this either uses customize to edit the variable
  16718. `org-agenda-files', or it visits the file that is holding the list. In the
  16719. latter case, the buffer is set up in a way that saving it automatically kills
  16720. the buffer and restores the previous window configuration."
  16721. (interactive)
  16722. (if (stringp org-agenda-files)
  16723. (let ((cw (current-window-configuration)))
  16724. (find-file org-agenda-files)
  16725. (setq-local org-window-configuration cw)
  16726. (add-hook 'after-save-hook
  16727. (lambda ()
  16728. (set-window-configuration
  16729. (prog1 org-window-configuration
  16730. (kill-buffer (current-buffer))))
  16731. (org-install-agenda-files-menu)
  16732. (message "New agenda file list installed"))
  16733. nil 'local)
  16734. (message "%s" (substitute-command-keys
  16735. "Edit list and finish with \\[save-buffer]")))
  16736. (customize-variable 'org-agenda-files)))
  16737. (defun org-store-new-agenda-file-list (list)
  16738. "Set new value for the agenda file list and save it correctly."
  16739. (if (stringp org-agenda-files)
  16740. (let ((fe (org-read-agenda-file-list t)) b u)
  16741. (while (setq b (find-buffer-visiting org-agenda-files))
  16742. (kill-buffer b))
  16743. (with-temp-file org-agenda-files
  16744. (insert
  16745. (mapconcat
  16746. (lambda (f) ;; Keep un-expanded entries.
  16747. (if (setq u (assoc f fe))
  16748. (cdr u)
  16749. f))
  16750. list "\n")
  16751. "\n")))
  16752. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16753. (org-insert-mode-line-in-empty-file nil))
  16754. (setq org-agenda-files list)
  16755. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16756. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16757. "Read the list of agenda files from a file.
  16758. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16759. filenames, used by `org-store-new-agenda-file-list' to write back
  16760. un-expanded file names."
  16761. (when (file-directory-p org-agenda-files)
  16762. (error "`org-agenda-files' cannot be a single directory"))
  16763. (when (stringp org-agenda-files)
  16764. (with-temp-buffer
  16765. (insert-file-contents org-agenda-files)
  16766. (mapcar
  16767. (lambda (f)
  16768. (let ((e (expand-file-name (substitute-in-file-name f)
  16769. org-directory)))
  16770. (if pair-with-expansion
  16771. (cons e f)
  16772. e)))
  16773. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16774. ;;;###autoload
  16775. (defun org-cycle-agenda-files ()
  16776. "Cycle through the files in `org-agenda-files'.
  16777. If the current buffer visits an agenda file, find the next one in the list.
  16778. If the current buffer does not, find the first agenda file."
  16779. (interactive)
  16780. (let* ((fs (or (org-agenda-files t)
  16781. (user-error "No agenda files")))
  16782. (files (copy-sequence fs))
  16783. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16784. file)
  16785. (when tcf
  16786. (while (and (setq file (pop files))
  16787. (not (equal (file-truename file) tcf)))))
  16788. (find-file (car (or files fs)))
  16789. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16790. (defun org-agenda-file-to-front (&optional to-end)
  16791. "Move/add the current file to the top of the agenda file list.
  16792. If the file is not present in the list, it is added to the front. If it is
  16793. present, it is moved there. With optional argument TO-END, add/move to the
  16794. end of the list."
  16795. (interactive "P")
  16796. (let ((org-agenda-skip-unavailable-files nil)
  16797. (file-alist (mapcar (lambda (x)
  16798. (cons (file-truename x) x))
  16799. (org-agenda-files t)))
  16800. (ctf (file-truename
  16801. (or buffer-file-name
  16802. (user-error "Please save the current buffer to a file"))))
  16803. x had)
  16804. (setq x (assoc ctf file-alist) had x)
  16805. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16806. (if to-end
  16807. (setq file-alist (append (delq x file-alist) (list x)))
  16808. (setq file-alist (cons x (delq x file-alist))))
  16809. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16810. (org-install-agenda-files-menu)
  16811. (message "File %s to %s of agenda file list"
  16812. (if had "moved" "added") (if to-end "end" "front"))))
  16813. (defun org-remove-file (&optional file)
  16814. "Remove current file from the list of files in variable `org-agenda-files'.
  16815. These are the files which are being checked for agenda entries.
  16816. Optional argument FILE means use this file instead of the current."
  16817. (interactive)
  16818. (let* ((org-agenda-skip-unavailable-files nil)
  16819. (file (or file buffer-file-name
  16820. (user-error "Current buffer does not visit a file")))
  16821. (true-file (file-truename file))
  16822. (afile (abbreviate-file-name file))
  16823. (files (delq nil (mapcar
  16824. (lambda (x)
  16825. (unless (equal true-file
  16826. (file-truename x))
  16827. x))
  16828. (org-agenda-files t)))))
  16829. (if (not (= (length files) (length (org-agenda-files t))))
  16830. (progn
  16831. (org-store-new-agenda-file-list files)
  16832. (org-install-agenda-files-menu)
  16833. (message "Removed from Org Agenda list: %s" afile))
  16834. (message "File was not in list: %s (not removed)" afile))))
  16835. (defun org-file-menu-entry (file)
  16836. (vector file (list 'find-file file) t))
  16837. (defun org-check-agenda-file (file)
  16838. "Make sure FILE exists. If not, ask user what to do."
  16839. (unless (file-exists-p file)
  16840. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16841. (abbreviate-file-name file))
  16842. (let ((r (downcase (read-char-exclusive))))
  16843. (cond
  16844. ((equal r ?r)
  16845. (org-remove-file file)
  16846. (throw 'nextfile t))
  16847. (t (user-error "Abort"))))))
  16848. (defun org-get-agenda-file-buffer (file)
  16849. "Get an agenda buffer visiting FILE.
  16850. If the buffer needs to be created, add it to the list of buffers
  16851. which might be released later."
  16852. (let ((buf (org-find-base-buffer-visiting file)))
  16853. (if buf
  16854. buf ; just return it
  16855. ;; Make a new buffer and remember it
  16856. (setq buf (find-file-noselect file))
  16857. (when buf (push buf org-agenda-new-buffers))
  16858. buf)))
  16859. (defun org-release-buffers (blist)
  16860. "Release all buffers in list, asking the user for confirmation when needed.
  16861. When a buffer is unmodified, it is just killed. When modified, it is saved
  16862. \(if the user agrees) and then killed."
  16863. (let (file)
  16864. (dolist (buf blist)
  16865. (setq file (buffer-file-name buf))
  16866. (when (and (buffer-modified-p buf)
  16867. file
  16868. (y-or-n-p (format "Save file %s? " file)))
  16869. (with-current-buffer buf (save-buffer)))
  16870. (kill-buffer buf))))
  16871. (defun org-agenda-prepare-buffers (files)
  16872. "Create buffers for all agenda files, protect archived trees and comments."
  16873. (interactive)
  16874. (let ((pa '(:org-archived t))
  16875. (pc '(:org-comment t))
  16876. (pall '(:org-archived t :org-comment t))
  16877. (inhibit-read-only t)
  16878. (org-inhibit-startup org-agenda-inhibit-startup)
  16879. (rea (concat ":" org-archive-tag ":"))
  16880. re pos)
  16881. (setq org-tag-alist-for-agenda nil
  16882. org-tag-groups-alist-for-agenda nil)
  16883. (save-excursion
  16884. (save-restriction
  16885. (dolist (file files)
  16886. (catch 'nextfile
  16887. (if (bufferp file)
  16888. (set-buffer file)
  16889. (org-check-agenda-file file)
  16890. (set-buffer (org-get-agenda-file-buffer file)))
  16891. (widen)
  16892. (org-set-regexps-and-options 'tags-only)
  16893. (setq pos (point))
  16894. (or (memq 'category org-agenda-ignore-properties)
  16895. (org-refresh-category-properties))
  16896. (or (memq 'stats org-agenda-ignore-properties)
  16897. (org-refresh-stats-properties))
  16898. (or (memq 'effort org-agenda-ignore-properties)
  16899. (org-refresh-effort-properties))
  16900. (or (memq 'appt org-agenda-ignore-properties)
  16901. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16902. (setq org-todo-keywords-for-agenda
  16903. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16904. (setq org-done-keywords-for-agenda
  16905. (append org-done-keywords-for-agenda org-done-keywords))
  16906. (setq org-todo-keyword-alist-for-agenda
  16907. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16908. (setq org-tag-alist-for-agenda
  16909. (org-uniquify
  16910. (append org-tag-alist-for-agenda
  16911. org-current-tag-alist)))
  16912. ;; Merge current file's tag groups into global
  16913. ;; `org-tag-groups-alist-for-agenda'.
  16914. (when org-group-tags
  16915. (dolist (alist org-tag-groups-alist)
  16916. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16917. (if old
  16918. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16919. (push alist org-tag-groups-alist-for-agenda)))))
  16920. (org-with-silent-modifications
  16921. (save-excursion
  16922. (remove-text-properties (point-min) (point-max) pall)
  16923. (when org-agenda-skip-archived-trees
  16924. (goto-char (point-min))
  16925. (while (re-search-forward rea nil t)
  16926. (when (org-at-heading-p t)
  16927. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16928. (goto-char (point-min))
  16929. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16930. (while (re-search-forward re nil t)
  16931. (when (save-match-data (org-in-commented-heading-p t))
  16932. (add-text-properties
  16933. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16934. (goto-char pos)))))
  16935. (setq org-todo-keywords-for-agenda
  16936. (org-uniquify org-todo-keywords-for-agenda))
  16937. (setq org-todo-keyword-alist-for-agenda
  16938. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16939. ;;;; CDLaTeX minor mode
  16940. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16941. "Keymap for the minor `org-cdlatex-mode'.")
  16942. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16943. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16944. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16945. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16946. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16947. (defvar org-cdlatex-texmathp-advice-is-done nil
  16948. "Flag remembering if we have applied the advice to texmathp already.")
  16949. (define-minor-mode org-cdlatex-mode
  16950. "Toggle the minor `org-cdlatex-mode'.
  16951. This mode supports entering LaTeX environment and math in LaTeX fragments
  16952. in Org mode.
  16953. \\{org-cdlatex-mode-map}"
  16954. nil " OCDL" nil
  16955. (when org-cdlatex-mode
  16956. (require 'cdlatex)
  16957. (run-hooks 'cdlatex-mode-hook)
  16958. (cdlatex-compute-tables))
  16959. (unless org-cdlatex-texmathp-advice-is-done
  16960. (setq org-cdlatex-texmathp-advice-is-done t)
  16961. (defadvice texmathp (around org-math-always-on activate)
  16962. "Always return t in Org buffers.
  16963. This is because we want to insert math symbols without dollars even outside
  16964. the LaTeX math segments. If Org mode thinks that point is actually inside
  16965. an embedded LaTeX fragment, let `texmathp' do its job.
  16966. `\\[org-cdlatex-mode-map]'"
  16967. (interactive)
  16968. (let (p)
  16969. (cond
  16970. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16971. ((eq this-command 'cdlatex-math-symbol)
  16972. (setq ad-return-value t
  16973. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16974. (t
  16975. (let ((p (org-inside-LaTeX-fragment-p)))
  16976. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16977. (setq ad-return-value t
  16978. texmathp-why '("Org mode embedded math" . 0))
  16979. (when p ad-do-it)))))))))
  16980. (defun turn-on-org-cdlatex ()
  16981. "Unconditionally turn on `org-cdlatex-mode'."
  16982. (org-cdlatex-mode 1))
  16983. (defun org-try-cdlatex-tab ()
  16984. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16985. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16986. - inside a LaTeX fragment, or
  16987. - after the first word in a line, where an abbreviation expansion could
  16988. insert a LaTeX environment."
  16989. (when org-cdlatex-mode
  16990. (cond
  16991. ;; Before any word on the line: No expansion possible.
  16992. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16993. ;; Just after first word on the line: Expand it. Make sure it
  16994. ;; cannot happen on headlines, though.
  16995. ((save-excursion
  16996. (skip-chars-backward "a-zA-Z0-9*")
  16997. (skip-chars-backward " \t")
  16998. (and (bolp) (not (org-at-heading-p))))
  16999. (cdlatex-tab) t)
  17000. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17001. (defun org-cdlatex-underscore-caret (&optional _arg)
  17002. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17003. Revert to the normal definition outside of these fragments."
  17004. (interactive "P")
  17005. (if (org-inside-LaTeX-fragment-p)
  17006. (call-interactively 'cdlatex-sub-superscript)
  17007. (let (org-cdlatex-mode)
  17008. (call-interactively (key-binding (vector last-input-event))))))
  17009. (defun org-cdlatex-math-modify (&optional _arg)
  17010. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17011. Revert to the normal definition outside of these fragments."
  17012. (interactive "P")
  17013. (if (org-inside-LaTeX-fragment-p)
  17014. (call-interactively 'cdlatex-math-modify)
  17015. (let (org-cdlatex-mode)
  17016. (call-interactively (key-binding (vector last-input-event))))))
  17017. (defun org-cdlatex-environment-indent (&optional environment item)
  17018. "Execute `cdlatex-environment' and indent the inserted environment.
  17019. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17020. The inserted environment is indented to current indentation
  17021. unless point is at the beginning of the line, in which the
  17022. environment remains unintended."
  17023. (interactive)
  17024. ;; cdlatex-environment always return nil. Therefore, capture output
  17025. ;; first and determine if an environment was selected.
  17026. (let* ((beg (point-marker))
  17027. (end (copy-marker (point) t))
  17028. (inserted (progn
  17029. (ignore-errors (cdlatex-environment environment item))
  17030. (< beg end)))
  17031. ;; Figure out how many lines to move forward after the
  17032. ;; environment has been inserted.
  17033. (lines (when inserted
  17034. (save-excursion
  17035. (- (cl-loop while (< beg (point))
  17036. with x = 0
  17037. do (forward-line -1)
  17038. (cl-incf x)
  17039. finally return x)
  17040. (if (progn (goto-char beg)
  17041. (and (progn (skip-chars-forward " \t") (eolp))
  17042. (progn (skip-chars-backward " \t") (bolp))))
  17043. 1 0)))))
  17044. (env (org-trim (delete-and-extract-region beg end))))
  17045. (when inserted
  17046. ;; Get indentation of next line unless at column 0.
  17047. (let ((ind (if (bolp) 0
  17048. (save-excursion
  17049. (org-return-indent)
  17050. (prog1 (org-get-indentation)
  17051. (when (progn (skip-chars-forward " \t") (eolp))
  17052. (delete-region beg (point)))))))
  17053. (bol (progn (skip-chars-backward " \t") (bolp))))
  17054. ;; Insert a newline before environment unless at column zero
  17055. ;; to "escape" the current line. Insert a newline if
  17056. ;; something is one the same line as \end{ENVIRONMENT}.
  17057. (insert
  17058. (concat (unless bol "\n") env
  17059. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17060. (unless (zerop ind)
  17061. (save-excursion
  17062. (goto-char beg)
  17063. (while (< (point) end)
  17064. (unless (eolp) (indent-line-to ind))
  17065. (forward-line))))
  17066. (goto-char beg)
  17067. (forward-line lines)
  17068. (indent-line-to ind)))
  17069. (set-marker beg nil)
  17070. (set-marker end nil)))
  17071. ;;;; LaTeX fragments
  17072. (defun org-inside-LaTeX-fragment-p ()
  17073. "Test if point is inside a LaTeX fragment.
  17074. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17075. sequence appearing also before point.
  17076. Even though the matchers for math are configurable, this function assumes
  17077. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17078. delimiters are skipped when they have been removed by customization.
  17079. The return value is nil, or a cons cell with the delimiter and the
  17080. position of this delimiter.
  17081. This function does a reasonably good job, but can locally be fooled by
  17082. for example currency specifications. For example it will assume being in
  17083. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17084. fragments that are properly closed, but during editing, we have to live
  17085. with the uncertainty caused by missing closing delimiters. This function
  17086. looks only before point, not after."
  17087. (catch 'exit
  17088. (let ((pos (point))
  17089. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17090. (lim (save-excursion (org-backward-paragraph) (point)))
  17091. dd-on str (start 0) m re)
  17092. (goto-char pos)
  17093. (when dodollar
  17094. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17095. re (nth 1 (assoc "$" org-latex-regexps)))
  17096. (while (string-match re str start)
  17097. (cond
  17098. ((= (match-end 0) (length str))
  17099. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17100. ((= (match-end 0) (- (length str) 5))
  17101. (throw 'exit nil))
  17102. (t (setq start (match-end 0))))))
  17103. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17104. (goto-char pos)
  17105. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17106. (and (match-beginning 2) (throw 'exit nil))
  17107. ;; count $$
  17108. (while (re-search-backward "\\$\\$" lim t)
  17109. (setq dd-on (not dd-on)))
  17110. (goto-char pos)
  17111. (when dd-on (cons "$$" m))))))
  17112. (defun org-inside-latex-macro-p ()
  17113. "Is point inside a LaTeX macro or its arguments?"
  17114. (save-match-data
  17115. (org-in-regexp
  17116. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17117. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17118. "Build an overlay between BEG and END using IMAGE file.
  17119. Argument IMAGETYPE is the extension of the displayed image,
  17120. as a string. It defaults to \"png\"."
  17121. (let ((ov (make-overlay beg end))
  17122. (imagetype (or (intern imagetype) 'png)))
  17123. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17124. (overlay-put ov 'evaporate t)
  17125. (overlay-put ov
  17126. 'modification-hooks
  17127. (list (lambda (o _flag _beg _end &optional _l)
  17128. (delete-overlay o))))
  17129. (overlay-put ov
  17130. 'display
  17131. (list 'image :type imagetype :file image :ascent 'center))))
  17132. (defun org--list-latex-overlays (&optional beg end)
  17133. "List all Org LaTeX overlays in current buffer.
  17134. Limit to overlays between BEG and END when those are provided."
  17135. (cl-remove-if-not
  17136. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17137. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17138. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17139. "Remove all overlays with LaTeX fragment images in current buffer.
  17140. When optional arguments BEG and END are non-nil, remove all
  17141. overlays between them instead. Return a non-nil value when some
  17142. overlays were removed, nil otherwise."
  17143. (let ((overlays (org--list-latex-overlays beg end)))
  17144. (mapc #'delete-overlay overlays)
  17145. overlays))
  17146. (defun org-toggle-latex-fragment (&optional arg)
  17147. "Preview the LaTeX fragment at point, or all locally or globally.
  17148. If the cursor is on a LaTeX fragment, create the image and overlay
  17149. it over the source code, if there is none. Remove it otherwise.
  17150. If there is no fragment at point, display all fragments in the
  17151. current section.
  17152. With prefix ARG, preview or clear image for all fragments in the
  17153. current subtree or in the whole buffer when used before the first
  17154. headline. With a prefix ARG `\\[universal-argument] \
  17155. \\[universal-argument]' preview or clear images
  17156. for all fragments in the buffer."
  17157. (interactive "P")
  17158. (when (display-graphic-p)
  17159. (catch 'exit
  17160. (save-excursion
  17161. (let (beg end msg)
  17162. (cond
  17163. ((or (equal arg '(16))
  17164. (and (equal arg '(4))
  17165. (org-with-limited-levels (org-before-first-heading-p))))
  17166. (if (org-remove-latex-fragment-image-overlays)
  17167. (progn (message "LaTeX fragments images removed from buffer")
  17168. (throw 'exit nil))
  17169. (setq msg "Creating images for buffer...")))
  17170. ((equal arg '(4))
  17171. (org-with-limited-levels (org-back-to-heading t))
  17172. (setq beg (point))
  17173. (setq end (progn (org-end-of-subtree t) (point)))
  17174. (if (org-remove-latex-fragment-image-overlays beg end)
  17175. (progn
  17176. (message "LaTeX fragment images removed from subtree")
  17177. (throw 'exit nil))
  17178. (setq msg "Creating images for subtree...")))
  17179. ((let ((datum (org-element-context)))
  17180. (when (memq (org-element-type datum)
  17181. '(latex-environment latex-fragment))
  17182. (setq beg (org-element-property :begin datum))
  17183. (setq end (org-element-property :end datum))
  17184. (if (org-remove-latex-fragment-image-overlays beg end)
  17185. (progn (message "LaTeX fragment image removed")
  17186. (throw 'exit nil))
  17187. (setq msg "Creating image...")))))
  17188. (t
  17189. (org-with-limited-levels
  17190. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17191. (outline-previous-heading)
  17192. (point)))
  17193. (setq end (progn (outline-next-heading) (point)))
  17194. (if (org-remove-latex-fragment-image-overlays beg end)
  17195. (progn
  17196. (message "LaTeX fragment images removed from section")
  17197. (throw 'exit nil))
  17198. (setq msg "Creating images for section...")))))
  17199. (let ((file (buffer-file-name (buffer-base-buffer))))
  17200. (org-format-latex
  17201. (concat org-preview-latex-image-directory "org-ltximg")
  17202. beg end
  17203. ;; Emacs cannot overlay images from remote hosts. Create
  17204. ;; it in `temporary-file-directory' instead.
  17205. (if (or (not file) (file-remote-p file))
  17206. temporary-file-directory
  17207. default-directory)
  17208. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17209. (message (concat msg "done")))))))
  17210. (defun org-format-latex
  17211. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17212. "Replace LaTeX fragments with links to an image.
  17213. The function takes care of creating the replacement image.
  17214. Only consider fragments between BEG and END when those are
  17215. provided.
  17216. When optional argument OVERLAYS is non-nil, display the image on
  17217. top of the fragment instead of replacing it.
  17218. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17219. Some of the options can be changed using the variable
  17220. `org-format-latex-options', which see."
  17221. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17222. (unless (eq processing-type 'verbatim)
  17223. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17224. (cnt 0)
  17225. checkdir-flag)
  17226. (goto-char (or beg (point-min)))
  17227. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17228. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17229. (overlay-recenter (or end (point-max))))
  17230. (while (re-search-forward math-regexp end t)
  17231. (unless (and overlays
  17232. (eq (get-char-property (point) 'org-overlay-type)
  17233. 'org-latex-overlay))
  17234. (let* ((context (org-element-context))
  17235. (type (org-element-type context)))
  17236. (when (memq type '(latex-environment latex-fragment))
  17237. (let ((block-type (eq type 'latex-environment))
  17238. (value (org-element-property :value context))
  17239. (beg (org-element-property :begin context))
  17240. (end (save-excursion
  17241. (goto-char (org-element-property :end context))
  17242. (skip-chars-backward " \r\t\n")
  17243. (point))))
  17244. (cond
  17245. ((eq processing-type 'mathjax)
  17246. ;; Prepare for MathJax processing.
  17247. (if (not (string-match "\\`\\$\\$?" value))
  17248. (goto-char end)
  17249. (delete-region beg end)
  17250. (if (string= (match-string 0 value) "$$")
  17251. (insert "\\[" (substring value 2 -2) "\\]")
  17252. (insert "\\(" (substring value 1 -1) "\\)"))))
  17253. ((assq processing-type org-preview-latex-process-alist)
  17254. ;; Process to an image.
  17255. (cl-incf cnt)
  17256. (goto-char beg)
  17257. (let* ((processing-info
  17258. (cdr (assq processing-type org-preview-latex-process-alist)))
  17259. (face (face-at-point))
  17260. ;; Get the colors from the face at point.
  17261. (fg
  17262. (let ((color (plist-get org-format-latex-options
  17263. :foreground)))
  17264. (if (and forbuffer (eq color 'auto))
  17265. (face-attribute face :foreground nil 'default)
  17266. color)))
  17267. (bg
  17268. (let ((color (plist-get org-format-latex-options
  17269. :background)))
  17270. (if (and forbuffer (eq color 'auto))
  17271. (face-attribute face :background nil 'default)
  17272. color)))
  17273. (hash (sha1 (prin1-to-string
  17274. (list org-format-latex-header
  17275. org-latex-default-packages-alist
  17276. org-latex-packages-alist
  17277. org-format-latex-options
  17278. forbuffer value fg bg))))
  17279. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17280. (absprefix (expand-file-name prefix dir))
  17281. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17282. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17283. (sep (and block-type "\n\n"))
  17284. (link (concat sep "[[file:" linkfile "]]" sep))
  17285. (options
  17286. (org-combine-plists
  17287. org-format-latex-options
  17288. `(:foreground ,fg :background ,bg))))
  17289. (when msg (message msg cnt))
  17290. (unless checkdir-flag ; Ensure the directory exists.
  17291. (setq checkdir-flag t)
  17292. (let ((todir (file-name-directory absprefix)))
  17293. (unless (file-directory-p todir)
  17294. (make-directory todir t))))
  17295. (unless (file-exists-p movefile)
  17296. (org-create-formula-image
  17297. value movefile options forbuffer processing-type))
  17298. (if overlays
  17299. (progn
  17300. (dolist (o (overlays-in beg end))
  17301. (when (eq (overlay-get o 'org-overlay-type)
  17302. 'org-latex-overlay)
  17303. (delete-overlay o)))
  17304. (org--format-latex-make-overlay beg end movefile imagetype)
  17305. (goto-char end))
  17306. (delete-region beg end)
  17307. (insert
  17308. (org-add-props link
  17309. (list 'org-latex-src
  17310. (replace-regexp-in-string "\"" "" value)
  17311. 'org-latex-src-embed-type
  17312. (if block-type 'paragraph 'character)))))))
  17313. ((eq processing-type 'mathml)
  17314. ;; Process to MathML.
  17315. (unless (org-format-latex-mathml-available-p)
  17316. (user-error "LaTeX to MathML converter not configured"))
  17317. (cl-incf cnt)
  17318. (when msg (message msg cnt))
  17319. (goto-char beg)
  17320. (delete-region beg end)
  17321. (insert (org-format-latex-as-mathml
  17322. value block-type prefix dir)))
  17323. (t
  17324. (error "Unknown conversion process %s for LaTeX fragments"
  17325. processing-type)))))))))))
  17326. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17327. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17328. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17329. sucessful, return the portion between \"<math...> </math>\"
  17330. elements otherwise return nil. When MATHML-FILE is specified,
  17331. write the results in to that file. When invoked as an
  17332. interactive command, prompt for LATEX-FRAG, with initial value
  17333. set to the current active region and echo the results for user
  17334. inspection."
  17335. (interactive (list (let ((frag (when (org-region-active-p)
  17336. (buffer-substring-no-properties
  17337. (region-beginning) (region-end)))))
  17338. (read-string "LaTeX Fragment: " frag nil frag))))
  17339. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17340. (let* ((tmp-in-file
  17341. (let ((file (file-relative-name
  17342. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17343. (write-region latex-frag nil file)
  17344. file))
  17345. (tmp-out-file (file-relative-name
  17346. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17347. (cmd (format-spec
  17348. org-latex-to-mathml-convert-command
  17349. `((?j . ,(and org-latex-to-mathml-jar-file
  17350. (shell-quote-argument
  17351. (expand-file-name
  17352. org-latex-to-mathml-jar-file))))
  17353. (?I . ,(shell-quote-argument tmp-in-file))
  17354. (?i . ,latex-frag)
  17355. (?o . ,(shell-quote-argument tmp-out-file)))))
  17356. mathml shell-command-output)
  17357. (when (called-interactively-p 'any)
  17358. (unless (org-format-latex-mathml-available-p)
  17359. (user-error "LaTeX to MathML converter not configured")))
  17360. (message "Running %s" cmd)
  17361. (setq shell-command-output (shell-command-to-string cmd))
  17362. (setq mathml
  17363. (when (file-readable-p tmp-out-file)
  17364. (with-current-buffer (find-file-noselect tmp-out-file t)
  17365. (goto-char (point-min))
  17366. (when (re-search-forward
  17367. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17368. (regexp-quote
  17369. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17370. nil t)
  17371. (prog1 (match-string 0) (kill-buffer))))))
  17372. (cond
  17373. (mathml
  17374. (setq mathml
  17375. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17376. (when mathml-file
  17377. (write-region mathml nil mathml-file))
  17378. (when (called-interactively-p 'any)
  17379. (message mathml)))
  17380. ((message "LaTeX to MathML conversion failed")
  17381. (message shell-command-output)))
  17382. (delete-file tmp-in-file)
  17383. (when (file-exists-p tmp-out-file)
  17384. (delete-file tmp-out-file))
  17385. mathml))
  17386. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17387. prefix &optional dir)
  17388. "Use `org-create-math-formula' but check local cache first."
  17389. (let* ((absprefix (expand-file-name prefix dir))
  17390. (print-length nil) (print-level nil)
  17391. (formula-id (concat
  17392. "formula-"
  17393. (sha1
  17394. (prin1-to-string
  17395. (list latex-frag
  17396. org-latex-to-mathml-convert-command)))))
  17397. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17398. (formula-cache-dir (file-name-directory formula-cache)))
  17399. (unless (file-directory-p formula-cache-dir)
  17400. (make-directory formula-cache-dir t))
  17401. (unless (file-exists-p formula-cache)
  17402. (org-create-math-formula latex-frag formula-cache))
  17403. (if (file-exists-p formula-cache)
  17404. ;; Successful conversion. Return the link to MathML file.
  17405. (org-add-props
  17406. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17407. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17408. 'org-latex-src-embed-type (if latex-frag-type
  17409. 'paragraph 'character)))
  17410. ;; Failed conversion. Return the LaTeX fragment verbatim
  17411. latex-frag)))
  17412. (defun org--get-display-dpi ()
  17413. "Get the DPI of the display.
  17414. The function assumes that the display has the same pixel width in
  17415. the horizontal and vertical directions."
  17416. (if (display-graphic-p)
  17417. (round (/ (display-pixel-height)
  17418. (/ (display-mm-height) 25.4)))
  17419. (error "Attempt to calculate the dpi of a non-graphic display")))
  17420. (defun org-create-formula-image
  17421. (string tofile options buffer &optional processing-type)
  17422. "Create an image from LaTeX source using external processes.
  17423. The LaTeX STRING is saved to a temporary LaTeX file, then
  17424. converted to an image file by process PROCESSING-TYPE defined in
  17425. `org-preview-latex-process-alist'. A nil value defaults to
  17426. `org-preview-latex-default-process'.
  17427. The generated image file is eventually moved to TOFILE.
  17428. The OPTIONS argument controls the size, foreground color and
  17429. background color of the generated image.
  17430. When BUFFER non-nil, this function is used for LaTeX previewing.
  17431. Otherwise, it is used to deal with LaTeX snippets showed in
  17432. a HTML file."
  17433. (let* ((processing-type (or processing-type
  17434. org-preview-latex-default-process))
  17435. (processing-info
  17436. (cdr (assq processing-type org-preview-latex-process-alist)))
  17437. (programs (plist-get processing-info :programs))
  17438. (error-message (or (plist-get processing-info :message) ""))
  17439. (use-xcolor (plist-get processing-info :use-xcolor))
  17440. (image-input-type (plist-get processing-info :image-input-type))
  17441. (image-output-type (plist-get processing-info :image-output-type))
  17442. (post-clean (or (plist-get processing-info :post-clean)
  17443. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17444. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17445. (latex-header
  17446. (or (plist-get processing-info :latex-header)
  17447. (org-latex-make-preamble
  17448. (org-export-get-environment (org-export-get-backend 'latex))
  17449. org-format-latex-header
  17450. 'snippet)))
  17451. (latex-compiler (plist-get processing-info :latex-compiler))
  17452. (image-converter (plist-get processing-info :image-converter))
  17453. (tmpdir temporary-file-directory)
  17454. (texfilebase (make-temp-name
  17455. (expand-file-name "orgtex" tmpdir)))
  17456. (texfile (concat texfilebase ".tex"))
  17457. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17458. '(1.0 . 1.0)))
  17459. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17460. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17461. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17462. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17463. "Black"))
  17464. (bg (or (plist-get options (if buffer :background :html-background))
  17465. "Transparent"))
  17466. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17467. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17468. (dolist (program programs)
  17469. (org-check-external-command program error-message))
  17470. (if use-xcolor
  17471. (progn (if (eq fg 'default)
  17472. (setq fg (org-latex-color :foreground))
  17473. (setq fg (org-latex-color-format fg)))
  17474. (if (eq bg 'default)
  17475. (setq bg (org-latex-color :background))
  17476. (setq bg (org-latex-color-format
  17477. (if (string= bg "Transparent") "white" bg))))
  17478. (with-temp-file texfile
  17479. (insert latex-header)
  17480. (insert "\n\\begin{document}\n"
  17481. "\\definecolor{fg}{rgb}{" fg "}\n"
  17482. "\\definecolor{bg}{rgb}{" bg "}\n"
  17483. "\n\\pagecolor{bg}\n"
  17484. "\n{\\color{fg}\n"
  17485. string
  17486. "\n}\n"
  17487. "\n\\end{document}\n")))
  17488. (if (eq fg 'default)
  17489. (setq fg (org-dvipng-color :foreground))
  17490. (unless (string= fg "Transparent")
  17491. (setq fg (org-dvipng-color-format fg))))
  17492. (if (eq bg 'default)
  17493. (setq bg (org-dvipng-color :background))
  17494. (unless (string= bg "Transparent")
  17495. (setq bg (org-dvipng-color-format bg))))
  17496. (with-temp-file texfile
  17497. (insert latex-header)
  17498. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17499. (let* ((err-msg (format "Please adjust `%s' part of \
  17500. `org-preview-latex-process-alist'."
  17501. processing-type))
  17502. (image-input-file
  17503. (org-compile-file
  17504. texfile latex-compiler image-input-type err-msg log-buf))
  17505. (image-output-file
  17506. (org-compile-file
  17507. image-input-file image-converter image-output-type err-msg log-buf
  17508. `((?F . ,(shell-quote-argument fg))
  17509. (?B . ,(shell-quote-argument bg))
  17510. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17511. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17512. (copy-file image-output-file tofile 'replace)
  17513. (dolist (e post-clean)
  17514. (when (file-exists-p (concat texfilebase e))
  17515. (delete-file (concat texfilebase e))))
  17516. image-output-file)))
  17517. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17518. "Fill a LaTeX header template TPL.
  17519. In the template, the following place holders will be recognized:
  17520. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17521. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17522. [PACKAGES] \\usepackage statements for PKG
  17523. [NO-PACKAGES] do not include PKG
  17524. [EXTRA] the string EXTRA
  17525. [NO-EXTRA] do not include EXTRA
  17526. For backward compatibility, if both the positive and the negative place
  17527. holder is missing, the positive one (without the \"NO-\") will be
  17528. assumed to be present at the end of the template.
  17529. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17530. EXTRA is a string.
  17531. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17532. (let (rpl (end ""))
  17533. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17534. (setq rpl (if (or (match-end 1) (not def-pkg))
  17535. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17536. tpl (replace-match rpl t t tpl))
  17537. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17538. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17539. (setq rpl (if (or (match-end 1) (not pkg))
  17540. "" (org-latex-packages-to-string pkg snippets-p t))
  17541. tpl (replace-match rpl t t tpl))
  17542. (when pkg (setq end
  17543. (concat end "\n"
  17544. (org-latex-packages-to-string pkg snippets-p)))))
  17545. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17546. (setq rpl (if (or (match-end 1) (not extra))
  17547. "" (concat extra "\n"))
  17548. tpl (replace-match rpl t t tpl))
  17549. (when (and extra (string-match "\\S-" extra))
  17550. (setq end (concat end "\n" extra))))
  17551. (if (string-match "\\S-" end)
  17552. (concat tpl "\n" end)
  17553. tpl)))
  17554. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17555. "Turn an alist of packages into a string with the \\usepackage macros."
  17556. (setq pkg (mapconcat (lambda(p)
  17557. (cond
  17558. ((stringp p) p)
  17559. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17560. (format "%% Package %s omitted" (cadr p)))
  17561. ((equal "" (car p))
  17562. (format "\\usepackage{%s}" (cadr p)))
  17563. (t
  17564. (format "\\usepackage[%s]{%s}"
  17565. (car p) (cadr p)))))
  17566. pkg
  17567. "\n"))
  17568. (if newline (concat pkg "\n") pkg))
  17569. (defun org-dvipng-color (attr)
  17570. "Return a RGB color specification for dvipng."
  17571. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17572. (defun org-dvipng-color-format (color-name)
  17573. "Convert COLOR-NAME to a RGB color value for dvipng."
  17574. (apply #'format "rgb %s %s %s"
  17575. (mapcar 'org-normalize-color
  17576. (color-values color-name))))
  17577. (defun org-latex-color (attr)
  17578. "Return a RGB color for the LaTeX color package."
  17579. (org-latex-color-format (face-attribute 'default attr nil)))
  17580. (defun org-latex-color-format (color-name)
  17581. "Convert COLOR-NAME to a RGB color value."
  17582. (apply #'format "%s,%s,%s"
  17583. (mapcar 'org-normalize-color
  17584. (color-values color-name))))
  17585. (defun org-normalize-color (value)
  17586. "Return string to be used as color value for an RGB component."
  17587. (format "%g" (/ value 65535.0)))
  17588. ;; Image display
  17589. (defvar-local org-inline-image-overlays nil)
  17590. (defun org-toggle-inline-images (&optional include-linked)
  17591. "Toggle the display of inline images.
  17592. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17593. (interactive "P")
  17594. (if org-inline-image-overlays
  17595. (progn
  17596. (org-remove-inline-images)
  17597. (when (called-interactively-p 'interactive)
  17598. (message "Inline image display turned off")))
  17599. (org-display-inline-images include-linked)
  17600. (when (called-interactively-p 'interactive)
  17601. (message (if org-inline-image-overlays
  17602. (format "%d images displayed inline"
  17603. (length org-inline-image-overlays))
  17604. "No images to display inline")))))
  17605. (defun org-redisplay-inline-images ()
  17606. "Refresh the display of inline images."
  17607. (interactive)
  17608. (if (not org-inline-image-overlays)
  17609. (org-toggle-inline-images)
  17610. (org-toggle-inline-images)
  17611. (org-toggle-inline-images)))
  17612. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17613. "Display inline images.
  17614. An inline image is a link which follows either of these
  17615. conventions:
  17616. 1. Its path is a file with an extension matching return value
  17617. from `image-file-name-regexp' and it has no contents.
  17618. 2. Its description consists in a single link of the previous
  17619. type.
  17620. When optional argument INCLUDE-LINKED is non-nil, also links with
  17621. a text description part will be inlined. This can be nice for
  17622. a quick look at those images, but it does not reflect what
  17623. exported files will look like.
  17624. When optional argument REFRESH is non-nil, refresh existing
  17625. images between BEG and END. This will create new image displays
  17626. only if necessary. BEG and END default to the buffer
  17627. boundaries."
  17628. (interactive "P")
  17629. (when (display-graphic-p)
  17630. (unless refresh
  17631. (org-remove-inline-images)
  17632. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17633. (org-with-wide-buffer
  17634. (goto-char (or beg (point-min)))
  17635. (let* ((case-fold-search t)
  17636. (file-extension-re (image-file-name-regexp))
  17637. (link-abbrevs (mapcar #'car
  17638. (append org-link-abbrev-alist-local
  17639. org-link-abbrev-alist)))
  17640. ;; Check absolute, relative file names and explicit
  17641. ;; "file:" links. Also check link abbreviations since
  17642. ;; some might expand to "file" links.
  17643. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17644. (if (not link-abbrevs) ""
  17645. (format "\\|\\(?:%s:\\)"
  17646. (regexp-opt link-abbrevs))))))
  17647. (while (re-search-forward file-types-re end t)
  17648. (let ((link (save-match-data (org-element-context))))
  17649. ;; Check if we're at an inline image, i.e., an image file
  17650. ;; link without a description (unless INCLUDE-LINKED is
  17651. ;; non-nil).
  17652. (when (and (equal "file" (org-element-property :type link))
  17653. (or include-linked
  17654. (null (org-element-contents link)))
  17655. (string-match-p file-extension-re
  17656. (org-element-property :path link)))
  17657. (let ((file (expand-file-name
  17658. (org-link-unescape
  17659. (org-element-property :path link)))))
  17660. (when (file-exists-p file)
  17661. (let ((width
  17662. ;; Apply `org-image-actual-width' specifications.
  17663. (cond
  17664. ((not (image-type-available-p 'imagemagick)) nil)
  17665. ((eq org-image-actual-width t) nil)
  17666. ((listp org-image-actual-width)
  17667. (or
  17668. ;; First try to find a width among
  17669. ;; attributes associated to the paragraph
  17670. ;; containing link.
  17671. (let ((paragraph
  17672. (let ((e link))
  17673. (while (and (setq e (org-element-property
  17674. :parent e))
  17675. (not (eq (org-element-type e)
  17676. 'paragraph))))
  17677. e)))
  17678. (when paragraph
  17679. (save-excursion
  17680. (goto-char (org-element-property :begin paragraph))
  17681. (when
  17682. (re-search-forward
  17683. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17684. (org-element-property
  17685. :post-affiliated paragraph)
  17686. t)
  17687. (string-to-number (match-string 1))))))
  17688. ;; Otherwise, fall-back to provided number.
  17689. (car org-image-actual-width)))
  17690. ((numberp org-image-actual-width)
  17691. org-image-actual-width)))
  17692. (old (get-char-property-and-overlay
  17693. (org-element-property :begin link)
  17694. 'org-image-overlay)))
  17695. (if (and (car-safe old) refresh)
  17696. (image-refresh (overlay-get (cdr old) 'display))
  17697. (let ((image (create-image file
  17698. (and width 'imagemagick)
  17699. nil
  17700. :width width)))
  17701. (when image
  17702. (let ((ov (make-overlay
  17703. (org-element-property :begin link)
  17704. (progn
  17705. (goto-char
  17706. (org-element-property :end link))
  17707. (skip-chars-backward " \t")
  17708. (point)))))
  17709. (overlay-put ov 'display image)
  17710. (overlay-put ov 'face 'default)
  17711. (overlay-put ov 'org-image-overlay t)
  17712. (overlay-put
  17713. ov 'modification-hooks
  17714. (list 'org-display-inline-remove-overlay))
  17715. (push ov org-inline-image-overlays)))))))))))))))
  17716. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17717. "Remove inline-display overlay if a corresponding region is modified."
  17718. (let ((inhibit-modification-hooks t))
  17719. (when (and ov after)
  17720. (delete ov org-inline-image-overlays)
  17721. (delete-overlay ov))))
  17722. (defun org-remove-inline-images ()
  17723. "Remove inline display of images."
  17724. (interactive)
  17725. (mapc #'delete-overlay org-inline-image-overlays)
  17726. (setq org-inline-image-overlays nil))
  17727. ;;;; Key bindings
  17728. (defun org-remap (map &rest commands)
  17729. "In MAP, remap the functions given in COMMANDS.
  17730. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17731. (let (new old)
  17732. (while commands
  17733. (setq old (pop commands) new (pop commands))
  17734. (org-defkey map (vector 'remap old) new))))
  17735. ;; Outline functions from `outline-mode-prefix-map'
  17736. ;; that can be remapped in Org:
  17737. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17738. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17739. (define-key org-mode-map [remap outline-forward-same-level]
  17740. 'org-forward-heading-same-level)
  17741. (define-key org-mode-map [remap outline-backward-same-level]
  17742. 'org-backward-heading-same-level)
  17743. (define-key org-mode-map [remap outline-show-branches]
  17744. 'org-kill-note-or-show-branches)
  17745. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17746. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17747. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17748. (define-key org-mode-map [remap outline-next-visible-heading]
  17749. 'org-next-visible-heading)
  17750. (define-key org-mode-map [remap outline-previous-visible-heading]
  17751. 'org-previous-visible-heading)
  17752. (define-key org-mode-map [remap show-children] 'org-show-children)
  17753. ;; Outline functions from `outline-mode-prefix-map' that can not
  17754. ;; be remapped in Org:
  17755. ;; - the column "key binding" shows whether the Outline function is still
  17756. ;; available in Org mode on the same key that it has been bound to in
  17757. ;; Outline mode:
  17758. ;; - "overridden": key used for a different functionality in Org mode
  17759. ;; - else: key still bound to the same Outline function in Org mode
  17760. ;; | Outline function | key binding | Org replacement |
  17761. ;; |------------------------------------+-------------+--------------------------|
  17762. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17763. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17764. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17765. ;; | `show-entry' | overridden | no replacement |
  17766. ;; | `show-branches' | `C-c C-k' | still same function |
  17767. ;; | `show-subtree' | overridden | visibility cycling |
  17768. ;; | `show-all' | overridden | no replacement |
  17769. ;; | `hide-subtree' | overridden | visibility cycling |
  17770. ;; | `hide-body' | overridden | no replacement |
  17771. ;; | `hide-entry' | overridden | visibility cycling |
  17772. ;; | `hide-leaves' | overridden | no replacement |
  17773. ;; | `hide-sublevels' | overridden | no replacement |
  17774. ;; | `hide-other' | overridden | no replacement |
  17775. ;; Make `C-c C-x' a prefix key
  17776. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17777. ;; TAB key with modifiers
  17778. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17779. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17780. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17781. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17782. ;; The following line is necessary under Suse GNU/Linux
  17783. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17784. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17785. (define-key org-mode-map [backtab] 'org-shifttab)
  17786. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17787. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17788. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17789. ;; Cursor keys with modifiers
  17790. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17791. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17792. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17793. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17794. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17795. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17796. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17797. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17798. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17799. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17800. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17801. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17802. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17803. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17804. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17805. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17806. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17807. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17808. ;; Babel keys
  17809. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17810. (dolist (pair org-babel-key-bindings)
  17811. (define-key org-babel-map (car pair) (cdr pair)))
  17812. ;;; Extra keys for tty access.
  17813. ;; We only set them when really needed because otherwise the
  17814. ;; menus don't show the simple keys
  17815. (when (or org-use-extra-keys (not window-system))
  17816. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17817. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17818. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17819. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17820. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17821. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17822. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17823. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17824. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17825. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17826. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17827. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17828. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17829. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17830. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17831. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17832. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17833. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17834. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17835. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17836. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17837. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17838. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17839. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17840. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17841. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17842. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17843. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17844. ;; All the other keys
  17845. (org-remap org-mode-map
  17846. 'self-insert-command 'org-self-insert-command
  17847. 'delete-char 'org-delete-char
  17848. 'delete-backward-char 'org-delete-backward-char)
  17849. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17850. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17851. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17852. (if (boundp 'narrow-map)
  17853. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17854. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17855. (if (boundp 'narrow-map)
  17856. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17857. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17858. (if (boundp 'narrow-map)
  17859. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17860. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17861. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17862. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17863. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17864. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17865. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17866. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17867. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17868. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17869. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17870. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17871. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17872. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17873. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17874. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17875. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17876. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17877. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17878. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17879. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17880. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17881. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17882. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17883. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17884. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17885. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17886. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17887. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17888. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17889. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17890. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17891. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17892. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17893. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17894. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17895. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17896. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17897. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17898. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17899. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17900. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17901. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17902. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17903. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17904. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17905. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17906. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17907. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17908. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17909. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17910. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17911. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17912. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17913. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17914. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17915. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17916. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17917. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17918. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17919. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17920. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17921. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17922. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17923. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17924. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17925. (org-defkey org-mode-map "\C-m" 'org-return)
  17926. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17927. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17928. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17929. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17930. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17931. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17932. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17933. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17934. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17935. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17936. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17937. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17938. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17939. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17940. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17941. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17942. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17943. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17944. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17945. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17946. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17947. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17948. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17949. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17950. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17951. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17952. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17953. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17954. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17955. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17956. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17957. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17958. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17959. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17960. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17961. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17962. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17963. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17964. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17965. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17966. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17967. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17968. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17969. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17970. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17971. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17972. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17973. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17974. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17975. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17976. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17977. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17978. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17979. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17980. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17981. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17982. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17983. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17984. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17985. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17986. (defconst org-speed-commands-default
  17987. '(
  17988. ("Outline Navigation")
  17989. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17990. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17991. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17992. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17993. ("F" . org-next-block)
  17994. ("B" . org-previous-block)
  17995. ("u" . (org-speed-move-safe 'outline-up-heading))
  17996. ("j" . org-goto)
  17997. ("g" . (org-refile t))
  17998. ("Outline Visibility")
  17999. ("c" . org-cycle)
  18000. ("C" . org-shifttab)
  18001. (" " . org-display-outline-path)
  18002. ("s" . org-narrow-to-subtree)
  18003. ("=" . org-columns)
  18004. ("Outline Structure Editing")
  18005. ("U" . org-metaup)
  18006. ("D" . org-metadown)
  18007. ("r" . org-metaright)
  18008. ("l" . org-metaleft)
  18009. ("R" . org-shiftmetaright)
  18010. ("L" . org-shiftmetaleft)
  18011. ("i" . (progn (forward-char 1) (call-interactively
  18012. 'org-insert-heading-respect-content)))
  18013. ("^" . org-sort)
  18014. ("w" . org-refile)
  18015. ("a" . org-archive-subtree-default-with-confirmation)
  18016. ("@" . org-mark-subtree)
  18017. ("#" . org-toggle-comment)
  18018. ("Clock Commands")
  18019. ("I" . org-clock-in)
  18020. ("O" . org-clock-out)
  18021. ("Meta Data Editing")
  18022. ("t" . org-todo)
  18023. ("," . (org-priority))
  18024. ("0" . (org-priority ?\ ))
  18025. ("1" . (org-priority ?A))
  18026. ("2" . (org-priority ?B))
  18027. ("3" . (org-priority ?C))
  18028. (":" . org-set-tags-command)
  18029. ("e" . org-set-effort)
  18030. ("E" . org-inc-effort)
  18031. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18032. (org-entry-put (point) "APPT_WARNTIME" m)))
  18033. ("Agenda Views etc")
  18034. ("v" . org-agenda)
  18035. ("/" . org-sparse-tree)
  18036. ("Misc")
  18037. ("o" . org-open-at-point)
  18038. ("?" . org-speed-command-help)
  18039. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18040. (">" . (org-agenda-remove-restriction-lock))
  18041. )
  18042. "The default speed commands.")
  18043. (defun org-print-speed-command (e)
  18044. (if (> (length (car e)) 1)
  18045. (progn
  18046. (princ "\n")
  18047. (princ (car e))
  18048. (princ "\n")
  18049. (princ (make-string (length (car e)) ?-))
  18050. (princ "\n"))
  18051. (princ (car e))
  18052. (princ " ")
  18053. (if (symbolp (cdr e))
  18054. (princ (symbol-name (cdr e)))
  18055. (prin1 (cdr e)))
  18056. (princ "\n")))
  18057. (defun org-speed-command-help ()
  18058. "Show the available speed commands."
  18059. (interactive)
  18060. (if (not org-use-speed-commands)
  18061. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18062. (with-output-to-temp-buffer "*Help*"
  18063. (princ "User-defined Speed commands\n===========================\n")
  18064. (mapc #'org-print-speed-command org-speed-commands-user)
  18065. (princ "\n")
  18066. (princ "Built-in Speed commands\n=======================\n")
  18067. (mapc #'org-print-speed-command org-speed-commands-default))
  18068. (with-current-buffer "*Help*"
  18069. (setq truncate-lines t))))
  18070. (defun org-speed-move-safe (cmd)
  18071. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18072. If not, return to the original position and throw an error."
  18073. (interactive)
  18074. (let ((pos (point)))
  18075. (call-interactively cmd)
  18076. (unless (and (bolp) (org-at-heading-p))
  18077. (goto-char pos)
  18078. (error "Boundary reached while executing %s" cmd))))
  18079. (defvar org-self-insert-command-undo-counter 0)
  18080. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18081. (defvar org-speed-command nil)
  18082. (defun org-speed-command-activate (keys)
  18083. "Hook for activating single-letter speed commands.
  18084. `org-speed-commands-default' specifies a minimal command set.
  18085. Use `org-speed-commands-user' for further customization."
  18086. (when (or (and (bolp) (looking-at org-outline-regexp))
  18087. (and (functionp org-use-speed-commands)
  18088. (funcall org-use-speed-commands)))
  18089. (cdr (assoc keys (append org-speed-commands-user
  18090. org-speed-commands-default)))))
  18091. (defun org-babel-speed-command-activate (keys)
  18092. "Hook for activating single-letter code block commands."
  18093. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18094. (cdr (assoc keys org-babel-key-bindings))))
  18095. (defcustom org-speed-command-hook
  18096. '(org-speed-command-activate org-babel-speed-command-activate)
  18097. "Hook for activating speed commands at strategic locations.
  18098. Hook functions are called in sequence until a valid handler is
  18099. found.
  18100. Each hook takes a single argument, a user-pressed command key
  18101. which is also a `self-insert-command' from the global map.
  18102. Within the hook, examine the cursor position and the command key
  18103. and return nil or a valid handler as appropriate. Handler could
  18104. be one of an interactive command, a function, or a form.
  18105. Set `org-use-speed-commands' to non-nil value to enable this
  18106. hook. The default setting is `org-speed-command-activate'."
  18107. :group 'org-structure
  18108. :version "24.1"
  18109. :type 'hook)
  18110. (defun org-self-insert-command (N)
  18111. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18112. If the cursor is in a table looking at whitespace, the whitespace is
  18113. overwritten, and the table is not marked as requiring realignment."
  18114. (interactive "p")
  18115. (org-check-before-invisible-edit 'insert)
  18116. (cond
  18117. ((and org-use-speed-commands
  18118. (let ((kv (this-command-keys-vector)))
  18119. (setq org-speed-command
  18120. (run-hook-with-args-until-success
  18121. 'org-speed-command-hook
  18122. (make-string 1 (aref kv (1- (length kv))))))))
  18123. (cond
  18124. ((commandp org-speed-command)
  18125. (setq this-command org-speed-command)
  18126. (call-interactively org-speed-command))
  18127. ((functionp org-speed-command)
  18128. (funcall org-speed-command))
  18129. ((and org-speed-command (listp org-speed-command))
  18130. (eval org-speed-command))
  18131. (t (let (org-use-speed-commands)
  18132. (call-interactively 'org-self-insert-command)))))
  18133. ((and
  18134. (org-at-table-p)
  18135. (eq N 1)
  18136. (not (org-region-active-p))
  18137. (progn
  18138. ;; Check if we blank the field, and if that triggers align.
  18139. (and (featurep 'org-table) org-table-auto-blank-field
  18140. (memq last-command
  18141. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18142. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18143. ;; Got extra space, this field does not determine
  18144. ;; column width.
  18145. (let (org-table-may-need-update) (org-table-blank-field))
  18146. ;; No extra space, this field may determine column
  18147. ;; width.
  18148. (org-table-blank-field)))
  18149. t)
  18150. (looking-at "[^|\n]* \\( \\)|"))
  18151. ;; There is room for insertion without re-aligning the table.
  18152. (delete-region (match-beginning 1) (match-end 1))
  18153. (self-insert-command N))
  18154. (t
  18155. (setq org-table-may-need-update t)
  18156. (self-insert-command N)
  18157. (org-fix-tags-on-the-fly)
  18158. (when org-self-insert-cluster-for-undo
  18159. (if (not (eq last-command 'org-self-insert-command))
  18160. (setq org-self-insert-command-undo-counter 1)
  18161. (if (>= org-self-insert-command-undo-counter 20)
  18162. (setq org-self-insert-command-undo-counter 1)
  18163. (and (> org-self-insert-command-undo-counter 0)
  18164. buffer-undo-list (listp buffer-undo-list)
  18165. (not (cadr buffer-undo-list)) ; remove nil entry
  18166. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18167. (setq org-self-insert-command-undo-counter
  18168. (1+ org-self-insert-command-undo-counter))))))))
  18169. (defun org-check-before-invisible-edit (kind)
  18170. "Check is editing if kind KIND would be dangerous with invisible text around.
  18171. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18172. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18173. (when (and org-catch-invisible-edits
  18174. (or (not (boundp 'visible-mode)) (not visible-mode))
  18175. (or (get-char-property (point) 'invisible)
  18176. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18177. ;; OK, we need to take a closer look. Do not consider
  18178. ;; invisibility obtained through text properties (e.g., link
  18179. ;; fontification), as it cannot be toggled.
  18180. (let* ((invisible-at-point
  18181. (pcase (get-char-property-and-overlay (point) 'invisible)
  18182. (`(,_ . ,(and (pred overlayp) o)) o)))
  18183. ;; Assume that point cannot land in the middle of an
  18184. ;; overlay, or between two overlays.
  18185. (invisible-before-point
  18186. (and (not invisible-at-point)
  18187. (not (bobp))
  18188. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18189. (`(,_ . ,(and (pred overlayp) o)) o))))
  18190. (border-and-ok-direction
  18191. (or
  18192. ;; Check if we are acting predictably before invisible
  18193. ;; text.
  18194. (and invisible-at-point
  18195. (memq kind '(insert delete-backward)))
  18196. ;; Check if we are acting predictably after invisible text
  18197. ;; This works not well, and I have turned it off. It seems
  18198. ;; better to always show and stop after invisible text.
  18199. ;; (and (not invisible-at-point) invisible-before-point
  18200. ;; (memq kind '(insert delete)))
  18201. )))
  18202. (when (or invisible-at-point invisible-before-point)
  18203. (when (eq org-catch-invisible-edits 'error)
  18204. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18205. (if (and org-custom-properties-overlays
  18206. (y-or-n-p "Display invisible properties in this buffer? "))
  18207. (org-toggle-custom-properties-visibility)
  18208. ;; Make the area visible
  18209. (save-excursion
  18210. (when invisible-before-point
  18211. (goto-char
  18212. (previous-single-char-property-change (point) 'invisible)))
  18213. ;; Remove whatever overlay is currently making yet-to-be
  18214. ;; edited text invisible. Also remove nested invisibility
  18215. ;; related overlays.
  18216. (delete-overlay (or invisible-at-point invisible-before-point))
  18217. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18218. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18219. (`(,_ . ,(and (pred overlayp) o))
  18220. (delete-overlay o)
  18221. t)))))
  18222. (cond
  18223. ((eq org-catch-invisible-edits 'show)
  18224. ;; That's it, we do the edit after showing
  18225. (message
  18226. "Unfolding invisible region around point before editing")
  18227. (sit-for 1))
  18228. ((and (eq org-catch-invisible-edits 'smart)
  18229. border-and-ok-direction)
  18230. (message "Unfolding invisible region around point before editing"))
  18231. (t
  18232. ;; Don't do the edit, make the user repeat it in full visibility
  18233. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18234. (defun org-fix-tags-on-the-fly ()
  18235. "Align tags in headline at point.
  18236. Unlike to `org-set-tags', it ignores region and sorting."
  18237. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18238. (org-at-heading-p))
  18239. (let ((org-ignore-region t)
  18240. (org-tags-sort-function nil))
  18241. (org-set-tags nil t))))
  18242. (defun org-delete-backward-char (N)
  18243. "Like `delete-backward-char', insert whitespace at field end in tables.
  18244. When deleting backwards, in tables this function will insert whitespace in
  18245. front of the next \"|\" separator, to keep the table aligned. The table will
  18246. still be marked for re-alignment if the field did fill the entire column,
  18247. because, in this case the deletion might narrow the column."
  18248. (interactive "p")
  18249. (save-match-data
  18250. (org-check-before-invisible-edit 'delete-backward)
  18251. (if (and (org-at-table-p)
  18252. (eq N 1)
  18253. (not (org-region-active-p))
  18254. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18255. (looking-at ".*?|"))
  18256. (let ((pos (point))
  18257. (noalign (looking-at "[^|\n\r]* |"))
  18258. (c org-table-may-need-update))
  18259. (backward-delete-char N)
  18260. (unless overwrite-mode
  18261. (skip-chars-forward "^|")
  18262. (insert " ")
  18263. (goto-char (1- pos)))
  18264. ;; noalign: if there were two spaces at the end, this field
  18265. ;; does not determine the width of the column.
  18266. (when noalign (setq org-table-may-need-update c)))
  18267. (backward-delete-char N)
  18268. (org-fix-tags-on-the-fly))))
  18269. (defun org-delete-char (N)
  18270. "Like `delete-char', but insert whitespace at field end in tables.
  18271. When deleting characters, in tables this function will insert whitespace in
  18272. front of the next \"|\" separator, to keep the table aligned. The table will
  18273. still be marked for re-alignment if the field did fill the entire column,
  18274. because, in this case the deletion might narrow the column."
  18275. (interactive "p")
  18276. (save-match-data
  18277. (org-check-before-invisible-edit 'delete)
  18278. (if (and (org-at-table-p)
  18279. (not (bolp))
  18280. (not (= (char-after) ?|))
  18281. (eq N 1))
  18282. (if (looking-at ".*?|")
  18283. (let ((pos (point))
  18284. (noalign (looking-at "[^|\n\r]* |"))
  18285. (c org-table-may-need-update))
  18286. (replace-match
  18287. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18288. (goto-char pos)
  18289. ;; noalign: if there were two spaces at the end, this field
  18290. ;; does not determine the width of the column.
  18291. (when noalign (setq org-table-may-need-update c)))
  18292. (delete-char N))
  18293. (delete-char N)
  18294. (org-fix-tags-on-the-fly))))
  18295. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18296. (put 'org-self-insert-command 'delete-selection
  18297. (lambda ()
  18298. (not (run-hook-with-args-until-success
  18299. 'self-insert-uses-region-functions))))
  18300. (put 'orgtbl-self-insert-command 'delete-selection
  18301. (lambda ()
  18302. (not (run-hook-with-args-until-success
  18303. 'self-insert-uses-region-functions))))
  18304. (put 'org-delete-char 'delete-selection 'supersede)
  18305. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18306. (put 'org-yank 'delete-selection 'yank)
  18307. ;; Make `flyspell-mode' delay after some commands
  18308. (put 'org-self-insert-command 'flyspell-delayed t)
  18309. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18310. (put 'org-delete-char 'flyspell-delayed t)
  18311. (put 'org-delete-backward-char 'flyspell-delayed t)
  18312. ;; Make pabbrev-mode expand after Org mode commands
  18313. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18314. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18315. (defun org-transpose-words ()
  18316. "Transpose words for Org.
  18317. This uses the `org-mode-transpose-word-syntax-table' syntax
  18318. table, which interprets characters in `org-emphasis-alist' as
  18319. word constituents."
  18320. (interactive)
  18321. (with-syntax-table org-mode-transpose-word-syntax-table
  18322. (call-interactively 'transpose-words)))
  18323. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18324. (defvar org-ctrl-c-ctrl-c-hook nil
  18325. "Hook for functions attaching themselves to `C-c C-c'.
  18326. This can be used to add additional functionality to the C-c C-c
  18327. key which executes context-dependent commands. This hook is run
  18328. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18329. run after the last test.
  18330. Each function will be called with no arguments. The function
  18331. must check if the context is appropriate for it to act. If yes,
  18332. it should do its thing and then return a non-nil value. If the
  18333. context is wrong, just do nothing and return nil.")
  18334. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18335. "Hook for functions attaching themselves to `C-c C-c'.
  18336. This can be used to add additional functionality to the C-c C-c
  18337. key which executes context-dependent commands. This hook is run
  18338. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18339. before the first test.
  18340. Each function will be called with no arguments. The function
  18341. must check if the context is appropriate for it to act. If yes,
  18342. it should do its thing and then return a non-nil value. If the
  18343. context is wrong, just do nothing and return nil.")
  18344. (defvar org-tab-first-hook nil
  18345. "Hook for functions to attach themselves to TAB.
  18346. See `org-ctrl-c-ctrl-c-hook' for more information.
  18347. This hook runs as the first action when TAB is pressed, even before
  18348. `org-cycle' messes around with the `outline-regexp' to cater for
  18349. inline tasks and plain list item folding.
  18350. If any function in this hook returns t, any other actions that
  18351. would have been caused by TAB (such as table field motion or visibility
  18352. cycling) will not occur.")
  18353. (defvar org-tab-after-check-for-table-hook nil
  18354. "Hook for functions to attach themselves to TAB.
  18355. See `org-ctrl-c-ctrl-c-hook' for more information.
  18356. This hook runs after it has been established that the cursor is not in a
  18357. table, but before checking if the cursor is in a headline or if global cycling
  18358. should be done.
  18359. If any function in this hook returns t, not other actions like visibility
  18360. cycling will be done.")
  18361. (defvar org-tab-after-check-for-cycling-hook nil
  18362. "Hook for functions to attach themselves to TAB.
  18363. See `org-ctrl-c-ctrl-c-hook' for more information.
  18364. This hook runs after it has been established that not table field motion and
  18365. not visibility should be done because of current context. This is probably
  18366. the place where a package like yasnippets can hook in.")
  18367. (defvar org-tab-before-tab-emulation-hook nil
  18368. "Hook for functions to attach themselves to TAB.
  18369. See `org-ctrl-c-ctrl-c-hook' for more information.
  18370. This hook runs after every other options for TAB have been exhausted, but
  18371. before indentation and \t insertion takes place.")
  18372. (defvar org-metaleft-hook nil
  18373. "Hook for functions attaching themselves to `M-left'.
  18374. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18375. (defvar org-metaright-hook nil
  18376. "Hook for functions attaching themselves to `M-right'.
  18377. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18378. (defvar org-metaup-hook nil
  18379. "Hook for functions attaching themselves to `M-up'.
  18380. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18381. (defvar org-metadown-hook nil
  18382. "Hook for functions attaching themselves to `M-down'.
  18383. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18384. (defvar org-shiftmetaleft-hook nil
  18385. "Hook for functions attaching themselves to `M-S-left'.
  18386. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18387. (defvar org-shiftmetaright-hook nil
  18388. "Hook for functions attaching themselves to `M-S-right'.
  18389. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18390. (defvar org-shiftmetaup-hook nil
  18391. "Hook for functions attaching themselves to `M-S-up'.
  18392. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18393. (defvar org-shiftmetadown-hook nil
  18394. "Hook for functions attaching themselves to `M-S-down'.
  18395. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18396. (defvar org-metareturn-hook nil
  18397. "Hook for functions attaching themselves to `M-RET'.
  18398. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18399. (defvar org-shiftup-hook nil
  18400. "Hook for functions attaching themselves to `S-up'.
  18401. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18402. (defvar org-shiftup-final-hook nil
  18403. "Hook for functions attaching themselves to `S-up'.
  18404. This one runs after all other options except shift-select have been excluded.
  18405. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18406. (defvar org-shiftdown-hook nil
  18407. "Hook for functions attaching themselves to `S-down'.
  18408. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18409. (defvar org-shiftdown-final-hook nil
  18410. "Hook for functions attaching themselves to `S-down'.
  18411. This one runs after all other options except shift-select have been excluded.
  18412. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18413. (defvar org-shiftleft-hook nil
  18414. "Hook for functions attaching themselves to `S-left'.
  18415. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18416. (defvar org-shiftleft-final-hook nil
  18417. "Hook for functions attaching themselves to `S-left'.
  18418. This one runs after all other options except shift-select have been excluded.
  18419. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18420. (defvar org-shiftright-hook nil
  18421. "Hook for functions attaching themselves to `S-right'.
  18422. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18423. (defvar org-shiftright-final-hook nil
  18424. "Hook for functions attaching themselves to `S-right'.
  18425. This one runs after all other options except shift-select have been excluded.
  18426. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18427. (defun org-modifier-cursor-error ()
  18428. "Throw an error, a modified cursor command was applied in wrong context."
  18429. (user-error "This command is active in special context like tables, headlines or items"))
  18430. (defun org-shiftselect-error ()
  18431. "Throw an error because Shift-Cursor command was applied in wrong context."
  18432. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18433. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18434. (user-error "This command works only in special context like headlines or timestamps")))
  18435. (defun org-call-for-shift-select (cmd)
  18436. (let ((this-command-keys-shift-translated t))
  18437. (call-interactively cmd)))
  18438. (defun org-shifttab (&optional arg)
  18439. "Global visibility cycling or move to previous table field.
  18440. Call `org-table-previous-field' within a table.
  18441. When ARG is nil, cycle globally through visibility states.
  18442. When ARG is a numeric prefix, show contents of this level."
  18443. (interactive "P")
  18444. (cond
  18445. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18446. ((integerp arg)
  18447. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18448. (message "Content view to level: %d" arg)
  18449. (org-content (prefix-numeric-value arg2))
  18450. (org-cycle-show-empty-lines t)
  18451. (setq org-cycle-global-status 'overview)))
  18452. (t (call-interactively 'org-global-cycle))))
  18453. (defun org-shiftmetaleft ()
  18454. "Promote subtree or delete table column.
  18455. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18456. `org-table-delete-column', depending on context. See the
  18457. individual commands for more information."
  18458. (interactive)
  18459. (cond
  18460. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18461. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18462. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18463. ((if (not (org-region-active-p)) (org-at-item-p)
  18464. (save-excursion (goto-char (region-beginning))
  18465. (org-at-item-p)))
  18466. (call-interactively 'org-outdent-item-tree))
  18467. (t (org-modifier-cursor-error))))
  18468. (defun org-shiftmetaright ()
  18469. "Demote subtree or insert table column.
  18470. Calls `org-demote-subtree', `org-indent-item-tree', or
  18471. `org-table-insert-column', depending on context. See the
  18472. individual commands for more information."
  18473. (interactive)
  18474. (cond
  18475. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18476. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18477. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18478. ((if (not (org-region-active-p)) (org-at-item-p)
  18479. (save-excursion (goto-char (region-beginning))
  18480. (org-at-item-p)))
  18481. (call-interactively 'org-indent-item-tree))
  18482. (t (org-modifier-cursor-error))))
  18483. (defun org-shiftmetaup (&optional _arg)
  18484. "Drag the line at point up.
  18485. In a table, kill the current row.
  18486. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18487. but also adjust the previous clocked item in the clock history.
  18488. Everywhere else, drag the line at point up."
  18489. (interactive "P")
  18490. (cond
  18491. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18492. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18493. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18494. (call-interactively 'org-timestamp-up)))
  18495. (t (call-interactively 'org-drag-line-backward))))
  18496. (defun org-shiftmetadown (&optional _arg)
  18497. "Drag the line at point down.
  18498. In a table, insert an empty row at the current line.
  18499. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18500. but also adjust the previous clocked item in the clock history.
  18501. Everywhere else, drag the line at point down."
  18502. (interactive "P")
  18503. (cond
  18504. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18505. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18506. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18507. (call-interactively 'org-timestamp-down)))
  18508. (t (call-interactively 'org-drag-line-forward))))
  18509. (defsubst org-hidden-tree-error ()
  18510. (user-error
  18511. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18512. (defun org-metaleft (&optional _arg)
  18513. "Promote heading, list item at point or move table column left.
  18514. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18515. depending on context. With no specific context, calls the Emacs
  18516. default `backward-word'. See the individual commands for more
  18517. information.
  18518. This function runs the hook `org-metaleft-hook' as a first step,
  18519. and returns at first non-nil value."
  18520. (interactive "P")
  18521. (cond
  18522. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18523. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18524. ((org-with-limited-levels
  18525. (or (org-at-heading-p)
  18526. (and (org-region-active-p)
  18527. (save-excursion
  18528. (goto-char (region-beginning))
  18529. (org-at-heading-p)))))
  18530. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18531. (call-interactively 'org-do-promote))
  18532. ;; At an inline task.
  18533. ((org-at-heading-p)
  18534. (call-interactively 'org-inlinetask-promote))
  18535. ((or (org-at-item-p)
  18536. (and (org-region-active-p)
  18537. (save-excursion
  18538. (goto-char (region-beginning))
  18539. (org-at-item-p))))
  18540. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18541. (call-interactively 'org-outdent-item))
  18542. (t (call-interactively 'backward-word))))
  18543. (defun org-metaright (&optional _arg)
  18544. "Demote heading, list item at point or move table column right.
  18545. In front of a drawer or a block keyword, indent it correctly.
  18546. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18547. `org-indent-drawer' or `org-indent-block' depending on context.
  18548. With no specific context, calls the Emacs default `forward-word'.
  18549. See the individual commands for more information.
  18550. This function runs the hook `org-metaright-hook' as a first step,
  18551. and returns at first non-nil value."
  18552. (interactive "P")
  18553. (cond
  18554. ((run-hook-with-args-until-success 'org-metaright-hook))
  18555. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18556. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18557. ((org-at-block-p) (call-interactively 'org-indent-block))
  18558. ((org-with-limited-levels
  18559. (or (org-at-heading-p)
  18560. (and (org-region-active-p)
  18561. (save-excursion
  18562. (goto-char (region-beginning))
  18563. (org-at-heading-p)))))
  18564. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18565. (call-interactively 'org-do-demote))
  18566. ;; At an inline task.
  18567. ((org-at-heading-p)
  18568. (call-interactively 'org-inlinetask-demote))
  18569. ((or (org-at-item-p)
  18570. (and (org-region-active-p)
  18571. (save-excursion
  18572. (goto-char (region-beginning))
  18573. (org-at-item-p))))
  18574. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18575. (call-interactively 'org-indent-item))
  18576. (t (call-interactively 'forward-word))))
  18577. (defun org-check-for-hidden (what)
  18578. "Check if there are hidden headlines/items in the current visual line.
  18579. WHAT can be either `headlines' or `items'. If the current line is
  18580. an outline or item heading and it has a folded subtree below it,
  18581. this function returns t, nil otherwise."
  18582. (let ((re (cond
  18583. ((eq what 'headlines) org-outline-regexp-bol)
  18584. ((eq what 'items) (org-item-beginning-re))
  18585. (t (error "This should not happen"))))
  18586. beg end)
  18587. (save-excursion
  18588. (catch 'exit
  18589. (unless (org-region-active-p)
  18590. (setq beg (point-at-bol))
  18591. (beginning-of-line 2)
  18592. (while (and (not (eobp)) ;; this is like `next-line'
  18593. (get-char-property (1- (point)) 'invisible))
  18594. (beginning-of-line 2))
  18595. (setq end (point))
  18596. (goto-char beg)
  18597. (goto-char (point-at-eol))
  18598. (setq end (max end (point)))
  18599. (while (re-search-forward re end t)
  18600. (when (get-char-property (match-beginning 0) 'invisible)
  18601. (throw 'exit t))))
  18602. nil))))
  18603. (defun org-metaup (&optional _arg)
  18604. "Move subtree up or move table row up.
  18605. Calls `org-move-subtree-up' or `org-table-move-row' or
  18606. `org-move-item-up', depending on context. See the individual commands
  18607. for more information."
  18608. (interactive "P")
  18609. (cond
  18610. ((run-hook-with-args-until-success 'org-metaup-hook))
  18611. ((org-region-active-p)
  18612. (let* ((a (min (region-beginning) (region-end)))
  18613. (b (1- (max (region-beginning) (region-end))))
  18614. (c (save-excursion (goto-char a)
  18615. (move-beginning-of-line 0)))
  18616. (d (save-excursion (goto-char a)
  18617. (move-end-of-line 0) (point))))
  18618. (transpose-regions a b c d)
  18619. (goto-char c)))
  18620. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18621. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18622. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18623. (t (org-drag-element-backward))))
  18624. (defun org-metadown (&optional _arg)
  18625. "Move subtree down or move table row down.
  18626. Calls `org-move-subtree-down' or `org-table-move-row' or
  18627. `org-move-item-down', depending on context. See the individual
  18628. commands for more information."
  18629. (interactive "P")
  18630. (cond
  18631. ((run-hook-with-args-until-success 'org-metadown-hook))
  18632. ((org-region-active-p)
  18633. (let* ((a (min (region-beginning) (region-end)))
  18634. (b (max (region-beginning) (region-end)))
  18635. (c (save-excursion (goto-char b)
  18636. (move-beginning-of-line 1)))
  18637. (d (save-excursion (goto-char b)
  18638. (move-end-of-line 1) (1+ (point)))))
  18639. (transpose-regions a b c d)
  18640. (goto-char d)))
  18641. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18642. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18643. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18644. (t (org-drag-element-forward))))
  18645. (defun org-shiftup (&optional arg)
  18646. "Increase item in timestamp or increase priority of current headline.
  18647. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18648. depending on context. See the individual commands for more information."
  18649. (interactive "P")
  18650. (cond
  18651. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18652. ((and org-support-shift-select (org-region-active-p))
  18653. (org-call-for-shift-select 'previous-line))
  18654. ((org-at-timestamp-p 'lax)
  18655. (call-interactively (if org-edit-timestamp-down-means-later
  18656. 'org-timestamp-down 'org-timestamp-up)))
  18657. ((and (not (eq org-support-shift-select 'always))
  18658. org-enable-priority-commands
  18659. (org-at-heading-p))
  18660. (call-interactively 'org-priority-up))
  18661. ((and (not org-support-shift-select) (org-at-item-p))
  18662. (call-interactively 'org-previous-item))
  18663. ((org-clocktable-try-shift 'up arg))
  18664. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18665. (org-support-shift-select
  18666. (org-call-for-shift-select 'previous-line))
  18667. (t (org-shiftselect-error))))
  18668. (defun org-shiftdown (&optional arg)
  18669. "Decrease item in timestamp or decrease priority of current headline.
  18670. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18671. depending on context. See the individual commands for more information."
  18672. (interactive "P")
  18673. (cond
  18674. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18675. ((and org-support-shift-select (org-region-active-p))
  18676. (org-call-for-shift-select 'next-line))
  18677. ((org-at-timestamp-p 'lax)
  18678. (call-interactively (if org-edit-timestamp-down-means-later
  18679. 'org-timestamp-up 'org-timestamp-down)))
  18680. ((and (not (eq org-support-shift-select 'always))
  18681. org-enable-priority-commands
  18682. (org-at-heading-p))
  18683. (call-interactively 'org-priority-down))
  18684. ((and (not org-support-shift-select) (org-at-item-p))
  18685. (call-interactively 'org-next-item))
  18686. ((org-clocktable-try-shift 'down arg))
  18687. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18688. (org-support-shift-select
  18689. (org-call-for-shift-select 'next-line))
  18690. (t (org-shiftselect-error))))
  18691. (defun org-shiftright (&optional arg)
  18692. "Cycle the thing at point or in the current line, depending on context.
  18693. Depending on context, this does one of the following:
  18694. - switch a timestamp at point one day into the future
  18695. - on a headline, switch to the next TODO keyword.
  18696. - on an item, switch entire list to the next bullet type
  18697. - on a property line, switch to the next allowed value
  18698. - on a clocktable definition line, move time block into the future"
  18699. (interactive "P")
  18700. (cond
  18701. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18702. ((and org-support-shift-select (org-region-active-p))
  18703. (org-call-for-shift-select 'forward-char))
  18704. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18705. ((and (not (eq org-support-shift-select 'always))
  18706. (org-at-heading-p))
  18707. (let ((org-inhibit-logging
  18708. (not org-treat-S-cursor-todo-selection-as-state-change))
  18709. (org-inhibit-blocking
  18710. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18711. (org-call-with-arg 'org-todo 'right)))
  18712. ((or (and org-support-shift-select
  18713. (not (eq org-support-shift-select 'always))
  18714. (org-at-item-bullet-p))
  18715. (and (not org-support-shift-select) (org-at-item-p)))
  18716. (org-call-with-arg 'org-cycle-list-bullet nil))
  18717. ((and (not (eq org-support-shift-select 'always))
  18718. (org-at-property-p))
  18719. (call-interactively 'org-property-next-allowed-value))
  18720. ((org-clocktable-try-shift 'right arg))
  18721. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18722. (org-support-shift-select
  18723. (org-call-for-shift-select 'forward-char))
  18724. (t (org-shiftselect-error))))
  18725. (defun org-shiftleft (&optional arg)
  18726. "Cycle the thing at point or in the current line, depending on context.
  18727. Depending on context, this does one of the following:
  18728. - switch a timestamp at point one day into the past
  18729. - on a headline, switch to the previous TODO keyword.
  18730. - on an item, switch entire list to the previous bullet type
  18731. - on a property line, switch to the previous allowed value
  18732. - on a clocktable definition line, move time block into the past"
  18733. (interactive "P")
  18734. (cond
  18735. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18736. ((and org-support-shift-select (org-region-active-p))
  18737. (org-call-for-shift-select 'backward-char))
  18738. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18739. ((and (not (eq org-support-shift-select 'always))
  18740. (org-at-heading-p))
  18741. (let ((org-inhibit-logging
  18742. (not org-treat-S-cursor-todo-selection-as-state-change))
  18743. (org-inhibit-blocking
  18744. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18745. (org-call-with-arg 'org-todo 'left)))
  18746. ((or (and org-support-shift-select
  18747. (not (eq org-support-shift-select 'always))
  18748. (org-at-item-bullet-p))
  18749. (and (not org-support-shift-select) (org-at-item-p)))
  18750. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18751. ((and (not (eq org-support-shift-select 'always))
  18752. (org-at-property-p))
  18753. (call-interactively 'org-property-previous-allowed-value))
  18754. ((org-clocktable-try-shift 'left arg))
  18755. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18756. (org-support-shift-select
  18757. (org-call-for-shift-select 'backward-char))
  18758. (t (org-shiftselect-error))))
  18759. (defun org-shiftcontrolright ()
  18760. "Switch to next TODO set."
  18761. (interactive)
  18762. (cond
  18763. ((and org-support-shift-select (org-region-active-p))
  18764. (org-call-for-shift-select 'forward-word))
  18765. ((and (not (eq org-support-shift-select 'always))
  18766. (org-at-heading-p))
  18767. (org-call-with-arg 'org-todo 'nextset))
  18768. (org-support-shift-select
  18769. (org-call-for-shift-select 'forward-word))
  18770. (t (org-shiftselect-error))))
  18771. (defun org-shiftcontrolleft ()
  18772. "Switch to previous TODO set."
  18773. (interactive)
  18774. (cond
  18775. ((and org-support-shift-select (org-region-active-p))
  18776. (org-call-for-shift-select 'backward-word))
  18777. ((and (not (eq org-support-shift-select 'always))
  18778. (org-at-heading-p))
  18779. (org-call-with-arg 'org-todo 'previousset))
  18780. (org-support-shift-select
  18781. (org-call-for-shift-select 'backward-word))
  18782. (t (org-shiftselect-error))))
  18783. (defun org-shiftcontrolup (&optional n)
  18784. "Change timestamps synchronously up in CLOCK log lines.
  18785. Optional argument N tells to change by that many units."
  18786. (interactive "P")
  18787. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18788. (let (org-support-shift-select)
  18789. (org-clock-timestamps-up n))
  18790. (user-error "Not at a clock log")))
  18791. (defun org-shiftcontroldown (&optional n)
  18792. "Change timestamps synchronously down in CLOCK log lines.
  18793. Optional argument N tells to change by that many units."
  18794. (interactive "P")
  18795. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18796. (let (org-support-shift-select)
  18797. (org-clock-timestamps-down n))
  18798. (user-error "Not at a clock log")))
  18799. (defun org-increase-number-at-point (&optional inc)
  18800. "Increment the number at point.
  18801. With an optional prefix numeric argument INC, increment using
  18802. this numeric value."
  18803. (interactive "p")
  18804. (if (not (number-at-point))
  18805. (user-error "Not on a number")
  18806. (unless inc (setq inc 1))
  18807. (let ((pos (point))
  18808. (beg (skip-chars-backward "-+^/*0-9eE."))
  18809. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18810. (setq nap (buffer-substring-no-properties
  18811. (+ pos beg) (+ pos beg end)))
  18812. (delete-region (+ pos beg) (+ pos beg end))
  18813. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18814. (when (org-at-table-p)
  18815. (org-table-align)
  18816. (org-table-end-of-field 1))))
  18817. (defun org-decrease-number-at-point (&optional inc)
  18818. "Decrement the number at point.
  18819. With an optional prefix numeric argument INC, decrement using
  18820. this numeric value."
  18821. (interactive "p")
  18822. (org-increase-number-at-point (- (or inc 1))))
  18823. (defun org-ctrl-c-ret ()
  18824. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18825. (interactive)
  18826. (cond
  18827. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18828. (t (call-interactively 'org-insert-heading))))
  18829. (defun org-find-visible ()
  18830. (let ((s (point)))
  18831. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18832. (get-char-property s 'invisible)))
  18833. s))
  18834. (defun org-find-invisible ()
  18835. (let ((s (point)))
  18836. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18837. (not (get-char-property s 'invisible))))
  18838. s))
  18839. (defun org-copy-visible (beg end)
  18840. "Copy the visible parts of the region."
  18841. (interactive "r")
  18842. (let ((result ""))
  18843. (while (/= beg end)
  18844. (when (get-char-property beg 'invisible)
  18845. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18846. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18847. (setq result (concat result (buffer-substring beg next)))
  18848. (setq beg next)))
  18849. (kill-new result)))
  18850. (defun org-copy-special ()
  18851. "Copy region in table or copy current subtree.
  18852. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18853. context. See the individual commands for more information."
  18854. (interactive)
  18855. (call-interactively
  18856. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18857. (defun org-cut-special ()
  18858. "Cut region in table or cut current subtree.
  18859. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18860. context. See the individual commands for more information."
  18861. (interactive)
  18862. (call-interactively
  18863. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18864. (defun org-paste-special (arg)
  18865. "Paste rectangular region into table, or past subtree relative to level.
  18866. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18867. See the individual commands for more information."
  18868. (interactive "P")
  18869. (if (org-at-table-p)
  18870. (org-table-paste-rectangle)
  18871. (org-paste-subtree arg)))
  18872. (defun org-edit-special (&optional arg)
  18873. "Call a special editor for the element at point.
  18874. When at a table, call the formula editor with `org-table-edit-formulas'.
  18875. When in a source code block, call `org-edit-src-code'.
  18876. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18877. When in an export block, call `org-edit-export-block'.
  18878. When in a LaTeX environment, call `org-edit-latex-environment'.
  18879. When at an #+INCLUDE keyword, visit the included file.
  18880. When at a footnote reference, call `org-edit-footnote-reference'
  18881. On a link, call `ffap' to visit the link at point.
  18882. Otherwise, return a user error."
  18883. (interactive "P")
  18884. (let ((element (org-element-at-point)))
  18885. (barf-if-buffer-read-only)
  18886. (pcase (org-element-type element)
  18887. (`src-block
  18888. (if (not arg) (org-edit-src-code)
  18889. (let* ((info (org-babel-get-src-block-info))
  18890. (lang (nth 0 info))
  18891. (params (nth 2 info))
  18892. (session (cdr (assq :session params))))
  18893. (if (not session) (org-edit-src-code)
  18894. ;; At a src-block with a session and function called with
  18895. ;; an ARG: switch to the buffer related to the inferior
  18896. ;; process.
  18897. (switch-to-buffer
  18898. (funcall (intern (concat "org-babel-prep-session:" lang))
  18899. session params))))))
  18900. (`keyword
  18901. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18902. (org-open-link-from-string
  18903. (format "[[%s]]"
  18904. (expand-file-name
  18905. (let ((value (org-element-property :value element)))
  18906. (cond ((org-file-url-p value)
  18907. (user-error "The file is specified as a URL, cannot be edited"))
  18908. ((not (org-string-nw-p value))
  18909. (user-error "No file to edit"))
  18910. ((string-match "\\`\"\\(.*?\\)\"" value)
  18911. (match-string 1 value))
  18912. ((string-match "\\`[^ \t\"]\\S-*" value)
  18913. (match-string 0 value))
  18914. (t (user-error "No valid file specified")))))))
  18915. (user-error "No special environment to edit here")))
  18916. (`table
  18917. (if (eq (org-element-property :type element) 'table.el)
  18918. (org-edit-table.el)
  18919. (call-interactively 'org-table-edit-formulas)))
  18920. ;; Only Org tables contain `table-row' type elements.
  18921. (`table-row (call-interactively 'org-table-edit-formulas))
  18922. (`example-block (org-edit-src-code))
  18923. (`export-block (org-edit-export-block))
  18924. (`fixed-width (org-edit-fixed-width-region))
  18925. (`latex-environment (org-edit-latex-environment))
  18926. (_
  18927. ;; No notable element at point. Though, we may be at a link or
  18928. ;; a footnote reference, which are objects. Thus, scan deeper.
  18929. (let ((context (org-element-context element)))
  18930. (pcase (org-element-type context)
  18931. (`footnote-reference (org-edit-footnote-reference))
  18932. (`inline-src-block (org-edit-inline-src-code))
  18933. (`link (call-interactively #'ffap))
  18934. (_ (user-error "No special environment to edit here"))))))))
  18935. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18936. (defun org-ctrl-c-ctrl-c (&optional arg)
  18937. "Set tags in headline, or update according to changed information at point.
  18938. This command does many different things, depending on context:
  18939. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18940. this is what we do.
  18941. - If the cursor is on a statistics cookie, update it.
  18942. - If the cursor is in a headline, prompt for tags and insert them
  18943. into the current line, aligned to `org-tags-column'. When called
  18944. with prefix arg, realign all tags in the current buffer.
  18945. - If the cursor is in one of the special #+KEYWORD lines, this
  18946. triggers scanning the buffer for these lines and updating the
  18947. information.
  18948. - If the cursor is inside a table, realign the table. This command
  18949. works even if the automatic table editor has been turned off.
  18950. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18951. the entire table.
  18952. - If the cursor is at a footnote reference or definition, jump to
  18953. the corresponding definition or references, respectively.
  18954. - If the cursor is a the beginning of a dynamic block, update it.
  18955. - If the current buffer is a capture buffer, close note and file it.
  18956. - If the cursor is on a <<<target>>>, update radio targets and
  18957. corresponding links in this buffer.
  18958. - If the cursor is on a numbered item in a plain list, renumber the
  18959. ordered list.
  18960. - If the cursor is on a checkbox, toggle it.
  18961. - If the cursor is on a code block, evaluate it. The variable
  18962. `org-confirm-babel-evaluate' can be used to control prompting
  18963. before code block evaluation, by default every code block
  18964. evaluation requires confirmation. Code block evaluation can be
  18965. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18966. (interactive "P")
  18967. (cond
  18968. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18969. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18970. (org-remove-occur-highlights)
  18971. (message "Temporary highlights/overlays removed from current buffer"))
  18972. ((and (local-variable-p 'org-finish-function)
  18973. (fboundp org-finish-function))
  18974. (funcall org-finish-function))
  18975. ((org-babel-hash-at-point))
  18976. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18977. (t
  18978. (let* ((context
  18979. (org-element-lineage
  18980. (org-element-context)
  18981. ;; Limit to supported contexts.
  18982. '(babel-call clock dynamic-block footnote-definition
  18983. footnote-reference inline-babel-call inline-src-block
  18984. inlinetask item keyword node-property paragraph
  18985. plain-list planning property-drawer radio-target
  18986. src-block statistics-cookie table table-cell table-row
  18987. timestamp)
  18988. t))
  18989. (type (org-element-type context)))
  18990. ;; For convenience: at the first line of a paragraph on the same
  18991. ;; line as an item, apply function on that item instead.
  18992. (when (eq type 'paragraph)
  18993. (let ((parent (org-element-property :parent context)))
  18994. (when (and (eq (org-element-type parent) 'item)
  18995. (= (line-beginning-position)
  18996. (org-element-property :begin parent)))
  18997. (setq context parent)
  18998. (setq type 'item))))
  18999. ;; Act according to type of element or object at point.
  19000. ;;
  19001. ;; Do nothing on a blank line, except if it is contained in
  19002. ;; a src block. Hence, we first check if point is in such
  19003. ;; a block and then if it is at a blank line.
  19004. (pcase type
  19005. ((or `inline-src-block `src-block)
  19006. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19007. (org-babel-eval-wipe-error-buffer)
  19008. (org-babel-execute-src-block
  19009. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19010. ((guard (org-match-line "[ \t]*$"))
  19011. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19012. (user-error
  19013. (substitute-command-keys
  19014. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19015. ((or `babel-call `inline-babel-call)
  19016. (let ((info (org-babel-lob-get-info context)))
  19017. (when info (org-babel-execute-src-block nil info))))
  19018. (`clock (org-clock-update-time-maybe))
  19019. (`dynamic-block
  19020. (save-excursion
  19021. (goto-char (org-element-property :post-affiliated context))
  19022. (org-update-dblock)))
  19023. (`footnote-definition
  19024. (goto-char (org-element-property :post-affiliated context))
  19025. (call-interactively 'org-footnote-action))
  19026. (`footnote-reference (call-interactively #'org-footnote-action))
  19027. ((or `headline `inlinetask)
  19028. (save-excursion (goto-char (org-element-property :begin context))
  19029. (call-interactively #'org-set-tags)))
  19030. (`item
  19031. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19032. ;; unconditionally, whereas `C-u' will toggle its presence.
  19033. ;; Without a universal argument, if the item has a checkbox,
  19034. ;; toggle it. Otherwise repair the list.
  19035. (let* ((box (org-element-property :checkbox context))
  19036. (struct (org-element-property :structure context))
  19037. (old-struct (copy-tree struct))
  19038. (parents (org-list-parents-alist struct))
  19039. (prevs (org-list-prevs-alist struct))
  19040. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19041. (org-list-set-checkbox
  19042. (org-element-property :begin context) struct
  19043. (cond ((equal arg '(16)) "[-]")
  19044. ((and (not box) (equal arg '(4))) "[ ]")
  19045. ((or (not box) (equal arg '(4))) nil)
  19046. ((eq box 'on) "[ ]")
  19047. (t "[X]")))
  19048. ;; Mimic `org-list-write-struct' but with grabbing a return
  19049. ;; value from `org-list-struct-fix-box'.
  19050. (org-list-struct-fix-ind struct parents 2)
  19051. (org-list-struct-fix-item-end struct)
  19052. (org-list-struct-fix-bul struct prevs)
  19053. (org-list-struct-fix-ind struct parents)
  19054. (let ((block-item
  19055. (org-list-struct-fix-box struct parents prevs orderedp)))
  19056. (if (and box (equal struct old-struct))
  19057. (if (equal arg '(16))
  19058. (message "Checkboxes already reset")
  19059. (user-error "Cannot toggle this checkbox: %s"
  19060. (if (eq box 'on)
  19061. "all subitems checked"
  19062. "unchecked subitems")))
  19063. (org-list-struct-apply-struct struct old-struct)
  19064. (org-update-checkbox-count-maybe))
  19065. (when block-item
  19066. (message "Checkboxes were removed due to empty box at line %d"
  19067. (org-current-line block-item))))))
  19068. (`keyword
  19069. (let ((org-inhibit-startup-visibility-stuff t)
  19070. (org-startup-align-all-tables nil))
  19071. (when (boundp 'org-table-coordinate-overlays)
  19072. (mapc #'delete-overlay org-table-coordinate-overlays)
  19073. (setq org-table-coordinate-overlays nil))
  19074. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19075. (message "Local setup has been refreshed"))
  19076. (`plain-list
  19077. ;; At a plain list, with a double C-u argument, set
  19078. ;; checkboxes of each item to "[-]", whereas a single one
  19079. ;; will toggle their presence according to the state of the
  19080. ;; first item in the list. Without an argument, repair the
  19081. ;; list.
  19082. (let* ((begin (org-element-property :contents-begin context))
  19083. (beginm (move-marker (make-marker) begin))
  19084. (struct (org-element-property :structure context))
  19085. (old-struct (copy-tree struct))
  19086. (first-box (save-excursion
  19087. (goto-char begin)
  19088. (looking-at org-list-full-item-re)
  19089. (match-string-no-properties 3)))
  19090. (new-box (cond ((equal arg '(16)) "[-]")
  19091. ((equal arg '(4)) (unless first-box "[ ]"))
  19092. ((equal first-box "[X]") "[ ]")
  19093. (t "[X]"))))
  19094. (cond
  19095. (arg
  19096. (dolist (pos
  19097. (org-list-get-all-items
  19098. begin struct (org-list-prevs-alist struct)))
  19099. (org-list-set-checkbox pos struct new-box)))
  19100. ((and first-box (eq (point) begin))
  19101. ;; For convenience, when point is at bol on the first
  19102. ;; item of the list and no argument is provided, simply
  19103. ;; toggle checkbox of that item, if any.
  19104. (org-list-set-checkbox begin struct new-box)))
  19105. (org-list-write-struct
  19106. struct (org-list-parents-alist struct) old-struct)
  19107. (org-update-checkbox-count-maybe)
  19108. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19109. ((or `property-drawer `node-property)
  19110. (call-interactively #'org-property-action))
  19111. (`radio-target
  19112. (call-interactively #'org-update-radio-target-regexp))
  19113. (`statistics-cookie
  19114. (call-interactively #'org-update-statistics-cookies))
  19115. ((or `table `table-cell `table-row)
  19116. ;; At a table, recalculate every field and align it. Also
  19117. ;; send the table if necessary. If the table has
  19118. ;; a `table.el' type, just give up. At a table row or cell,
  19119. ;; maybe recalculate line but always align table.
  19120. (if (eq (org-element-property :type context) 'table.el)
  19121. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19122. Use `\\[org-edit-special]' to edit table.el tables"))
  19123. (if (or (eq type 'table)
  19124. ;; Check if point is at a TBLFM line.
  19125. (and (eq type 'table-row)
  19126. (= (point) (org-element-property :end context))))
  19127. (save-excursion
  19128. (if (org-at-TBLFM-p)
  19129. (progn (require 'org-table)
  19130. (org-table-calc-current-TBLFM))
  19131. (goto-char (org-element-property :contents-begin context))
  19132. (org-call-with-arg 'org-table-recalculate (or arg t))
  19133. (orgtbl-send-table 'maybe)))
  19134. (org-table-maybe-eval-formula)
  19135. (cond (arg (call-interactively #'org-table-recalculate))
  19136. ((org-table-maybe-recalculate-line))
  19137. (t (org-table-align))))))
  19138. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  19139. (org-timestamp-change 0 'day))
  19140. ((and `nil (guard (org-at-heading-p)))
  19141. ;; When point is on an unsupported object type, we can miss
  19142. ;; the fact that it also is at a heading. Handle it here.
  19143. (call-interactively #'org-set-tags))
  19144. ((guard
  19145. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19146. (_
  19147. (user-error
  19148. (substitute-command-keys
  19149. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19150. (defun org-mode-restart ()
  19151. (interactive)
  19152. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19153. (funcall major-mode)
  19154. (hack-local-variables)
  19155. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19156. (org-indent-mode -1))
  19157. (org-reset-file-cache))
  19158. (message "%s restarted" major-mode))
  19159. (defun org-kill-note-or-show-branches ()
  19160. "Abort storing current note, or call `outline-show-branches'."
  19161. (interactive)
  19162. (if (not org-finish-function)
  19163. (progn
  19164. (outline-hide-subtree)
  19165. (call-interactively 'outline-show-branches))
  19166. (let ((org-note-abort t))
  19167. (funcall org-finish-function))))
  19168. (defun org-delete-indentation (&optional arg)
  19169. "Join current line to previous and fix whitespace at join.
  19170. If previous line is a headline add to headline title. Otherwise
  19171. the function calls `delete-indentation'.
  19172. With a non-nil optional argument, join it to the following one."
  19173. (interactive "*P")
  19174. (if (save-excursion
  19175. (beginning-of-line (if arg 1 0))
  19176. (let ((case-fold-search nil))
  19177. (looking-at org-complex-heading-regexp)))
  19178. ;; At headline.
  19179. (let ((tags-column (when (match-beginning 5)
  19180. (save-excursion (goto-char (match-beginning 5))
  19181. (current-column))))
  19182. (string (concat " " (progn (when arg (forward-line 1))
  19183. (org-trim (delete-and-extract-region
  19184. (line-beginning-position)
  19185. (line-end-position)))))))
  19186. (unless (bobp) (delete-region (point) (1- (point))))
  19187. (goto-char (or (match-end 4)
  19188. (match-beginning 5)
  19189. (match-end 0)))
  19190. (skip-chars-backward " \t")
  19191. (save-excursion (insert string))
  19192. ;; Adjust alignment of tags.
  19193. (cond
  19194. ((not tags-column)) ;no tags
  19195. (org-auto-align-tags (org-set-tags nil t))
  19196. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19197. (delete-indentation arg)))
  19198. (defun org-open-line (n)
  19199. "Insert a new row in tables, call `open-line' elsewhere.
  19200. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19201. As a special case, when a document starts with a table, allow to
  19202. call `open-line' on the very first character."
  19203. (interactive "*p")
  19204. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19205. (org-table-insert-row)
  19206. (open-line n)))
  19207. (defun org-return (&optional indent)
  19208. "Goto next table row or insert a newline.
  19209. Calls `org-table-next-row' or `newline', depending on context.
  19210. When optional INDENT argument is non-nil, call
  19211. `newline-and-indent' instead of `newline'.
  19212. When `org-return-follows-link' is non-nil and point is on
  19213. a timestamp or a link, call `org-open-at-point'. However, it
  19214. will not happen if point is in a table or on a \"dead\"
  19215. object (e.g., within a comment). In these case, you need to use
  19216. `org-open-at-point' directly."
  19217. (interactive)
  19218. (let ((context (if org-return-follows-link (org-element-context)
  19219. (org-element-at-point))))
  19220. (cond
  19221. ;; In a table, call `org-table-next-row'.
  19222. ((or (and (eq (org-element-type context) 'table)
  19223. (>= (point) (org-element-property :contents-begin context))
  19224. (< (point) (org-element-property :contents-end context)))
  19225. (org-element-lineage context '(table-row table-cell) t))
  19226. (org-table-justify-field-maybe)
  19227. (call-interactively #'org-table-next-row))
  19228. ;; On a link or a timestamp, call `org-open-at-point' if
  19229. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19230. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19231. ((and org-return-follows-link
  19232. (or (org-in-regexp org-ts-regexp-both nil t)
  19233. (org-in-regexp org-tsr-regexp-both nil t)
  19234. (org-in-regexp org-any-link-re nil t)))
  19235. (call-interactively #'org-open-at-point))
  19236. ;; Insert newline in heading, but preserve tags.
  19237. ((and (not (bolp))
  19238. (save-excursion (beginning-of-line)
  19239. (let ((case-fold-search nil))
  19240. (looking-at org-complex-heading-regexp))))
  19241. ;; At headline. Split line. However, if point is on keyword,
  19242. ;; priority cookie or tags, do not break any of them: add
  19243. ;; a newline after the headline instead.
  19244. (let ((tags-column (and (match-beginning 5)
  19245. (save-excursion (goto-char (match-beginning 5))
  19246. (current-column))))
  19247. (string
  19248. (when (and (match-end 4) (org-point-in-group (point) 4))
  19249. (delete-and-extract-region (point) (match-end 4)))))
  19250. ;; Adjust tag alignment.
  19251. (cond
  19252. ((not (and tags-column string)))
  19253. (org-auto-align-tags (org-set-tags nil t))
  19254. (t (org--align-tags-here tags-column))) ;preserve tags column
  19255. (end-of-line)
  19256. (org-show-entry)
  19257. (if indent (newline-and-indent) (newline))
  19258. (when string (save-excursion (insert (org-trim string))))))
  19259. ;; In a list, make sure indenting keeps trailing text within.
  19260. ((and indent
  19261. (not (eolp))
  19262. (org-element-lineage context '(item)))
  19263. (let ((trailing-data
  19264. (delete-and-extract-region (point) (line-end-position))))
  19265. (newline-and-indent)
  19266. (save-excursion (insert trailing-data))))
  19267. (t (if indent (newline-and-indent) (newline))))))
  19268. (defun org-return-indent ()
  19269. "Goto next table row or insert a newline and indent.
  19270. Calls `org-table-next-row' or `newline-and-indent', depending on
  19271. context. See the individual commands for more information."
  19272. (interactive)
  19273. (org-return t))
  19274. (defun org-ctrl-c-star ()
  19275. "Compute table, or change heading status of lines.
  19276. Calls `org-table-recalculate' or `org-toggle-heading',
  19277. depending on context."
  19278. (interactive)
  19279. (cond
  19280. ((org-at-table-p)
  19281. (call-interactively 'org-table-recalculate))
  19282. (t
  19283. ;; Convert all lines in region to list items
  19284. (call-interactively 'org-toggle-heading))))
  19285. (defun org-ctrl-c-minus ()
  19286. "Insert separator line in table or modify bullet status of line.
  19287. Also turns a plain line or a region of lines into list items.
  19288. Calls `org-table-insert-hline', `org-toggle-item', or
  19289. `org-cycle-list-bullet', depending on context."
  19290. (interactive)
  19291. (cond
  19292. ((org-at-table-p)
  19293. (call-interactively 'org-table-insert-hline))
  19294. ((org-region-active-p)
  19295. (call-interactively 'org-toggle-item))
  19296. ((org-in-item-p)
  19297. (call-interactively 'org-cycle-list-bullet))
  19298. (t
  19299. (call-interactively 'org-toggle-item))))
  19300. (defun org-toggle-heading (&optional nstars)
  19301. "Convert headings to normal text, or items or text to headings.
  19302. If there is no active region, only convert the current line.
  19303. With a `\\[universal-argument]' prefix, convert the whole list at
  19304. point into heading.
  19305. In a region:
  19306. - If the first non blank line is a headline, remove the stars
  19307. from all headlines in the region.
  19308. - If it is a normal line, turn each and every normal line (i.e.,
  19309. not an heading or an item) in the region into headings. If you
  19310. want to convert only the first line of this region, use one
  19311. universal prefix argument.
  19312. - If it is a plain list item, turn all plain list items into headings.
  19313. When converting a line into a heading, the number of stars is chosen
  19314. such that the lines become children of the current entry. However,
  19315. when a numeric prefix argument is given, its value determines the
  19316. number of stars to add."
  19317. (interactive "P")
  19318. (let ((skip-blanks
  19319. (function
  19320. ;; Return beginning of first non-blank line, starting from
  19321. ;; line at POS.
  19322. (lambda (pos)
  19323. (save-excursion
  19324. (goto-char pos)
  19325. (while (org-at-comment-p) (forward-line))
  19326. (skip-chars-forward " \r\t\n")
  19327. (point-at-bol)))))
  19328. beg end toggled)
  19329. ;; Determine boundaries of changes. If a universal prefix has
  19330. ;; been given, put the list in a region. If region ends at a bol,
  19331. ;; do not consider the last line to be in the region.
  19332. (when (and current-prefix-arg (org-at-item-p))
  19333. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19334. (org-mark-element))
  19335. (if (org-region-active-p)
  19336. (setq beg (funcall skip-blanks (region-beginning))
  19337. end (copy-marker (save-excursion
  19338. (goto-char (region-end))
  19339. (if (bolp) (point) (point-at-eol)))))
  19340. (setq beg (funcall skip-blanks (point-at-bol))
  19341. end (copy-marker (point-at-eol))))
  19342. ;; Ensure inline tasks don't count as headings.
  19343. (org-with-limited-levels
  19344. (save-excursion
  19345. (goto-char beg)
  19346. (cond
  19347. ;; Case 1. Started at an heading: de-star headings.
  19348. ((org-at-heading-p)
  19349. (while (< (point) end)
  19350. (when (org-at-heading-p t)
  19351. (looking-at org-outline-regexp) (replace-match "")
  19352. (setq toggled t))
  19353. (forward-line)))
  19354. ;; Case 2. Started at an item: change items into headlines.
  19355. ;; One star will be added by `org-list-to-subtree'.
  19356. ((org-at-item-p)
  19357. (while (< (point) end)
  19358. (when (org-at-item-p)
  19359. ;; Pay attention to cases when region ends before list.
  19360. (let* ((struct (org-list-struct))
  19361. (list-end
  19362. (min (org-list-get-bottom-point struct) (1+ end))))
  19363. (save-restriction
  19364. (narrow-to-region (point) list-end)
  19365. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19366. (setq toggled t))
  19367. (forward-line)))
  19368. ;; Case 3. Started at normal text: make every line an heading,
  19369. ;; skipping headlines and items.
  19370. (t (let* ((stars
  19371. (make-string
  19372. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19373. (add-stars
  19374. (cond (nstars "") ; stars from prefix only
  19375. ((equal stars "") "*") ; before first heading
  19376. (org-odd-levels-only "**") ; inside heading, odd
  19377. (t "*"))) ; inside heading, oddeven
  19378. (rpl (concat stars add-stars " "))
  19379. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19380. (while (< (point) (if (equal nstars '(4)) lend end))
  19381. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19382. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19383. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19384. (forward-line)))))))
  19385. (unless toggled (message "Cannot toggle heading from here"))))
  19386. (defun org-meta-return (&optional arg)
  19387. "Insert a new heading or wrap a region in a table.
  19388. Calls `org-insert-heading', `org-insert-item' or
  19389. `org-table-wrap-region', depending on context. When called with
  19390. an argument, unconditionally call `org-insert-heading'."
  19391. (interactive "P")
  19392. (org-check-before-invisible-edit 'insert)
  19393. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19394. (call-interactively (cond (arg #'org-insert-heading)
  19395. ((org-at-table-p) #'org-table-wrap-region)
  19396. ((org-in-item-p) #'org-insert-item)
  19397. (t #'org-insert-heading)))))
  19398. ;;; Menu entries
  19399. (defsubst org-in-subtree-not-table-p ()
  19400. "Are we in a subtree and not in a table?"
  19401. (and (not (org-before-first-heading-p))
  19402. (not (org-at-table-p))))
  19403. ;; Define the Org mode menus
  19404. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19405. '("Tbl"
  19406. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19407. ["Next Field" org-cycle (org-at-table-p)]
  19408. ["Previous Field" org-shifttab (org-at-table-p)]
  19409. ["Next Row" org-return (org-at-table-p)]
  19410. "--"
  19411. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19412. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19413. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19414. "--"
  19415. ("Column"
  19416. ["Move Column Left" org-metaleft (org-at-table-p)]
  19417. ["Move Column Right" org-metaright (org-at-table-p)]
  19418. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19419. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19420. ("Row"
  19421. ["Move Row Up" org-metaup (org-at-table-p)]
  19422. ["Move Row Down" org-metadown (org-at-table-p)]
  19423. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19424. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19425. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19426. "--"
  19427. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19428. ("Rectangle"
  19429. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19430. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19431. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19432. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19433. "--"
  19434. ("Calculate"
  19435. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19436. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19437. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19438. "--"
  19439. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19440. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19441. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19442. "--"
  19443. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19444. "--"
  19445. ["Sum Column/Rectangle" org-table-sum
  19446. (or (org-at-table-p) (org-region-active-p))]
  19447. ["Which Column?" org-table-current-column (org-at-table-p)])
  19448. ["Debug Formulas"
  19449. org-table-toggle-formula-debugger
  19450. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19451. ["Show Col/Row Numbers"
  19452. org-table-toggle-coordinate-overlays
  19453. :style toggle
  19454. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19455. "--"
  19456. ["Create" org-table-create (not (org-at-table-p))]
  19457. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19458. ["Import from File" org-table-import (not (org-at-table-p))]
  19459. ["Export to File" org-table-export (org-at-table-p)]
  19460. "--"
  19461. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19462. "--"
  19463. ("Plot"
  19464. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19465. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19466. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19467. '("Org"
  19468. ("Show/Hide"
  19469. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19470. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19471. ["Sparse Tree..." org-sparse-tree t]
  19472. ["Reveal Context" org-reveal t]
  19473. ["Show All" outline-show-all t]
  19474. "--"
  19475. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19476. "--"
  19477. ["New Heading" org-insert-heading t]
  19478. ("Navigate Headings"
  19479. ["Up" outline-up-heading t]
  19480. ["Next" outline-next-visible-heading t]
  19481. ["Previous" outline-previous-visible-heading t]
  19482. ["Next Same Level" outline-forward-same-level t]
  19483. ["Previous Same Level" outline-backward-same-level t]
  19484. "--"
  19485. ["Jump" org-goto t])
  19486. ("Edit Structure"
  19487. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19488. "--"
  19489. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19490. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19491. "--"
  19492. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19493. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19494. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19495. "--"
  19496. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19497. "--"
  19498. ["Copy visible text" org-copy-visible t]
  19499. "--"
  19500. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19501. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19502. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19503. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19504. "--"
  19505. ["Sort Region/Children" org-sort t]
  19506. "--"
  19507. ["Convert to odd levels" org-convert-to-odd-levels t]
  19508. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19509. ("Editing"
  19510. ["Emphasis..." org-emphasize t]
  19511. ["Edit Source Example" org-edit-special t]
  19512. "--"
  19513. ["Footnote new/jump" org-footnote-action t]
  19514. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19515. ("Archive"
  19516. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19517. "--"
  19518. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19519. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19520. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19521. )
  19522. "--"
  19523. ("Hyperlinks"
  19524. ["Store Link (Global)" org-store-link t]
  19525. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19526. ["Insert Link" org-insert-link t]
  19527. ["Follow Link" org-open-at-point t]
  19528. "--"
  19529. ["Next link" org-next-link t]
  19530. ["Previous link" org-previous-link t]
  19531. "--"
  19532. ["Descriptive Links"
  19533. org-toggle-link-display
  19534. :style radio
  19535. :selected org-descriptive-links
  19536. ]
  19537. ["Literal Links"
  19538. org-toggle-link-display
  19539. :style radio
  19540. :selected (not org-descriptive-links)])
  19541. "--"
  19542. ("TODO Lists"
  19543. ["TODO/DONE/-" org-todo t]
  19544. ("Select keyword"
  19545. ["Next keyword" org-shiftright (org-at-heading-p)]
  19546. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19547. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19548. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19549. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19550. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19551. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19552. "--"
  19553. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19554. :selected org-enforce-todo-dependencies :style toggle :active t]
  19555. "Settings for tree at point"
  19556. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19557. :selected (org-entry-get nil "ORDERED")
  19558. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19559. ["Do Children parallel" org-toggle-ordered-property :style radio
  19560. :selected (not (org-entry-get nil "ORDERED"))
  19561. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19562. "--"
  19563. ["Set Priority" org-priority t]
  19564. ["Priority Up" org-shiftup t]
  19565. ["Priority Down" org-shiftdown t]
  19566. "--"
  19567. ["Get news from all feeds" org-feed-update-all t]
  19568. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19569. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19570. ("TAGS and Properties"
  19571. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19572. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19573. "--"
  19574. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19575. ["Column view of properties" org-columns t]
  19576. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19577. ("Dates and Scheduling"
  19578. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19579. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19580. ("Change Date"
  19581. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19582. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19583. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19584. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19585. ["Compute Time Range" org-evaluate-time-range t]
  19586. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19587. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19588. "--"
  19589. ["Custom time format" org-toggle-time-stamp-overlays
  19590. :style radio :selected org-display-custom-times]
  19591. "--"
  19592. ["Goto Calendar" org-goto-calendar t]
  19593. ["Date from Calendar" org-date-from-calendar t]
  19594. "--"
  19595. ["Start/Restart Timer" org-timer-start t]
  19596. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19597. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19598. ["Insert Timer String" org-timer t]
  19599. ["Insert Timer Item" org-timer-item t])
  19600. ("Logging work"
  19601. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19602. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19603. ["Clock out" org-clock-out t]
  19604. ["Clock cancel" org-clock-cancel t]
  19605. "--"
  19606. ["Mark as default task" org-clock-mark-default-task t]
  19607. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19608. ["Goto running clock" org-clock-goto t]
  19609. "--"
  19610. ["Display times" org-clock-display t]
  19611. ["Create clock table" org-clock-report t]
  19612. "--"
  19613. ["Record DONE time"
  19614. (progn (setq org-log-done (not org-log-done))
  19615. (message "Switching to %s will %s record a timestamp"
  19616. (car org-done-keywords)
  19617. (if org-log-done "automatically" "not")))
  19618. :style toggle :selected org-log-done])
  19619. "--"
  19620. ["Agenda Command..." org-agenda t]
  19621. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19622. ("File List for Agenda")
  19623. ("Special views current file"
  19624. ["TODO Tree" org-show-todo-tree t]
  19625. ["Check Deadlines" org-check-deadlines t]
  19626. ["Tags/Property tree" org-match-sparse-tree t])
  19627. "--"
  19628. ["Export/Publish..." org-export-dispatch t]
  19629. ("LaTeX"
  19630. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19631. :selected org-cdlatex-mode]
  19632. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19633. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19634. ["Modify math symbol" org-cdlatex-math-modify
  19635. (org-inside-LaTeX-fragment-p)]
  19636. ["Insert citation" org-reftex-citation t])
  19637. "--"
  19638. ("MobileOrg"
  19639. ["Push Files and Views" org-mobile-push t]
  19640. ["Get Captured and Flagged" org-mobile-pull t]
  19641. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19642. "--"
  19643. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19644. "--"
  19645. ("Documentation"
  19646. ["Show Version" org-version t]
  19647. ["Info Documentation" org-info t])
  19648. ("Customize"
  19649. ["Browse Org Group" org-customize t]
  19650. "--"
  19651. ["Expand This Menu" org-create-customize-menu
  19652. (fboundp 'customize-menu-create)])
  19653. ["Send bug report" org-submit-bug-report t]
  19654. "--"
  19655. ("Refresh/Reload"
  19656. ["Refresh setup current buffer" org-mode-restart t]
  19657. ["Reload Org (after update)" org-reload t]
  19658. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19659. ))
  19660. (defun org-info (&optional node)
  19661. "Read documentation for Org in the info system.
  19662. With optional NODE, go directly to that node."
  19663. (interactive)
  19664. (info (format "(org)%s" (or node ""))))
  19665. ;;;###autoload
  19666. (defun org-submit-bug-report ()
  19667. "Submit a bug report on Org via mail.
  19668. Don't hesitate to report any problems or inaccurate documentation.
  19669. If you don't have setup sending mail from (X)Emacs, please copy the
  19670. output buffer into your mail program, as it gives us important
  19671. information about your Org version and configuration."
  19672. (interactive)
  19673. (require 'reporter)
  19674. (defvar reporter-prompt-for-summary-p)
  19675. (org-load-modules-maybe)
  19676. (org-require-autoloaded-modules)
  19677. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19678. (reporter-submit-bug-report
  19679. "emacs-orgmode@gnu.org"
  19680. (org-version nil 'full)
  19681. (let (list)
  19682. (save-window-excursion
  19683. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19684. (delete-other-windows)
  19685. (erase-buffer)
  19686. (insert "You are about to submit a bug report to the Org mailing list.
  19687. We would like to add your full Org and Outline configuration to the
  19688. bug report. This greatly simplifies the work of the maintainer and
  19689. other experts on the mailing list.
  19690. HOWEVER, some variables you have customized may contain private
  19691. information. The names of customers, colleagues, or friends, might
  19692. appear in the form of file names, tags, todo states, or search strings.
  19693. If you answer yes to the prompt, you might want to check and remove
  19694. such private information before sending the email.")
  19695. (add-text-properties (point-min) (point-max) '(face org-warning))
  19696. (when (yes-or-no-p "Include your Org configuration ")
  19697. (mapatoms
  19698. (lambda (v)
  19699. (and (boundp v)
  19700. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19701. (or (and (symbol-value v)
  19702. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19703. (and
  19704. (get v 'custom-type) (get v 'standard-value)
  19705. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19706. (push v list)))))
  19707. (kill-buffer (get-buffer "*Warn about privacy*"))
  19708. list))
  19709. nil nil
  19710. "Remember to cover the basics, that is, what you expected to happen and
  19711. what in fact did happen. You don't know how to make a good report? See
  19712. http://orgmode.org/manual/Feedback.html#Feedback
  19713. Your bug report will be posted to the Org mailing list.
  19714. ------------------------------------------------------------------------")
  19715. (save-excursion
  19716. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19717. (replace-match "\\1Bug: \\3 [\\2]")))))
  19718. (defun org-install-agenda-files-menu ()
  19719. (let ((bl (buffer-list)))
  19720. (save-excursion
  19721. (while bl
  19722. (set-buffer (pop bl))
  19723. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19724. (when (derived-mode-p 'org-mode)
  19725. (easy-menu-change
  19726. '("Org") "File List for Agenda"
  19727. (append
  19728. (list
  19729. ["Edit File List" (org-edit-agenda-file-list) t]
  19730. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19731. ["Remove Current File from List" org-remove-file t]
  19732. ["Cycle through agenda files" org-cycle-agenda-files t]
  19733. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19734. "--")
  19735. (mapcar 'org-file-menu-entry
  19736. ;; Prevent initialization from failing.
  19737. (ignore-errors (org-agenda-files t)))))))))
  19738. ;;;; Documentation
  19739. (defun org-require-autoloaded-modules ()
  19740. (interactive)
  19741. (mapc #'require
  19742. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19743. org-table org-timer)))
  19744. ;;;###autoload
  19745. (defun org-reload (&optional uncompiled)
  19746. "Reload all org lisp files.
  19747. With prefix arg UNCOMPILED, load the uncompiled versions."
  19748. (interactive "P")
  19749. (require 'loadhist)
  19750. (let* ((org-dir (org-find-library-dir "org"))
  19751. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19752. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19753. (remove-re (format "\\`%s\\'"
  19754. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19755. (feats (delete-dups
  19756. (mapcar 'file-name-sans-extension
  19757. (mapcar 'file-name-nondirectory
  19758. (delq nil
  19759. (mapcar 'feature-file
  19760. features))))))
  19761. (lfeat (append
  19762. (sort
  19763. (setq feats
  19764. (delq nil (mapcar
  19765. (lambda (f)
  19766. (if (and (string-match feature-re f)
  19767. (not (string-match remove-re f)))
  19768. f nil))
  19769. feats)))
  19770. 'string-lessp)
  19771. (list "org-version" "org")))
  19772. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19773. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19774. load-uncore load-misses)
  19775. (setq load-misses
  19776. (delq 't
  19777. (mapcar (lambda (f)
  19778. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19779. (and (string= org-dir contrib-dir)
  19780. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19781. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19782. (add-to-list 'load-uncore f 'append)
  19783. 't)
  19784. f))
  19785. lfeat)))
  19786. (when load-uncore
  19787. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19788. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19789. (if load-misses
  19790. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19791. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19792. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19793. ;;;###autoload
  19794. (defun org-customize ()
  19795. "Call the customize function with org as argument."
  19796. (interactive)
  19797. (org-load-modules-maybe)
  19798. (org-require-autoloaded-modules)
  19799. (customize-browse 'org))
  19800. (defun org-create-customize-menu ()
  19801. "Create a full customization menu for Org mode, insert it into the menu."
  19802. (interactive)
  19803. (org-load-modules-maybe)
  19804. (org-require-autoloaded-modules)
  19805. (if (fboundp 'customize-menu-create)
  19806. (progn
  19807. (easy-menu-change
  19808. '("Org") "Customize"
  19809. `(["Browse Org group" org-customize t]
  19810. "--"
  19811. ,(customize-menu-create 'org)
  19812. ["Set" Custom-set t]
  19813. ["Save" Custom-save t]
  19814. ["Reset to Current" Custom-reset-current t]
  19815. ["Reset to Saved" Custom-reset-saved t]
  19816. ["Reset to Standard Settings" Custom-reset-standard t]))
  19817. (message "\"Org\"-menu now contains full customization menu"))
  19818. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19819. ;;;; Miscellaneous stuff
  19820. ;;; Generally useful functions
  19821. (defun org-get-at-eol (property n)
  19822. "Get text property PROPERTY at the end of line less N characters."
  19823. (get-text-property (- (point-at-eol) n) property))
  19824. (defun org-find-text-property-in-string (prop s)
  19825. "Return the first non-nil value of property PROP in string S."
  19826. (or (get-text-property 0 prop s)
  19827. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19828. prop s)))
  19829. (defun org-display-warning (message)
  19830. "Display the given MESSAGE as a warning."
  19831. (display-warning 'org message :warning))
  19832. (defun org-eval (form)
  19833. "Eval FORM and return result."
  19834. (condition-case error
  19835. (eval form)
  19836. (error (format "%%![Error: %s]" error))))
  19837. (defun org-in-clocktable-p ()
  19838. "Check if the cursor is in a clocktable."
  19839. (let ((pos (point)) start)
  19840. (save-excursion
  19841. (end-of-line 1)
  19842. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19843. (setq start (match-beginning 0))
  19844. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19845. (>= (match-end 0) pos)
  19846. start))))
  19847. (defun org-in-verbatim-emphasis ()
  19848. (save-match-data
  19849. (and (org-in-regexp org-verbatim-re 2)
  19850. (>= (point) (match-beginning 3))
  19851. (<= (point) (match-end 4)))))
  19852. (defun org-overlay-display (ovl text &optional face evap)
  19853. "Make overlay OVL display TEXT with face FACE."
  19854. (overlay-put ovl 'display text)
  19855. (if face (overlay-put ovl 'face face))
  19856. (if evap (overlay-put ovl 'evaporate t)))
  19857. (defun org-overlay-before-string (ovl text &optional face evap)
  19858. "Make overlay OVL display TEXT with face FACE."
  19859. (if face (org-add-props text nil 'face face))
  19860. (overlay-put ovl 'before-string text)
  19861. (if evap (overlay-put ovl 'evaporate t)))
  19862. (defun org-find-overlays (prop &optional pos delete)
  19863. "Find all overlays specifying PROP at POS or point.
  19864. If DELETE is non-nil, delete all those overlays."
  19865. (let (found)
  19866. (dolist (ov (overlays-at (or pos (point))) found)
  19867. (cond ((not (overlay-get ov prop)))
  19868. (delete (delete-overlay ov))
  19869. (t (push ov found))))))
  19870. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19871. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19872. (if (and marker (marker-buffer marker)
  19873. (buffer-live-p (marker-buffer marker)))
  19874. (progn
  19875. (pop-to-buffer-same-window (marker-buffer marker))
  19876. (when (or (> marker (point-max)) (< marker (point-min)))
  19877. (widen))
  19878. (goto-char marker)
  19879. (org-show-context 'org-goto))
  19880. (if bookmark
  19881. (bookmark-jump bookmark)
  19882. (error "Cannot find location"))))
  19883. (defun org-quote-csv-field (s)
  19884. "Quote field for inclusion in CSV material."
  19885. (if (string-match "[\",]" s)
  19886. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19887. s))
  19888. (defun org-force-self-insert (N)
  19889. "Needed to enforce self-insert under remapping."
  19890. (interactive "p")
  19891. (self-insert-command N))
  19892. (defun org-shorten-string (s maxlength)
  19893. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19894. If the string is shorter or has length MAXLENGTH, just return the
  19895. original string. If it is longer, the functions finds a space in the
  19896. string, breaks this string off at that locations and adds three dots
  19897. as ellipsis. Including the ellipsis, the string will not be longer
  19898. than MAXLENGTH. If finding a good breaking point in the string does
  19899. not work, the string is just chopped off in the middle of a word
  19900. if necessary."
  19901. (if (<= (length s) maxlength)
  19902. s
  19903. (let* ((n (max (- maxlength 4) 1))
  19904. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19905. (if (string-match re s)
  19906. (concat (match-string 1 s) "...")
  19907. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19908. (defun org-get-indentation (&optional line)
  19909. "Get the indentation of the current line, interpreting tabs.
  19910. When LINE is given, assume it represents a line and compute its indentation."
  19911. (if line
  19912. (when (string-match "^ *" (org-remove-tabs line))
  19913. (match-end 0))
  19914. (save-excursion
  19915. (beginning-of-line 1)
  19916. (skip-chars-forward " \t")
  19917. (current-column))))
  19918. (defun org-get-string-indentation (s)
  19919. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19920. (let ((n -1) (i 0) (w tab-width) c)
  19921. (catch 'exit
  19922. (while (< (setq n (1+ n)) (length s))
  19923. (setq c (aref s n))
  19924. (cond ((= c ?\ ) (setq i (1+ i)))
  19925. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19926. (t (throw 'exit t)))))
  19927. i))
  19928. (defun org-remove-tabs (s &optional width)
  19929. "Replace tabulators in S with spaces.
  19930. Assumes that s is a single line, starting in column 0."
  19931. (setq width (or width tab-width))
  19932. (while (string-match "\t" s)
  19933. (setq s (replace-match
  19934. (make-string
  19935. (- (* width (/ (+ (match-beginning 0) width) width))
  19936. (match-beginning 0)) ?\ )
  19937. t t s)))
  19938. s)
  19939. (defun org-fix-indentation (line ind)
  19940. "Fix indentation in LINE.
  19941. IND is a cons cell with target and minimum indentation.
  19942. If the current indentation in LINE is smaller than the minimum,
  19943. leave it alone. If it is larger than ind, set it to the target."
  19944. (let* ((l (org-remove-tabs line))
  19945. (i (org-get-indentation l))
  19946. (i1 (car ind)) (i2 (cdr ind)))
  19947. (when (>= i i2) (setq l (substring line i2)))
  19948. (if (> i1 0)
  19949. (concat (make-string i1 ?\ ) l)
  19950. l)))
  19951. (defun org-remove-indentation (code &optional n)
  19952. "Remove maximum common indentation in string CODE and return it.
  19953. N may optionally be the number of columns to remove. Return CODE
  19954. as-is if removal failed."
  19955. (with-temp-buffer
  19956. (insert code)
  19957. (if (org-do-remove-indentation n) (buffer-string) code)))
  19958. (defun org-do-remove-indentation (&optional n)
  19959. "Remove the maximum common indentation from the buffer.
  19960. When optional argument N is a positive integer, remove exactly
  19961. that much characters from indentation, if possible. Return nil
  19962. if it fails."
  19963. (catch :exit
  19964. (goto-char (point-min))
  19965. ;; Find maximum common indentation, if not specified.
  19966. (let ((n (or n
  19967. (let ((min-ind (point-max)))
  19968. (save-excursion
  19969. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19970. (let ((ind (1- (current-column))))
  19971. (if (zerop ind) (throw :exit nil)
  19972. (setq min-ind (min min-ind ind))))))
  19973. min-ind))))
  19974. (if (zerop n) (throw :exit nil)
  19975. ;; Remove exactly N indentation, but give up if not possible.
  19976. (while (not (eobp))
  19977. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  19978. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  19979. ((< ind n) (throw :exit nil))
  19980. (t (indent-line-to (- ind n))))
  19981. (forward-line)))
  19982. ;; Signal success.
  19983. t))))
  19984. (defun org-fill-template (template alist)
  19985. "Find each %key of ALIST in TEMPLATE and replace it."
  19986. (let ((case-fold-search nil))
  19987. (dolist (entry (sort (copy-sequence alist)
  19988. (lambda (a b) (< (length (car a)) (length (car b))))))
  19989. (setq template
  19990. (replace-regexp-in-string
  19991. (concat "%" (regexp-quote (car entry)))
  19992. (or (cdr entry) "") template t t)))
  19993. template))
  19994. (defun org-base-buffer (buffer)
  19995. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  19996. (if (not buffer)
  19997. buffer
  19998. (or (buffer-base-buffer buffer)
  19999. buffer)))
  20000. (defun org-wrap (string &optional width lines)
  20001. "Wrap string to either a number of lines, or a width in characters.
  20002. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20003. that costs. If there is a word longer than WIDTH, the text is actually
  20004. wrapped to the length of that word.
  20005. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20006. many lines, whatever width that takes.
  20007. The return value is a list of lines, without newlines at the end."
  20008. (let* ((words (split-string string))
  20009. (maxword (apply 'max (mapcar 'org-string-width words)))
  20010. w ll)
  20011. (cond (width
  20012. (org-do-wrap words (max maxword width)))
  20013. (lines
  20014. (setq w maxword)
  20015. (setq ll (org-do-wrap words maxword))
  20016. (if (<= (length ll) lines)
  20017. ll
  20018. (setq ll words)
  20019. (while (> (length ll) lines)
  20020. (setq w (1+ w))
  20021. (setq ll (org-do-wrap words w)))
  20022. ll))
  20023. (t (error "Cannot wrap this")))))
  20024. (defun org-do-wrap (words width)
  20025. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20026. (let (lines line)
  20027. (while words
  20028. (setq line (pop words))
  20029. (while (and words (< (+ (length line) (length (car words))) width))
  20030. (setq line (concat line " " (pop words))))
  20031. (setq lines (push line lines)))
  20032. (nreverse lines)))
  20033. (defun org-quote-vert (s)
  20034. "Replace \"|\" with \"\\vert\"."
  20035. (while (string-match "|" s)
  20036. (setq s (replace-match "\\vert" t t s)))
  20037. s)
  20038. (defun org-uuidgen-p (s)
  20039. "Is S an ID created by UUIDGEN?"
  20040. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20041. (defun org-in-src-block-p (&optional inside)
  20042. "Whether point is in a code source block.
  20043. When INSIDE is non-nil, don't consider we are within a src block
  20044. when point is at #+BEGIN_SRC or #+END_SRC."
  20045. (let ((case-fold-search t))
  20046. (or (and (eq (get-char-property (point) 'src-block) t))
  20047. (and (not inside)
  20048. (save-match-data
  20049. (save-excursion
  20050. (beginning-of-line)
  20051. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20052. (defun org-context ()
  20053. "Return a list of contexts of the current cursor position.
  20054. If several contexts apply, all are returned.
  20055. Each context entry is a list with a symbol naming the context, and
  20056. two positions indicating start and end of the context. Possible
  20057. contexts are:
  20058. :headline anywhere in a headline
  20059. :headline-stars on the leading stars in a headline
  20060. :todo-keyword on a TODO keyword (including DONE) in a headline
  20061. :tags on the TAGS in a headline
  20062. :priority on the priority cookie in a headline
  20063. :item on the first line of a plain list item
  20064. :item-bullet on the bullet/number of a plain list item
  20065. :checkbox on the checkbox in a plain list item
  20066. :table in an Org table
  20067. :table-special on a special filed in a table
  20068. :table-table in a table.el table
  20069. :clocktable in a clocktable
  20070. :src-block in a source block
  20071. :link on a hyperlink
  20072. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20073. :target on a <<target>>
  20074. :radio-target on a <<<radio-target>>>
  20075. :latex-fragment on a LaTeX fragment
  20076. :latex-preview on a LaTeX fragment with overlaid preview image
  20077. This function expects the position to be visible because it uses font-lock
  20078. faces as a help to recognize the following contexts: :table-special, :link,
  20079. and :keyword."
  20080. (let* ((f (get-text-property (point) 'face))
  20081. (faces (if (listp f) f (list f)))
  20082. (case-fold-search t)
  20083. (p (point)) clist o)
  20084. ;; First the large context
  20085. (cond
  20086. ((org-at-heading-p t)
  20087. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20088. (when (progn
  20089. (beginning-of-line 1)
  20090. (looking-at org-todo-line-tags-regexp))
  20091. (push (org-point-in-group p 1 :headline-stars) clist)
  20092. (push (org-point-in-group p 2 :todo-keyword) clist)
  20093. (push (org-point-in-group p 4 :tags) clist))
  20094. (goto-char p)
  20095. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20096. (when (looking-at "\\[#[A-Z0-9]\\]")
  20097. (push (org-point-in-group p 0 :priority) clist)))
  20098. ((org-at-item-p)
  20099. (push (org-point-in-group p 2 :item-bullet) clist)
  20100. (push (list :item (point-at-bol)
  20101. (save-excursion (org-end-of-item) (point)))
  20102. clist)
  20103. (and (org-at-item-checkbox-p)
  20104. (push (org-point-in-group p 0 :checkbox) clist)))
  20105. ((org-at-table-p)
  20106. (push (list :table (org-table-begin) (org-table-end)) clist)
  20107. (when (memq 'org-formula faces)
  20108. (push (list :table-special
  20109. (previous-single-property-change p 'face)
  20110. (next-single-property-change p 'face)) clist)))
  20111. ((org-at-table-p 'any)
  20112. (push (list :table-table) clist)))
  20113. (goto-char p)
  20114. (let ((case-fold-search t))
  20115. ;; New the "medium" contexts: clocktables, source blocks
  20116. (cond ((org-in-clocktable-p)
  20117. (push (list :clocktable
  20118. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20119. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20120. (match-beginning 1))
  20121. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20122. (match-end 0))) clist))
  20123. ((org-in-src-block-p)
  20124. (push (list :src-block
  20125. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20126. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20127. (match-beginning 1))
  20128. (and (search-forward "#+END_SRC" nil t)
  20129. (match-beginning 0))) clist))))
  20130. (goto-char p)
  20131. ;; Now the small context
  20132. (cond
  20133. ((org-at-timestamp-p)
  20134. (push (org-point-in-group p 0 :timestamp) clist))
  20135. ((memq 'org-link faces)
  20136. (push (list :link
  20137. (previous-single-property-change p 'face)
  20138. (next-single-property-change p 'face)) clist))
  20139. ((memq 'org-special-keyword faces)
  20140. (push (list :keyword
  20141. (previous-single-property-change p 'face)
  20142. (next-single-property-change p 'face)) clist))
  20143. ((org-at-target-p)
  20144. (push (org-point-in-group p 0 :target) clist)
  20145. (goto-char (1- (match-beginning 0)))
  20146. (when (looking-at org-radio-target-regexp)
  20147. (push (org-point-in-group p 0 :radio-target) clist))
  20148. (goto-char p))
  20149. ((setq o (cl-some
  20150. (lambda (o)
  20151. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20152. o))
  20153. (overlays-at (point))))
  20154. (push (list :latex-fragment
  20155. (overlay-start o) (overlay-end o)) clist)
  20156. (push (list :latex-preview
  20157. (overlay-start o) (overlay-end o)) clist))
  20158. ((org-inside-LaTeX-fragment-p)
  20159. ;; FIXME: positions wrong.
  20160. (push (list :latex-fragment (point) (point)) clist)))
  20161. (setq clist (nreverse (delq nil clist)))
  20162. clist))
  20163. (defun org-in-regexp (regexp &optional nlines visually)
  20164. "Check if point is inside a match of REGEXP.
  20165. Normally only the current line is checked, but you can include
  20166. NLINES extra lines around point into the search. If VISUALLY is
  20167. set, require that the cursor is not after the match but really
  20168. on, so that the block visually is on the match.
  20169. Return nil or a cons cell (BEG . END) where BEG and END are,
  20170. respectively, the positions at the beginning and the end of the
  20171. match."
  20172. (catch :exit
  20173. (let ((pos (point))
  20174. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20175. (save-excursion
  20176. (beginning-of-line (- 1 (or nlines 0)))
  20177. (while (and (re-search-forward regexp eol t)
  20178. (<= (match-beginning 0) pos))
  20179. (let ((end (match-end 0)))
  20180. (when (or (> end pos) (and (= end pos) (not visually)))
  20181. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20182. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20183. "Non-nil when point is between matches of START-RE and END-RE.
  20184. Also return a non-nil value when point is on one of the matches.
  20185. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20186. buffer positions. Default values are the positions of headlines
  20187. surrounding the point.
  20188. The functions returns a cons cell whose car (resp. cdr) is the
  20189. position before START-RE (resp. after END-RE)."
  20190. (save-match-data
  20191. (let ((pos (point))
  20192. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20193. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20194. beg end)
  20195. (save-excursion
  20196. ;; Point is on a block when on START-RE or if START-RE can be
  20197. ;; found before it...
  20198. (and (or (org-in-regexp start-re)
  20199. (re-search-backward start-re limit-up t))
  20200. (setq beg (match-beginning 0))
  20201. ;; ... and END-RE after it...
  20202. (goto-char (match-end 0))
  20203. (re-search-forward end-re limit-down t)
  20204. (> (setq end (match-end 0)) pos)
  20205. ;; ... without another START-RE in-between.
  20206. (goto-char (match-beginning 0))
  20207. (not (re-search-backward start-re (1+ beg) t))
  20208. ;; Return value.
  20209. (cons beg end))))))
  20210. (defun org-in-block-p (names)
  20211. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20212. NAMES is a list of strings containing names of blocks.
  20213. Return first block name matched, or nil. Beware that in case of
  20214. nested blocks, the returned name may not belong to the closest
  20215. block from point."
  20216. (save-match-data
  20217. (catch 'exit
  20218. (let ((case-fold-search t)
  20219. (lim-up (save-excursion (outline-previous-heading)))
  20220. (lim-down (save-excursion (outline-next-heading))))
  20221. (dolist (name names)
  20222. (let ((n (regexp-quote name)))
  20223. (when (org-between-regexps-p
  20224. (concat "^[ \t]*#\\+begin_" n)
  20225. (concat "^[ \t]*#\\+end_" n)
  20226. lim-up lim-down)
  20227. (throw 'exit n)))))
  20228. nil)))
  20229. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20230. "Call `multi-occur' with buffers for all agenda files."
  20231. (interactive "sOrg-files matching: ")
  20232. (let* ((files (org-agenda-files))
  20233. (tnames (mapcar #'file-truename files))
  20234. (extra org-agenda-text-search-extra-files))
  20235. (when (eq (car extra) 'agenda-archives)
  20236. (setq extra (cdr extra))
  20237. (setq files (org-add-archive-files files)))
  20238. (dolist (f extra)
  20239. (unless (member (file-truename f) tnames)
  20240. (unless (member f files) (setq files (append files (list f))))
  20241. (setq tnames (append tnames (list (file-truename f))))))
  20242. (multi-occur
  20243. (mapcar (lambda (x)
  20244. (with-current-buffer
  20245. ;; FIXME: Why not just (find-file-noselect x)?
  20246. ;; Is it to avoid the "revert buffer" prompt?
  20247. (or (get-file-buffer x) (find-file-noselect x))
  20248. (widen)
  20249. (current-buffer)))
  20250. files)
  20251. regexp)))
  20252. (add-hook 'occur-mode-find-occurrence-hook
  20253. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20254. (defun org-occur-link-in-agenda-files ()
  20255. "Create a link and search for it in the agendas.
  20256. The link is not stored in `org-stored-links', it is just created
  20257. for the search purpose."
  20258. (interactive)
  20259. (let ((link (condition-case nil
  20260. (org-store-link nil)
  20261. (error "Unable to create a link to here"))))
  20262. (org-occur-in-agenda-files (regexp-quote link))))
  20263. (defun org-reverse-string (string)
  20264. "Return the reverse of STRING."
  20265. (apply 'string (reverse (string-to-list string))))
  20266. ;; defsubst org-uniquify must be defined before first use
  20267. (defun org-uniquify-alist (alist)
  20268. "Merge elements of ALIST with the same key.
  20269. For example, in this alist:
  20270. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20271. => \\='((a 1 3) (b 2))
  20272. merge (a 1) and (a 3) into (a 1 3).
  20273. The function returns the new ALIST."
  20274. (let (rtn)
  20275. (dolist (e alist rtn)
  20276. (let (n)
  20277. (if (not (assoc (car e) rtn))
  20278. (push e rtn)
  20279. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20280. (setq rtn (assq-delete-all (car e) rtn))
  20281. (push n rtn))))))
  20282. (defun org-delete-all (elts list)
  20283. "Remove all elements in ELTS from LIST.
  20284. Comparison is done with `equal'. It is a destructive operation
  20285. that may remove elements by altering the list structure."
  20286. (while elts
  20287. (setq list (delete (pop elts) list)))
  20288. list)
  20289. (defun org-back-over-empty-lines ()
  20290. "Move backwards over whitespace, to the beginning of the first empty line.
  20291. Returns the number of empty lines passed."
  20292. (let ((pos (point)))
  20293. (if (cdr (assq 'heading org-blank-before-new-entry))
  20294. (skip-chars-backward " \t\n\r")
  20295. (unless (eobp)
  20296. (forward-line -1)))
  20297. (beginning-of-line 2)
  20298. (goto-char (min (point) pos))
  20299. (count-lines (point) pos)))
  20300. (defun org-skip-whitespace ()
  20301. (skip-chars-forward " \t\n\r"))
  20302. (defun org-point-in-group (point group &optional context)
  20303. "Check if POINT is in match-group GROUP.
  20304. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20305. match. If the match group does not exist or point is not inside it,
  20306. return nil."
  20307. (and (match-beginning group)
  20308. (>= point (match-beginning group))
  20309. (<= point (match-end group))
  20310. (if context
  20311. (list context (match-beginning group) (match-end group))
  20312. t)))
  20313. (defun org-switch-to-buffer-other-window (&rest args)
  20314. "Switch to buffer in a second window on the current frame.
  20315. In particular, do not allow pop-up frames.
  20316. Returns the newly created buffer."
  20317. (org-no-popups
  20318. (apply 'switch-to-buffer-other-window args)))
  20319. (defun org-combine-plists (&rest plists)
  20320. "Create a single property list from all plists in PLISTS.
  20321. The process starts by copying the first list, and then setting properties
  20322. from the other lists. Settings in the last list are the most significant
  20323. ones and overrule settings in the other lists."
  20324. (let ((rtn (copy-sequence (pop plists)))
  20325. p v ls)
  20326. (while plists
  20327. (setq ls (pop plists))
  20328. (while ls
  20329. (setq p (pop ls) v (pop ls))
  20330. (setq rtn (plist-put rtn p v))))
  20331. rtn))
  20332. (defun org-replace-escapes (string table)
  20333. "Replace %-escapes in STRING with values in TABLE.
  20334. TABLE is an association list with keys like \"%a\" and string values.
  20335. The sequences in STRING may contain normal field width and padding information,
  20336. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20337. so values can contain further %-escapes if they are define later in TABLE."
  20338. (let ((tbl (copy-alist table))
  20339. (case-fold-search nil)
  20340. (pchg 0)
  20341. re rpl)
  20342. (dolist (e tbl)
  20343. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20344. (when (and (cdr e) (string-match re (cdr e)))
  20345. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20346. (safe "SREF"))
  20347. (add-text-properties 0 3 (list 'sref sref) safe)
  20348. (setcdr e (replace-match safe t t (cdr e)))))
  20349. (while (string-match re string)
  20350. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20351. (cdr e)))
  20352. (setq string (replace-match rpl t t string))))
  20353. (while (setq pchg (next-property-change pchg string))
  20354. (let ((sref (get-text-property pchg 'sref string)))
  20355. (when (and sref (string-match "SREF" string pchg))
  20356. (setq string (replace-match sref t t string)))))
  20357. string))
  20358. (defun org-find-base-buffer-visiting (file)
  20359. "Like `find-buffer-visiting' but always return the base buffer and
  20360. not an indirect buffer."
  20361. (let ((buf (or (get-file-buffer file)
  20362. (find-buffer-visiting file))))
  20363. (if buf
  20364. (or (buffer-base-buffer buf) buf)
  20365. nil)))
  20366. ;;; TODO: Only called once, from ox-odt which should probably use
  20367. ;;; org-export-inline-image-p or something.
  20368. (defun org-file-image-p (file)
  20369. "Return non-nil if FILE is an image."
  20370. (save-match-data
  20371. (string-match (image-file-name-regexp) file)))
  20372. (defun org-get-cursor-date (&optional with-time)
  20373. "Return the date at cursor in as a time.
  20374. This works in the calendar and in the agenda, anywhere else it just
  20375. returns the current time.
  20376. If WITH-TIME is non-nil, returns the time of the event at point (in
  20377. the agenda) or the current time of the day."
  20378. (let (date day defd tp hod mod)
  20379. (when with-time
  20380. (setq tp (get-text-property (point) 'time))
  20381. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20382. (setq hod (string-to-number (match-string 1 tp))
  20383. mod (string-to-number (match-string 2 tp))))
  20384. (or tp (let ((now (decode-time)))
  20385. (setq hod (nth 2 now)
  20386. mod (nth 1 now)))))
  20387. (cond
  20388. ((eq major-mode 'calendar-mode)
  20389. (setq date (calendar-cursor-to-date)
  20390. defd (encode-time 0 (or mod 0) (or hod 0)
  20391. (nth 1 date) (nth 0 date) (nth 2 date))))
  20392. ((eq major-mode 'org-agenda-mode)
  20393. (setq day (get-text-property (point) 'day))
  20394. (when day
  20395. (setq date (calendar-gregorian-from-absolute day)
  20396. defd (encode-time 0 (or mod 0) (or hod 0)
  20397. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20398. (or defd (current-time))))
  20399. (defun org-mark-subtree (&optional up)
  20400. "Mark the current subtree.
  20401. This puts point at the start of the current subtree, and mark at
  20402. the end. If a numeric prefix UP is given, move up into the
  20403. hierarchy of headlines by UP levels before marking the subtree."
  20404. (interactive "P")
  20405. (org-with-limited-levels
  20406. (cond ((org-at-heading-p) (beginning-of-line))
  20407. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20408. (t (outline-previous-visible-heading 1))))
  20409. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20410. (if (called-interactively-p 'any)
  20411. (call-interactively 'org-mark-element)
  20412. (org-mark-element)))
  20413. (defun org-file-newer-than-p (file time)
  20414. "Non-nil if FILE is newer than TIME.
  20415. FILE is a filename, as a string, TIME is a list of integers, as
  20416. returned by, e.g., `current-time'."
  20417. (and (file-exists-p file)
  20418. ;; Only compare times up to whole seconds as some file-systems
  20419. ;; (e.g. HFS+) do not retain any finer granularity. As
  20420. ;; a consequence, make sure we return non-nil when the two
  20421. ;; times are equal.
  20422. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20423. (cl-subseq time 0 2)))))
  20424. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20425. "Compile a SOURCE file using PROCESS.
  20426. PROCESS is either a function or a list of shell commands, as
  20427. strings. EXT is a file extension, without the leading dot, as
  20428. a string. It is used to check if the process actually succeeded.
  20429. PROCESS must create a file with the same base name and directory
  20430. as SOURCE, but ending with EXT. The function then returns its
  20431. filename. Otherwise, it raises an error. The error message can
  20432. then be refined by providing string ERR-MSG, which is appended to
  20433. the standard message.
  20434. If PROCESS is a function, it is called with a single argument:
  20435. the SOURCE file.
  20436. If it is a list of commands, each of them is called using
  20437. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20438. %O are replaced with, respectively, SOURCE base name, name, full
  20439. name, directory and absolute output file name. It is possible,
  20440. however, to use more place-holders by specifying them in optional
  20441. argument SPEC, as an alist following the pattern
  20442. (CHARACTER . REPLACEMENT-STRING).
  20443. When PROCESS is a list of commands, optional argument LOG-BUF can
  20444. be set to a buffer or a buffer name. `shell-command' then uses
  20445. it for output."
  20446. (let* ((base-name (file-name-base source))
  20447. (full-name (file-truename source))
  20448. (out-dir (or (file-name-directory source) "./"))
  20449. (output (expand-file-name (concat base-name "." ext) out-dir))
  20450. (time (current-time))
  20451. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20452. (save-window-excursion
  20453. (pcase process
  20454. ((pred functionp) (funcall process (shell-quote-argument source)))
  20455. ((pred consp)
  20456. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20457. (spec (append spec
  20458. `((?b . ,(shell-quote-argument base-name))
  20459. (?f . ,(shell-quote-argument source))
  20460. (?F . ,(shell-quote-argument full-name))
  20461. (?o . ,(shell-quote-argument out-dir))
  20462. (?O . ,(shell-quote-argument output))))))
  20463. (dolist (command process)
  20464. (shell-command (format-spec command spec) log-buf))
  20465. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20466. (_ (error "No valid command to process %S%s" source err-msg))))
  20467. ;; Check for process failure. Output file is expected to be
  20468. ;; located in the same directory as SOURCE.
  20469. (unless (org-file-newer-than-p output time)
  20470. (error (format "File %S wasn't produced%s" output err-msg)))
  20471. output))
  20472. ;;; Indentation
  20473. (defvar org-element-greater-elements)
  20474. (defun org--get-expected-indentation (element contentsp)
  20475. "Expected indentation column for current line, according to ELEMENT.
  20476. ELEMENT is an element containing point. CONTENTSP is non-nil
  20477. when indentation is to be computed according to contents of
  20478. ELEMENT."
  20479. (let ((type (org-element-type element))
  20480. (start (org-element-property :begin element))
  20481. (post-affiliated (org-element-property :post-affiliated element)))
  20482. (org-with-wide-buffer
  20483. (cond
  20484. (contentsp
  20485. (cl-case type
  20486. ((diary-sexp footnote-definition) 0)
  20487. ((headline inlinetask nil)
  20488. (if (not org-adapt-indentation) 0
  20489. (let ((level (org-current-level)))
  20490. (if level (1+ level) 0))))
  20491. ((item plain-list) (org-list-item-body-column post-affiliated))
  20492. (t
  20493. (goto-char start)
  20494. (org-get-indentation))))
  20495. ((memq type '(headline inlinetask nil))
  20496. (if (org-match-line "[ \t]*$")
  20497. (org--get-expected-indentation element t)
  20498. 0))
  20499. ((memq type '(diary-sexp footnote-definition)) 0)
  20500. ;; First paragraph of a footnote definition or an item.
  20501. ;; Indent like parent.
  20502. ((< (line-beginning-position) start)
  20503. (org--get-expected-indentation
  20504. (org-element-property :parent element) t))
  20505. ;; At first line: indent according to previous sibling, if any,
  20506. ;; ignoring footnote definitions and inline tasks, or parent's
  20507. ;; contents.
  20508. ((= (line-beginning-position) start)
  20509. (catch 'exit
  20510. (while t
  20511. (if (= (point-min) start) (throw 'exit 0)
  20512. (goto-char (1- start))
  20513. (let* ((previous (org-element-at-point))
  20514. (parent previous))
  20515. (while (and parent (<= (org-element-property :end parent) start))
  20516. (setq previous parent
  20517. parent (org-element-property :parent parent)))
  20518. (cond
  20519. ((not previous) (throw 'exit 0))
  20520. ((> (org-element-property :end previous) start)
  20521. (throw 'exit (org--get-expected-indentation previous t)))
  20522. ((memq (org-element-type previous)
  20523. '(footnote-definition inlinetask))
  20524. (setq start (org-element-property :begin previous)))
  20525. (t (goto-char (org-element-property :begin previous))
  20526. (throw 'exit
  20527. (if (bolp) (org-get-indentation)
  20528. ;; At first paragraph in an item or
  20529. ;; a footnote definition.
  20530. (org--get-expected-indentation
  20531. (org-element-property :parent previous) t))))))))))
  20532. ;; Otherwise, move to the first non-blank line above.
  20533. (t
  20534. (beginning-of-line)
  20535. (let ((pos (point)))
  20536. (skip-chars-backward " \r\t\n")
  20537. (cond
  20538. ;; Two blank lines end a footnote definition or a plain
  20539. ;; list. When we indent an empty line after them, the
  20540. ;; containing list or footnote definition is over, so it
  20541. ;; qualifies as a previous sibling. Therefore, we indent
  20542. ;; like its first line.
  20543. ((and (memq type '(footnote-definition plain-list))
  20544. (> (count-lines (point) pos) 2))
  20545. (goto-char start)
  20546. (org-get-indentation))
  20547. ;; Line above is the first one of a paragraph at the
  20548. ;; beginning of an item or a footnote definition. Indent
  20549. ;; like parent.
  20550. ((< (line-beginning-position) start)
  20551. (org--get-expected-indentation
  20552. (org-element-property :parent element) t))
  20553. ;; Line above is the beginning of an element, i.e., point
  20554. ;; was originally on the blank lines between element's start
  20555. ;; and contents.
  20556. ((= (line-beginning-position) post-affiliated)
  20557. (org--get-expected-indentation element t))
  20558. ;; POS is after contents in a greater element. Indent like
  20559. ;; the beginning of the element.
  20560. ((and (memq type org-element-greater-elements)
  20561. (let ((cend (org-element-property :contents-end element)))
  20562. (and cend (<= cend pos))))
  20563. ;; As a special case, if point is at the end of a footnote
  20564. ;; definition or an item, indent like the very last element
  20565. ;; within. If that last element is an item, indent like
  20566. ;; its contents.
  20567. (if (memq type '(footnote-definition item plain-list))
  20568. (let ((last (org-element-at-point)))
  20569. (goto-char pos)
  20570. (org--get-expected-indentation
  20571. last (eq (org-element-type last) 'item)))
  20572. (goto-char start)
  20573. (org-get-indentation)))
  20574. ;; In any other case, indent like the current line.
  20575. (t (org-get-indentation)))))))))
  20576. (defun org--align-node-property ()
  20577. "Align node property at point.
  20578. Alignment is done according to `org-property-format', which see."
  20579. (when (save-excursion
  20580. (beginning-of-line)
  20581. (looking-at org-property-re))
  20582. (replace-match
  20583. (concat (match-string 4)
  20584. (org-trim
  20585. (format org-property-format (match-string 1) (match-string 3))))
  20586. t t)))
  20587. (defun org-indent-line ()
  20588. "Indent line depending on context.
  20589. Indentation is done according to the following rules:
  20590. - Footnote definitions, diary sexps, headlines and inline tasks
  20591. have to start at column 0.
  20592. - On the very first line of an element, consider, in order, the
  20593. next rules until one matches:
  20594. 1. If there's a sibling element before, ignoring footnote
  20595. definitions and inline tasks, indent like its first line.
  20596. 2. If element has a parent, indent like its contents. More
  20597. precisely, if parent is an item, indent after the
  20598. description part, if any, or the bullet (see
  20599. `org-list-description-max-indent'). Else, indent like
  20600. parent's first line.
  20601. 3. Otherwise, indent relatively to current level, if
  20602. `org-adapt-indentation' is non-nil, or to left margin.
  20603. - On a blank line at the end of an element, indent according to
  20604. the type of the element. More precisely
  20605. 1. If element is a plain list, an item, or a footnote
  20606. definition, indent like the very last element within.
  20607. 2. If element is a paragraph, indent like its last non blank
  20608. line.
  20609. 3. Otherwise, indent like its very first line.
  20610. - In the code part of a source block, use language major mode
  20611. to indent current line if `org-src-tab-acts-natively' is
  20612. non-nil. If it is nil, do nothing.
  20613. - Otherwise, indent like the first non-blank line above.
  20614. The function doesn't indent an item as it could break the whole
  20615. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20616. `\\[org-shiftmetaright]'.
  20617. Also align node properties according to `org-property-format'."
  20618. (interactive)
  20619. (cond
  20620. (orgstruct-is-++
  20621. (let ((indent-line-function
  20622. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20623. (indent-according-to-mode)))
  20624. ((org-at-heading-p) 'noindent)
  20625. (t
  20626. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20627. (type (org-element-type element)))
  20628. (cond ((and (memq type '(plain-list item))
  20629. (= (line-beginning-position)
  20630. (org-element-property :post-affiliated element)))
  20631. 'noindent)
  20632. ((and (eq type 'latex-environment)
  20633. (>= (point) (org-element-property :post-affiliated element))
  20634. (< (point) (org-with-wide-buffer
  20635. (goto-char (org-element-property :end element))
  20636. (skip-chars-backward " \r\t\n")
  20637. (line-beginning-position 2))))
  20638. 'noindent)
  20639. ((and (eq type 'src-block)
  20640. org-src-tab-acts-natively
  20641. (> (line-beginning-position)
  20642. (org-element-property :post-affiliated element))
  20643. (< (line-beginning-position)
  20644. (org-with-wide-buffer
  20645. (goto-char (org-element-property :end element))
  20646. (skip-chars-backward " \r\t\n")
  20647. (line-beginning-position))))
  20648. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20649. (t
  20650. (let ((column (org--get-expected-indentation element nil)))
  20651. ;; Preserve current column.
  20652. (if (<= (current-column) (current-indentation))
  20653. (indent-line-to column)
  20654. (save-excursion (indent-line-to column))))
  20655. ;; Align node property. Also preserve current column.
  20656. (when (eq type 'node-property)
  20657. (let ((column (current-column)))
  20658. (org--align-node-property)
  20659. (org-move-to-column column)))))))))
  20660. (defun org-indent-region (start end)
  20661. "Indent each non-blank line in the region.
  20662. Called from a program, START and END specify the region to
  20663. indent. The function will not indent contents of example blocks,
  20664. verse blocks and export blocks as leading white spaces are
  20665. assumed to be significant there."
  20666. (interactive "r")
  20667. (save-excursion
  20668. (goto-char start)
  20669. (skip-chars-forward " \r\t\n")
  20670. (unless (eobp) (beginning-of-line))
  20671. (let ((indent-to
  20672. (lambda (ind pos)
  20673. ;; Set IND as indentation for all lines between point and
  20674. ;; POS. Blank lines are ignored. Leave point after POS
  20675. ;; once done.
  20676. (let ((limit (copy-marker pos)))
  20677. (while (< (point) limit)
  20678. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20679. (forward-line))
  20680. (set-marker limit nil))))
  20681. (end (copy-marker end)))
  20682. (while (< (point) end)
  20683. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20684. (let* ((element (org-element-at-point))
  20685. (type (org-element-type element))
  20686. (element-end (copy-marker (org-element-property :end element)))
  20687. (ind (org--get-expected-indentation element nil)))
  20688. (cond
  20689. ;; Element indented as a single block. Example blocks
  20690. ;; preserving indentation are a special case since the
  20691. ;; "contents" must not be indented whereas the block
  20692. ;; boundaries can.
  20693. ((or (memq type '(export-block latex-environment))
  20694. (and (eq type 'example-block)
  20695. (not
  20696. (or org-src-preserve-indentation
  20697. (org-element-property :preserve-indent element)))))
  20698. (let ((offset (- ind (org-get-indentation))))
  20699. (unless (zerop offset)
  20700. (indent-rigidly (org-element-property :begin element)
  20701. (org-element-property :end element)
  20702. offset)))
  20703. (goto-char element-end))
  20704. ;; Elements indented line wise. Be sure to exclude
  20705. ;; example blocks (preserving indentation) and source
  20706. ;; blocks from this category as they are treated
  20707. ;; specially later.
  20708. ((or (memq type '(paragraph table table-row))
  20709. (not (or (org-element-property :contents-begin element)
  20710. (memq type '(example-block src-block)))))
  20711. (when (eq type 'node-property)
  20712. (org--align-node-property)
  20713. (beginning-of-line))
  20714. (funcall indent-to ind (min element-end end)))
  20715. ;; Elements consisting of three parts: before the
  20716. ;; contents, the contents, and after the contents. The
  20717. ;; contents are treated specially, according to the
  20718. ;; element type, or not indented at all. Other parts are
  20719. ;; indented as a single block.
  20720. (t
  20721. (let* ((post (copy-marker
  20722. (org-element-property :post-affiliated element)))
  20723. (cbeg
  20724. (copy-marker
  20725. (cond
  20726. ((not (org-element-property :contents-begin element))
  20727. ;; Fake contents for source blocks.
  20728. (org-with-wide-buffer
  20729. (goto-char post)
  20730. (line-beginning-position 2)))
  20731. ((memq type '(footnote-definition item plain-list))
  20732. ;; Contents in these elements could start on
  20733. ;; the same line as the beginning of the
  20734. ;; element. Make sure we start indenting
  20735. ;; from the second line.
  20736. (org-with-wide-buffer
  20737. (goto-char post)
  20738. (end-of-line)
  20739. (skip-chars-forward " \r\t\n")
  20740. (if (eobp) (point) (line-beginning-position))))
  20741. (t (org-element-property :contents-begin element)))))
  20742. (cend (copy-marker
  20743. (or (org-element-property :contents-end element)
  20744. ;; Fake contents for source blocks.
  20745. (org-with-wide-buffer
  20746. (goto-char element-end)
  20747. (skip-chars-backward " \r\t\n")
  20748. (line-beginning-position)))
  20749. t)))
  20750. ;; Do not change items indentation individually as it
  20751. ;; might break the list as a whole. On the other
  20752. ;; hand, when at a plain list, indent it as a whole.
  20753. (cond ((eq type 'plain-list)
  20754. (let ((offset (- ind (org-get-indentation))))
  20755. (unless (zerop offset)
  20756. (indent-rigidly (org-element-property :begin element)
  20757. (org-element-property :end element)
  20758. offset))
  20759. (goto-char cbeg)))
  20760. ((eq type 'item) (goto-char cbeg))
  20761. (t (funcall indent-to ind (min cbeg end))))
  20762. (when (< (point) end)
  20763. (cl-case type
  20764. ((example-block verse-block))
  20765. (src-block
  20766. ;; In a source block, indent source code
  20767. ;; according to language major mode, but only if
  20768. ;; `org-src-tab-acts-natively' is non-nil.
  20769. (when (and (< (point) end) org-src-tab-acts-natively)
  20770. (ignore-errors
  20771. (org-babel-do-in-edit-buffer
  20772. (indent-region (point-min) (point-max))))))
  20773. (t (org-indent-region (point) (min cend end))))
  20774. (goto-char (min cend end))
  20775. (when (< (point) end)
  20776. (funcall indent-to ind (min element-end end))))
  20777. (set-marker post nil)
  20778. (set-marker cbeg nil)
  20779. (set-marker cend nil))))
  20780. (set-marker element-end nil))))
  20781. (set-marker end nil))))
  20782. (defun org-indent-drawer ()
  20783. "Indent the drawer at point."
  20784. (interactive)
  20785. (unless (save-excursion
  20786. (beginning-of-line)
  20787. (looking-at-p org-drawer-regexp))
  20788. (user-error "Not at a drawer"))
  20789. (let ((element (org-element-at-point)))
  20790. (unless (memq (org-element-type element) '(drawer property-drawer))
  20791. (user-error "Not at a drawer"))
  20792. (org-with-wide-buffer
  20793. (org-indent-region (org-element-property :begin element)
  20794. (org-element-property :end element))))
  20795. (message "Drawer at point indented"))
  20796. (defun org-indent-block ()
  20797. "Indent the block at point."
  20798. (interactive)
  20799. (unless (save-excursion
  20800. (beginning-of-line)
  20801. (let ((case-fold-search t))
  20802. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20803. (user-error "Not at a block"))
  20804. (let ((element (org-element-at-point)))
  20805. (unless (memq (org-element-type element)
  20806. '(comment-block center-block dynamic-block example-block
  20807. export-block quote-block special-block
  20808. src-block verse-block))
  20809. (user-error "Not at a block"))
  20810. (org-with-wide-buffer
  20811. (org-indent-region (org-element-property :begin element)
  20812. (org-element-property :end element))))
  20813. (message "Block at point indented"))
  20814. ;;; Filling
  20815. ;; We use our own fill-paragraph and auto-fill functions.
  20816. ;; `org-fill-paragraph' relies on adaptive filling and context
  20817. ;; checking. Appropriate `fill-prefix' is computed with
  20818. ;; `org-adaptive-fill-function'.
  20819. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20820. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20821. ;; `org-adaptive-fill-function' value. Internally,
  20822. ;; `org-comment-line-break-function' breaks the line.
  20823. ;; `org-setup-filling' installs filling and auto-filling related
  20824. ;; variables during `org-mode' initialization.
  20825. (defvar org-element-paragraph-separate) ; org-element.el
  20826. (defun org-setup-filling ()
  20827. (require 'org-element)
  20828. ;; Prevent auto-fill from inserting unwanted new items.
  20829. (when (boundp 'fill-nobreak-predicate)
  20830. (setq-local
  20831. fill-nobreak-predicate
  20832. (org-uniquify
  20833. (append fill-nobreak-predicate
  20834. '(org-fill-line-break-nobreak-p
  20835. org-fill-n-macro-as-item-nobreak-p
  20836. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20837. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20838. (setq-local paragraph-start paragraph-ending)
  20839. (setq-local paragraph-separate paragraph-ending))
  20840. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20841. (setq-local auto-fill-inhibit-regexp nil)
  20842. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20843. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20844. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20845. (defun org-fill-line-break-nobreak-p ()
  20846. "Non-nil when a new line at point would create an Org line break."
  20847. (save-excursion
  20848. (skip-chars-backward "[ \t]")
  20849. (skip-chars-backward "\\\\")
  20850. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20851. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20852. "Non-nil when a new line at point would split a timestamp."
  20853. (and (org-at-timestamp-p 'lax)
  20854. (not (looking-at org-ts-regexp-both))))
  20855. (defun org-fill-n-macro-as-item-nobreak-p ()
  20856. "Non-nil when a new line at point would create a new list."
  20857. ;; During export, a "n" macro followed by a dot or a closing
  20858. ;; parenthesis can end up being parsed as a new list item.
  20859. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20860. (declare-function message-in-body-p "message" ())
  20861. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20862. (defun org-adaptive-fill-function ()
  20863. "Compute a fill prefix for the current line.
  20864. Return fill prefix, as a string, or nil if current line isn't
  20865. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20866. matches in paragraphs or comments, use it."
  20867. (catch 'exit
  20868. (when (derived-mode-p 'message-mode)
  20869. (save-excursion
  20870. (beginning-of-line)
  20871. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20872. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20873. ((looking-at message-cite-prefix-regexp)
  20874. (throw 'exit (match-string-no-properties 0)))
  20875. ((looking-at org-outline-regexp)
  20876. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20877. (org-with-wide-buffer
  20878. (unless (org-at-heading-p)
  20879. (let* ((p (line-beginning-position))
  20880. (element (save-excursion
  20881. (beginning-of-line)
  20882. (org-element-at-point)))
  20883. (type (org-element-type element))
  20884. (post-affiliated (org-element-property :post-affiliated element)))
  20885. (unless (< p post-affiliated)
  20886. (cl-case type
  20887. (comment
  20888. (save-excursion
  20889. (beginning-of-line)
  20890. (looking-at "[ \t]*")
  20891. (concat (match-string 0) "# ")))
  20892. (footnote-definition "")
  20893. ((item plain-list)
  20894. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20895. (paragraph
  20896. ;; Fill prefix is usually the same as the current line,
  20897. ;; unless the paragraph is at the beginning of an item.
  20898. (let ((parent (org-element-property :parent element)))
  20899. (save-excursion
  20900. (beginning-of-line)
  20901. (cond ((eq (org-element-type parent) 'item)
  20902. (make-string (org-list-item-body-column
  20903. (org-element-property :begin parent))
  20904. ?\s))
  20905. ((and adaptive-fill-regexp
  20906. ;; Locally disable
  20907. ;; `adaptive-fill-function' to let
  20908. ;; `fill-context-prefix' handle
  20909. ;; `adaptive-fill-regexp' variable.
  20910. (let (adaptive-fill-function)
  20911. (fill-context-prefix
  20912. post-affiliated
  20913. (org-element-property :end element)))))
  20914. ((looking-at "[ \t]+") (match-string 0))
  20915. (t "")))))
  20916. (comment-block
  20917. ;; Only fill contents if P is within block boundaries.
  20918. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20919. (forward-line)
  20920. (point)))
  20921. (cend (save-excursion
  20922. (goto-char (org-element-property :end element))
  20923. (skip-chars-backward " \r\t\n")
  20924. (line-beginning-position))))
  20925. (when (and (>= p cbeg) (< p cend))
  20926. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20927. (match-string 0)
  20928. "")))))))))))
  20929. (declare-function message-goto-body "message" ())
  20930. (defvar message-cite-prefix-regexp) ; From message.el
  20931. (defun org-fill-element (&optional justify)
  20932. "Fill element at point, when applicable.
  20933. This function only applies to comment blocks, comments, example
  20934. blocks and paragraphs. Also, as a special case, re-align table
  20935. when point is at one.
  20936. If JUSTIFY is non-nil (interactively, with prefix argument),
  20937. justify as well. If `sentence-end-double-space' is non-nil, then
  20938. period followed by one space does not end a sentence, so don't
  20939. break a line there. The variable `fill-column' controls the
  20940. width for filling.
  20941. For convenience, when point is at a plain list, an item or
  20942. a footnote definition, try to fill the first paragraph within."
  20943. (with-syntax-table org-mode-transpose-word-syntax-table
  20944. ;; Move to end of line in order to get the first paragraph within
  20945. ;; a plain list or a footnote definition.
  20946. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20947. ;; First check if point is in a blank line at the beginning of
  20948. ;; the buffer. In that case, ignore filling.
  20949. (cl-case (org-element-type element)
  20950. ;; Use major mode filling function is src blocks.
  20951. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20952. ;; Align Org tables, leave table.el tables as-is.
  20953. (table-row (org-table-align) t)
  20954. (table
  20955. (when (eq (org-element-property :type element) 'org)
  20956. (save-excursion
  20957. (goto-char (org-element-property :post-affiliated element))
  20958. (org-table-align)))
  20959. t)
  20960. (paragraph
  20961. ;; Paragraphs may contain `line-break' type objects.
  20962. (let ((beg (max (point-min)
  20963. (org-element-property :contents-begin element)))
  20964. (end (min (point-max)
  20965. (org-element-property :contents-end element))))
  20966. ;; Do nothing if point is at an affiliated keyword.
  20967. (if (< (line-end-position) beg) t
  20968. (when (derived-mode-p 'message-mode)
  20969. ;; In `message-mode', do not fill following citation
  20970. ;; in current paragraph nor text before message body.
  20971. (let ((body-start (save-excursion (message-goto-body))))
  20972. (when body-start (setq beg (max body-start beg))))
  20973. (when (save-excursion
  20974. (re-search-forward
  20975. (concat "^" message-cite-prefix-regexp) end t))
  20976. (setq end (match-beginning 0))))
  20977. ;; Fill paragraph, taking line breaks into account.
  20978. (save-excursion
  20979. (goto-char beg)
  20980. (let ((cuts (list beg)))
  20981. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20982. (when (eq 'line-break
  20983. (org-element-type
  20984. (save-excursion (backward-char)
  20985. (org-element-context))))
  20986. (push (point) cuts)))
  20987. (dolist (c (delq end cuts))
  20988. (fill-region-as-paragraph c end justify)
  20989. (setq end c))))
  20990. t)))
  20991. ;; Contents of `comment-block' type elements should be
  20992. ;; filled as plain text, but only if point is within block
  20993. ;; markers.
  20994. (comment-block
  20995. (let* ((case-fold-search t)
  20996. (beg (save-excursion
  20997. (goto-char (org-element-property :begin element))
  20998. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20999. (forward-line)
  21000. (point)))
  21001. (end (save-excursion
  21002. (goto-char (org-element-property :end element))
  21003. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21004. (line-beginning-position))))
  21005. (if (or (< (point) beg) (> (point) end)) t
  21006. (fill-region-as-paragraph
  21007. (save-excursion (end-of-line)
  21008. (re-search-backward "^[ \t]*$" beg 'move)
  21009. (line-beginning-position))
  21010. (save-excursion (beginning-of-line)
  21011. (re-search-forward "^[ \t]*$" end 'move)
  21012. (line-beginning-position))
  21013. justify))))
  21014. ;; Fill comments.
  21015. (comment
  21016. (let ((begin (org-element-property :post-affiliated element))
  21017. (end (org-element-property :end element)))
  21018. (when (and (>= (point) begin) (<= (point) end))
  21019. (let ((begin (save-excursion
  21020. (end-of-line)
  21021. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21022. (progn (forward-line) (point))
  21023. begin)))
  21024. (end (save-excursion
  21025. (end-of-line)
  21026. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21027. (1- (line-beginning-position))
  21028. (skip-chars-backward " \r\t\n")
  21029. (line-end-position)))))
  21030. ;; Do not fill comments when at a blank line.
  21031. (when (> end begin)
  21032. (let ((fill-prefix
  21033. (save-excursion
  21034. (beginning-of-line)
  21035. (looking-at "[ \t]*#")
  21036. (let ((comment-prefix (match-string 0)))
  21037. (goto-char (match-end 0))
  21038. (if (looking-at adaptive-fill-regexp)
  21039. (concat comment-prefix (match-string 0))
  21040. (concat comment-prefix " "))))))
  21041. (save-excursion
  21042. (fill-region-as-paragraph begin end justify))))))
  21043. t))
  21044. ;; Ignore every other element.
  21045. (otherwise t)))))
  21046. (defun org-fill-paragraph (&optional justify region)
  21047. "Fill element at point, when applicable.
  21048. This function only applies to comment blocks, comments, example
  21049. blocks and paragraphs. Also, as a special case, re-align table
  21050. when point is at one.
  21051. For convenience, when point is at a plain list, an item or
  21052. a footnote definition, try to fill the first paragraph within.
  21053. If JUSTIFY is non-nil (interactively, with prefix argument),
  21054. justify as well. If `sentence-end-double-space' is non-nil, then
  21055. period followed by one space does not end a sentence, so don't
  21056. break a line there. The variable `fill-column' controls the
  21057. width for filling.
  21058. The REGION argument is non-nil if called interactively; in that
  21059. case, if Transient Mark mode is enabled and the mark is active,
  21060. fill each of the elements in the active region, instead of just
  21061. filling the current element."
  21062. (interactive (progn
  21063. (barf-if-buffer-read-only)
  21064. (list (if current-prefix-arg 'full) t)))
  21065. (cond
  21066. ((and (derived-mode-p 'message-mode)
  21067. (or (not (message-in-body-p))
  21068. (save-excursion (move-beginning-of-line 1)
  21069. (looking-at message-cite-prefix-regexp))))
  21070. ;; First ensure filling is correct in message-mode.
  21071. (let ((fill-paragraph-function
  21072. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21073. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21074. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21075. (paragraph-separate
  21076. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21077. (fill-paragraph nil)))
  21078. ((and region transient-mark-mode mark-active
  21079. (not (eq (region-beginning) (region-end))))
  21080. (let ((origin (point-marker))
  21081. (start (region-beginning)))
  21082. (unwind-protect
  21083. (progn
  21084. (goto-char (region-end))
  21085. (while (> (point) start)
  21086. (org-backward-paragraph)
  21087. (org-fill-element justify)))
  21088. (goto-char origin)
  21089. (set-marker origin nil))))
  21090. (t (org-fill-element justify))))
  21091. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21092. (defun org-auto-fill-function ()
  21093. "Auto-fill function."
  21094. ;; Check if auto-filling is meaningful.
  21095. (let ((fc (current-fill-column)))
  21096. (when (and fc (> (current-column) fc))
  21097. (let* ((fill-prefix (org-adaptive-fill-function))
  21098. ;; Enforce empty fill prefix, if required. Otherwise, it
  21099. ;; will be computed again.
  21100. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21101. (when fill-prefix (do-auto-fill))))))
  21102. (defun org-comment-line-break-function (&optional soft)
  21103. "Break line at point and indent, continuing comment if within one.
  21104. The inserted newline is marked hard if variable
  21105. `use-hard-newlines' is true, unless optional argument SOFT is
  21106. non-nil."
  21107. (if soft (insert-and-inherit ?\n) (newline 1))
  21108. (save-excursion (forward-char -1) (delete-horizontal-space))
  21109. (delete-horizontal-space)
  21110. (indent-to-left-margin)
  21111. (insert-before-markers-and-inherit fill-prefix))
  21112. ;;; Fixed Width Areas
  21113. (defun org-toggle-fixed-width ()
  21114. "Toggle fixed-width markup.
  21115. Add or remove fixed-width markup on current line, whenever it
  21116. makes sense. Return an error otherwise.
  21117. If a region is active and if it contains only fixed-width areas
  21118. or blank lines, remove all fixed-width markup in it. If the
  21119. region contains anything else, convert all non-fixed-width lines
  21120. to fixed-width ones.
  21121. Blank lines at the end of the region are ignored unless the
  21122. region only contains such lines."
  21123. (interactive)
  21124. (if (not (org-region-active-p))
  21125. ;; No region:
  21126. ;;
  21127. ;; Remove fixed width marker only in a fixed-with element.
  21128. ;;
  21129. ;; Add fixed width maker in paragraphs, in blank lines after
  21130. ;; elements or at the beginning of a headline or an inlinetask,
  21131. ;; and before any one-line elements (e.g., a clock).
  21132. (progn
  21133. (beginning-of-line)
  21134. (let* ((element (org-element-at-point))
  21135. (type (org-element-type element)))
  21136. (cond
  21137. ((and (eq type 'fixed-width)
  21138. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21139. (replace-match
  21140. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21141. ((and (memq type '(babel-call clock comment diary-sexp headline
  21142. horizontal-rule keyword paragraph
  21143. planning))
  21144. (<= (org-element-property :post-affiliated element) (point)))
  21145. (skip-chars-forward " \t")
  21146. (insert ": "))
  21147. ((and (looking-at-p "[ \t]*$")
  21148. (or (eq type 'inlinetask)
  21149. (save-excursion
  21150. (skip-chars-forward " \r\t\n")
  21151. (<= (org-element-property :end element) (point)))))
  21152. (delete-region (point) (line-end-position))
  21153. (org-indent-line)
  21154. (insert ": "))
  21155. (t (user-error "Cannot insert a fixed-width line here")))))
  21156. ;; Region active.
  21157. (let* ((begin (save-excursion
  21158. (goto-char (region-beginning))
  21159. (line-beginning-position)))
  21160. (end (copy-marker
  21161. (save-excursion
  21162. (goto-char (region-end))
  21163. (unless (eolp) (beginning-of-line))
  21164. (if (save-excursion (re-search-backward "\\S-" begin t))
  21165. (progn (skip-chars-backward " \r\t\n") (point))
  21166. (point)))))
  21167. (all-fixed-width-p
  21168. (catch 'not-all-p
  21169. (save-excursion
  21170. (goto-char begin)
  21171. (skip-chars-forward " \r\t\n")
  21172. (when (eobp) (throw 'not-all-p nil))
  21173. (while (< (point) end)
  21174. (let ((element (org-element-at-point)))
  21175. (if (eq (org-element-type element) 'fixed-width)
  21176. (goto-char (org-element-property :end element))
  21177. (throw 'not-all-p nil))))
  21178. t))))
  21179. (if all-fixed-width-p
  21180. (save-excursion
  21181. (goto-char begin)
  21182. (while (< (point) end)
  21183. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21184. (replace-match
  21185. "" nil nil nil
  21186. (if (= (line-end-position) (match-end 0)) 0 1)))
  21187. (forward-line)))
  21188. (let ((min-ind (point-max)))
  21189. ;; Find minimum indentation across all lines.
  21190. (save-excursion
  21191. (goto-char begin)
  21192. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21193. (setq min-ind 0)
  21194. (catch 'zerop
  21195. (while (< (point) end)
  21196. (unless (looking-at-p "[ \t]*$")
  21197. (let ((ind (org-get-indentation)))
  21198. (setq min-ind (min min-ind ind))
  21199. (when (zerop ind) (throw 'zerop t))))
  21200. (forward-line)))))
  21201. ;; Loop over all lines and add fixed-width markup everywhere
  21202. ;; but in fixed-width lines.
  21203. (save-excursion
  21204. (goto-char begin)
  21205. (while (< (point) end)
  21206. (cond
  21207. ((org-at-heading-p)
  21208. (insert ": ")
  21209. (forward-line)
  21210. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21211. (insert ":")
  21212. (forward-line)))
  21213. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21214. (let* ((element (org-element-at-point))
  21215. (element-end (org-element-property :end element)))
  21216. (if (eq (org-element-type element) 'fixed-width)
  21217. (progn (goto-char element-end)
  21218. (skip-chars-backward " \r\t\n")
  21219. (forward-line))
  21220. (let ((limit (min end element-end)))
  21221. (while (< (point) limit)
  21222. (org-move-to-column min-ind t)
  21223. (insert ": ")
  21224. (forward-line))))))
  21225. (t
  21226. (org-move-to-column min-ind t)
  21227. (insert ": ")
  21228. (forward-line)))))))
  21229. (set-marker end nil))))
  21230. ;;; Comments
  21231. ;; Org comments syntax is quite complex. It requires the entire line
  21232. ;; to be just a comment. Also, even with the right syntax at the
  21233. ;; beginning of line, some elements (e.g., verse-block or
  21234. ;; example-block) don't accept comments. Usual Emacs comment commands
  21235. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21236. ;; Org still relies on `comment-dwim', but cannot trust
  21237. ;; `comment-only-p'. So, `comment-region-function' and
  21238. ;; `uncomment-region-function' both point
  21239. ;; to`org-comment-or-uncomment-region'. Eventually,
  21240. ;; `org-insert-comment' takes care of insertion of comments at the
  21241. ;; beginning of line.
  21242. ;; `org-setup-comments-handling' install comments related variables
  21243. ;; during `org-mode' initialization.
  21244. (defun org-setup-comments-handling ()
  21245. (interactive)
  21246. (setq-local comment-use-syntax nil)
  21247. (setq-local comment-start "# ")
  21248. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21249. (setq-local comment-insert-comment-function 'org-insert-comment)
  21250. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21251. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21252. (defun org-insert-comment ()
  21253. "Insert an empty comment above current line.
  21254. If the line is empty, insert comment at its beginning. When
  21255. point is within a source block, comment according to the related
  21256. major mode."
  21257. (if (let ((element (org-element-at-point)))
  21258. (and (eq (org-element-type element) 'src-block)
  21259. (< (save-excursion
  21260. (goto-char (org-element-property :post-affiliated element))
  21261. (line-end-position))
  21262. (point))
  21263. (> (save-excursion
  21264. (goto-char (org-element-property :end element))
  21265. (skip-chars-backward " \r\t\n")
  21266. (line-beginning-position))
  21267. (point))))
  21268. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21269. (beginning-of-line)
  21270. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21271. (open-line 1))
  21272. (org-indent-line)
  21273. (insert "# ")))
  21274. (defvar comment-empty-lines) ; From newcomment.el.
  21275. (defun org-comment-or-uncomment-region (beg end &rest _)
  21276. "Comment or uncomment each non-blank line in the region.
  21277. Uncomment each non-blank line between BEG and END if it only
  21278. contains commented lines. Otherwise, comment them. If region is
  21279. strictly within a source block, use appropriate comment syntax."
  21280. (if (let ((element (org-element-at-point)))
  21281. (and (eq (org-element-type element) 'src-block)
  21282. (< (save-excursion
  21283. (goto-char (org-element-property :post-affiliated element))
  21284. (line-end-position))
  21285. beg)
  21286. (>= (save-excursion
  21287. (goto-char (org-element-property :end element))
  21288. (skip-chars-backward " \r\t\n")
  21289. (line-beginning-position))
  21290. end)))
  21291. ;; Translate region boundaries for the Org buffer to the source
  21292. ;; buffer.
  21293. (let ((offset (- end beg)))
  21294. (save-excursion
  21295. (goto-char beg)
  21296. (org-babel-do-in-edit-buffer
  21297. (comment-or-uncomment-region (point) (+ offset (point))))))
  21298. (save-restriction
  21299. ;; Restrict region
  21300. (narrow-to-region (save-excursion (goto-char beg)
  21301. (skip-chars-forward " \r\t\n" end)
  21302. (line-beginning-position))
  21303. (save-excursion (goto-char end)
  21304. (skip-chars-backward " \r\t\n" beg)
  21305. (line-end-position)))
  21306. (let ((uncommentp
  21307. ;; UNCOMMENTP is non-nil when every non blank line between
  21308. ;; BEG and END is a comment.
  21309. (save-excursion
  21310. (goto-char (point-min))
  21311. (while (and (not (eobp))
  21312. (let ((element (org-element-at-point)))
  21313. (and (eq (org-element-type element) 'comment)
  21314. (goto-char (min (point-max)
  21315. (org-element-property
  21316. :end element)))))))
  21317. (eobp))))
  21318. (if uncommentp
  21319. ;; Only blank lines and comments in region: uncomment it.
  21320. (save-excursion
  21321. (goto-char (point-min))
  21322. (while (not (eobp))
  21323. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21324. (replace-match "" nil nil nil 1))
  21325. (forward-line)))
  21326. ;; Comment each line in region.
  21327. (let ((min-indent (point-max)))
  21328. ;; First find the minimum indentation across all lines.
  21329. (save-excursion
  21330. (goto-char (point-min))
  21331. (while (and (not (eobp)) (not (zerop min-indent)))
  21332. (unless (looking-at "[ \t]*$")
  21333. (setq min-indent (min min-indent (current-indentation))))
  21334. (forward-line)))
  21335. ;; Then loop over all lines.
  21336. (save-excursion
  21337. (goto-char (point-min))
  21338. (while (not (eobp))
  21339. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21340. ;; Don't get fooled by invisible text (e.g. link path)
  21341. ;; when moving to column MIN-INDENT.
  21342. (let ((buffer-invisibility-spec nil))
  21343. (org-move-to-column min-indent t))
  21344. (insert comment-start))
  21345. (forward-line)))))))))
  21346. (defun org-comment-dwim (_arg)
  21347. "Call `comment-dwim' within a source edit buffer if needed."
  21348. (interactive "*P")
  21349. (if (org-in-src-block-p)
  21350. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21351. (call-interactively 'comment-dwim)))
  21352. ;;; Timestamps API
  21353. ;; This section contains tools to operate on timestamp objects, as
  21354. ;; returned by, e.g. `org-element-context'.
  21355. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21356. "Encode TIMESTAMP object into Emacs internal time.
  21357. Use end of date range or time range when END is non-nil."
  21358. (apply #'encode-time
  21359. (cons 0
  21360. (mapcar
  21361. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21362. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21363. '(:minute-start :hour-start :day-start :month-start
  21364. :year-start))))))
  21365. (defun org-timestamp-has-time-p (timestamp)
  21366. "Non-nil when TIMESTAMP has a time specified."
  21367. (org-element-property :hour-start timestamp))
  21368. (defun org-timestamp-format (timestamp format &optional end utc)
  21369. "Format a TIMESTAMP object into a string.
  21370. FORMAT is a format specifier to be passed to
  21371. `format-time-string'.
  21372. When optional argument END is non-nil, use end of date-range or
  21373. time-range, if possible.
  21374. When optional argument UTC is non-nil, time will be expressed as
  21375. Universal Time."
  21376. (format-time-string
  21377. format (org-timestamp--to-internal-time timestamp end)
  21378. (and utc t)))
  21379. (defun org-timestamp-split-range (timestamp &optional end)
  21380. "Extract a TIMESTAMP object from a date or time range.
  21381. END, when non-nil, means extract the end of the range.
  21382. Otherwise, extract its start.
  21383. Return a new timestamp object."
  21384. (let ((type (org-element-property :type timestamp)))
  21385. (if (memq type '(active inactive diary)) timestamp
  21386. (let ((split-ts (org-element-copy timestamp)))
  21387. ;; Set new type.
  21388. (org-element-put-property
  21389. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21390. ;; Copy start properties over end properties if END is
  21391. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21392. (let ((p-alist '((:minute-start . :minute-end)
  21393. (:hour-start . :hour-end)
  21394. (:day-start . :day-end)
  21395. (:month-start . :month-end)
  21396. (:year-start . :year-end))))
  21397. (dolist (p-cell p-alist)
  21398. (org-element-put-property
  21399. split-ts
  21400. (funcall (if end #'car #'cdr) p-cell)
  21401. (org-element-property
  21402. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21403. ;; Eventually refresh `:raw-value'.
  21404. (org-element-put-property split-ts :raw-value nil)
  21405. (org-element-put-property
  21406. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21407. (defun org-timestamp-translate (timestamp &optional boundary)
  21408. "Translate TIMESTAMP object to custom format.
  21409. Format string is defined in `org-time-stamp-custom-formats',
  21410. which see.
  21411. When optional argument BOUNDARY is non-nil, it is either the
  21412. symbol `start' or `end'. In this case, only translate the
  21413. starting or ending part of TIMESTAMP if it is a date or time
  21414. range. Otherwise, translate both parts.
  21415. Return timestamp as-is if `org-display-custom-times' is nil or if
  21416. it has a `diary' type."
  21417. (let ((type (org-element-property :type timestamp)))
  21418. (if (or (not org-display-custom-times) (eq type 'diary))
  21419. (org-element-interpret-data timestamp)
  21420. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21421. org-time-stamp-custom-formats)))
  21422. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21423. (concat (org-timestamp-format timestamp fmt)
  21424. "--"
  21425. (org-timestamp-format timestamp fmt t))
  21426. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21427. ;;; Other stuff.
  21428. (defvar reftex-docstruct-symbol)
  21429. (defvar org--rds)
  21430. (defun org-reftex-citation ()
  21431. "Use reftex-citation to insert a citation into the buffer.
  21432. This looks for a line like
  21433. #+BIBLIOGRAPHY: foo plain option:-d
  21434. and derives from it that foo.bib is the bibliography file relevant
  21435. for this document. It then installs the necessary environment for RefTeX
  21436. to work in this buffer and calls `reftex-citation' to insert a citation
  21437. into the buffer.
  21438. Export of such citations to both LaTeX and HTML is handled by the contributed
  21439. package ox-bibtex by Taru Karttunen."
  21440. (interactive)
  21441. (let ((reftex-docstruct-symbol 'org--rds)
  21442. org--rds bib)
  21443. (org-with-wide-buffer
  21444. (let ((case-fold-search t)
  21445. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21446. (if (not (save-excursion
  21447. (or (re-search-forward re nil t)
  21448. (re-search-backward re nil t))))
  21449. (user-error "No bibliography defined in file")
  21450. (setq bib (concat (match-string 1) ".bib")
  21451. org--rds (list (list 'bib bib))))))
  21452. (call-interactively 'reftex-citation)))
  21453. ;;;; Functions extending outline functionality
  21454. (defun org-beginning-of-line (&optional n)
  21455. "Go to the beginning of the current visible line.
  21456. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21457. tags on the first attempt, and only move to after the tags when
  21458. the cursor is already beyond the end of the headline.
  21459. With argument N not nil or 1, move forward N - 1 lines first."
  21460. (interactive "^p")
  21461. (let ((origin (point))
  21462. (special (pcase org-special-ctrl-a/e
  21463. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21464. deactivate-mark)
  21465. ;; First move to a visible line.
  21466. (if (bound-and-true-p visual-line-mode)
  21467. (beginning-of-visual-line n)
  21468. (move-beginning-of-line n)
  21469. ;; `move-beginning-of-line' may leave point after invisible
  21470. ;; characters if line starts with such of these (e.g., with
  21471. ;; a link at column 0). Really move to the beginning of the
  21472. ;; current visible line.
  21473. (beginning-of-line))
  21474. (cond
  21475. ;; No special behavior. Point is already at the beginning of
  21476. ;; a line, logical or visual.
  21477. ((not special))
  21478. ;; `beginning-of-visual-line' left point before logical beginning
  21479. ;; of line: point is at the beginning of a visual line. Bail
  21480. ;; out.
  21481. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21482. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21483. ;; At a headline, special position is before the title, but
  21484. ;; after any TODO keyword or priority cookie.
  21485. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21486. (line-end-position)))
  21487. (bol (point)))
  21488. (if (eq special 'reversed)
  21489. (when (and (= origin bol) (eq last-command this-command))
  21490. (goto-char refpos))
  21491. (when (or (> origin refpos) (= origin bol))
  21492. (goto-char refpos)))))
  21493. ((and (looking-at org-list-full-item-re)
  21494. (memq (org-element-type (save-match-data (org-element-at-point)))
  21495. '(item plain-list)))
  21496. ;; Set special position at first white space character after
  21497. ;; bullet, and check-box, if any.
  21498. (let ((after-bullet
  21499. (let ((box (match-end 3)))
  21500. (cond ((not box) (match-end 1))
  21501. ((eq (char-after box) ?\s) (1+ box))
  21502. (t box)))))
  21503. (if (eq special 'reversed)
  21504. (when (and (= (point) origin) (eq last-command this-command))
  21505. (goto-char after-bullet))
  21506. (when (or (> origin after-bullet) (= (point) origin))
  21507. (goto-char after-bullet)))))
  21508. ;; No special context. Point is already at beginning of line.
  21509. (t nil))))
  21510. (defun org-end-of-line (&optional n)
  21511. "Go to the end of the line, but before ellipsis, if any.
  21512. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21513. tags on the first attempt, and only move to after the tags when
  21514. the cursor is already beyond the end of the headline.
  21515. With argument N not nil or 1, move forward N - 1 lines first."
  21516. (interactive "^p")
  21517. (let ((origin (point))
  21518. (special (pcase org-special-ctrl-a/e
  21519. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21520. deactivate-mark)
  21521. ;; First move to a visible line.
  21522. (if (bound-and-true-p visual-line-mode)
  21523. (beginning-of-visual-line n)
  21524. (move-beginning-of-line n))
  21525. (cond
  21526. ;; At a headline, with tags.
  21527. ((and special
  21528. (save-excursion
  21529. (beginning-of-line)
  21530. (let ((case-fold-search nil))
  21531. (looking-at org-complex-heading-regexp)))
  21532. (match-end 5))
  21533. (let ((tags (save-excursion
  21534. (goto-char (match-beginning 5))
  21535. (skip-chars-backward " \t")
  21536. (point)))
  21537. (visual-end (and (bound-and-true-p visual-line-mode)
  21538. (save-excursion
  21539. (end-of-visual-line)
  21540. (point)))))
  21541. ;; If `end-of-visual-line' brings us before end of line or
  21542. ;; even tags, i.e., the headline spans over multiple visual
  21543. ;; lines, move there.
  21544. (cond ((and visual-end
  21545. (< visual-end tags)
  21546. (<= origin visual-end))
  21547. (goto-char visual-end))
  21548. ((eq special 'reversed)
  21549. (if (and (= origin (line-end-position))
  21550. (eq this-command last-command))
  21551. (goto-char tags)
  21552. (end-of-line)))
  21553. (t
  21554. (if (or (< origin tags) (= origin (line-end-position)))
  21555. (goto-char tags)
  21556. (end-of-line))))))
  21557. ((bound-and-true-p visual-line-mode)
  21558. (let ((bol (line-beginning-position)))
  21559. (end-of-visual-line)
  21560. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21561. ;; end of a line, backtrack and use `end-of-line' instead.
  21562. (when (/= bol (line-beginning-position))
  21563. (goto-char bol)
  21564. (end-of-line))))
  21565. (t (end-of-line)))))
  21566. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21567. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21568. (defun org-backward-sentence (&optional _arg)
  21569. "Go to beginning of sentence, or beginning of table field.
  21570. This will call `backward-sentence' or `org-table-beginning-of-field',
  21571. depending on context."
  21572. (interactive)
  21573. (let* ((element (org-element-at-point))
  21574. (contents-begin (org-element-property :contents-begin element))
  21575. (table (org-element-lineage element '(table) t)))
  21576. (if (and table
  21577. (> (point) contents-begin)
  21578. (<= (point) (org-element-property :contents-end table)))
  21579. (call-interactively #'org-table-beginning-of-field)
  21580. (save-restriction
  21581. (when (and contents-begin
  21582. (< (point-min) contents-begin)
  21583. (> (point) contents-begin))
  21584. (narrow-to-region contents-begin
  21585. (org-element-property :contents-end element)))
  21586. (call-interactively #'backward-sentence)))))
  21587. (defun org-forward-sentence (&optional _arg)
  21588. "Go to end of sentence, or end of table field.
  21589. This will call `forward-sentence' or `org-table-end-of-field',
  21590. depending on context."
  21591. (interactive)
  21592. (if (and (org-at-heading-p)
  21593. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21594. (save-restriction
  21595. (narrow-to-region (line-beginning-position) (line-end-position))
  21596. (call-interactively #'forward-sentence))
  21597. (let* ((element (org-element-at-point))
  21598. (contents-end (org-element-property :contents-end element))
  21599. (table (org-element-lineage element '(table) t)))
  21600. (if (and table
  21601. (>= (point) (org-element-property :contents-begin table))
  21602. (< (point) contents-end))
  21603. (call-interactively #'org-table-end-of-field)
  21604. (save-restriction
  21605. (when (and contents-end
  21606. (> (point-max) contents-end)
  21607. ;; Skip blank lines between elements.
  21608. (< (org-element-property :end element)
  21609. (save-excursion (goto-char contents-end)
  21610. (skip-chars-forward " \r\t\n"))))
  21611. (narrow-to-region (org-element-property :contents-begin element)
  21612. contents-end))
  21613. ;; End of heading is considered as the end of a sentence.
  21614. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21615. (call-interactively #'forward-sentence)))))))
  21616. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21617. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21618. (defun org-kill-line (&optional _arg)
  21619. "Kill line, to tags or end of line."
  21620. (interactive)
  21621. (cond
  21622. ((or (not org-special-ctrl-k)
  21623. (bolp)
  21624. (not (org-at-heading-p)))
  21625. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21626. org-ctrl-k-protect-subtree
  21627. (or (eq org-ctrl-k-protect-subtree 'error)
  21628. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21629. (user-error "C-k aborted as it would kill a hidden subtree"))
  21630. (call-interactively
  21631. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21632. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21633. (kill-region (point) (match-beginning 1))
  21634. (org-set-tags nil t))
  21635. (t (kill-region (point) (point-at-eol)))))
  21636. (define-key org-mode-map "\C-k" 'org-kill-line)
  21637. (defun org-yank (&optional arg)
  21638. "Yank. If the kill is a subtree, treat it specially.
  21639. This command will look at the current kill and check if is a single
  21640. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21641. cursor is at the beginning of a line or after the stars of a currently
  21642. empty headline, then the yank is handled specially. How exactly depends
  21643. on the value of the following variables.
  21644. `org-yank-folded-subtrees'
  21645. By default, this variable is non-nil, which results in
  21646. subtree(s) being folded after insertion, except if doing so
  21647. would swallow text after the yanked text.
  21648. `org-yank-adjusted-subtrees'
  21649. When non-nil (the default value is nil), the subtree will be
  21650. promoted or demoted in order to fit into the local outline tree
  21651. structure, which means that the level will be adjusted so that it
  21652. becomes the smaller one of the two *visible* surrounding headings.
  21653. Any prefix to this command will cause `yank' to be called directly with
  21654. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21655. will just
  21656. plainly yank the text as it is.
  21657. \[1] The test checks if the first non-white line is a heading
  21658. and if there are no other headings with fewer stars."
  21659. (interactive "P")
  21660. (org-yank-generic 'yank arg))
  21661. (defun org-yank-generic (command arg)
  21662. "Perform some yank-like command.
  21663. This function implements the behavior described in the `org-yank'
  21664. documentation. However, it has been generalized to work for any
  21665. interactive command with similar behavior."
  21666. ;; pretend to be command COMMAND
  21667. (setq this-command command)
  21668. (if arg
  21669. (call-interactively command)
  21670. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21671. (and (org-kill-is-subtree-p)
  21672. (or (bolp)
  21673. (and (looking-at "[ \t]*$")
  21674. (string-match
  21675. "\\`\\*+\\'"
  21676. (buffer-substring (point-at-bol) (point)))))))
  21677. swallowp)
  21678. (cond
  21679. ((and subtreep org-yank-folded-subtrees)
  21680. (let ((beg (point))
  21681. end)
  21682. (if (and subtreep org-yank-adjusted-subtrees)
  21683. (org-paste-subtree nil nil 'for-yank)
  21684. (call-interactively command))
  21685. (setq end (point))
  21686. (goto-char beg)
  21687. (when (and (bolp) subtreep
  21688. (not (setq swallowp
  21689. (org-yank-folding-would-swallow-text beg end))))
  21690. (org-with-limited-levels
  21691. (or (looking-at org-outline-regexp)
  21692. (re-search-forward org-outline-regexp-bol end t))
  21693. (while (and (< (point) end) (looking-at org-outline-regexp))
  21694. (outline-hide-subtree)
  21695. (org-cycle-show-empty-lines 'folded)
  21696. (condition-case nil
  21697. (outline-forward-same-level 1)
  21698. (error (goto-char end))))))
  21699. (when swallowp
  21700. (message
  21701. "Inserted text not folded because that would swallow text"))
  21702. (goto-char end)
  21703. (skip-chars-forward " \t\n\r")
  21704. (beginning-of-line 1)
  21705. (push-mark beg 'nomsg)))
  21706. ((and subtreep org-yank-adjusted-subtrees)
  21707. (let ((beg (point-at-bol)))
  21708. (org-paste-subtree nil nil 'for-yank)
  21709. (push-mark beg 'nomsg)))
  21710. (t
  21711. (call-interactively command))))))
  21712. (defun org-yank-folding-would-swallow-text (beg end)
  21713. "Would hide-subtree at BEG swallow any text after END?"
  21714. (let (level)
  21715. (org-with-limited-levels
  21716. (save-excursion
  21717. (goto-char beg)
  21718. (when (or (looking-at org-outline-regexp)
  21719. (re-search-forward org-outline-regexp-bol end t))
  21720. (setq level (org-outline-level)))
  21721. (goto-char end)
  21722. (skip-chars-forward " \t\r\n\v\f")
  21723. (not (or (eobp)
  21724. (and (bolp) (looking-at-p org-outline-regexp)
  21725. (<= (org-outline-level) level))))))))
  21726. (define-key org-mode-map "\C-y" 'org-yank)
  21727. (defun org-truely-invisible-p ()
  21728. "Check if point is at a character currently not visible.
  21729. This version does not only check the character property, but also
  21730. `visible-mode'."
  21731. (unless (bound-and-true-p visible-mode)
  21732. (org-invisible-p)))
  21733. (defun org-invisible-p2 ()
  21734. "Check if point is at a character currently not visible.
  21735. If the point is at EOL (and not at the beginning of a buffer too),
  21736. move it back by one char before doing this check."
  21737. (save-excursion
  21738. (when (and (eolp) (not (bobp)))
  21739. (backward-char 1))
  21740. (org-invisible-p)))
  21741. (defun org-back-to-heading (&optional invisible-ok)
  21742. "Call `outline-back-to-heading', but provide a better error message."
  21743. (condition-case nil
  21744. (outline-back-to-heading invisible-ok)
  21745. (error (error "Before first headline at position %d in buffer %s"
  21746. (point) (current-buffer)))))
  21747. (defun org-before-first-heading-p ()
  21748. "Before first heading?"
  21749. (save-excursion
  21750. (end-of-line)
  21751. (null (re-search-backward org-outline-regexp-bol nil t))))
  21752. (defun org-at-heading-p (&optional ignored)
  21753. (outline-on-heading-p t))
  21754. (defun org-in-commented-heading-p (&optional no-inheritance)
  21755. "Non-nil if point is under a commented heading.
  21756. This function also checks ancestors of the current headline,
  21757. unless optional argument NO-INHERITANCE is non-nil."
  21758. (cond
  21759. ((org-before-first-heading-p) nil)
  21760. ((let ((headline (nth 4 (org-heading-components))))
  21761. (and headline
  21762. (let ((case-fold-search nil))
  21763. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21764. headline)))))
  21765. (no-inheritance nil)
  21766. (t
  21767. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21768. (defun org-at-comment-p nil
  21769. "Is cursor in a commented line?"
  21770. (save-excursion
  21771. (save-match-data
  21772. (beginning-of-line)
  21773. (looking-at "^[ \t]*# "))))
  21774. (defun org-at-drawer-p nil
  21775. "Is cursor at a drawer keyword?"
  21776. (save-excursion
  21777. (move-beginning-of-line 1)
  21778. (looking-at org-drawer-regexp)))
  21779. (defun org-at-block-p nil
  21780. "Is cursor at a block keyword?"
  21781. (save-excursion
  21782. (move-beginning-of-line 1)
  21783. (looking-at org-block-regexp)))
  21784. (defun org-point-at-end-of-empty-headline ()
  21785. "If point is at the end of an empty headline, return t, else nil.
  21786. If the heading only contains a TODO keyword, it is still still considered
  21787. empty."
  21788. (let ((case-fold-search nil))
  21789. (and (looking-at "[ \t]*$")
  21790. org-todo-line-regexp
  21791. (save-excursion
  21792. (beginning-of-line)
  21793. (looking-at org-todo-line-regexp)
  21794. (string= (match-string 3) "")))))
  21795. (defun org-at-heading-or-item-p ()
  21796. (or (org-at-heading-p) (org-at-item-p)))
  21797. (defun org-at-target-p ()
  21798. (or (org-in-regexp org-radio-target-regexp)
  21799. (org-in-regexp org-target-regexp)))
  21800. ;; Compatibility alias with Org versions < 7.8.03
  21801. (defalias 'org-on-target-p 'org-at-target-p)
  21802. (defun org-up-heading-all (arg)
  21803. "Move to the heading line of which the present line is a subheading.
  21804. This function considers both visible and invisible heading lines.
  21805. With argument, move up ARG levels."
  21806. (outline-up-heading arg t))
  21807. (defun org-up-heading-safe ()
  21808. "Move to the heading line of which the present line is a subheading.
  21809. This version will not throw an error. It will return the level of the
  21810. headline found, or nil if no higher level is found.
  21811. Also, this function will be a lot faster than `outline-up-heading',
  21812. because it relies on stars being the outline starters. This can really
  21813. make a significant difference in outlines with very many siblings."
  21814. (when (ignore-errors (org-back-to-heading t))
  21815. (let ((level-up (1- (funcall outline-level))))
  21816. (and (> level-up 0)
  21817. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21818. (funcall outline-level)))))
  21819. (defun org-first-sibling-p ()
  21820. "Is this heading the first child of its parents?"
  21821. (interactive)
  21822. (let ((re org-outline-regexp-bol)
  21823. level l)
  21824. (unless (org-at-heading-p t)
  21825. (user-error "Not at a heading"))
  21826. (setq level (funcall outline-level))
  21827. (save-excursion
  21828. (if (not (re-search-backward re nil t))
  21829. t
  21830. (setq l (funcall outline-level))
  21831. (< l level)))))
  21832. (defun org-goto-sibling (&optional previous)
  21833. "Goto the next sibling, even if it is invisible.
  21834. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21835. when a sibling was found. When none is found, return nil and don't
  21836. move point."
  21837. (let ((fun (if previous 're-search-backward 're-search-forward))
  21838. (pos (point))
  21839. (re org-outline-regexp-bol)
  21840. level l)
  21841. (when (ignore-errors (org-back-to-heading t))
  21842. (setq level (funcall outline-level))
  21843. (catch 'exit
  21844. (or previous (forward-char 1))
  21845. (while (funcall fun re nil t)
  21846. (setq l (funcall outline-level))
  21847. (when (< l level) (goto-char pos) (throw 'exit nil))
  21848. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21849. (goto-char pos)
  21850. nil))))
  21851. (defun org-show-siblings ()
  21852. "Show all siblings of the current headline."
  21853. (save-excursion
  21854. (while (org-goto-sibling) (org-flag-heading nil)))
  21855. (save-excursion
  21856. (while (org-goto-sibling 'previous)
  21857. (org-flag-heading nil))))
  21858. (defun org-goto-first-child ()
  21859. "Goto the first child, even if it is invisible.
  21860. Return t when a child was found. Otherwise don't move point and
  21861. return nil."
  21862. (let (level (pos (point)) (re org-outline-regexp-bol))
  21863. (when (ignore-errors (org-back-to-heading t))
  21864. (setq level (outline-level))
  21865. (forward-char 1)
  21866. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21867. (progn (goto-char (match-beginning 0)) t)
  21868. (goto-char pos) nil))))
  21869. (defun org-show-hidden-entry ()
  21870. "Show an entry where even the heading is hidden."
  21871. (save-excursion
  21872. (org-show-entry)))
  21873. (defun org-flag-heading (flag &optional entry)
  21874. "Flag the current heading. FLAG non-nil means make invisible.
  21875. When ENTRY is non-nil, show the entire entry."
  21876. (save-excursion
  21877. (org-back-to-heading t)
  21878. ;; Check if we should show the entire entry
  21879. (if entry
  21880. (progn
  21881. (org-show-entry)
  21882. (save-excursion
  21883. (and (outline-next-heading)
  21884. (org-flag-heading nil))))
  21885. (outline-flag-region (max (point-min) (1- (point)))
  21886. (save-excursion (outline-end-of-heading) (point))
  21887. flag))))
  21888. (defun org-get-next-sibling ()
  21889. "Move to next heading of the same level, and return point.
  21890. If there is no such heading, return nil.
  21891. This is like outline-next-sibling, but invisible headings are ok."
  21892. (let ((level (funcall outline-level)))
  21893. (outline-next-heading)
  21894. (while (and (not (eobp)) (> (funcall outline-level) level))
  21895. (outline-next-heading))
  21896. (unless (or (eobp) (< (funcall outline-level) level))
  21897. (point))))
  21898. (defun org-get-last-sibling ()
  21899. "Move to previous heading of the same level, and return point.
  21900. If there is no such heading, return nil."
  21901. (let ((opoint (point))
  21902. (level (funcall outline-level)))
  21903. (outline-previous-heading)
  21904. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21905. (while (and (> (funcall outline-level) level)
  21906. (not (bobp)))
  21907. (outline-previous-heading))
  21908. (unless (< (funcall outline-level) level)
  21909. (point)))))
  21910. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21911. "Goto to the end of a subtree."
  21912. ;; This contains an exact copy of the original function, but it uses
  21913. ;; `org-back-to-heading', to make it work also in invisible
  21914. ;; trees. And is uses an invisible-ok argument.
  21915. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21916. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21917. ;; with many children and grandchildren etc, this can be much faster
  21918. ;; than the outline version.
  21919. (org-back-to-heading invisible-ok)
  21920. (let ((first t)
  21921. (level (funcall outline-level)))
  21922. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21923. ;; A true heading (not a plain list item), in Org
  21924. ;; This means we can easily find the end by looking
  21925. ;; only for the right number of stars. Using a regexp to do
  21926. ;; this is so much faster than using a Lisp loop.
  21927. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21928. (forward-char 1)
  21929. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21930. ;; something else, do it the slow way
  21931. (while (and (not (eobp))
  21932. (or first (> (funcall outline-level) level)))
  21933. (setq first nil)
  21934. (outline-next-heading)))
  21935. (unless to-heading
  21936. (when (memq (preceding-char) '(?\n ?\^M))
  21937. ;; Go to end of line before heading
  21938. (forward-char -1)
  21939. (when (memq (preceding-char) '(?\n ?\^M))
  21940. ;; leave blank line before heading
  21941. (forward-char -1)))))
  21942. (point))
  21943. (defun org-end-of-meta-data (&optional full)
  21944. "Skip planning line and properties drawer in current entry.
  21945. When optional argument FULL is non-nil, also skip empty lines,
  21946. clocking lines and regular drawers at the beginning of the
  21947. entry."
  21948. (org-back-to-heading t)
  21949. (forward-line)
  21950. (when (looking-at-p org-planning-line-re) (forward-line))
  21951. (when (looking-at org-property-drawer-re)
  21952. (goto-char (match-end 0))
  21953. (forward-line))
  21954. (when (and full (not (org-at-heading-p)))
  21955. (catch 'exit
  21956. (let ((end (save-excursion (outline-next-heading) (point)))
  21957. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21958. (while (not (eobp))
  21959. (cond ((looking-at-p org-drawer-regexp)
  21960. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21961. (forward-line)
  21962. (throw 'exit t)))
  21963. ((looking-at-p re) (forward-line))
  21964. (t (throw 'exit t))))))))
  21965. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21966. "Move forward to the ARG'th subheading at same level as this one.
  21967. Stop at the first and last subheadings of a superior heading.
  21968. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21969. non-nil it will also look at invisible ones."
  21970. (interactive "p")
  21971. (let ((backward? (and arg (< arg 0))))
  21972. (if (org-before-first-heading-p)
  21973. (if backward? (goto-char (point-min)) (outline-next-heading))
  21974. (org-back-to-heading invisible-ok)
  21975. (unless backward? (end-of-line)) ;do not match current headline
  21976. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21977. (f (if backward? #'re-search-backward #'re-search-forward))
  21978. (count (if arg (abs arg) 1))
  21979. (result (point)))
  21980. (while (and (> count 0)
  21981. (funcall f org-outline-regexp-bol nil 'move))
  21982. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21983. (cond ((< l level) (setq count 0))
  21984. ((and (= l level)
  21985. (or invisible-ok
  21986. (not (org-invisible-p
  21987. (line-beginning-position)))))
  21988. (cl-decf count)
  21989. (when (= l level) (setq result (point)))))))
  21990. (goto-char result))
  21991. (beginning-of-line))))
  21992. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21993. "Move backward to the ARG'th subheading at same level as this one.
  21994. Stop at the first and last subheadings of a superior heading."
  21995. (interactive "p")
  21996. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21997. (defun org-next-visible-heading (arg)
  21998. "Move to the next visible heading.
  21999. This function wraps `outline-next-visible-heading' with
  22000. `org-with-limited-levels' in order to skip over inline tasks and
  22001. respect customization of `org-odd-levels-only'."
  22002. (interactive "p")
  22003. (org-with-limited-levels
  22004. (outline-next-visible-heading arg)))
  22005. (defun org-previous-visible-heading (arg)
  22006. "Move to the previous visible heading.
  22007. This function wraps `outline-previous-visible-heading' with
  22008. `org-with-limited-levels' in order to skip over inline tasks and
  22009. respect customization of `org-odd-levels-only'."
  22010. (interactive "p")
  22011. (org-with-limited-levels
  22012. (outline-previous-visible-heading arg)))
  22013. (defun org-next-block (arg &optional backward block-regexp)
  22014. "Jump to the next block.
  22015. With a prefix argument ARG, jump forward ARG many blocks.
  22016. When BACKWARD is non-nil, jump to the previous block.
  22017. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22018. Match data is set according to this regexp when the function
  22019. returns.
  22020. Return point at beginning of the opening line of found block.
  22021. Throw an error if no block is found."
  22022. (interactive "p")
  22023. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22024. (case-fold-search t)
  22025. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22026. (count (or arg 1))
  22027. (origin (point))
  22028. last-element)
  22029. (if backward (beginning-of-line) (end-of-line))
  22030. (while (and (> count 0) (funcall search-fn re nil t))
  22031. (let ((element (save-excursion
  22032. (goto-char (match-beginning 0))
  22033. (save-match-data (org-element-at-point)))))
  22034. (when (and (memq (org-element-type element)
  22035. '(center-block comment-block dynamic-block
  22036. example-block export-block quote-block
  22037. special-block src-block verse-block))
  22038. (<= (match-beginning 0)
  22039. (org-element-property :post-affiliated element)))
  22040. (setq last-element element)
  22041. (cl-decf count))))
  22042. (if (= count 0)
  22043. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22044. (save-match-data (org-show-context)))
  22045. (goto-char origin)
  22046. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22047. (defun org-previous-block (arg &optional block-regexp)
  22048. "Jump to the previous block.
  22049. With a prefix argument ARG, jump backward ARG many source blocks.
  22050. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22051. (interactive "p")
  22052. (org-next-block arg t block-regexp))
  22053. (defun org-forward-paragraph ()
  22054. "Move forward to beginning of next paragraph or equivalent.
  22055. The function moves point to the beginning of the next visible
  22056. structural element, which can be a paragraph, a table, a list
  22057. item, etc. It also provides some special moves for convenience:
  22058. - On an affiliated keyword, jump to the beginning of the
  22059. relative element.
  22060. - On an item or a footnote definition, move to the second
  22061. element inside, if any.
  22062. - On a table or a property drawer, jump after it.
  22063. - On a verse or source block, stop after blank lines."
  22064. (interactive)
  22065. (unless (eobp)
  22066. (let* ((deactivate-mark nil)
  22067. (element (org-element-at-point))
  22068. (type (org-element-type element))
  22069. (post-affiliated (org-element-property :post-affiliated element))
  22070. (contents-begin (org-element-property :contents-begin element))
  22071. (contents-end (org-element-property :contents-end element))
  22072. (end (let ((end (org-element-property :end element)) (parent element))
  22073. (while (and (setq parent (org-element-property :parent parent))
  22074. (= (org-element-property :contents-end parent) end))
  22075. (setq end (org-element-property :end parent)))
  22076. end)))
  22077. (cond ((not element)
  22078. (skip-chars-forward " \r\t\n")
  22079. (or (eobp) (beginning-of-line)))
  22080. ;; On affiliated keywords, move to element's beginning.
  22081. ((< (point) post-affiliated)
  22082. (goto-char post-affiliated))
  22083. ;; At a table row, move to the end of the table. Similarly,
  22084. ;; at a node property, move to the end of the property
  22085. ;; drawer.
  22086. ((memq type '(node-property table-row))
  22087. (goto-char (org-element-property
  22088. :end (org-element-property :parent element))))
  22089. ((memq type '(property-drawer table)) (goto-char end))
  22090. ;; Consider blank lines as separators in verse and source
  22091. ;; blocks to ease editing.
  22092. ((memq type '(src-block verse-block))
  22093. (when (eq type 'src-block)
  22094. (setq contents-end
  22095. (save-excursion (goto-char end)
  22096. (skip-chars-backward " \r\t\n")
  22097. (line-beginning-position))))
  22098. (beginning-of-line)
  22099. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22100. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22101. (goto-char end)
  22102. (skip-chars-forward " \r\t\n")
  22103. (if (= (point) contents-end) (goto-char end)
  22104. (beginning-of-line))))
  22105. ;; With no contents, just skip element.
  22106. ((not contents-begin) (goto-char end))
  22107. ;; If contents are invisible, skip the element altogether.
  22108. ((org-invisible-p (line-end-position))
  22109. (cl-case type
  22110. (headline
  22111. (org-with-limited-levels (outline-next-visible-heading 1)))
  22112. ;; At a plain list, make sure we move to the next item
  22113. ;; instead of skipping the whole list.
  22114. (plain-list (forward-char)
  22115. (org-forward-paragraph))
  22116. (otherwise (goto-char end))))
  22117. ((>= (point) contents-end) (goto-char end))
  22118. ((>= (point) contents-begin)
  22119. ;; This can only happen on paragraphs and plain lists.
  22120. (cl-case type
  22121. (paragraph (goto-char end))
  22122. ;; At a plain list, try to move to second element in
  22123. ;; first item, if possible.
  22124. (plain-list (end-of-line)
  22125. (org-forward-paragraph))))
  22126. ;; When contents start on the middle of a line (e.g. in
  22127. ;; items and footnote definitions), try to reach first
  22128. ;; element starting after current line.
  22129. ((> (line-end-position) contents-begin)
  22130. (end-of-line)
  22131. (org-forward-paragraph))
  22132. (t (goto-char contents-begin))))))
  22133. (defun org-backward-paragraph ()
  22134. "Move backward to start of previous paragraph or equivalent.
  22135. The function moves point to the beginning of the current
  22136. structural element, which can be a paragraph, a table, a list
  22137. item, etc., or to the beginning of the previous visible one if
  22138. point is already there. It also provides some special moves for
  22139. convenience:
  22140. - On an affiliated keyword, jump to the first one.
  22141. - On a table or a property drawer, move to its beginning.
  22142. - On comment, example, export, src and verse blocks, stop
  22143. before blank lines."
  22144. (interactive)
  22145. (unless (bobp)
  22146. (let* ((deactivate-mark nil)
  22147. (element (org-element-at-point))
  22148. (type (org-element-type element))
  22149. (contents-end (org-element-property :contents-end element))
  22150. (post-affiliated (org-element-property :post-affiliated element))
  22151. (begin (org-element-property :begin element))
  22152. (special? ;blocks handled specially
  22153. (memq type '(comment-block example-block export-block src-block
  22154. verse-block)))
  22155. (contents-begin
  22156. (if special?
  22157. ;; These types have no proper contents. Fake line
  22158. ;; below the block opening line as contents beginning.
  22159. (save-excursion (goto-char begin) (line-beginning-position 2))
  22160. (org-element-property :contents-begin element))))
  22161. (cond
  22162. ((not element) (goto-char (point-min)))
  22163. ((= (point) begin)
  22164. (backward-char)
  22165. (org-backward-paragraph))
  22166. ((<= (point) post-affiliated) (goto-char begin))
  22167. ;; Special behavior: on a table or a property drawer, move to
  22168. ;; its beginning.
  22169. ((memq type '(node-property table-row))
  22170. (goto-char (org-element-property
  22171. :post-affiliated (org-element-property :parent element))))
  22172. (special?
  22173. (if (<= (point) contents-begin) (goto-char post-affiliated)
  22174. ;; Inside a verse block, see blank lines as paragraph
  22175. ;; separators.
  22176. (let ((origin (point)))
  22177. (skip-chars-backward " \r\t\n" contents-begin)
  22178. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22179. (skip-chars-forward " \r\t\n" origin)
  22180. (if (= (point) origin) (goto-char contents-begin)
  22181. (beginning-of-line))))))
  22182. ((eq type 'paragraph) (goto-char contents-begin)
  22183. ;; When at first paragraph in an item or a footnote definition,
  22184. ;; move directly to beginning of line.
  22185. (let ((parent-contents
  22186. (org-element-property
  22187. :contents-begin (org-element-property :parent element))))
  22188. (when (and parent-contents (= parent-contents contents-begin))
  22189. (beginning-of-line))))
  22190. ;; At the end of a greater element, move to the beginning of
  22191. ;; the last element within.
  22192. ((and contents-end (>= (point) contents-end))
  22193. (goto-char (1- contents-end))
  22194. (org-backward-paragraph))
  22195. (t (goto-char (or post-affiliated begin))))
  22196. ;; Ensure we never leave point invisible.
  22197. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  22198. (defun org-forward-element ()
  22199. "Move forward by one element.
  22200. Move to the next element at the same level, when possible."
  22201. (interactive)
  22202. (cond ((eobp) (user-error "Cannot move further down"))
  22203. ((org-with-limited-levels (org-at-heading-p))
  22204. (let ((origin (point)))
  22205. (goto-char (org-end-of-subtree nil t))
  22206. (unless (org-with-limited-levels (org-at-heading-p))
  22207. (goto-char origin)
  22208. (user-error "Cannot move further down"))))
  22209. (t
  22210. (let* ((elem (org-element-at-point))
  22211. (end (org-element-property :end elem))
  22212. (parent (org-element-property :parent elem)))
  22213. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22214. (goto-char (org-element-property :end parent)))
  22215. ((integer-or-marker-p end) (goto-char end))
  22216. (t (message "No element at point")))))))
  22217. (defun org-backward-element ()
  22218. "Move backward by one element.
  22219. Move to the previous element at the same level, when possible."
  22220. (interactive)
  22221. (cond ((bobp) (user-error "Cannot move further up"))
  22222. ((org-with-limited-levels (org-at-heading-p))
  22223. ;; At a headline, move to the previous one, if any, or stay
  22224. ;; here.
  22225. (let ((origin (point)))
  22226. (org-with-limited-levels (org-backward-heading-same-level 1))
  22227. ;; When current headline has no sibling above, move to its
  22228. ;; parent.
  22229. (when (= (point) origin)
  22230. (or (org-with-limited-levels (org-up-heading-safe))
  22231. (progn (goto-char origin)
  22232. (user-error "Cannot move further up"))))))
  22233. (t
  22234. (let* ((elem (org-element-at-point))
  22235. (beg (org-element-property :begin elem)))
  22236. (cond
  22237. ;; Move to beginning of current element if point isn't
  22238. ;; there already.
  22239. ((null beg) (message "No element at point"))
  22240. ((/= (point) beg) (goto-char beg))
  22241. (t (goto-char beg)
  22242. (skip-chars-backward " \r\t\n")
  22243. (unless (bobp)
  22244. (let ((prev (org-element-at-point)))
  22245. (goto-char (org-element-property :begin prev))
  22246. (while (and (setq prev (org-element-property :parent prev))
  22247. (<= (org-element-property :end prev) beg))
  22248. (goto-char (org-element-property :begin prev)))))))))))
  22249. (defun org-up-element ()
  22250. "Move to upper element."
  22251. (interactive)
  22252. (if (org-with-limited-levels (org-at-heading-p))
  22253. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22254. (let* ((elem (org-element-at-point))
  22255. (parent (org-element-property :parent elem)))
  22256. (if parent (goto-char (org-element-property :begin parent))
  22257. (if (org-with-limited-levels (org-before-first-heading-p))
  22258. (user-error "No surrounding element")
  22259. (org-with-limited-levels (org-back-to-heading)))))))
  22260. (defun org-down-element ()
  22261. "Move to inner element."
  22262. (interactive)
  22263. (let ((element (org-element-at-point)))
  22264. (cond
  22265. ((memq (org-element-type element) '(plain-list table))
  22266. (goto-char (org-element-property :contents-begin element))
  22267. (forward-char))
  22268. ((memq (org-element-type element) org-element-greater-elements)
  22269. ;; If contents are hidden, first disclose them.
  22270. (when (org-invisible-p (line-end-position)) (org-cycle))
  22271. (goto-char (or (org-element-property :contents-begin element)
  22272. (user-error "No content for this element"))))
  22273. (t (user-error "No inner element")))))
  22274. (defun org-drag-element-backward ()
  22275. "Move backward element at point."
  22276. (interactive)
  22277. (let ((elem (or (org-element-at-point)
  22278. (user-error "No element at point"))))
  22279. (if (eq (org-element-type elem) 'headline)
  22280. ;; Preserve point when moving a whole tree, even if point was
  22281. ;; on blank lines below the headline.
  22282. (let ((offset (skip-chars-backward " \t\n")))
  22283. (unwind-protect (org-move-subtree-up)
  22284. (forward-char (- offset))))
  22285. (let ((prev-elem
  22286. (save-excursion
  22287. (goto-char (org-element-property :begin elem))
  22288. (skip-chars-backward " \r\t\n")
  22289. (unless (bobp)
  22290. (let* ((beg (org-element-property :begin elem))
  22291. (prev (org-element-at-point))
  22292. (up prev))
  22293. (while (and (setq up (org-element-property :parent up))
  22294. (<= (org-element-property :end up) beg))
  22295. (setq prev up))
  22296. prev)))))
  22297. ;; Error out if no previous element or previous element is
  22298. ;; a parent of the current one.
  22299. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22300. (user-error "Cannot drag element backward")
  22301. (let ((pos (point)))
  22302. (org-element-swap-A-B prev-elem elem)
  22303. (goto-char (+ (org-element-property :begin prev-elem)
  22304. (- pos (org-element-property :begin elem))))))))))
  22305. (defun org-drag-element-forward ()
  22306. "Move forward element at point."
  22307. (interactive)
  22308. (let* ((pos (point))
  22309. (elem (or (org-element-at-point)
  22310. (user-error "No element at point"))))
  22311. (when (= (point-max) (org-element-property :end elem))
  22312. (user-error "Cannot drag element forward"))
  22313. (goto-char (org-element-property :end elem))
  22314. (let ((next-elem (org-element-at-point)))
  22315. (when (or (org-element-nested-p elem next-elem)
  22316. (and (eq (org-element-type next-elem) 'headline)
  22317. (not (eq (org-element-type elem) 'headline))))
  22318. (goto-char pos)
  22319. (user-error "Cannot drag element forward"))
  22320. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22321. ;; body's length (without final blanks) and by the length of
  22322. ;; blanks between ELEM and NEXT-ELEM.
  22323. (let ((size-next (- (save-excursion
  22324. (goto-char (org-element-property :end next-elem))
  22325. (skip-chars-backward " \r\t\n")
  22326. (forward-line)
  22327. ;; Small correction if buffer doesn't end
  22328. ;; with a newline character.
  22329. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22330. (org-element-property :begin next-elem)))
  22331. (size-blank (- (org-element-property :end elem)
  22332. (save-excursion
  22333. (goto-char (org-element-property :end elem))
  22334. (skip-chars-backward " \r\t\n")
  22335. (forward-line)
  22336. (point)))))
  22337. (org-element-swap-A-B elem next-elem)
  22338. (goto-char (+ pos size-next size-blank))))))
  22339. (defun org-drag-line-forward (arg)
  22340. "Drag the line at point ARG lines forward."
  22341. (interactive "p")
  22342. (dotimes (_ (abs arg))
  22343. (let ((c (current-column)))
  22344. (if (< 0 arg)
  22345. (progn
  22346. (beginning-of-line 2)
  22347. (transpose-lines 1)
  22348. (beginning-of-line 0))
  22349. (transpose-lines 1)
  22350. (beginning-of-line -1))
  22351. (org-move-to-column c))))
  22352. (defun org-drag-line-backward (arg)
  22353. "Drag the line at point ARG lines backward."
  22354. (interactive "p")
  22355. (org-drag-line-forward (- arg)))
  22356. (defun org-mark-element ()
  22357. "Put point at beginning of this element, mark at end.
  22358. Interactively, if this command is repeated or (in Transient Mark
  22359. mode) if the mark is active, it marks the next element after the
  22360. ones already marked."
  22361. (interactive)
  22362. (let (deactivate-mark)
  22363. (if (and (called-interactively-p 'any)
  22364. (or (and (eq last-command this-command) (mark t))
  22365. (and transient-mark-mode mark-active)))
  22366. (set-mark
  22367. (save-excursion
  22368. (goto-char (mark))
  22369. (goto-char (org-element-property :end (org-element-at-point)))))
  22370. (let ((element (org-element-at-point)))
  22371. (end-of-line)
  22372. (push-mark (org-element-property :end element) t t)
  22373. (goto-char (org-element-property :begin element))))))
  22374. (defun org-narrow-to-element ()
  22375. "Narrow buffer to current element."
  22376. (interactive)
  22377. (let ((elem (org-element-at-point)))
  22378. (cond
  22379. ((eq (car elem) 'headline)
  22380. (narrow-to-region
  22381. (org-element-property :begin elem)
  22382. (org-element-property :end elem)))
  22383. ((memq (car elem) org-element-greater-elements)
  22384. (narrow-to-region
  22385. (org-element-property :contents-begin elem)
  22386. (org-element-property :contents-end elem)))
  22387. (t
  22388. (narrow-to-region
  22389. (org-element-property :begin elem)
  22390. (org-element-property :end elem))))))
  22391. (defun org-transpose-element ()
  22392. "Transpose current and previous elements, keeping blank lines between.
  22393. Point is moved after both elements."
  22394. (interactive)
  22395. (org-skip-whitespace)
  22396. (let ((end (org-element-property :end (org-element-at-point))))
  22397. (org-drag-element-backward)
  22398. (goto-char end)))
  22399. (defun org-unindent-buffer ()
  22400. "Un-indent the visible part of the buffer.
  22401. Relative indentation (between items, inside blocks, etc.) isn't
  22402. modified."
  22403. (interactive)
  22404. (unless (eq major-mode 'org-mode)
  22405. (user-error "Cannot un-indent a buffer not in Org mode"))
  22406. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22407. (unindent-tree
  22408. (lambda (contents)
  22409. (dolist (element (reverse contents))
  22410. (if (memq (org-element-type element) '(headline section))
  22411. (funcall unindent-tree (org-element-contents element))
  22412. (save-excursion
  22413. (save-restriction
  22414. (narrow-to-region
  22415. (org-element-property :begin element)
  22416. (org-element-property :end element))
  22417. (org-do-remove-indentation))))))))
  22418. (funcall unindent-tree (org-element-contents parse-tree))))
  22419. (defun org-show-children (&optional level)
  22420. "Show all direct subheadings of this heading.
  22421. Prefix arg LEVEL is how many levels below the current level
  22422. should be shown. Default is enough to cause the following
  22423. heading to appear."
  22424. (interactive "p")
  22425. ;; If `orgstruct-mode' is active, use the slower version.
  22426. (if orgstruct-mode (call-interactively #'outline-show-children)
  22427. (save-excursion
  22428. (org-back-to-heading t)
  22429. (let* ((current-level (funcall outline-level))
  22430. (max-level (org-get-valid-level
  22431. current-level
  22432. (if level (prefix-numeric-value level) 1)))
  22433. (end (save-excursion (org-end-of-subtree t t)))
  22434. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22435. (past-first-child nil)
  22436. ;; Make sure to skip inlinetasks.
  22437. (re (format regexp-fmt
  22438. current-level
  22439. (cond
  22440. ((not (featurep 'org-inlinetask)) "")
  22441. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22442. 3))
  22443. (t (1- org-inlinetask-min-level))))))
  22444. ;; Display parent heading.
  22445. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22446. (forward-line)
  22447. ;; Display children. First child may be deeper than expected
  22448. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22449. ;; MAX-LEVEL accordingly.
  22450. (while (re-search-forward re end t)
  22451. (unless past-first-child
  22452. (setq re (format regexp-fmt
  22453. current-level
  22454. (max (funcall outline-level) max-level)))
  22455. (setq past-first-child t))
  22456. (outline-flag-region
  22457. (line-end-position 0) (line-end-position) nil))))))
  22458. (defun org-show-subtree ()
  22459. "Show everything after this heading at deeper levels."
  22460. (interactive)
  22461. (outline-flag-region
  22462. (point)
  22463. (save-excursion
  22464. (org-end-of-subtree t t))
  22465. nil))
  22466. (defun org-show-entry ()
  22467. "Show the body directly following this heading.
  22468. Show the heading too, if it is currently invisible."
  22469. (interactive)
  22470. (save-excursion
  22471. (ignore-errors
  22472. (org-back-to-heading t)
  22473. (outline-flag-region
  22474. (max (point-min) (1- (point)))
  22475. (save-excursion
  22476. (if (re-search-forward
  22477. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22478. (match-beginning 1)
  22479. (point-max)))
  22480. nil)
  22481. (org-cycle-hide-drawers 'children))))
  22482. (defun org-make-options-regexp (kwds &optional extra)
  22483. "Make a regular expression for keyword lines.
  22484. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22485. when non-nil, is a regexp matching keywords names."
  22486. (concat "^[ \t]*#\\+\\("
  22487. (regexp-opt kwds)
  22488. (and extra (concat (and kwds "\\|") extra))
  22489. "\\):[ \t]*\\(.*\\)"))
  22490. ;;;; Integration with and fixes for other packages
  22491. ;;; Imenu support
  22492. (defvar-local org-imenu-markers nil
  22493. "All markers currently used by Imenu.")
  22494. (defun org-imenu-new-marker (&optional pos)
  22495. "Return a new marker for use by Imenu, and remember the marker."
  22496. (let ((m (make-marker)))
  22497. (move-marker m (or pos (point)))
  22498. (push m org-imenu-markers)
  22499. m))
  22500. (defun org-imenu-get-tree ()
  22501. "Produce the index for Imenu."
  22502. (dolist (x org-imenu-markers) (move-marker x nil))
  22503. (setq org-imenu-markers nil)
  22504. (let* ((case-fold-search nil)
  22505. (n org-imenu-depth)
  22506. (re (concat "^" (org-get-limited-outline-regexp)))
  22507. (subs (make-vector (1+ n) nil))
  22508. (last-level 0)
  22509. m level head0 head)
  22510. (org-with-wide-buffer
  22511. (goto-char (point-max))
  22512. (while (re-search-backward re nil t)
  22513. (setq level (org-reduced-level (funcall outline-level)))
  22514. (when (and (<= level n)
  22515. (looking-at org-complex-heading-regexp)
  22516. (setq head0 (match-string-no-properties 4)))
  22517. (setq head (org-link-display-format head0)
  22518. m (org-imenu-new-marker))
  22519. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22520. (if (>= level last-level)
  22521. (push (cons head m) (aref subs level))
  22522. (push (cons head (aref subs (1+ level))) (aref subs level))
  22523. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22524. (setq last-level level))))
  22525. (aref subs 1)))
  22526. (eval-after-load "imenu"
  22527. '(progn
  22528. (add-hook 'imenu-after-jump-hook
  22529. (lambda ()
  22530. (when (derived-mode-p 'org-mode)
  22531. (org-show-context 'org-goto))))))
  22532. (defun org-link-display-format (s)
  22533. "Replace links in string S with their description.
  22534. If there is no description, use the link target."
  22535. (save-match-data
  22536. (replace-regexp-in-string
  22537. org-bracket-link-analytic-regexp
  22538. (lambda (m)
  22539. (if (match-end 5) (match-string 5 m)
  22540. (concat (match-string 1 m) (match-string 3 m))))
  22541. s nil t)))
  22542. (defun org-toggle-link-display ()
  22543. "Toggle the literal or descriptive display of links."
  22544. (interactive)
  22545. (if org-descriptive-links
  22546. (progn (org-remove-from-invisibility-spec '(org-link))
  22547. (org-restart-font-lock)
  22548. (setq org-descriptive-links nil))
  22549. (progn (add-to-invisibility-spec '(org-link))
  22550. (org-restart-font-lock)
  22551. (setq org-descriptive-links t))))
  22552. ;; Speedbar support
  22553. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22554. "Overlay marking the agenda restriction line in speedbar.")
  22555. (overlay-put org-speedbar-restriction-lock-overlay
  22556. 'face 'org-agenda-restriction-lock)
  22557. (overlay-put org-speedbar-restriction-lock-overlay
  22558. 'help-echo "Agendas are currently limited to this item.")
  22559. (delete-overlay org-speedbar-restriction-lock-overlay)
  22560. (defun org-speedbar-set-agenda-restriction ()
  22561. "Restrict future agenda commands to the location at point in speedbar.
  22562. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22563. (interactive)
  22564. (require 'org-agenda)
  22565. (let (p m tp np dir txt)
  22566. (cond
  22567. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22568. 'org-imenu t))
  22569. (setq m (get-text-property p 'org-imenu-marker))
  22570. (with-current-buffer (marker-buffer m)
  22571. (goto-char m)
  22572. (org-agenda-set-restriction-lock 'subtree)))
  22573. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22574. 'speedbar-function 'speedbar-find-file))
  22575. (setq tp (previous-single-property-change
  22576. (1+ p) 'speedbar-function)
  22577. np (next-single-property-change
  22578. tp 'speedbar-function)
  22579. dir (speedbar-line-directory)
  22580. txt (buffer-substring-no-properties (or tp (point-min))
  22581. (or np (point-max))))
  22582. (with-current-buffer (find-file-noselect
  22583. (let ((default-directory dir))
  22584. (expand-file-name txt)))
  22585. (unless (derived-mode-p 'org-mode)
  22586. (user-error "Cannot restrict to non-Org mode file"))
  22587. (org-agenda-set-restriction-lock 'file)))
  22588. (t (user-error "Don't know how to restrict Org mode agenda")))
  22589. (move-overlay org-speedbar-restriction-lock-overlay
  22590. (point-at-bol) (point-at-eol))
  22591. (setq current-prefix-arg nil)
  22592. (org-agenda-maybe-redo)))
  22593. (defvar speedbar-file-key-map)
  22594. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22595. (eval-after-load "speedbar"
  22596. '(progn
  22597. (speedbar-add-supported-extension ".org")
  22598. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22599. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22600. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22601. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22602. (add-hook 'speedbar-visiting-tag-hook
  22603. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22604. ;;; Fixes and Hacks for problems with other packages
  22605. (defun org--flyspell-object-check-p (element)
  22606. "Non-nil when Flyspell can check object at point.
  22607. ELEMENT is the element at point."
  22608. (let ((object (save-excursion
  22609. (when (looking-at-p "\\>") (backward-char))
  22610. (org-element-context element))))
  22611. (cl-case (org-element-type object)
  22612. ;; Prevent checks in links due to keybinding conflict with
  22613. ;; Flyspell.
  22614. ((code entity export-snippet inline-babel-call
  22615. inline-src-block line-break latex-fragment link macro
  22616. statistics-cookie target timestamp verbatim)
  22617. nil)
  22618. (footnote-reference
  22619. ;; Only in inline footnotes, within the definition.
  22620. (and (eq (org-element-property :type object) 'inline)
  22621. (< (save-excursion
  22622. (goto-char (org-element-property :begin object))
  22623. (search-forward ":" nil t 2))
  22624. (point))))
  22625. (otherwise t))))
  22626. (defun org-mode-flyspell-verify ()
  22627. "Function used for `flyspell-generic-check-word-predicate'."
  22628. (if (org-at-heading-p)
  22629. ;; At a headline or an inlinetask, check title only. This is
  22630. ;; faster than relying on `org-element-at-point'.
  22631. (and (save-excursion (beginning-of-line)
  22632. (and (let ((case-fold-search t))
  22633. (not (looking-at-p "\\*+ END[ \t]*$")))
  22634. (let ((case-fold-search nil))
  22635. (looking-at org-complex-heading-regexp))))
  22636. (match-beginning 4)
  22637. (>= (point) (match-beginning 4))
  22638. (or (not (match-beginning 5))
  22639. (< (point) (match-beginning 5))))
  22640. (let* ((element (org-element-at-point))
  22641. (post-affiliated (org-element-property :post-affiliated element)))
  22642. (cond
  22643. ;; Ignore checks in all affiliated keywords but captions.
  22644. ((< (point) post-affiliated)
  22645. (and (save-excursion
  22646. (beginning-of-line)
  22647. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22648. (> (point) (match-end 0))
  22649. (org--flyspell-object-check-p element)))
  22650. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22651. ((let ((log (org-log-into-drawer)))
  22652. (and log
  22653. (let ((drawer (org-element-lineage element '(drawer))))
  22654. (and drawer
  22655. (eq (compare-strings
  22656. log nil nil
  22657. (org-element-property :drawer-name drawer) nil nil t)
  22658. t)))))
  22659. nil)
  22660. (t
  22661. (cl-case (org-element-type element)
  22662. ((comment quote-section) t)
  22663. (comment-block
  22664. ;; Allow checks between block markers, not on them.
  22665. (and (> (line-beginning-position) post-affiliated)
  22666. (save-excursion
  22667. (end-of-line)
  22668. (skip-chars-forward " \r\t\n")
  22669. (< (point) (org-element-property :end element)))))
  22670. ;; Arbitrary list of keywords where checks are meaningful.
  22671. ;; Make sure point is on the value part of the element.
  22672. (keyword
  22673. (and (member (org-element-property :key element)
  22674. '("DESCRIPTION" "TITLE"))
  22675. (save-excursion
  22676. (search-backward ":" (line-beginning-position) t))))
  22677. ;; Check is globally allowed in paragraphs verse blocks and
  22678. ;; table rows (after affiliated keywords) but some objects
  22679. ;; must not be affected.
  22680. ((paragraph table-row verse-block)
  22681. (let ((cbeg (org-element-property :contents-begin element))
  22682. (cend (org-element-property :contents-end element)))
  22683. (and cbeg (>= (point) cbeg) (< (point) cend)
  22684. (org--flyspell-object-check-p element))))))))))
  22685. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22686. (defun org-remove-flyspell-overlays-in (beg end)
  22687. "Remove flyspell overlays in region."
  22688. (and (bound-and-true-p flyspell-mode)
  22689. (fboundp 'flyspell-delete-region-overlays)
  22690. (flyspell-delete-region-overlays beg end)))
  22691. (defvar flyspell-delayed-commands)
  22692. (eval-after-load "flyspell"
  22693. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22694. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22695. (eval-after-load "bookmark"
  22696. '(if (boundp 'bookmark-after-jump-hook)
  22697. ;; We can use the hook
  22698. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22699. ;; Hook not available, use advice
  22700. (defadvice bookmark-jump (after org-make-visible activate)
  22701. "Make the position visible."
  22702. (org-bookmark-jump-unhide))))
  22703. ;; Make sure saveplace shows the location if it was hidden
  22704. (eval-after-load "saveplace"
  22705. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22706. "Make the position visible."
  22707. (org-bookmark-jump-unhide)))
  22708. ;; Make sure ecb shows the location if it was hidden
  22709. (eval-after-load "ecb"
  22710. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22711. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22712. (when (derived-mode-p 'org-mode)
  22713. (org-show-context))))
  22714. (defun org-bookmark-jump-unhide ()
  22715. "Unhide the current position, to show the bookmark location."
  22716. (and (derived-mode-p 'org-mode)
  22717. (or (org-invisible-p)
  22718. (save-excursion (goto-char (max (point-min) (1- (point))))
  22719. (org-invisible-p)))
  22720. (org-show-context 'bookmark-jump)))
  22721. (defun org-mark-jump-unhide ()
  22722. "Make the point visible with `org-show-context' after jumping to the mark."
  22723. (when (and (derived-mode-p 'org-mode)
  22724. (org-invisible-p))
  22725. (org-show-context 'mark-goto)))
  22726. (eval-after-load "simple"
  22727. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22728. "Make the point visible with `org-show-context'."
  22729. (org-mark-jump-unhide)))
  22730. (eval-after-load "simple"
  22731. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22732. "Make the point visible with `org-show-context'."
  22733. (org-mark-jump-unhide)))
  22734. (eval-after-load "simple"
  22735. '(defadvice pop-global-mark (after org-make-visible activate)
  22736. "Make the point visible with `org-show-context'."
  22737. (org-mark-jump-unhide)))
  22738. ;; Make session.el ignore our circular variable
  22739. (defvar session-globals-exclude)
  22740. (eval-after-load "session"
  22741. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22742. ;;;; Finish up
  22743. (provide 'org)
  22744. (run-hooks 'org-load-hook)
  22745. ;;; org.el ends here