org.el 941 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function
  119. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  120. (declare-function org-element-at-point "org-element" ())
  121. (declare-function org-element-cache-refresh "org-element" (pos))
  122. (declare-function org-element-cache-reset "org-element" (&optional all))
  123. (declare-function org-element-contents "org-element" (element))
  124. (declare-function org-element-context "org-element" (&optional element))
  125. (declare-function org-element-copy "org-element" (datum))
  126. (declare-function org-element-interpret-data "org-element" (data))
  127. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  128. (declare-function org-element-link-parser "org-element" ())
  129. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  130. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  131. (declare-function org-element-property "org-element" (property element))
  132. (declare-function org-element-put-property "org-element" (element property value))
  133. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  134. (declare-function org-element-type "org-element" (element))
  135. (declare-function org-element-update-syntax "org-element" ())
  136. (declare-function org-id-find-id-file "org-id" (id))
  137. (declare-function org-id-get-create "org-id" (&optional force))
  138. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  139. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  140. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  141. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  142. (declare-function org-table-align "org-table" ())
  143. (declare-function org-table-begin "org-table" (&optional table-type))
  144. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  145. (declare-function org-table-blank-field "org-table" ())
  146. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  147. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  148. (declare-function org-table-cut-region "org-table" (beg end))
  149. (declare-function org-table-edit-field "org-table" (arg))
  150. (declare-function org-table-end "org-table" (&optional table-type))
  151. (declare-function org-table-end-of-field "org-table" (&optional n))
  152. (declare-function org-table-insert-row "org-table" (&optional arg))
  153. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  154. (declare-function org-table-maybe-eval-formula "org-table" ())
  155. (declare-function org-table-maybe-recalculate-line "org-table" ())
  156. (declare-function org-table-next-row "org-table" ())
  157. (declare-function org-table-paste-rectangle "org-table" ())
  158. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  159. (declare-function
  160. org-table-sort-lines "org-table"
  161. (&optional with-case sorting-type getkey-func compare-func interactive?))
  162. (declare-function org-table-wrap-region "org-table" (arg))
  163. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  164. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  165. (declare-function orgtbl-mode "org-table" (&optional arg))
  166. (declare-function org-export-get-backend "ox" (name))
  167. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  168. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  169. (defvar ffap-url-regexp) ;Silence byte-compiler
  170. (defsubst org-uniquify (list)
  171. "Non-destructively remove duplicate elements from LIST."
  172. (let ((res (copy-sequence list))) (delete-dups res)))
  173. (defsubst org-get-at-bol (property)
  174. "Get text property PROPERTY at the beginning of line."
  175. (get-text-property (point-at-bol) property))
  176. (defsubst org-trim (s &optional keep-lead)
  177. "Remove whitespace at the beginning and the end of string S.
  178. When optional argument KEEP-LEAD is non-nil, removing blank lines
  179. at the beginning of the string does not affect leading indentation."
  180. (replace-regexp-in-string
  181. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  182. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (funcall 'fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (funcall 'fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  198. ;;;###autoload
  199. (defun org-babel-load-file (file &optional compile)
  200. "Load Emacs Lisp source code blocks in the Org FILE.
  201. This function exports the source code using `org-babel-tangle'
  202. and then loads the resulting file using `load-file'. With prefix
  203. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  204. file to byte-code before it is loaded."
  205. (interactive "fFile to load: \nP")
  206. (let* ((age (lambda (file)
  207. (float-time
  208. (time-subtract (current-time)
  209. (nth 5 (or (file-attributes (file-truename file))
  210. (file-attributes file)))))))
  211. (base-name (file-name-sans-extension file))
  212. (exported-file (concat base-name ".el")))
  213. ;; tangle if the Org file is newer than the elisp file
  214. (unless (and (file-exists-p exported-file)
  215. (> (funcall age file) (funcall age exported-file)))
  216. ;; Tangle-file traversal returns reversed list of tangled files
  217. ;; and we want to evaluate the first target.
  218. (setq exported-file
  219. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  220. (message "%s %s"
  221. (if compile
  222. (progn (byte-compile-file exported-file 'load)
  223. "Compiled and loaded")
  224. (progn (load-file exported-file) "Loaded"))
  225. exported-file)))
  226. (defcustom org-babel-load-languages '((emacs-lisp . t))
  227. "Languages which can be evaluated in Org buffers.
  228. This list can be used to load support for any of the languages
  229. below, note that each language will depend on a different set of
  230. system executables and/or Emacs modes. When a language is
  231. \"loaded\", then code blocks in that language can be evaluated
  232. with `org-babel-execute-src-block' bound by default to C-c
  233. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  234. be set to remove code block evaluation from the C-c C-c
  235. keybinding. By default only Emacs Lisp (which has no
  236. requirements) is loaded."
  237. :group 'org-babel
  238. :set 'org-babel-do-load-languages
  239. :version "24.1"
  240. :type '(alist :tag "Babel Languages"
  241. :key-type
  242. (choice
  243. (const :tag "Awk" awk)
  244. (const :tag "C" C)
  245. (const :tag "R" R)
  246. (const :tag "Asymptote" asymptote)
  247. (const :tag "Calc" calc)
  248. (const :tag "Clojure" clojure)
  249. (const :tag "CSS" css)
  250. (const :tag "Ditaa" ditaa)
  251. (const :tag "Dot" dot)
  252. (const :tag "Ebnf2ps" ebnf2ps)
  253. (const :tag "Emacs Lisp" emacs-lisp)
  254. (const :tag "Forth" forth)
  255. (const :tag "Fortran" fortran)
  256. (const :tag "Gnuplot" gnuplot)
  257. (const :tag "Haskell" haskell)
  258. (const :tag "hledger" hledger)
  259. (const :tag "IO" io)
  260. (const :tag "J" J)
  261. (const :tag "Java" java)
  262. (const :tag "Javascript" js)
  263. (const :tag "LaTeX" latex)
  264. (const :tag "Ledger" ledger)
  265. (const :tag "Lilypond" lilypond)
  266. (const :tag "Lisp" lisp)
  267. (const :tag "Makefile" makefile)
  268. (const :tag "Maxima" maxima)
  269. (const :tag "Matlab" matlab)
  270. (const :tag "Mscgen" mscgen)
  271. (const :tag "Ocaml" ocaml)
  272. (const :tag "Octave" octave)
  273. (const :tag "Org" org)
  274. (const :tag "Perl" perl)
  275. (const :tag "Pico Lisp" picolisp)
  276. (const :tag "PlantUML" plantuml)
  277. (const :tag "Python" python)
  278. (const :tag "Ruby" ruby)
  279. (const :tag "Sass" sass)
  280. (const :tag "Scala" scala)
  281. (const :tag "Scheme" scheme)
  282. (const :tag "Screen" screen)
  283. (const :tag "Shell Script" shell)
  284. (const :tag "Shen" shen)
  285. (const :tag "Sql" sql)
  286. (const :tag "Sqlite" sqlite)
  287. (const :tag "Stan" stan)
  288. (const :tag "Vala" vala))
  289. :value-type (boolean :tag "Activate" :value t)))
  290. ;;;; Customization variables
  291. (defcustom org-clone-delete-id nil
  292. "Remove ID property of clones of a subtree.
  293. When non-nil, clones of a subtree don't inherit the ID property.
  294. Otherwise they inherit the ID property with a new unique
  295. identifier."
  296. :type 'boolean
  297. :version "24.1"
  298. :group 'org-id)
  299. ;;; Version
  300. (org-check-version)
  301. ;;;###autoload
  302. (defun org-version (&optional here full message)
  303. "Show the Org version.
  304. Interactively, or when MESSAGE is non-nil, show it in echo area.
  305. With prefix argument, or when HERE is non-nil, insert it at point.
  306. In non-interactive uses, a reduced version string is output unless
  307. FULL is given."
  308. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  309. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  310. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  311. (load-suffixes (list ".el"))
  312. (org-install-dir
  313. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  314. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  315. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  316. (let* ((load-suffixes save-load-suffixes)
  317. (release (org-release))
  318. (git-version (org-git-version))
  319. (version (format "Org mode version %s (%s @ %s)"
  320. release
  321. git-version
  322. (if org-install-dir
  323. (if (string= org-dir org-install-dir)
  324. org-install-dir
  325. (concat "mixed installation! "
  326. org-install-dir
  327. " and "
  328. org-dir))
  329. "org-loaddefs.el can not be found!")))
  330. (version1 (if full version release)))
  331. (when here (insert version1))
  332. (when message (message "%s" version1))
  333. version1)))
  334. (defconst org-version (org-version))
  335. ;;; Syntax Constants
  336. ;;;; Block
  337. (defconst org-block-regexp
  338. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  339. "Regular expression for hiding blocks.")
  340. (defconst org-dblock-start-re
  341. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  342. "Matches the start line of a dynamic block, with parameters.")
  343. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  344. "Matches the end of a dynamic block.")
  345. ;;;; Clock and Planning
  346. (defconst org-clock-string "CLOCK:"
  347. "String used as prefix for timestamps clocking work hours on an item.")
  348. (defvar org-closed-string "CLOSED:"
  349. "String used as the prefix for timestamps logging closing a TODO entry.")
  350. (defvar org-deadline-string "DEADLINE:"
  351. "String to mark deadline entries.
  352. \\<org-mode-map>
  353. A deadline is this string, followed by a time stamp. It must be
  354. a word, terminated by a colon. You can insert a schedule keyword
  355. and a timestamp with `\\[org-deadline]'.")
  356. (defvar org-scheduled-string "SCHEDULED:"
  357. "String to mark scheduled TODO entries.
  358. \\<org-mode-map>
  359. A schedule is this string, followed by a time stamp. It must be
  360. a word, terminated by a colon. You can insert a schedule keyword
  361. and a timestamp with `\\[org-schedule]'.")
  362. (defconst org-ds-keyword-length
  363. (+ 2
  364. (apply #'max
  365. (mapcar #'length
  366. (list org-deadline-string org-scheduled-string
  367. org-clock-string org-closed-string))))
  368. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  369. (defconst org-planning-line-re
  370. (concat "^[ \t]*"
  371. (regexp-opt
  372. (list org-closed-string org-deadline-string org-scheduled-string)
  373. t))
  374. "Matches a line with planning info.
  375. Matched keyword is in group 1.")
  376. (defconst org-clock-line-re
  377. (concat "^[ \t]*" org-clock-string)
  378. "Matches a line with clock info.")
  379. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  380. "Matches the DEADLINE keyword.")
  381. (defconst org-deadline-time-regexp
  382. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  383. "Matches the DEADLINE keyword together with a time stamp.")
  384. (defconst org-deadline-time-hour-regexp
  385. (concat "\\<" org-deadline-string
  386. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  387. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  388. (defconst org-deadline-line-regexp
  389. (concat "\\<\\(" org-deadline-string "\\).*")
  390. "Matches the DEADLINE keyword and the rest of the line.")
  391. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  392. "Matches the SCHEDULED keyword.")
  393. (defconst org-scheduled-time-regexp
  394. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  395. "Matches the SCHEDULED keyword together with a time stamp.")
  396. (defconst org-scheduled-time-hour-regexp
  397. (concat "\\<" org-scheduled-string
  398. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  399. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  400. (defconst org-closed-time-regexp
  401. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  402. "Matches the CLOSED keyword together with a time stamp.")
  403. (defconst org-keyword-time-regexp
  404. (concat "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string
  407. org-clock-string)
  408. t)
  409. " *[[<]\\([^]>]+\\)[]>]")
  410. "Matches any of the 4 keywords, together with the time stamp.")
  411. (defconst org-keyword-time-not-clock-regexp
  412. (concat
  413. "\\<"
  414. (regexp-opt
  415. (list org-scheduled-string org-deadline-string org-closed-string) t)
  416. " *[[<]\\([^]>]+\\)[]>]")
  417. "Matches any of the 3 keywords, together with the time stamp.")
  418. (defconst org-maybe-keyword-time-regexp
  419. (concat "\\(\\<"
  420. (regexp-opt
  421. (list org-scheduled-string org-deadline-string org-closed-string
  422. org-clock-string)
  423. t)
  424. "\\)?"
  425. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  426. "\\|"
  427. "<%%([^\r\n>]*>\\)")
  428. "Matches a timestamp, possibly preceded by a keyword.")
  429. (defconst org-all-time-keywords
  430. (mapcar (lambda (w) (substring w 0 -1))
  431. (list org-scheduled-string org-deadline-string
  432. org-clock-string org-closed-string))
  433. "List of time keywords.")
  434. ;;;; Drawer
  435. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  436. "Matches first or last line of a hidden block.
  437. Group 1 contains drawer's name or \"END\".")
  438. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  439. "Regular expression matching the first line of a property drawer.")
  440. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  441. "Regular expression matching the last line of a property drawer.")
  442. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  443. "Regular expression matching the first line of a clock drawer.")
  444. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  445. "Regular expression matching the last line of a clock drawer.")
  446. (defconst org-property-drawer-re
  447. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  448. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  449. "[ \t]*:END:[ \t]*$")
  450. "Matches an entire property drawer.")
  451. (defconst org-clock-drawer-re
  452. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  453. org-clock-drawer-end-re "\\)\n?")
  454. "Matches an entire clock drawer.")
  455. ;;;; Headline
  456. (defconst org-heading-keyword-regexp-format
  457. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  458. "Printf format for a regexp matching a headline with some keyword.
  459. This regexp will match the headline of any node which has the
  460. exact keyword that is put into the format. The keyword isn't in
  461. any group by default, but the stars and the body are.")
  462. (defconst org-heading-keyword-maybe-regexp-format
  463. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  464. "Printf format for a regexp matching a headline, possibly with some keyword.
  465. This regexp can match any headline with the specified keyword, or
  466. without a keyword. The keyword isn't in any group by default,
  467. but the stars and the body are.")
  468. (defconst org-archive-tag "ARCHIVE"
  469. "The tag that marks a subtree as archived.
  470. An archived subtree does not open during visibility cycling, and does
  471. not contribute to the agenda listings.")
  472. (eval-and-compile
  473. (defconst org-comment-string "COMMENT"
  474. "Entries starting with this keyword will never be exported.
  475. \\<org-mode-map>
  476. An entry can be toggled between COMMENT and normal with
  477. `\\[org-toggle-comment]'."))
  478. ;;;; LaTeX Environments and Fragments
  479. (defconst org-latex-regexps
  480. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  481. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  482. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  483. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  484. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  486. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  487. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  488. "Regular expressions for matching embedded LaTeX.")
  489. ;;;; Node Property
  490. (defconst org-effort-property "Effort"
  491. "The property that is being used to keep track of effort estimates.
  492. Effort estimates given in this property need to have the format H:MM.")
  493. ;;;; Table
  494. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  495. "Detect an org-type or table-type table.")
  496. (defconst org-table-line-regexp "^[ \t]*|"
  497. "Detect an org-type table line.")
  498. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  499. "Detect an org-type table line.")
  500. (defconst org-table-hline-regexp "^[ \t]*|-"
  501. "Detect an org-type table hline.")
  502. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  503. "Detect a table-type table hline.")
  504. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  505. "Detect the first line outside a table when searching from within it.
  506. This works for both table types.")
  507. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  508. "Detect a #+TBLFM line.")
  509. ;;;; Timestamp
  510. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  511. "Regular expression for fast time stamp matching.")
  512. (defconst org-ts-regexp-inactive
  513. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  514. "Regular expression for fast inactive time stamp matching.")
  515. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  516. "Regular expression for fast time stamp matching.")
  517. (defconst org-ts-regexp0
  518. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  519. "Regular expression matching time strings for analysis.
  520. This one does not require the space after the date, so it can be used
  521. on a string that terminates immediately after the date.")
  522. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  523. "Regular expression matching time strings for analysis.")
  524. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  525. "Regular expression matching time stamps, with groups.")
  526. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  527. "Regular expression matching time stamps (also [..]), with groups.")
  528. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  529. "Regular expression matching a time stamp range.")
  530. (defconst org-tr-regexp-both
  531. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  532. "Regular expression matching a time stamp range.")
  533. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  534. org-ts-regexp "\\)?")
  535. "Regular expression matching a time stamp or time stamp range.")
  536. (defconst org-tsr-regexp-both
  537. (concat org-ts-regexp-both "\\(--?-?"
  538. org-ts-regexp-both "\\)?")
  539. "Regular expression matching a time stamp or time stamp range.
  540. The time stamps may be either active or inactive.")
  541. (defconst org-repeat-re
  542. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  543. "Regular expression for specifying repeated events.
  544. After a match, group 1 contains the repeat expression.")
  545. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  546. "Formats for `format-time-string' which are used for time stamps.")
  547. ;;; The custom variables
  548. (defgroup org nil
  549. "Outline-based notes management and organizer."
  550. :tag "Org"
  551. :group 'outlines
  552. :group 'calendar)
  553. (defcustom org-mode-hook nil
  554. "Mode hook for Org mode, run after the mode was turned on."
  555. :group 'org
  556. :type 'hook)
  557. (defcustom org-load-hook nil
  558. "Hook that is run after org.el has been loaded."
  559. :group 'org
  560. :type 'hook)
  561. (defcustom org-log-buffer-setup-hook nil
  562. "Hook that is run after an Org log buffer is created."
  563. :group 'org
  564. :version "24.1"
  565. :type 'hook)
  566. (defvar org-modules) ; defined below
  567. (defvar org-modules-loaded nil
  568. "Have the modules been loaded already?")
  569. (defun org-load-modules-maybe (&optional force)
  570. "Load all extensions listed in `org-modules'."
  571. (when (or force (not org-modules-loaded))
  572. (dolist (ext org-modules)
  573. (condition-case nil (require ext)
  574. (error (message "Problems while trying to load feature `%s'" ext))))
  575. (setq org-modules-loaded t)))
  576. (defun org-set-modules (var value)
  577. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  578. (set var value)
  579. (when (featurep 'org)
  580. (org-load-modules-maybe 'force)
  581. (org-element-cache-reset 'all)))
  582. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  583. "Modules that should always be loaded together with org.el.
  584. If a description starts with <C>, the file is not part of Emacs
  585. and loading it will require that you have downloaded and properly
  586. installed the Org mode distribution.
  587. You can also use this system to load external packages (i.e. neither Org
  588. core modules, nor modules from the CONTRIB directory). Just add symbols
  589. to the end of the list. If the package is called org-xyz.el, then you need
  590. to add the symbol `xyz', and the package must have a call to:
  591. (provide \\='org-xyz)
  592. For export specific modules, see also `org-export-backends'."
  593. :group 'org
  594. :set 'org-set-modules
  595. :version "24.4"
  596. :package-version '(Org . "8.0")
  597. :type
  598. '(set :greedy t
  599. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  600. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  601. (const :tag " crypt: Encryption of subtrees" org-crypt)
  602. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  603. (const :tag " docview: Links to doc-view buffers" org-docview)
  604. (const :tag " eww: Store link to url of eww" org-eww)
  605. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  606. (const :tag " habit: Track your consistency with habits" org-habit)
  607. (const :tag " id: Global IDs for identifying entries" org-id)
  608. (const :tag " info: Links to Info nodes" org-info)
  609. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  610. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  611. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  612. (const :tag " mouse: Additional mouse support" org-mouse)
  613. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  614. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  615. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  616. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  617. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  618. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  619. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  620. (const :tag "C collector: Collect properties into tables" org-collector)
  621. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  622. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  623. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  624. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  625. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  626. (const :tag "C eval: Include command output as text" org-eval)
  627. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  628. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  629. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  630. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  631. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  632. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  633. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  634. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  635. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  636. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  637. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  638. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  639. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  640. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  641. (const :tag "C registry: A registry for Org links" org-registry)
  642. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  643. (const :tag "C secretary: Team management with org-mode" org-secretary)
  644. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  645. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  646. (const :tag "C track: Keep up with Org mode development" org-track)
  647. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  648. (const :tag "C vm: Links to VM folders/messages" org-vm)
  649. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  650. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  651. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  652. (defvar org-export-registered-backends) ; From ox.el.
  653. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  654. (declare-function org-export-backend-name "ox" (backend) t)
  655. (defcustom org-export-backends '(ascii html icalendar latex odt)
  656. "List of export back-ends that should be always available.
  657. If a description starts with <C>, the file is not part of Emacs
  658. and loading it will require that you have downloaded and properly
  659. installed the Org mode distribution.
  660. Unlike to `org-modules', libraries in this list will not be
  661. loaded along with Org, but only once the export framework is
  662. needed.
  663. This variable needs to be set before org.el is loaded. If you
  664. need to make a change while Emacs is running, use the customize
  665. interface or run the following code, where VAL stands for the new
  666. value of the variable, after updating it:
  667. (progn
  668. (setq org-export-registered-backends
  669. (cl-remove-if-not
  670. (lambda (backend)
  671. (let ((name (org-export-backend-name backend)))
  672. (or (memq name val)
  673. (catch \\='parentp
  674. (dolist (b val)
  675. (and (org-export-derived-backend-p b name)
  676. (throw \\='parentp t)))))))
  677. org-export-registered-backends))
  678. (let ((new-list (mapcar #\\='org-export-backend-name
  679. org-export-registered-backends)))
  680. (dolist (backend val)
  681. (cond
  682. ((not (load (format \"ox-%s\" backend) t t))
  683. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  684. backend))
  685. ((not (memq backend new-list)) (push backend new-list))))
  686. (set-default \\='org-export-backends new-list)))
  687. Adding a back-end to this list will also pull the back-end it
  688. depends on, if any."
  689. :group 'org
  690. :group 'org-export
  691. :version "26.1"
  692. :package-version '(Org . "9.0")
  693. :initialize 'custom-initialize-set
  694. :set (lambda (var val)
  695. (if (not (featurep 'ox)) (set-default var val)
  696. ;; Any back-end not required anymore (not present in VAL and not
  697. ;; a parent of any back-end in the new value) is removed from the
  698. ;; list of registered back-ends.
  699. (setq org-export-registered-backends
  700. (cl-remove-if-not
  701. (lambda (backend)
  702. (let ((name (org-export-backend-name backend)))
  703. (or (memq name val)
  704. (catch 'parentp
  705. (dolist (b val)
  706. (and (org-export-derived-backend-p b name)
  707. (throw 'parentp t)))))))
  708. org-export-registered-backends))
  709. ;; Now build NEW-LIST of both new back-ends and required
  710. ;; parents.
  711. (let ((new-list (mapcar #'org-export-backend-name
  712. org-export-registered-backends)))
  713. (dolist (backend val)
  714. (cond
  715. ((not (load (format "ox-%s" backend) t t))
  716. (message "Problems while trying to load export back-end `%s'"
  717. backend))
  718. ((not (memq backend new-list)) (push backend new-list))))
  719. ;; Set VAR to that list with fixed dependencies.
  720. (set-default var new-list))))
  721. :type '(set :greedy t
  722. (const :tag " ascii Export buffer to ASCII format" ascii)
  723. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  724. (const :tag " html Export buffer to HTML format" html)
  725. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  726. (const :tag " latex Export buffer to LaTeX format" latex)
  727. (const :tag " man Export buffer to MAN format" man)
  728. (const :tag " md Export buffer to Markdown format" md)
  729. (const :tag " odt Export buffer to ODT format" odt)
  730. (const :tag " org Export buffer to Org format" org)
  731. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  732. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  733. (const :tag "C deck Export buffer to deck.js presentations" deck)
  734. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  735. (const :tag "C groff Export buffer to Groff format" groff)
  736. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  737. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  738. (const :tag "C s5 Export buffer to s5 presentations" s5)
  739. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  740. (eval-after-load 'ox
  741. '(dolist (backend org-export-backends)
  742. (condition-case nil (require (intern (format "ox-%s" backend)))
  743. (error (message "Problems while trying to load export back-end `%s'"
  744. backend)))))
  745. (defcustom org-support-shift-select nil
  746. "Non-nil means make shift-cursor commands select text when possible.
  747. \\<org-mode-map>\
  748. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  749. start selecting a region, or enlarge regions started in this way.
  750. In Org mode, in special contexts, these same keys are used for
  751. other purposes, important enough to compete with shift selection.
  752. Org tries to balance these needs by supporting `shift-select-mode'
  753. outside these special contexts, under control of this variable.
  754. The default of this variable is nil, to avoid confusing behavior. Shifted
  755. cursor keys will then execute Org commands in the following contexts:
  756. - on a headline, changing TODO state (left/right) and priority (up/down)
  757. - on a time stamp, changing the time
  758. - in a plain list item, changing the bullet type
  759. - in a property definition line, switching between allowed values
  760. - in the BEGIN line of a clock table (changing the time block).
  761. Outside these contexts, the commands will throw an error.
  762. When this variable is t and the cursor is not in a special
  763. context, Org mode will support shift-selection for making and
  764. enlarging regions. To make this more effective, the bullet
  765. cycling will no longer happen anywhere in an item line, but only
  766. if the cursor is exactly on the bullet.
  767. If you set this variable to the symbol `always', then the keys
  768. will not be special in headlines, property lines, and item lines,
  769. to make shift selection work there as well. If this is what you
  770. want, you can use the following alternative commands:
  771. `\\[org-todo]' and `\\[org-priority]' \
  772. to change TODO state and priority,
  773. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  774. can be used to switch TODO sets,
  775. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  776. and properties can be edited by hand or in column view.
  777. However, when the cursor is on a timestamp, shift-cursor commands
  778. will still edit the time stamp - this is just too good to give up."
  779. :group 'org
  780. :type '(choice
  781. (const :tag "Never" nil)
  782. (const :tag "When outside special context" t)
  783. (const :tag "Everywhere except timestamps" always)))
  784. (defcustom org-loop-over-headlines-in-active-region nil
  785. "Shall some commands act upon headlines in the active region?
  786. When set to t, some commands will be performed in all headlines
  787. within the active region.
  788. When set to `start-level', some commands will be performed in all
  789. headlines within the active region, provided that these headlines
  790. are of the same level than the first one.
  791. When set to a string, those commands will be performed on the
  792. matching headlines within the active region. Such string must be
  793. a tags/property/todo match as it is used in the agenda tags view.
  794. The list of commands is: `org-schedule', `org-deadline',
  795. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  796. `org-archive-to-archive-sibling'. The archiving commands skip
  797. already archived entries."
  798. :type '(choice (const :tag "Don't loop" nil)
  799. (const :tag "All headlines in active region" t)
  800. (const :tag "In active region, headlines at the same level than the first one" start-level)
  801. (string :tag "Tags/Property/Todo matcher"))
  802. :version "24.1"
  803. :group 'org-todo
  804. :group 'org-archive)
  805. (defgroup org-startup nil
  806. "Options concerning startup of Org mode."
  807. :tag "Org Startup"
  808. :group 'org)
  809. (defcustom org-startup-folded t
  810. "Non-nil means entering Org mode will switch to OVERVIEW.
  811. This can also be configured on a per-file basis by adding one of
  812. the following lines anywhere in the buffer:
  813. #+STARTUP: fold (or `overview', this is equivalent)
  814. #+STARTUP: nofold (or `showall', this is equivalent)
  815. #+STARTUP: content
  816. #+STARTUP: showeverything
  817. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  818. to ignore this option when Org opens agenda files for the first
  819. time."
  820. :group 'org-startup
  821. :type '(choice
  822. (const :tag "nofold: show all" nil)
  823. (const :tag "fold: overview" t)
  824. (const :tag "content: all headlines" content)
  825. (const :tag "show everything, even drawers" showeverything)))
  826. (defcustom org-startup-truncated t
  827. "Non-nil means entering Org mode will set `truncate-lines'.
  828. This is useful since some lines containing links can be very long and
  829. uninteresting. Also tables look terrible when wrapped.
  830. The variable `org-startup-truncated' allows to configure
  831. truncation for Org mode different to the other modes that use the
  832. variable `truncate-lines' and as a shortcut instead of putting
  833. the variable `truncate-lines' into the `org-mode-hook'. If one
  834. wants to configure truncation for Org mode not statically but
  835. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  836. the variable `truncate-lines' has to be used because in such a
  837. case it is too late to set the variable `org-startup-truncated'."
  838. :group 'org-startup
  839. :type 'boolean)
  840. (defcustom org-startup-indented nil
  841. "Non-nil means turn on `org-indent-mode' on startup.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: indent
  845. #+STARTUP: noindent"
  846. :group 'org-structure
  847. :type '(choice
  848. (const :tag "Not" nil)
  849. (const :tag "Globally (slow on startup in large files)" t)))
  850. (defcustom org-use-sub-superscripts t
  851. "Non-nil means interpret \"_\" and \"^\" for display.
  852. If you want to control how Org exports those characters, see
  853. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  854. used to be an alias for `org-export-with-sub-superscripts' in
  855. Org <8.0, it is not anymore.
  856. When this option is turned on, you can use TeX-like syntax for
  857. sub- and superscripts within the buffer. Several characters after
  858. \"_\" or \"^\" will be considered as a single item - so grouping
  859. with {} is normally not needed. For example, the following things
  860. will be parsed as single sub- or superscripts:
  861. 10^24 or 10^tau several digits will be considered 1 item.
  862. 10^-12 or 10^-tau a leading sign with digits or a word
  863. x^2-y^3 will be read as x^2 - y^3, because items are
  864. terminated by almost any nonword/nondigit char.
  865. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  866. Still, ambiguity is possible. So when in doubt, use {} to enclose
  867. the sub/superscript. If you set this variable to the symbol `{}',
  868. the braces are *required* in order to trigger interpretations as
  869. sub/superscript. This can be helpful in documents that need \"_\"
  870. frequently in plain text."
  871. :group 'org-startup
  872. :version "24.4"
  873. :package-version '(Org . "8.0")
  874. :type '(choice
  875. (const :tag "Always interpret" t)
  876. (const :tag "Only with braces" {})
  877. (const :tag "Never interpret" nil)))
  878. (defcustom org-startup-with-beamer-mode nil
  879. "Non-nil means turn on `org-beamer-mode' on startup.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: beamer"
  883. :group 'org-startup
  884. :version "24.1"
  885. :type 'boolean)
  886. (defcustom org-startup-align-all-tables nil
  887. "Non-nil means align all tables when visiting a file.
  888. This is useful when the column width in tables is forced with <N> cookies
  889. in table fields. Such tables will look correct only after the first re-align.
  890. This can also be configured on a per-file basis by adding one of
  891. the following lines anywhere in the buffer:
  892. #+STARTUP: align
  893. #+STARTUP: noalign"
  894. :group 'org-startup
  895. :type 'boolean)
  896. (defcustom org-startup-with-inline-images nil
  897. "Non-nil means show inline images when loading a new Org file.
  898. This can also be configured on a per-file basis by adding one of
  899. the following lines anywhere in the buffer:
  900. #+STARTUP: inlineimages
  901. #+STARTUP: noinlineimages"
  902. :group 'org-startup
  903. :version "24.1"
  904. :type 'boolean)
  905. (defcustom org-startup-with-latex-preview nil
  906. "Non-nil means preview LaTeX fragments when loading a new Org file.
  907. This can also be configured on a per-file basis by adding one of
  908. the following lines anywhere in the buffer:
  909. #+STARTUP: latexpreview
  910. #+STARTUP: nolatexpreview"
  911. :group 'org-startup
  912. :version "24.4"
  913. :package-version '(Org . "8.0")
  914. :type 'boolean)
  915. (defcustom org-insert-mode-line-in-empty-file nil
  916. "Non-nil means insert the first line setting Org mode in empty files.
  917. When the function `org-mode' is called interactively in an empty file, this
  918. normally means that the file name does not automatically trigger Org mode.
  919. To ensure that the file will always be in Org mode in the future, a
  920. line enforcing Org mode will be inserted into the buffer, if this option
  921. has been set."
  922. :group 'org-startup
  923. :type 'boolean)
  924. (defcustom org-replace-disputed-keys nil
  925. "Non-nil means use alternative key bindings for some keys.
  926. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  927. These keys are also used by other packages like shift-selection-mode'
  928. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  929. If you want to use Org mode together with one of these other modes,
  930. or more generally if you would like to move some Org mode commands to
  931. other keys, set this variable and configure the keys with the variable
  932. `org-disputed-keys'.
  933. This option is only relevant at load-time of Org mode, and must be set
  934. *before* org.el is loaded. Changing it requires a restart of Emacs to
  935. become effective."
  936. :group 'org-startup
  937. :type 'boolean)
  938. (defcustom org-use-extra-keys nil
  939. "Non-nil means use extra key sequence definitions for certain commands.
  940. This happens automatically if `window-system' is nil. This
  941. variable lets you do the same manually. You must set it before
  942. loading Org."
  943. :group 'org-startup
  944. :type 'boolean)
  945. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  946. (defcustom org-disputed-keys
  947. '(([(shift up)] . [(meta p)])
  948. ([(shift down)] . [(meta n)])
  949. ([(shift left)] . [(meta -)])
  950. ([(shift right)] . [(meta +)])
  951. ([(control shift right)] . [(meta shift +)])
  952. ([(control shift left)] . [(meta shift -)]))
  953. "Keys for which Org mode and other modes compete.
  954. This is an alist, cars are the default keys, second element specifies
  955. the alternative to use when `org-replace-disputed-keys' is t.
  956. Keys can be specified in any syntax supported by `define-key'.
  957. The value of this option takes effect only at Org mode startup,
  958. therefore you'll have to restart Emacs to apply it after changing."
  959. :group 'org-startup
  960. :type 'alist)
  961. (defun org-key (key)
  962. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  963. Or return the original if not disputed."
  964. (when org-replace-disputed-keys
  965. (let* ((nkey (key-description key))
  966. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  967. org-disputed-keys)))
  968. (setq key (if x (cdr x) key))))
  969. key)
  970. (defun org-defkey (keymap key def)
  971. "Define a key, possibly translated, as returned by `org-key'."
  972. (define-key keymap (org-key key) def))
  973. (defcustom org-ellipsis nil
  974. "The ellipsis to use in the Org mode outline.
  975. When nil, just use the standard three dots. When a non-empty string,
  976. use that string instead.
  977. The change affects only Org mode (which will then use its own display table).
  978. Changing this requires executing `\\[org-mode]' in a buffer to become
  979. effective."
  980. :group 'org-startup
  981. :type '(choice (const :tag "Default" nil)
  982. (string :tag "String" :value "...#"))
  983. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  984. (defvar org-display-table nil
  985. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  986. (defgroup org-keywords nil
  987. "Keywords in Org mode."
  988. :tag "Org Keywords"
  989. :group 'org)
  990. (defcustom org-closed-keep-when-no-todo nil
  991. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  992. :group 'org-todo
  993. :group 'org-keywords
  994. :version "24.4"
  995. :package-version '(Org . "8.0")
  996. :type 'boolean)
  997. (defgroup org-structure nil
  998. "Options concerning the general structure of Org files."
  999. :tag "Org Structure"
  1000. :group 'org)
  1001. (defgroup org-reveal-location nil
  1002. "Options about how to make context of a location visible."
  1003. :tag "Org Reveal Location"
  1004. :group 'org-structure)
  1005. (defcustom org-show-context-detail '((agenda . local)
  1006. (bookmark-jump . lineage)
  1007. (isearch . lineage)
  1008. (default . ancestors))
  1009. "Alist between context and visibility span when revealing a location.
  1010. \\<org-mode-map>Some actions may move point into invisible
  1011. locations. As a consequence, Org always expose a neighborhood
  1012. around point. How much is shown depends on the initial action,
  1013. or context. Valid contexts are
  1014. agenda when exposing an entry from the agenda
  1015. org-goto when using the command `org-goto' (`\\[org-goto]')
  1016. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1017. tags-tree when constructing a sparse tree based on tags matches
  1018. link-search when exposing search matches associated with a link
  1019. mark-goto when exposing the jump goal of a mark
  1020. bookmark-jump when exposing a bookmark location
  1021. isearch when exiting from an incremental search
  1022. default default for all contexts not set explicitly
  1023. Allowed visibility spans are
  1024. minimal show current headline; if point is not on headline,
  1025. also show entry
  1026. local show current headline, entry and next headline
  1027. ancestors show current headline and its direct ancestors; if
  1028. point is not on headline, also show entry
  1029. lineage show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and first child
  1032. tree show current headline, its direct ancestors and all
  1033. their children; if point is not on headline, also show
  1034. entry and all children
  1035. canonical show current headline, its direct ancestors along with
  1036. their entries and children; if point is not located on
  1037. the headline, also show current entry and all children
  1038. As special cases, a nil or t value means show all contexts in
  1039. `minimal' or `canonical' view, respectively.
  1040. Some views can make displayed information very compact, but also
  1041. make it harder to edit the location of the match. In such
  1042. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1043. more context."
  1044. :group 'org-reveal-location
  1045. :version "26.1"
  1046. :package-version '(Org . "9.0")
  1047. :type '(choice
  1048. (const :tag "Canonical" t)
  1049. (const :tag "Minimal" nil)
  1050. (repeat :greedy t :tag "Individual contexts"
  1051. (cons
  1052. (choice :tag "Context"
  1053. (const agenda)
  1054. (const org-goto)
  1055. (const occur-tree)
  1056. (const tags-tree)
  1057. (const link-search)
  1058. (const mark-goto)
  1059. (const bookmark-jump)
  1060. (const isearch)
  1061. (const default))
  1062. (choice :tag "Detail level"
  1063. (const minimal)
  1064. (const local)
  1065. (const ancestors)
  1066. (const lineage)
  1067. (const tree)
  1068. (const canonical))))))
  1069. (defcustom org-indirect-buffer-display 'other-window
  1070. "How should indirect tree buffers be displayed?
  1071. This applies to indirect buffers created with the commands
  1072. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1073. Valid values are:
  1074. current-window Display in the current window
  1075. other-window Just display in another window.
  1076. dedicated-frame Create one new frame, and re-use it each time.
  1077. new-frame Make a new frame each time. Note that in this case
  1078. previously-made indirect buffers are kept, and you need to
  1079. kill these buffers yourself."
  1080. :group 'org-structure
  1081. :group 'org-agenda-windows
  1082. :type '(choice
  1083. (const :tag "In current window" current-window)
  1084. (const :tag "In current frame, other window" other-window)
  1085. (const :tag "Each time a new frame" new-frame)
  1086. (const :tag "One dedicated frame" dedicated-frame)))
  1087. (defcustom org-use-speed-commands nil
  1088. "Non-nil means activate single letter commands at beginning of a headline.
  1089. This may also be a function to test for appropriate locations where speed
  1090. commands should be active.
  1091. For example, to activate speed commands when the point is on any
  1092. star at the beginning of the headline, you can do this:
  1093. (setq org-use-speed-commands
  1094. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1095. :group 'org-structure
  1096. :type '(choice
  1097. (const :tag "Never" nil)
  1098. (const :tag "At beginning of headline stars" t)
  1099. (function)))
  1100. (defcustom org-speed-commands-user nil
  1101. "Alist of additional speed commands.
  1102. This list will be checked before `org-speed-commands-default'
  1103. when the variable `org-use-speed-commands' is non-nil
  1104. and when the cursor is at the beginning of a headline.
  1105. The car if each entry is a string with a single letter, which must
  1106. be assigned to `self-insert-command' in the global map.
  1107. The cdr is either a command to be called interactively, a function
  1108. to be called, or a form to be evaluated.
  1109. An entry that is just a list with a single string will be interpreted
  1110. as a descriptive headline that will be added when listing the speed
  1111. commands in the Help buffer using the `?' speed command."
  1112. :group 'org-structure
  1113. :type '(repeat :value ("k" . ignore)
  1114. (choice :value ("k" . ignore)
  1115. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1116. (cons :tag "Letter and Command"
  1117. (string :tag "Command letter")
  1118. (choice
  1119. (function)
  1120. (sexp))))))
  1121. (defcustom org-bookmark-names-plist
  1122. '(:last-capture "org-capture-last-stored"
  1123. :last-refile "org-refile-last-stored"
  1124. :last-capture-marker "org-capture-last-stored-marker")
  1125. "Names for bookmarks automatically set by some Org commands.
  1126. This can provide strings as names for a number of bookmarks Org sets
  1127. automatically. The following keys are currently implemented:
  1128. :last-capture
  1129. :last-capture-marker
  1130. :last-refile
  1131. When a key does not show up in the property list, the corresponding bookmark
  1132. is not set."
  1133. :group 'org-structure
  1134. :type 'plist)
  1135. (defgroup org-cycle nil
  1136. "Options concerning visibility cycling in Org mode."
  1137. :tag "Org Cycle"
  1138. :group 'org-structure)
  1139. (defcustom org-cycle-skip-children-state-if-no-children t
  1140. "Non-nil means skip CHILDREN state in entries that don't have any."
  1141. :group 'org-cycle
  1142. :type 'boolean)
  1143. (defcustom org-cycle-max-level nil
  1144. "Maximum level which should still be subject to visibility cycling.
  1145. Levels higher than this will, for cycling, be treated as text, not a headline.
  1146. When `org-odd-levels-only' is set, a value of N in this variable actually
  1147. means 2N-1 stars as the limiting headline.
  1148. When nil, cycle all levels.
  1149. Note that the limiting level of cycling is also influenced by
  1150. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1151. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1152. than its value."
  1153. :group 'org-cycle
  1154. :type '(choice
  1155. (const :tag "No limit" nil)
  1156. (integer :tag "Maximum level")))
  1157. (defcustom org-hide-block-startup nil
  1158. "Non-nil means entering Org mode will fold all blocks.
  1159. This can also be set in on a per-file basis with
  1160. #+STARTUP: hideblocks
  1161. #+STARTUP: showblocks"
  1162. :group 'org-startup
  1163. :group 'org-cycle
  1164. :type 'boolean)
  1165. (defcustom org-cycle-global-at-bob nil
  1166. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1167. This makes it possible to do global cycling without having to use `S-TAB'
  1168. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1169. line of the buffer
  1170. must not be a headline -- it may be empty or some other text.
  1171. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1172. sure the cursor stays at the beginning of the buffer.
  1173. When this option is nil, don't do anything special at the beginning of
  1174. the buffer."
  1175. :group 'org-cycle
  1176. :type 'boolean)
  1177. (defcustom org-cycle-level-after-item/entry-creation t
  1178. "Non-nil means cycle entry level or item indentation in new empty entries.
  1179. When the cursor is at the end of an empty headline, i.e., with only stars
  1180. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1181. and then all possible ancestor states, before returning to the original state.
  1182. This makes data entry extremely fast: M-RET to create a new headline,
  1183. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1184. When the cursor is at the end of an empty plain list item, one TAB will
  1185. make it a subitem, two or more tabs will back up to make this an item
  1186. higher up in the item hierarchy."
  1187. :group 'org-cycle
  1188. :type 'boolean)
  1189. (defcustom org-cycle-emulate-tab t
  1190. "Where should `org-cycle' emulate TAB.
  1191. nil Never
  1192. white Only in completely white lines
  1193. whitestart Only at the beginning of lines, before the first non-white char
  1194. t Everywhere except in headlines
  1195. exc-hl-bol Everywhere except at the start of a headline
  1196. If TAB is used in a place where it does not emulate TAB, the current subtree
  1197. visibility is cycled."
  1198. :group 'org-cycle
  1199. :type '(choice (const :tag "Never" nil)
  1200. (const :tag "Only in completely white lines" white)
  1201. (const :tag "Before first char in a line" whitestart)
  1202. (const :tag "Everywhere except in headlines" t)
  1203. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1204. (defcustom org-cycle-separator-lines 2
  1205. "Number of empty lines needed to keep an empty line between collapsed trees.
  1206. If you leave an empty line between the end of a subtree and the following
  1207. headline, this empty line is hidden when the subtree is folded.
  1208. Org mode will leave (exactly) one empty line visible if the number of
  1209. empty lines is equal or larger to the number given in this variable.
  1210. So the default 2 means at least 2 empty lines after the end of a subtree
  1211. are needed to produce free space between a collapsed subtree and the
  1212. following headline.
  1213. If the number is negative, and the number of empty lines is at least -N,
  1214. all empty lines are shown.
  1215. Special case: when 0, never leave empty lines in collapsed view."
  1216. :group 'org-cycle
  1217. :type 'integer)
  1218. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1219. (defcustom org-pre-cycle-hook nil
  1220. "Hook that is run before visibility cycling is happening.
  1221. The function(s) in this hook must accept a single argument which indicates
  1222. the new state that will be set right after running this hook. The
  1223. argument is a symbol. Before a global state change, it can have the values
  1224. `overview', `content', or `all'. Before a local state change, it can have
  1225. the values `folded', `children', or `subtree'."
  1226. :group 'org-cycle
  1227. :type 'hook)
  1228. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1229. org-cycle-hide-drawers
  1230. org-cycle-show-empty-lines
  1231. org-optimize-window-after-visibility-change)
  1232. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1233. The function(s) in this hook must accept a single argument which indicates
  1234. the new state that was set by the most recent `org-cycle' command. The
  1235. argument is a symbol. After a global state change, it can have the values
  1236. `overview', `contents', or `all'. After a local state change, it can have
  1237. the values `folded', `children', or `subtree'."
  1238. :group 'org-cycle
  1239. :type 'hook
  1240. :version "26.1"
  1241. :package-version '(Org . "8.3"))
  1242. (defgroup org-edit-structure nil
  1243. "Options concerning structure editing in Org mode."
  1244. :tag "Org Edit Structure"
  1245. :group 'org-structure)
  1246. (defcustom org-odd-levels-only nil
  1247. "Non-nil means skip even levels and only use odd levels for the outline.
  1248. This has the effect that two stars are being added/taken away in
  1249. promotion/demotion commands. It also influences how levels are
  1250. handled by the exporters.
  1251. Changing it requires restart of `font-lock-mode' to become effective
  1252. for fontification also in regions already fontified.
  1253. You may also set this on a per-file basis by adding one of the following
  1254. lines to the buffer:
  1255. #+STARTUP: odd
  1256. #+STARTUP: oddeven"
  1257. :group 'org-edit-structure
  1258. :group 'org-appearance
  1259. :type 'boolean)
  1260. (defcustom org-adapt-indentation t
  1261. "Non-nil means adapt indentation to outline node level.
  1262. When this variable is set, Org assumes that you write outlines by
  1263. indenting text in each node to align with the headline (after the
  1264. stars). The following issues are influenced by this variable:
  1265. - The indentation is increased by one space in a demotion
  1266. command, and decreased by one in a promotion command. However,
  1267. in the latter case, if shifting some line in the entry body
  1268. would alter document structure (e.g., insert a new headline),
  1269. indentation is not changed at all.
  1270. - Property drawers and planning information is inserted indented
  1271. when this variable is set. When nil, they will not be indented.
  1272. - TAB indents a line relative to current level. The lines below
  1273. a headline will be indented when this variable is set.
  1274. Note that this is all about true indentation, by adding and
  1275. removing space characters. See also `org-indent.el' which does
  1276. level-dependent indentation in a virtual way, i.e. at display
  1277. time in Emacs."
  1278. :group 'org-edit-structure
  1279. :type 'boolean)
  1280. (defcustom org-special-ctrl-a/e nil
  1281. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1282. When t, `C-a' will bring back the cursor to the beginning of the
  1283. headline text, i.e. after the stars and after a possible TODO
  1284. keyword. In an item, this will be the position after bullet and
  1285. check-box, if any. When the cursor is already at that position,
  1286. another `C-a' will bring it to the beginning of the line.
  1287. `C-e' will jump to the end of the headline, ignoring the presence
  1288. of tags in the headline. A second `C-e' will then jump to the
  1289. true end of the line, after any tags. This also means that, when
  1290. this variable is non-nil, `C-e' also will never jump beyond the
  1291. end of the heading of a folded section, i.e. not after the
  1292. ellipses.
  1293. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1294. normally, going to the true line boundary first. Only a directly
  1295. following, identical keypress will bring the cursor to the
  1296. special positions.
  1297. This may also be a cons cell where the behavior for `C-a' and
  1298. `C-e' is set separately."
  1299. :group 'org-edit-structure
  1300. :type '(choice
  1301. (const :tag "off" nil)
  1302. (const :tag "on: after stars/bullet and before tags first" t)
  1303. (const :tag "reversed: true line boundary first" reversed)
  1304. (cons :tag "Set C-a and C-e separately"
  1305. (choice :tag "Special C-a"
  1306. (const :tag "off" nil)
  1307. (const :tag "on: after stars/bullet first" t)
  1308. (const :tag "reversed: before stars/bullet first" reversed))
  1309. (choice :tag "Special C-e"
  1310. (const :tag "off" nil)
  1311. (const :tag "on: before tags first" t)
  1312. (const :tag "reversed: after tags first" reversed)))))
  1313. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1314. (defcustom org-special-ctrl-k nil
  1315. "Non-nil means `C-k' will behave specially in headlines.
  1316. When nil, `C-k' will call the default `kill-line' command.
  1317. When t, the following will happen while the cursor is in the headline:
  1318. - When the cursor is at the beginning of a headline, kill the entire
  1319. line and possible the folded subtree below the line.
  1320. - When in the middle of the headline text, kill the headline up to the tags.
  1321. - When after the headline text, kill the tags."
  1322. :group 'org-edit-structure
  1323. :type 'boolean)
  1324. (defcustom org-ctrl-k-protect-subtree nil
  1325. "Non-nil means, do not delete a hidden subtree with C-k.
  1326. When set to the symbol `error', simply throw an error when C-k is
  1327. used to kill (part-of) a headline that has hidden text behind it.
  1328. Any other non-nil value will result in a query to the user, if it is
  1329. OK to kill that hidden subtree. When nil, kill without remorse."
  1330. :group 'org-edit-structure
  1331. :version "24.1"
  1332. :type '(choice
  1333. (const :tag "Do not protect hidden subtrees" nil)
  1334. (const :tag "Protect hidden subtrees with a security query" t)
  1335. (const :tag "Never kill a hidden subtree with C-k" error)))
  1336. (defcustom org-special-ctrl-o t
  1337. "Non-nil means, make `C-o' insert a row in tables."
  1338. :group 'org-edit-structure
  1339. :type 'boolean)
  1340. (defcustom org-catch-invisible-edits nil
  1341. "Check if in invisible region before inserting or deleting a character.
  1342. Valid values are:
  1343. nil Do not check, so just do invisible edits.
  1344. error Throw an error and do nothing.
  1345. show Make point visible, and do the requested edit.
  1346. show-and-error Make point visible, then throw an error and abort the edit.
  1347. smart Make point visible, and do insertion/deletion if it is
  1348. adjacent to visible text and the change feels predictable.
  1349. Never delete a previously invisible character or add in the
  1350. middle or right after an invisible region. Basically, this
  1351. allows insertion and backward-delete right before ellipses.
  1352. FIXME: maybe in this case we should not even show?"
  1353. :group 'org-edit-structure
  1354. :version "24.1"
  1355. :type '(choice
  1356. (const :tag "Do not check" nil)
  1357. (const :tag "Throw error when trying to edit" error)
  1358. (const :tag "Unhide, but do not do the edit" show-and-error)
  1359. (const :tag "Show invisible part and do the edit" show)
  1360. (const :tag "Be smart and do the right thing" smart)))
  1361. (defcustom org-yank-folded-subtrees t
  1362. "Non-nil means when yanking subtrees, fold them.
  1363. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1364. it starts with a heading and all other headings in it are either children
  1365. or siblings, then fold all the subtrees. However, do this only if no
  1366. text after the yank would be swallowed into a folded tree by this action."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-yank-adjusted-subtrees nil
  1370. "Non-nil means when yanking subtrees, adjust the level.
  1371. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1372. this function for details."
  1373. :group 'org-edit-structure
  1374. :type 'boolean)
  1375. (defcustom org-M-RET-may-split-line '((default . t))
  1376. "Non-nil means M-RET will split the line at the cursor position.
  1377. When nil, it will go to the end of the line before making a
  1378. new line.
  1379. You may also set this option in a different way for different
  1380. contexts. Valid contexts are:
  1381. headline when creating a new headline
  1382. item when creating a new item
  1383. table in a table field
  1384. default the value to be used for all contexts not explicitly
  1385. customized"
  1386. :group 'org-structure
  1387. :group 'org-table
  1388. :type '(choice
  1389. (const :tag "Always" t)
  1390. (const :tag "Never" nil)
  1391. (repeat :greedy t :tag "Individual contexts"
  1392. (cons
  1393. (choice :tag "Context"
  1394. (const headline)
  1395. (const item)
  1396. (const table)
  1397. (const default))
  1398. (boolean)))))
  1399. (defcustom org-insert-heading-respect-content nil
  1400. "Non-nil means insert new headings after the current subtree.
  1401. \\<org-mode-map>
  1402. When nil, the new heading is created directly after the current line.
  1403. The commands `\\[org-insert-heading-respect-content]' and \
  1404. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1405. for the duration of the command."
  1406. :group 'org-structure
  1407. :type 'boolean)
  1408. (defcustom org-blank-before-new-entry '((heading . auto)
  1409. (plain-list-item . auto))
  1410. "Should `org-insert-heading' leave a blank line before new heading/item?
  1411. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1412. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1413. which case Org will look at the surrounding headings/items and try to
  1414. make an intelligent decision whether to insert a blank line or not."
  1415. :group 'org-edit-structure
  1416. :type '(list
  1417. (cons (const heading)
  1418. (choice (const :tag "Never" nil)
  1419. (const :tag "Always" t)
  1420. (const :tag "Auto" auto)))
  1421. (cons (const plain-list-item)
  1422. (choice (const :tag "Never" nil)
  1423. (const :tag "Always" t)
  1424. (const :tag "Auto" auto)))))
  1425. (defcustom org-insert-heading-hook nil
  1426. "Hook being run after inserting a new heading."
  1427. :group 'org-edit-structure
  1428. :type 'hook)
  1429. (defcustom org-enable-fixed-width-editor t
  1430. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1431. This currently only means they are never auto-wrapped.
  1432. When nil, such lines will be treated like ordinary lines."
  1433. :group 'org-edit-structure
  1434. :type 'boolean)
  1435. (defcustom org-goto-auto-isearch t
  1436. "Non-nil means typing characters in `org-goto' starts incremental search.
  1437. When nil, you can use these keybindings to navigate the buffer:
  1438. q Quit the org-goto interface
  1439. n Go to the next visible heading
  1440. p Go to the previous visible heading
  1441. f Go one heading forward on same level
  1442. b Go one heading backward on same level
  1443. u Go one heading up"
  1444. :group 'org-edit-structure
  1445. :type 'boolean)
  1446. (defgroup org-sparse-trees nil
  1447. "Options concerning sparse trees in Org mode."
  1448. :tag "Org Sparse Trees"
  1449. :group 'org-structure)
  1450. (defcustom org-highlight-sparse-tree-matches t
  1451. "Non-nil means highlight all matches that define a sparse tree.
  1452. The highlights will automatically disappear the next time the buffer is
  1453. changed by an edit command."
  1454. :group 'org-sparse-trees
  1455. :type 'boolean)
  1456. (defcustom org-remove-highlights-with-change t
  1457. "Non-nil means any change to the buffer will remove temporary highlights.
  1458. \\<org-mode-map>\
  1459. Such highlights are created by `org-occur' and `org-clock-display'.
  1460. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1461. to get rid of the highlights.
  1462. The highlights created by `org-toggle-latex-fragment' always need
  1463. `\\[org-toggle-latex-fragment]' to be removed."
  1464. :group 'org-sparse-trees
  1465. :group 'org-time
  1466. :type 'boolean)
  1467. (defcustom org-occur-case-fold-search t
  1468. "Non-nil means `org-occur' should be case-insensitive.
  1469. If set to `smart' the search will be case-insensitive only if it
  1470. doesn't specify any upper case character."
  1471. :group 'org-sparse-trees
  1472. :version "26.1"
  1473. :type '(choice
  1474. (const :tag "Case-sensitive" nil)
  1475. (const :tag "Case-insensitive" t)
  1476. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1477. (defcustom org-occur-hook '(org-first-headline-recenter)
  1478. "Hook that is run after `org-occur' has constructed a sparse tree.
  1479. This can be used to recenter the window to show as much of the structure
  1480. as possible."
  1481. :group 'org-sparse-trees
  1482. :type 'hook)
  1483. (defgroup org-imenu-and-speedbar nil
  1484. "Options concerning imenu and speedbar in Org mode."
  1485. :tag "Org Imenu and Speedbar"
  1486. :group 'org-structure)
  1487. (defcustom org-imenu-depth 2
  1488. "The maximum level for Imenu access to Org headlines.
  1489. This also applied for speedbar access."
  1490. :group 'org-imenu-and-speedbar
  1491. :type 'integer)
  1492. (defgroup org-table nil
  1493. "Options concerning tables in Org mode."
  1494. :tag "Org Table"
  1495. :group 'org)
  1496. (defcustom org-enable-table-editor 'optimized
  1497. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1498. When nil, such lines will be treated like ordinary lines.
  1499. When equal to the symbol `optimized', the table editor will be optimized to
  1500. do the following:
  1501. - Automatic overwrite mode in front of whitespace in table fields.
  1502. This makes the structure of the table stay in tact as long as the edited
  1503. field does not exceed the column width.
  1504. - Minimize the number of realigns. Normally, the table is aligned each time
  1505. TAB or RET are pressed to move to another field. With optimization this
  1506. happens only if changes to a field might have changed the column width.
  1507. Optimization requires replacing the functions `self-insert-command',
  1508. `delete-char', and `backward-delete-char' in Org buffers, with a
  1509. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1510. good at guessing when a re-align will be necessary, but you can always
  1511. force one with `\\[org-ctrl-c-ctrl-c]'.
  1512. If you would like to use the optimized version in Org mode, but the
  1513. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1514. This variable can be used to turn on and off the table editor during a session,
  1515. but in order to toggle optimization, a restart is required.
  1516. See also the variable `org-table-auto-blank-field'."
  1517. :group 'org-table
  1518. :type '(choice
  1519. (const :tag "off" nil)
  1520. (const :tag "on" t)
  1521. (const :tag "on, optimized" optimized)))
  1522. (defcustom org-self-insert-cluster-for-undo nil
  1523. "Non-nil means cluster self-insert commands for undo when possible.
  1524. If this is set, then, like in the Emacs command loop, 20 consecutive
  1525. characters will be undone together.
  1526. This is configurable, because there is some impact on typing performance."
  1527. :group 'org-table
  1528. :type 'boolean)
  1529. (defcustom org-table-tab-recognizes-table.el t
  1530. "Non-nil means TAB will automatically notice a table.el table.
  1531. When it sees such a table, it moves point into it and - if necessary -
  1532. calls `table-recognize-table'."
  1533. :group 'org-table-editing
  1534. :type 'boolean)
  1535. (defgroup org-link nil
  1536. "Options concerning links in Org mode."
  1537. :tag "Org Link"
  1538. :group 'org)
  1539. (defvar-local org-link-abbrev-alist-local nil
  1540. "Buffer-local version of `org-link-abbrev-alist', which see.
  1541. The value of this is taken from the #+LINK lines.")
  1542. (defcustom org-link-parameters
  1543. '(("doi" :follow org--open-doi-link)
  1544. ("elisp" :follow org--open-elisp-link)
  1545. ("file" :complete org-file-complete-link)
  1546. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1547. ("help" :follow org--open-help-link)
  1548. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1549. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1550. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1551. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1552. ("shell" :follow org--open-shell-link))
  1553. "An alist of properties that defines all the links in Org mode.
  1554. The key in each association is a string of the link type.
  1555. Subsequent optional elements make up a p-list of link properties.
  1556. :follow - A function that takes the link path as an argument.
  1557. :export - A function that takes the link path, description and
  1558. export-backend as arguments.
  1559. :store - A function responsible for storing the link. See the
  1560. function `org-store-link-functions'.
  1561. :complete - A function that inserts a link with completion. The
  1562. function takes one optional prefix arg.
  1563. :face - A face for the link, or a function that returns a face.
  1564. The function takes one argument which is the link path. The
  1565. default face is `org-link'.
  1566. :mouse-face - The mouse-face. The default is `highlight'.
  1567. :display - `full' will not fold the link in descriptive
  1568. display. Default is `org-link'.
  1569. :help-echo - A string or function that takes (window object position)
  1570. as arguments and returns a string.
  1571. :keymap - A keymap that is active on the link. The default is
  1572. `org-mouse-map'.
  1573. :htmlize-link - A function for the htmlize-link. Defaults
  1574. to (list :uri \"type:path\")
  1575. :activate-func - A function to run at the end of font-lock
  1576. activation. The function must accept (link-start link-end path bracketp)
  1577. as arguments."
  1578. :group 'org-link
  1579. :type '(alist :tag "Link display parameters"
  1580. :value-type plist)
  1581. :version "26.1"
  1582. :package-version '(Org . "9.1"))
  1583. (defun org-link-get-parameter (type key)
  1584. "Get TYPE link property for KEY.
  1585. TYPE is a string and KEY is a plist keyword."
  1586. (plist-get
  1587. (cdr (assoc type org-link-parameters))
  1588. key))
  1589. (defun org-link-set-parameters (type &rest parameters)
  1590. "Set link TYPE properties to PARAMETERS.
  1591. PARAMETERS should be :key val pairs."
  1592. (let ((data (assoc type org-link-parameters)))
  1593. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1594. (push (cons type parameters) org-link-parameters)
  1595. (org-make-link-regexps)
  1596. (org-element-update-syntax))))
  1597. (defun org-link-types ()
  1598. "Return a list of known link types."
  1599. (mapcar #'car org-link-parameters))
  1600. (defcustom org-link-abbrev-alist nil
  1601. "Alist of link abbreviations.
  1602. The car of each element is a string, to be replaced at the start of a link.
  1603. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1604. links in Org buffers can have an optional tag after a double colon, e.g.,
  1605. [[linkkey:tag][description]]
  1606. The `linkkey' must be a single word, starting with a letter, followed
  1607. by letters, numbers, `-' or `_'.
  1608. If REPLACE is a string, the tag will simply be appended to create the link.
  1609. If the string contains \"%s\", the tag will be inserted there. If the string
  1610. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1611. at that point (see the function `url-hexify-string'). If the string contains
  1612. the specifier \"%(my-function)\", then the custom function `my-function' will
  1613. be invoked: this function takes the tag as its only argument and must return
  1614. a string.
  1615. REPLACE may also be a function that will be called with the tag as the
  1616. only argument to create the link, which should be returned as a string.
  1617. See the manual for examples."
  1618. :group 'org-link
  1619. :type '(repeat
  1620. (cons
  1621. (string :tag "Protocol")
  1622. (choice
  1623. (string :tag "Format")
  1624. (function)))))
  1625. (defcustom org-descriptive-links t
  1626. "Non-nil means Org will display descriptive links.
  1627. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1628. \"Org Website\", hiding the link itself and just displaying its
  1629. description. When set to nil, Org will display the full links
  1630. literally.
  1631. You can interactively set the value of this variable by calling
  1632. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1633. :group 'org-link
  1634. :type 'boolean)
  1635. (defcustom org-link-file-path-type 'adaptive
  1636. "How the path name in file links should be stored.
  1637. Valid values are:
  1638. relative Relative to the current directory, i.e. the directory of the file
  1639. into which the link is being inserted.
  1640. absolute Absolute path, if possible with ~ for home directory.
  1641. noabbrev Absolute path, no abbreviation of home directory.
  1642. adaptive Use relative path for files in the current directory and sub-
  1643. directories of it. For other files, use an absolute path."
  1644. :group 'org-link
  1645. :type '(choice
  1646. (const relative)
  1647. (const absolute)
  1648. (const noabbrev)
  1649. (const adaptive)))
  1650. (defvaralias 'org-activate-links 'org-highlight-links)
  1651. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1652. "Types of links that should be highlighted in Org files.
  1653. This is a list of symbols, each one of them leading to the
  1654. highlighting of a certain link type.
  1655. You can still open links that are not highlighted.
  1656. In principle, it does not hurt to turn on highlighting for all
  1657. link types. There may be a small gain when turning off unused
  1658. link types. The types are:
  1659. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1660. angle Links in angular brackets that may contain whitespace like
  1661. <bbdb:Carsten Dominik>.
  1662. plain Plain links in normal text, no whitespace, like http://google.com.
  1663. radio Text that is matched by a radio target, see manual for details.
  1664. tag Tag settings in a headline (link to tag search).
  1665. date Time stamps (link to calendar).
  1666. footnote Footnote labels.
  1667. If you set this variable during an Emacs session, use `org-mode-restart'
  1668. in the Org buffer so that the change takes effect."
  1669. :group 'org-link
  1670. :group 'org-appearance
  1671. :type '(set :greedy t
  1672. (const :tag "Double bracket links" bracket)
  1673. (const :tag "Angular bracket links" angle)
  1674. (const :tag "Plain text links" plain)
  1675. (const :tag "Radio target matches" radio)
  1676. (const :tag "Tags" tag)
  1677. (const :tag "Timestamps" date)
  1678. (const :tag "Footnotes" footnote)))
  1679. (defcustom org-make-link-description-function nil
  1680. "Function to use for generating link descriptions from links.
  1681. When nil, the link location will be used. This function must take
  1682. two parameters: the first one is the link, the second one is the
  1683. description generated by `org-insert-link'. The function should
  1684. return the description to use."
  1685. :group 'org-link
  1686. :type '(choice (const nil) (function)))
  1687. (defgroup org-link-store nil
  1688. "Options concerning storing links in Org mode."
  1689. :tag "Org Store Link"
  1690. :group 'org-link)
  1691. (defcustom org-url-hexify-p t
  1692. "When non-nil, hexify URL when creating a link."
  1693. :type 'boolean
  1694. :version "24.3"
  1695. :group 'org-link-store)
  1696. (defcustom org-email-link-description-format "Email %c: %.30s"
  1697. "Format of the description part of a link to an email or usenet message.
  1698. The following %-escapes will be replaced by corresponding information:
  1699. %F full \"From\" field
  1700. %f name, taken from \"From\" field, address if no name
  1701. %T full \"To\" field
  1702. %t first name in \"To\" field, address if no name
  1703. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1704. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1705. %s subject
  1706. %d date
  1707. %m message-id.
  1708. You may use normal field width specification between the % and the letter.
  1709. This is for example useful to limit the length of the subject.
  1710. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1711. :group 'org-link-store
  1712. :type 'string)
  1713. (defcustom org-from-is-user-regexp
  1714. (let (r1 r2)
  1715. (when (and user-mail-address (not (string= user-mail-address "")))
  1716. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1717. (when (and user-full-name (not (string= user-full-name "")))
  1718. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1719. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1720. "Regexp matched against the \"From:\" header of an email or usenet message.
  1721. It should match if the message is from the user him/herself."
  1722. :group 'org-link-store
  1723. :type 'regexp)
  1724. (defcustom org-context-in-file-links t
  1725. "Non-nil means file links from `org-store-link' contain context.
  1726. \\<org-mode-map>
  1727. A search string will be added to the file name with :: as separator
  1728. and used to find the context when the link is activated by the command
  1729. `org-open-at-point'. When this option is t, the entire active region
  1730. will be placed in the search string of the file link. If set to a
  1731. positive integer, only the first n lines of context will be stored.
  1732. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1733. \\[org-store-link]')
  1734. negates this setting for the duration of the command."
  1735. :group 'org-link-store
  1736. :type '(choice boolean integer))
  1737. (defcustom org-keep-stored-link-after-insertion nil
  1738. "Non-nil means keep link in list for entire session.
  1739. \\<org-mode-map>
  1740. The command `org-store-link' adds a link pointing to the current
  1741. location to an internal list. These links accumulate during a session.
  1742. The command `org-insert-link' can be used to insert links into any
  1743. Org file (offering completion for all stored links).
  1744. When this option is nil, every link which has been inserted once using
  1745. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1746. unused
  1747. links more efficient."
  1748. :group 'org-link-store
  1749. :type 'boolean)
  1750. (defgroup org-link-follow nil
  1751. "Options concerning following links in Org mode."
  1752. :tag "Org Follow Link"
  1753. :group 'org-link)
  1754. (defcustom org-link-translation-function nil
  1755. "Function to translate links with different syntax to Org syntax.
  1756. This can be used to translate links created for example by the Planner
  1757. or emacs-wiki packages to Org syntax.
  1758. The function must accept two parameters, a TYPE containing the link
  1759. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1760. which is everything after the link protocol. It should return a cons
  1761. with possibly modified values of type and path.
  1762. Org contains a function for this, so if you set this variable to
  1763. `org-translate-link-from-planner', you should be able follow many
  1764. links created by planner."
  1765. :group 'org-link-follow
  1766. :type '(choice (const nil) (function)))
  1767. (defcustom org-follow-link-hook nil
  1768. "Hook that is run after a link has been followed."
  1769. :group 'org-link-follow
  1770. :type 'hook)
  1771. (defcustom org-tab-follows-link nil
  1772. "Non-nil means on links TAB will follow the link.
  1773. Needs to be set before org.el is loaded.
  1774. This really should not be used, it does not make sense, and the
  1775. implementation is bad."
  1776. :group 'org-link-follow
  1777. :type 'boolean)
  1778. (defcustom org-return-follows-link nil
  1779. "Non-nil means on links RET will follow the link.
  1780. In tables, the special behavior of RET has precedence."
  1781. :group 'org-link-follow
  1782. :type 'boolean)
  1783. (defcustom org-mouse-1-follows-link
  1784. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1785. "Non-nil means mouse-1 on a link will follow the link.
  1786. A longer mouse click will still set point. Needs to be set
  1787. before org.el is loaded."
  1788. :group 'org-link-follow
  1789. :version "24.4"
  1790. :package-version '(Org . "8.3")
  1791. :type '(choice
  1792. (const :tag "A double click follows the link" double)
  1793. (const :tag "Unconditionally follow the link with mouse-1" t)
  1794. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1795. (defcustom org-mark-ring-length 4
  1796. "Number of different positions to be recorded in the ring.
  1797. Changing this requires a restart of Emacs to work correctly."
  1798. :group 'org-link-follow
  1799. :type 'integer)
  1800. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1801. "Non-nil means internal fuzzy links can only match headlines.
  1802. When nil, the a fuzzy link may point to a target or a named
  1803. construct in the document. When set to the special value
  1804. `query-to-create', offer to create a new headline when none
  1805. matched.
  1806. Spaces and statistics cookies are ignored during heading searches."
  1807. :group 'org-link-follow
  1808. :version "24.1"
  1809. :type '(choice
  1810. (const :tag "Use fuzzy text search" nil)
  1811. (const :tag "Match only exact headline" t)
  1812. (const :tag "Match exact headline or query to create it"
  1813. query-to-create))
  1814. :safe #'symbolp)
  1815. (defcustom org-link-frame-setup
  1816. '((vm . vm-visit-folder-other-frame)
  1817. (vm-imap . vm-visit-imap-folder-other-frame)
  1818. (gnus . org-gnus-no-new-news)
  1819. (file . find-file-other-window)
  1820. (wl . wl-other-frame))
  1821. "Setup the frame configuration for following links.
  1822. When following a link with Emacs, it may often be useful to display
  1823. this link in another window or frame. This variable can be used to
  1824. set this up for the different types of links.
  1825. For VM, use any of
  1826. `vm-visit-folder'
  1827. `vm-visit-folder-other-window'
  1828. `vm-visit-folder-other-frame'
  1829. For Gnus, use any of
  1830. `gnus'
  1831. `gnus-other-frame'
  1832. `org-gnus-no-new-news'
  1833. For FILE, use any of
  1834. `find-file'
  1835. `find-file-other-window'
  1836. `find-file-other-frame'
  1837. For Wanderlust use any of
  1838. `wl'
  1839. `wl-other-frame'
  1840. For the calendar, use the variable `calendar-setup'.
  1841. For BBDB, it is currently only possible to display the matches in
  1842. another window."
  1843. :group 'org-link-follow
  1844. :type '(list
  1845. (cons (const vm)
  1846. (choice
  1847. (const vm-visit-folder)
  1848. (const vm-visit-folder-other-window)
  1849. (const vm-visit-folder-other-frame)))
  1850. (cons (const vm-imap)
  1851. (choice
  1852. (const vm-visit-imap-folder)
  1853. (const vm-visit-imap-folder-other-window)
  1854. (const vm-visit-imap-folder-other-frame)))
  1855. (cons (const gnus)
  1856. (choice
  1857. (const gnus)
  1858. (const gnus-other-frame)
  1859. (const org-gnus-no-new-news)))
  1860. (cons (const file)
  1861. (choice
  1862. (const find-file)
  1863. (const find-file-other-window)
  1864. (const find-file-other-frame)))
  1865. (cons (const wl)
  1866. (choice
  1867. (const wl)
  1868. (const wl-other-frame)))))
  1869. (defcustom org-display-internal-link-with-indirect-buffer nil
  1870. "Non-nil means use indirect buffer to display infile links.
  1871. Activating internal links (from one location in a file to another location
  1872. in the same file) normally just jumps to the location. When the link is
  1873. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1874. is displayed in
  1875. another window. When this option is set, the other window actually displays
  1876. an indirect buffer clone of the current buffer, to avoid any visibility
  1877. changes to the current buffer."
  1878. :group 'org-link-follow
  1879. :type 'boolean)
  1880. (defcustom org-open-non-existing-files nil
  1881. "Non-nil means `org-open-file' will open non-existing files.
  1882. When nil, an error will be generated.
  1883. This variable applies only to external applications because they
  1884. might choke on non-existing files. If the link is to a file that
  1885. will be opened in Emacs, the variable is ignored."
  1886. :group 'org-link-follow
  1887. :type 'boolean)
  1888. (defcustom org-open-directory-means-index-dot-org nil
  1889. "Non-nil means a link to a directory really means to index.org.
  1890. When nil, following a directory link will run dired or open a finder/explorer
  1891. window on that directory."
  1892. :group 'org-link-follow
  1893. :type 'boolean)
  1894. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1895. "Non-nil means ask for confirmation before executing shell links.
  1896. Shell links can be dangerous: just think about a link
  1897. [[shell:rm -rf ~/*][Google Search]]
  1898. This link would show up in your Org document as \"Google Search\",
  1899. but really it would remove your entire home directory.
  1900. Therefore we advise against setting this variable to nil.
  1901. Just change it to `y-or-n-p' if you want to confirm with a
  1902. single keystroke rather than having to type \"yes\"."
  1903. :group 'org-link-follow
  1904. :type '(choice
  1905. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1906. (const :tag "with y-or-n (faster)" y-or-n-p)
  1907. (const :tag "no confirmation (dangerous)" nil)))
  1908. (put 'org-confirm-shell-link-function
  1909. 'safe-local-variable
  1910. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1911. (defcustom org-confirm-shell-link-not-regexp ""
  1912. "A regexp to skip confirmation for shell links."
  1913. :group 'org-link-follow
  1914. :version "24.1"
  1915. :type 'regexp)
  1916. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1917. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1918. Elisp links can be dangerous: just think about a link
  1919. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1920. This link would show up in your Org document as \"Google Search\",
  1921. but really it would remove your entire home directory.
  1922. Therefore we advise against setting this variable to nil.
  1923. Just change it to `y-or-n-p' if you want to confirm with a
  1924. single keystroke rather than having to type \"yes\"."
  1925. :group 'org-link-follow
  1926. :type '(choice
  1927. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1928. (const :tag "with y-or-n (faster)" y-or-n-p)
  1929. (const :tag "no confirmation (dangerous)" nil)))
  1930. (put 'org-confirm-shell-link-function
  1931. 'safe-local-variable
  1932. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1933. (defcustom org-confirm-elisp-link-not-regexp ""
  1934. "A regexp to skip confirmation for Elisp links."
  1935. :group 'org-link-follow
  1936. :version "24.1"
  1937. :type 'regexp)
  1938. (defconst org-file-apps-defaults-gnu
  1939. '((remote . emacs)
  1940. (system . mailcap)
  1941. (t . mailcap))
  1942. "Default file applications on a UNIX or GNU/Linux system.
  1943. See `org-file-apps'.")
  1944. (defconst org-file-apps-defaults-macosx
  1945. '((remote . emacs)
  1946. (system . "open %s")
  1947. ("ps.gz" . "gv %s")
  1948. ("eps.gz" . "gv %s")
  1949. ("dvi" . "xdvi %s")
  1950. ("fig" . "xfig %s")
  1951. (t . "open %s"))
  1952. "Default file applications on a macOS system.
  1953. The system \"open\" is known as a default, but we use X11 applications
  1954. for some files for which the OS does not have a good default.
  1955. See `org-file-apps'.")
  1956. (defconst org-file-apps-defaults-windowsnt
  1957. (list '(remote . emacs)
  1958. (cons 'system (lambda (file _path)
  1959. (with-no-warnings (w32-shell-execute "open" file))))
  1960. (cons t (lambda (file _path)
  1961. (with-no-warnings (w32-shell-execute "open" file)))))
  1962. "Default file applications on a Windows NT system.
  1963. The system \"open\" is used for most files.
  1964. See `org-file-apps'.")
  1965. (defcustom org-file-apps
  1966. '((auto-mode . emacs)
  1967. ("\\.mm\\'" . default)
  1968. ("\\.x?html?\\'" . default)
  1969. ("\\.pdf\\'" . default))
  1970. "External applications for opening `file:path' items in a document.
  1971. \\<org-mode-map>\
  1972. Org mode uses system defaults for different file types, but
  1973. you can use this variable to set the application for a given file
  1974. extension. The entries in this list are cons cells where the car identifies
  1975. files and the cdr the corresponding command.
  1976. Possible values for the file identifier are:
  1977. \"string\" A string as a file identifier can be interpreted in different
  1978. ways, depending on its contents:
  1979. - Alphanumeric characters only:
  1980. Match links with this file extension.
  1981. Example: (\"pdf\" . \"evince %s\")
  1982. to open PDFs with evince.
  1983. - Regular expression: Match links where the
  1984. filename matches the regexp. If you want to
  1985. use groups here, use shy groups.
  1986. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1987. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1988. to open *.html and *.xhtml with firefox.
  1989. - Regular expression which contains (non-shy) groups:
  1990. Match links where the whole link, including \"::\", and
  1991. anything after that, matches the regexp.
  1992. In a custom command string, %1, %2, etc. are replaced with
  1993. the parts of the link that were matched by the groups.
  1994. For backwards compatibility, if a command string is given
  1995. that does not use any of the group matches, this case is
  1996. handled identically to the second one (i.e. match against
  1997. file name only).
  1998. In a custom function, you can access the group matches with
  1999. (match-string n link).
  2000. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  2001. \"evince -p %1 %s\")
  2002. to open [[file:document.pdf::5]] with evince at page 5.
  2003. `directory' Matches a directory
  2004. `remote' Matches a remote file, accessible through tramp or efs.
  2005. Remote files most likely should be visited through Emacs
  2006. because external applications cannot handle such paths.
  2007. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2008. so all files Emacs knows how to handle. Using this with
  2009. command `emacs' will open most files in Emacs. Beware that this
  2010. will also open html files inside Emacs, unless you add
  2011. (\"html\" . default) to the list as well.
  2012. `system' The system command to open files, like `open' on Windows
  2013. and macOS, and mailcap under GNU/Linux. This is the command
  2014. that will be selected if you call `org-open-at-point' with a
  2015. double prefix argument (`\\[universal-argument] \
  2016. \\[universal-argument] \\[org-open-at-point]').
  2017. t Default for files not matched by any of the other options.
  2018. Possible values for the command are:
  2019. `emacs' The file will be visited by the current Emacs process.
  2020. `default' Use the default application for this file type, which is the
  2021. association for t in the list, most likely in the system-specific
  2022. part. This can be used to overrule an unwanted setting in the
  2023. system-specific variable.
  2024. `system' Use the system command for opening files, like \"open\".
  2025. This command is specified by the entry whose car is `system'.
  2026. Most likely, the system-specific version of this variable
  2027. does define this command, but you can overrule/replace it
  2028. here.
  2029. `mailcap' Use command specified in the mailcaps.
  2030. string A command to be executed by a shell; %s will be replaced
  2031. by the path to the file.
  2032. function A Lisp function, which will be called with two arguments:
  2033. the file path and the original link string, without the
  2034. \"file:\" prefix.
  2035. For more examples, see the system specific constants
  2036. `org-file-apps-defaults-macosx'
  2037. `org-file-apps-defaults-windowsnt'
  2038. `org-file-apps-defaults-gnu'."
  2039. :group 'org-link-follow
  2040. :type '(repeat
  2041. (cons (choice :value ""
  2042. (string :tag "Extension")
  2043. (const :tag "System command to open files" system)
  2044. (const :tag "Default for unrecognized files" t)
  2045. (const :tag "Remote file" remote)
  2046. (const :tag "Links to a directory" directory)
  2047. (const :tag "Any files that have Emacs modes"
  2048. auto-mode))
  2049. (choice :value ""
  2050. (const :tag "Visit with Emacs" emacs)
  2051. (const :tag "Use default" default)
  2052. (const :tag "Use the system command" system)
  2053. (string :tag "Command")
  2054. (function :tag "Function")))))
  2055. (defcustom org-doi-server-url "http://dx.doi.org/"
  2056. "The URL of the DOI server."
  2057. :type 'string
  2058. :version "24.3"
  2059. :group 'org-link-follow)
  2060. (defgroup org-refile nil
  2061. "Options concerning refiling entries in Org mode."
  2062. :tag "Org Refile"
  2063. :group 'org)
  2064. (defcustom org-directory "~/org"
  2065. "Directory with Org files.
  2066. This is just a default location to look for Org files. There is no need
  2067. at all to put your files into this directory. It is used in the
  2068. following situations:
  2069. 1. When a capture template specifies a target file that is not an
  2070. absolute path. The path will then be interpreted relative to
  2071. `org-directory'
  2072. 2. When the value of variable `org-agenda-files' is a single file, any
  2073. relative paths in this file will be taken as relative to
  2074. `org-directory'."
  2075. :group 'org-refile
  2076. :group 'org-capture
  2077. :type 'directory)
  2078. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2079. "Default target for storing notes.
  2080. Used as a fall back file for org-capture.el, for templates that
  2081. do not specify a target file."
  2082. :group 'org-refile
  2083. :group 'org-capture
  2084. :type 'file)
  2085. (defcustom org-goto-interface 'outline
  2086. "The default interface to be used for `org-goto'.
  2087. Allowed values are:
  2088. outline The interface shows an outline of the relevant file
  2089. and the correct heading is found by moving through
  2090. the outline or by searching with incremental search.
  2091. outline-path-completion Headlines in the current buffer are offered via
  2092. completion. This is the interface also used by
  2093. the refile command."
  2094. :group 'org-refile
  2095. :type '(choice
  2096. (const :tag "Outline" outline)
  2097. (const :tag "Outline-path-completion" outline-path-completion)))
  2098. (defcustom org-goto-max-level 5
  2099. "Maximum target level when running `org-goto' with refile interface."
  2100. :group 'org-refile
  2101. :type 'integer)
  2102. (defcustom org-reverse-note-order nil
  2103. "Non-nil means store new notes at the beginning of a file or entry.
  2104. When nil, new notes will be filed to the end of a file or entry.
  2105. This can also be a list with cons cells of regular expressions that
  2106. are matched against file names, and values."
  2107. :group 'org-capture
  2108. :group 'org-refile
  2109. :type '(choice
  2110. (const :tag "Reverse always" t)
  2111. (const :tag "Reverse never" nil)
  2112. (repeat :tag "By file name regexp"
  2113. (cons regexp boolean))))
  2114. (defcustom org-log-refile nil
  2115. "Information to record when a task is refiled.
  2116. Possible values are:
  2117. nil Don't add anything
  2118. time Add a time stamp to the task
  2119. note Prompt for a note and add it with template `org-log-note-headings'
  2120. This option can also be set with on a per-file-basis with
  2121. #+STARTUP: nologrefile
  2122. #+STARTUP: logrefile
  2123. #+STARTUP: lognoterefile
  2124. You can have local logging settings for a subtree by setting the LOGGING
  2125. property to one or more of these keywords.
  2126. When bulk-refiling from the agenda, the value `note' is forbidden and
  2127. will temporarily be changed to `time'."
  2128. :group 'org-refile
  2129. :group 'org-progress
  2130. :version "24.1"
  2131. :type '(choice
  2132. (const :tag "No logging" nil)
  2133. (const :tag "Record timestamp" time)
  2134. (const :tag "Record timestamp with note." note)))
  2135. (defcustom org-refile-targets nil
  2136. "Targets for refiling entries with `\\[org-refile]'.
  2137. This is a list of cons cells. Each cell contains:
  2138. - a specification of the files to be considered, either a list of files,
  2139. or a symbol whose function or variable value will be used to retrieve
  2140. a file name or a list of file names. If you use `org-agenda-files' for
  2141. that, all agenda files will be scanned for targets. Nil means consider
  2142. headings in the current buffer.
  2143. - A specification of how to find candidate refile targets. This may be
  2144. any of:
  2145. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2146. This tag has to be present in all target headlines, inheritance will
  2147. not be considered.
  2148. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2149. todo keyword.
  2150. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2151. headlines that are refiling targets.
  2152. - a cons cell (:level . N). Any headline of level N is considered a target.
  2153. Note that, when `org-odd-levels-only' is set, level corresponds to
  2154. order in hierarchy, not to the number of stars.
  2155. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2156. Note that, when `org-odd-levels-only' is set, level corresponds to
  2157. order in hierarchy, not to the number of stars.
  2158. Each element of this list generates a set of possible targets.
  2159. The union of these sets is presented (with completion) to
  2160. the user by `org-refile'.
  2161. You can set the variable `org-refile-target-verify-function' to a function
  2162. to verify each headline found by the simple criteria above.
  2163. When this variable is nil, all top-level headlines in the current buffer
  2164. are used, equivalent to the value `((nil . (:level . 1))'."
  2165. :group 'org-refile
  2166. :type '(repeat
  2167. (cons
  2168. (choice :value org-agenda-files
  2169. (const :tag "All agenda files" org-agenda-files)
  2170. (const :tag "Current buffer" nil)
  2171. (function) (variable) (file))
  2172. (choice :tag "Identify target headline by"
  2173. (cons :tag "Specific tag" (const :value :tag) (string))
  2174. (cons :tag "TODO keyword" (const :value :todo) (string))
  2175. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2176. (cons :tag "Level number" (const :value :level) (integer))
  2177. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2178. (defcustom org-refile-target-verify-function nil
  2179. "Function to verify if the headline at point should be a refile target.
  2180. The function will be called without arguments, with point at the
  2181. beginning of the headline. It should return t and leave point
  2182. where it is if the headline is a valid target for refiling.
  2183. If the target should not be selected, the function must return nil.
  2184. In addition to this, it may move point to a place from where the search
  2185. should be continued. For example, the function may decide that the entire
  2186. subtree of the current entry should be excluded and move point to the end
  2187. of the subtree."
  2188. :group 'org-refile
  2189. :type '(choice
  2190. (const nil)
  2191. (function)))
  2192. (defcustom org-refile-use-cache nil
  2193. "Non-nil means cache refile targets to speed up the process.
  2194. \\<org-mode-map>\
  2195. The cache for a particular file will be updated automatically when
  2196. the buffer has been killed, or when any of the marker used for flagging
  2197. refile targets no longer points at a live buffer.
  2198. If you have added new entries to a buffer that might themselves be targets,
  2199. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2200. if you find that easier, \
  2201. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2202. \\[org-refile]'."
  2203. :group 'org-refile
  2204. :version "24.1"
  2205. :type 'boolean)
  2206. (defcustom org-refile-use-outline-path nil
  2207. "Non-nil means provide refile targets as paths.
  2208. So a level 3 headline will be available as level1/level2/level3.
  2209. When the value is `file', also include the file name (without directory)
  2210. into the path. In this case, you can also stop the completion after
  2211. the file name, to get entries inserted as top level in the file.
  2212. When `full-file-path', include the full file path.
  2213. When `buffer-name', use the buffer name."
  2214. :group 'org-refile
  2215. :type '(choice
  2216. (const :tag "Not" nil)
  2217. (const :tag "Yes" t)
  2218. (const :tag "Start with file name" file)
  2219. (const :tag "Start with full file path" full-file-path)
  2220. (const :tag "Start with buffer name" buffer-name)))
  2221. (defcustom org-outline-path-complete-in-steps t
  2222. "Non-nil means complete the outline path in hierarchical steps.
  2223. When Org uses the refile interface to select an outline path (see
  2224. `org-refile-use-outline-path'), the completion of the path can be
  2225. done in a single go, or it can be done in steps down the headline
  2226. hierarchy. Going in steps is probably the best if you do not use
  2227. a special completion package like `ido' or `icicles'. However,
  2228. when using these packages, going in one step can be very fast,
  2229. while still showing the whole path to the entry."
  2230. :group 'org-refile
  2231. :type 'boolean)
  2232. (defcustom org-refile-allow-creating-parent-nodes nil
  2233. "Non-nil means allow the creation of new nodes as refile targets.
  2234. New nodes are then created by adding \"/new node name\" to the completion
  2235. of an existing node. When the value of this variable is `confirm',
  2236. new node creation must be confirmed by the user (recommended).
  2237. When nil, the completion must match an existing entry.
  2238. Note that, if the new heading is not seen by the criteria
  2239. listed in `org-refile-targets', multiple instances of the same
  2240. heading would be created by trying again to file under the new
  2241. heading."
  2242. :group 'org-refile
  2243. :type '(choice
  2244. (const :tag "Never" nil)
  2245. (const :tag "Always" t)
  2246. (const :tag "Prompt for confirmation" confirm)))
  2247. (defcustom org-refile-active-region-within-subtree nil
  2248. "Non-nil means also refile active region within a subtree.
  2249. By default `org-refile' doesn't allow refiling regions if they
  2250. don't contain a set of subtrees, but it might be convenient to
  2251. do so sometimes: in that case, the first line of the region is
  2252. converted to a headline before refiling."
  2253. :group 'org-refile
  2254. :version "24.1"
  2255. :type 'boolean)
  2256. (defgroup org-todo nil
  2257. "Options concerning TODO items in Org mode."
  2258. :tag "Org TODO"
  2259. :group 'org)
  2260. (defgroup org-progress nil
  2261. "Options concerning Progress logging in Org mode."
  2262. :tag "Org Progress"
  2263. :group 'org-time)
  2264. (defvar org-todo-interpretation-widgets
  2265. '((:tag "Sequence (cycling hits every state)" sequence)
  2266. (:tag "Type (cycling directly to DONE)" type))
  2267. "The available interpretation symbols for customizing `org-todo-keywords'.
  2268. Interested libraries should add to this list.")
  2269. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2270. "List of TODO entry keyword sequences and their interpretation.
  2271. \\<org-mode-map>This is a list of sequences.
  2272. Each sequence starts with a symbol, either `sequence' or `type',
  2273. indicating if the keywords should be interpreted as a sequence of
  2274. action steps, or as different types of TODO items. The first
  2275. keywords are states requiring action - these states will select a headline
  2276. for inclusion into the global TODO list Org produces. If one of the
  2277. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2278. signify that no further action is necessary. If \"|\" is not found,
  2279. the last keyword is treated as the only DONE state of the sequence.
  2280. The command `\\[org-todo]' cycles an entry through these states, and one
  2281. additional state where no keyword is present. For details about this
  2282. cycling, see the manual.
  2283. TODO keywords and interpretation can also be set on a per-file basis with
  2284. the special #+SEQ_TODO and #+TYP_TODO lines.
  2285. Each keyword can optionally specify a character for fast state selection
  2286. \(in combination with the variable `org-use-fast-todo-selection')
  2287. and specifiers for state change logging, using the same syntax that
  2288. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2289. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2290. indicates to record a time stamp each time this state is selected.
  2291. Each keyword may also specify if a timestamp or a note should be
  2292. recorded when entering or leaving the state, by adding additional
  2293. characters in the parenthesis after the keyword. This looks like this:
  2294. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2295. record only the time of the state change. With X and Y being either
  2296. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2297. Y when leaving the state if and only if the *target* state does not
  2298. define X. You may omit any of the fast-selection key or X or /Y,
  2299. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2300. For backward compatibility, this variable may also be just a list
  2301. of keywords. In this case the interpretation (sequence or type) will be
  2302. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2303. :group 'org-todo
  2304. :group 'org-keywords
  2305. :type '(choice
  2306. (repeat :tag "Old syntax, just keywords"
  2307. (string :tag "Keyword"))
  2308. (repeat :tag "New syntax"
  2309. (cons
  2310. (choice
  2311. :tag "Interpretation"
  2312. ;;Quick and dirty way to see
  2313. ;;`org-todo-interpretations'. This takes the
  2314. ;;place of item arguments
  2315. :convert-widget
  2316. (lambda (widget)
  2317. (widget-put widget
  2318. :args (mapcar
  2319. (lambda (x)
  2320. (widget-convert
  2321. (cons 'const x)))
  2322. org-todo-interpretation-widgets))
  2323. widget))
  2324. (repeat
  2325. (string :tag "Keyword"))))))
  2326. (defvar-local org-todo-keywords-1 nil
  2327. "All TODO and DONE keywords active in a buffer.")
  2328. (defvar org-todo-keywords-for-agenda nil)
  2329. (defvar org-done-keywords-for-agenda nil)
  2330. (defvar org-todo-keyword-alist-for-agenda nil)
  2331. (defvar org-tag-alist-for-agenda nil
  2332. "Alist of all tags from all agenda files.")
  2333. (defvar org-tag-groups-alist-for-agenda nil
  2334. "Alist of all groups tags from all current agenda files.")
  2335. (defvar-local org-tag-groups-alist nil)
  2336. (defvar org-agenda-contributing-files nil)
  2337. (defvar-local org-current-tag-alist nil
  2338. "Alist of all tag groups in current buffer.
  2339. This variable takes into consideration `org-tag-alist',
  2340. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2341. (defvar-local org-not-done-keywords nil)
  2342. (defvar-local org-done-keywords nil)
  2343. (defvar-local org-todo-heads nil)
  2344. (defvar-local org-todo-sets nil)
  2345. (defvar-local org-todo-log-states nil)
  2346. (defvar-local org-todo-kwd-alist nil)
  2347. (defvar-local org-todo-key-alist nil)
  2348. (defvar-local org-todo-key-trigger nil)
  2349. (defcustom org-todo-interpretation 'sequence
  2350. "Controls how TODO keywords are interpreted.
  2351. This variable is in principle obsolete and is only used for
  2352. backward compatibility, if the interpretation of todo keywords is
  2353. not given already in `org-todo-keywords'. See that variable for
  2354. more information."
  2355. :group 'org-todo
  2356. :group 'org-keywords
  2357. :type '(choice (const sequence)
  2358. (const type)))
  2359. (defcustom org-use-fast-todo-selection t
  2360. "\\<org-mode-map>\
  2361. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2362. This variable describes if and under what circumstances the cycling
  2363. mechanism for TODO keywords will be replaced by a single-key, direct
  2364. selection scheme.
  2365. When nil, fast selection is never used.
  2366. When the symbol `prefix', it will be used when `org-todo' is called
  2367. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2368. in an Org buffer, and
  2369. `\\[universal-argument] t' in an agenda buffer.
  2370. When t, fast selection is used by default. In this case, the prefix
  2371. argument forces cycling instead.
  2372. In all cases, the special interface is only used if access keys have
  2373. actually been assigned by the user, i.e. if keywords in the configuration
  2374. are followed by a letter in parenthesis, like TODO(t)."
  2375. :group 'org-todo
  2376. :type '(choice
  2377. (const :tag "Never" nil)
  2378. (const :tag "By default" t)
  2379. (const :tag "Only with C-u C-c C-t" prefix)))
  2380. (defcustom org-provide-todo-statistics t
  2381. "Non-nil means update todo statistics after insert and toggle.
  2382. ALL-HEADLINES means update todo statistics by including headlines
  2383. with no TODO keyword as well, counting them as not done.
  2384. A list of TODO keywords means the same, but skip keywords that are
  2385. not in this list.
  2386. When set to a list of two lists, the first list contains keywords
  2387. to consider as TODO keywords, the second list contains keywords
  2388. to consider as DONE keywords.
  2389. When this is set, todo statistics is updated in the parent of the
  2390. current entry each time a todo state is changed."
  2391. :group 'org-todo
  2392. :type '(choice
  2393. (const :tag "Yes, only for TODO entries" t)
  2394. (const :tag "Yes, including all entries" all-headlines)
  2395. (repeat :tag "Yes, for TODOs in this list"
  2396. (string :tag "TODO keyword"))
  2397. (list :tag "Yes, for TODOs and DONEs in these lists"
  2398. (repeat (string :tag "TODO keyword"))
  2399. (repeat (string :tag "DONE keyword")))
  2400. (other :tag "No TODO statistics" nil)))
  2401. (defcustom org-hierarchical-todo-statistics t
  2402. "Non-nil means TODO statistics covers just direct children.
  2403. When nil, all entries in the subtree are considered.
  2404. This has only an effect if `org-provide-todo-statistics' is set.
  2405. To set this to nil for only a single subtree, use a COOKIE_DATA
  2406. property and include the word \"recursive\" into the value."
  2407. :group 'org-todo
  2408. :type 'boolean)
  2409. (defcustom org-after-todo-state-change-hook nil
  2410. "Hook which is run after the state of a TODO item was changed.
  2411. The new state (a string with a TODO keyword, or nil) is available in the
  2412. Lisp variable `org-state'."
  2413. :group 'org-todo
  2414. :type 'hook)
  2415. (defvar org-blocker-hook nil
  2416. "Hook for functions that are allowed to block a state change.
  2417. Functions in this hook should not modify the buffer.
  2418. Each function gets as its single argument a property list,
  2419. see `org-trigger-hook' for more information about this list.
  2420. If any of the functions in this hook returns nil, the state change
  2421. is blocked.")
  2422. (defvar org-trigger-hook nil
  2423. "Hook for functions that are triggered by a state change.
  2424. Each function gets as its single argument a property list with at
  2425. least the following elements:
  2426. (:type type-of-change :position pos-at-entry-start
  2427. :from old-state :to new-state)
  2428. Depending on the type, more properties may be present.
  2429. This mechanism is currently implemented for:
  2430. TODO state changes
  2431. ------------------
  2432. :type todo-state-change
  2433. :from previous state (keyword as a string), or nil, or a symbol
  2434. `todo' or `done', to indicate the general type of state.
  2435. :to new state, like in :from")
  2436. (defcustom org-enforce-todo-dependencies nil
  2437. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2438. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2439. be blocked if any prior sibling is not yet done.
  2440. Finally, if the parent is blocked because of ordered siblings of its own,
  2441. the child will also be blocked."
  2442. :set (lambda (var val)
  2443. (set var val)
  2444. (if val
  2445. (add-hook 'org-blocker-hook
  2446. 'org-block-todo-from-children-or-siblings-or-parent)
  2447. (remove-hook 'org-blocker-hook
  2448. 'org-block-todo-from-children-or-siblings-or-parent)))
  2449. :group 'org-todo
  2450. :type 'boolean)
  2451. (defcustom org-enforce-todo-checkbox-dependencies nil
  2452. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2453. When this is nil, checkboxes have no influence on switching TODO states.
  2454. When non-nil, you first need to check off all check boxes before the TODO
  2455. entry can be switched to DONE.
  2456. This variable needs to be set before org.el is loaded, and you need to
  2457. restart Emacs after a change to make the change effective. The only way
  2458. to change is while Emacs is running is through the customize interface."
  2459. :set (lambda (var val)
  2460. (set var val)
  2461. (if val
  2462. (add-hook 'org-blocker-hook
  2463. 'org-block-todo-from-checkboxes)
  2464. (remove-hook 'org-blocker-hook
  2465. 'org-block-todo-from-checkboxes)))
  2466. :group 'org-todo
  2467. :type 'boolean)
  2468. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2469. "Non-nil means inserting a TODO heading is treated as state change.
  2470. So when the command `\\[org-insert-todo-heading]' is used, state change
  2471. logging will apply if appropriate. When nil, the new TODO item will
  2472. be inserted directly, and no logging will take place."
  2473. :group 'org-todo
  2474. :type 'boolean)
  2475. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2476. "Non-nil means switching TODO states with S-cursor counts as state change.
  2477. This is the default behavior. However, setting this to nil allows a
  2478. convenient way to select a TODO state and bypass any logging associated
  2479. with that."
  2480. :group 'org-todo
  2481. :type 'boolean)
  2482. (defcustom org-todo-state-tags-triggers nil
  2483. "Tag changes that should be triggered by TODO state changes.
  2484. This is a list. Each entry is
  2485. (state-change (tag . flag) .......)
  2486. State-change can be a string with a state, and empty string to indicate the
  2487. state that has no TODO keyword, or it can be one of the symbols `todo'
  2488. or `done', meaning any not-done or done state, respectively."
  2489. :group 'org-todo
  2490. :group 'org-tags
  2491. :type '(repeat
  2492. (cons (choice :tag "When changing to"
  2493. (const :tag "Not-done state" todo)
  2494. (const :tag "Done state" done)
  2495. (string :tag "State"))
  2496. (repeat
  2497. (cons :tag "Tag action"
  2498. (string :tag "Tag")
  2499. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2500. (defcustom org-log-done nil
  2501. "Information to record when a task moves to the DONE state.
  2502. Possible values are:
  2503. nil Don't add anything, just change the keyword
  2504. time Add a time stamp to the task
  2505. note Prompt for a note and add it with template `org-log-note-headings'
  2506. This option can also be set with on a per-file-basis with
  2507. #+STARTUP: nologdone
  2508. #+STARTUP: logdone
  2509. #+STARTUP: lognotedone
  2510. You can have local logging settings for a subtree by setting the LOGGING
  2511. property to one or more of these keywords."
  2512. :group 'org-todo
  2513. :group 'org-progress
  2514. :type '(choice
  2515. (const :tag "No logging" nil)
  2516. (const :tag "Record CLOSED timestamp" time)
  2517. (const :tag "Record CLOSED timestamp with note." note)))
  2518. ;; Normalize old uses of org-log-done.
  2519. (cond
  2520. ((eq org-log-done t) (setq org-log-done 'time))
  2521. ((and (listp org-log-done) (memq 'done org-log-done))
  2522. (setq org-log-done 'note)))
  2523. (defcustom org-log-reschedule nil
  2524. "Information to record when the scheduling date of a tasks is modified.
  2525. Possible values are:
  2526. nil Don't add anything, just change the date
  2527. time Add a time stamp to the task
  2528. note Prompt for a note and add it with template `org-log-note-headings'
  2529. This option can also be set with on a per-file-basis with
  2530. #+STARTUP: nologreschedule
  2531. #+STARTUP: logreschedule
  2532. #+STARTUP: lognotereschedule"
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type '(choice
  2536. (const :tag "No logging" nil)
  2537. (const :tag "Record timestamp" time)
  2538. (const :tag "Record timestamp with note." note)))
  2539. (defcustom org-log-redeadline nil
  2540. "Information to record when the deadline date of a tasks is modified.
  2541. Possible values are:
  2542. nil Don't add anything, just change the date
  2543. time Add a time stamp to the task
  2544. note Prompt for a note and add it with template `org-log-note-headings'
  2545. This option can also be set with on a per-file-basis with
  2546. #+STARTUP: nologredeadline
  2547. #+STARTUP: logredeadline
  2548. #+STARTUP: lognoteredeadline
  2549. You can have local logging settings for a subtree by setting the LOGGING
  2550. property to one or more of these keywords."
  2551. :group 'org-todo
  2552. :group 'org-progress
  2553. :type '(choice
  2554. (const :tag "No logging" nil)
  2555. (const :tag "Record timestamp" time)
  2556. (const :tag "Record timestamp with note." note)))
  2557. (defcustom org-log-note-clock-out nil
  2558. "Non-nil means record a note when clocking out of an item.
  2559. This can also be configured on a per-file basis by adding one of
  2560. the following lines anywhere in the buffer:
  2561. #+STARTUP: lognoteclock-out
  2562. #+STARTUP: nolognoteclock-out"
  2563. :group 'org-todo
  2564. :group 'org-progress
  2565. :type 'boolean)
  2566. (defcustom org-log-done-with-time t
  2567. "Non-nil means the CLOSED time stamp will contain date and time.
  2568. When nil, only the date will be recorded."
  2569. :group 'org-progress
  2570. :type 'boolean)
  2571. (defcustom org-log-note-headings
  2572. '((done . "CLOSING NOTE %t")
  2573. (state . "State %-12s from %-12S %t")
  2574. (note . "Note taken on %t")
  2575. (reschedule . "Rescheduled from %S on %t")
  2576. (delschedule . "Not scheduled, was %S on %t")
  2577. (redeadline . "New deadline from %S on %t")
  2578. (deldeadline . "Removed deadline, was %S on %t")
  2579. (refile . "Refiled on %t")
  2580. (clock-out . ""))
  2581. "Headings for notes added to entries.
  2582. The value is an alist, with the car being a symbol indicating the
  2583. note context, and the cdr is the heading to be used. The heading
  2584. may also be the empty string. The following placeholders can be
  2585. used:
  2586. %t a time stamp.
  2587. %T an active time stamp instead the default inactive one
  2588. %d a short-format time stamp.
  2589. %D an active short-format time stamp.
  2590. %s the new TODO state or time stamp (inactive), in double quotes.
  2591. %S the old TODO state or time stamp (inactive), in double quotes.
  2592. %u the user name.
  2593. %U full user name.
  2594. In fact, it is not a good idea to change the `state' entry,
  2595. because Agenda Log mode depends on the format of these entries."
  2596. :group 'org-todo
  2597. :group 'org-progress
  2598. :type '(list :greedy t
  2599. (cons (const :tag "Heading when closing an item" done) string)
  2600. (cons (const :tag
  2601. "Heading when changing todo state (todo sequence only)"
  2602. state) string)
  2603. (cons (const :tag "Heading when just taking a note" note) string)
  2604. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2605. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2606. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2607. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2608. (cons (const :tag "Heading when refiling" refile) string)
  2609. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2610. (unless (assq 'note org-log-note-headings)
  2611. (push '(note . "%t") org-log-note-headings))
  2612. (defcustom org-log-into-drawer nil
  2613. "Non-nil means insert state change notes and time stamps into a drawer.
  2614. When nil, state changes notes will be inserted after the headline and
  2615. any scheduling and clock lines, but not inside a drawer.
  2616. The value of this variable should be the name of the drawer to use.
  2617. LOGBOOK is proposed as the default drawer for this purpose, you can
  2618. also set this to a string to define the drawer of your choice.
  2619. A value of t is also allowed, representing \"LOGBOOK\".
  2620. A value of t or nil can also be set with on a per-file-basis with
  2621. #+STARTUP: logdrawer
  2622. #+STARTUP: nologdrawer
  2623. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2624. will be ignored.
  2625. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2626. a subtree.
  2627. Do not check directly this variable in a Lisp program. Call
  2628. function `org-log-into-drawer' instead."
  2629. :group 'org-todo
  2630. :group 'org-progress
  2631. :type '(choice
  2632. (const :tag "Not into a drawer" nil)
  2633. (const :tag "LOGBOOK" t)
  2634. (string :tag "Other")))
  2635. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2636. (defun org-log-into-drawer ()
  2637. "Name of the log drawer, as a string, or nil.
  2638. This is the value of `org-log-into-drawer'. However, if the
  2639. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2640. be used instead of the default value."
  2641. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2642. (cond ((equal p "nil") nil)
  2643. ((equal p "t") "LOGBOOK")
  2644. ((stringp p) p)
  2645. (p "LOGBOOK")
  2646. ((stringp org-log-into-drawer) org-log-into-drawer)
  2647. (org-log-into-drawer "LOGBOOK"))))
  2648. (defcustom org-log-state-notes-insert-after-drawers nil
  2649. "Non-nil means insert state change notes after any drawers in entry.
  2650. Only the drawers that *immediately* follow the headline and the
  2651. deadline/scheduled line are skipped.
  2652. When nil, insert notes right after the heading and perhaps the line
  2653. with deadline/scheduling if present.
  2654. This variable will have no effect if `org-log-into-drawer' is
  2655. set."
  2656. :group 'org-todo
  2657. :group 'org-progress
  2658. :type 'boolean)
  2659. (defcustom org-log-states-order-reversed t
  2660. "Non-nil means the latest state note will be directly after heading.
  2661. When nil, the state change notes will be ordered according to time.
  2662. This option can also be set with on a per-file-basis with
  2663. #+STARTUP: logstatesreversed
  2664. #+STARTUP: nologstatesreversed"
  2665. :group 'org-todo
  2666. :group 'org-progress
  2667. :type 'boolean)
  2668. (defcustom org-todo-repeat-to-state nil
  2669. "The TODO state to which a repeater should return the repeating task.
  2670. By default this is the first task in a TODO sequence, or the previous state
  2671. in a TODO_TYP set. But you can specify another task here.
  2672. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2673. :group 'org-todo
  2674. :version "24.1"
  2675. :type '(choice (const :tag "Head of sequence" nil)
  2676. (string :tag "Specific state")))
  2677. (defcustom org-log-repeat 'time
  2678. "Non-nil means record moving through the DONE state when triggering repeat.
  2679. An auto-repeating task is immediately switched back to TODO when
  2680. marked DONE. If you are not logging state changes (by adding \"@\"
  2681. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2682. record a closing note, there will be no record of the task moving
  2683. through DONE. This variable forces taking a note anyway.
  2684. nil Don't force a record
  2685. time Record a time stamp
  2686. note Prompt for a note and add it with template `org-log-note-headings'
  2687. This option can also be set with on a per-file-basis with
  2688. #+STARTUP: nologrepeat
  2689. #+STARTUP: logrepeat
  2690. #+STARTUP: lognoterepeat
  2691. You can have local logging settings for a subtree by setting the LOGGING
  2692. property to one or more of these keywords."
  2693. :group 'org-todo
  2694. :group 'org-progress
  2695. :type '(choice
  2696. (const :tag "Don't force a record" nil)
  2697. (const :tag "Force recording the DONE state" time)
  2698. (const :tag "Force recording a note with the DONE state" note)))
  2699. (defgroup org-priorities nil
  2700. "Priorities in Org mode."
  2701. :tag "Org Priorities"
  2702. :group 'org-todo)
  2703. (defcustom org-enable-priority-commands t
  2704. "Non-nil means priority commands are active.
  2705. When nil, these commands will be disabled, so that you never accidentally
  2706. set a priority."
  2707. :group 'org-priorities
  2708. :type 'boolean)
  2709. (defcustom org-highest-priority ?A
  2710. "The highest priority of TODO items. A character like ?A, ?B etc.
  2711. Must have a smaller ASCII number than `org-lowest-priority'."
  2712. :group 'org-priorities
  2713. :type 'character)
  2714. (defcustom org-lowest-priority ?C
  2715. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2716. Must have a larger ASCII number than `org-highest-priority'."
  2717. :group 'org-priorities
  2718. :type 'character)
  2719. (defcustom org-default-priority ?B
  2720. "The default priority of TODO items.
  2721. This is the priority an item gets if no explicit priority is given.
  2722. When starting to cycle on an empty priority the first step in the cycle
  2723. depends on `org-priority-start-cycle-with-default'. The resulting first
  2724. step priority must not exceed the range from `org-highest-priority' to
  2725. `org-lowest-priority' which means that `org-default-priority' has to be
  2726. in this range exclusive or inclusive the range boundaries. Else the
  2727. first step refuses to set the default and the second will fall back
  2728. to (depending on the command used) the highest or lowest priority."
  2729. :group 'org-priorities
  2730. :type 'character)
  2731. (defcustom org-priority-start-cycle-with-default t
  2732. "Non-nil means start with default priority when starting to cycle.
  2733. When this is nil, the first step in the cycle will be (depending on the
  2734. command used) one higher or lower than the default priority.
  2735. See also `org-default-priority'."
  2736. :group 'org-priorities
  2737. :type 'boolean)
  2738. (defcustom org-get-priority-function nil
  2739. "Function to extract the priority from a string.
  2740. The string is normally the headline. If this is nil Org computes the
  2741. priority from the priority cookie like [#A] in the headline. It returns
  2742. an integer, increasing by 1000 for each priority level.
  2743. The user can set a different function here, which should take a string
  2744. as an argument and return the numeric priority."
  2745. :group 'org-priorities
  2746. :version "24.1"
  2747. :type '(choice
  2748. (const nil)
  2749. (function)))
  2750. (defgroup org-time nil
  2751. "Options concerning time stamps and deadlines in Org mode."
  2752. :tag "Org Time"
  2753. :group 'org)
  2754. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2755. "Number of minutes to round time stamps to.
  2756. \\<org-mode-map>\
  2757. These are two values, the first applies when first creating a time stamp.
  2758. The second applies when changing it with the commands `S-up' and `S-down'.
  2759. When changing the time stamp, this means that it will change in steps
  2760. of N minutes, as given by the second value.
  2761. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2762. numbers should be factors of 60, so for example 5, 10, 15.
  2763. When this is larger than 1, you can still force an exact time stamp by using
  2764. a double prefix argument to a time stamp command like \
  2765. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2766. and by using a prefix arg to `S-up/down' to specify the exact number
  2767. of minutes to shift."
  2768. :group 'org-time
  2769. :get (lambda (var) ; Make sure both elements are there
  2770. (if (integerp (default-value var))
  2771. (list (default-value var) 5)
  2772. (default-value var)))
  2773. :type '(list
  2774. (integer :tag "when inserting times")
  2775. (integer :tag "when modifying times")))
  2776. ;; Normalize old customizations of this variable.
  2777. (when (integerp org-time-stamp-rounding-minutes)
  2778. (setq org-time-stamp-rounding-minutes
  2779. (list org-time-stamp-rounding-minutes
  2780. org-time-stamp-rounding-minutes)))
  2781. (defcustom org-display-custom-times nil
  2782. "Non-nil means overlay custom formats over all time stamps.
  2783. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2784. To turn this on on a per-file basis, insert anywhere in the file:
  2785. #+STARTUP: customtime"
  2786. :group 'org-time
  2787. :set 'set-default
  2788. :type 'sexp)
  2789. (make-variable-buffer-local 'org-display-custom-times)
  2790. (defcustom org-time-stamp-custom-formats
  2791. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2792. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2793. These are overlaid over the default ISO format if the variable
  2794. `org-display-custom-times' is set. Time like %H:%M should be at the
  2795. end of the second format. The custom formats are also honored by export
  2796. commands, if custom time display is turned on at the time of export."
  2797. :group 'org-time
  2798. :type 'sexp)
  2799. (defun org-time-stamp-format (&optional long inactive)
  2800. "Get the right format for a time string."
  2801. (let ((f (if long (cdr org-time-stamp-formats)
  2802. (car org-time-stamp-formats))))
  2803. (if inactive
  2804. (concat "[" (substring f 1 -1) "]")
  2805. f)))
  2806. (defcustom org-deadline-warning-days 14
  2807. "Number of days before expiration during which a deadline becomes active.
  2808. This variable governs the display in sparse trees and in the agenda.
  2809. When 0 or negative, it means use this number (the absolute value of it)
  2810. even if a deadline has a different individual lead time specified.
  2811. Custom commands can set this variable in the options section."
  2812. :group 'org-time
  2813. :group 'org-agenda-daily/weekly
  2814. :type 'integer)
  2815. (defcustom org-scheduled-delay-days 0
  2816. "Number of days before a scheduled item becomes active.
  2817. This variable governs the display in sparse trees and in the agenda.
  2818. The default value (i.e. 0) means: don't delay scheduled item.
  2819. When negative, it means use this number (the absolute value of it)
  2820. even if a scheduled item has a different individual delay time
  2821. specified.
  2822. Custom commands can set this variable in the options section."
  2823. :group 'org-time
  2824. :group 'org-agenda-daily/weekly
  2825. :version "24.4"
  2826. :package-version '(Org . "8.0")
  2827. :type 'integer)
  2828. (defcustom org-read-date-prefer-future t
  2829. "Non-nil means assume future for incomplete date input from user.
  2830. This affects the following situations:
  2831. 1. The user gives a month but not a year.
  2832. For example, if it is April and you enter \"feb 2\", this will be read
  2833. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2834. 2. The user gives a day, but no month.
  2835. For example, if today is the 15th, and you enter \"3\", Org will read
  2836. this as the third of *next* month. However, if you enter \"17\",
  2837. it will be considered as *this* month.
  2838. If you set this variable to the symbol `time', then also the following
  2839. will work:
  2840. 3. If the user gives a time.
  2841. If the time is before now, it will be interpreted as tomorrow.
  2842. Currently none of this works for ISO week specifications.
  2843. When this option is nil, the current day, month and year will always be
  2844. used as defaults.
  2845. See also `org-agenda-jump-prefer-future'."
  2846. :group 'org-time
  2847. :type '(choice
  2848. (const :tag "Never" nil)
  2849. (const :tag "Check month and day" t)
  2850. (const :tag "Check month, day, and time" time)))
  2851. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2852. "Should the agenda jump command prefer the future for incomplete dates?
  2853. The default is to do the same as configured in `org-read-date-prefer-future'.
  2854. But you can also set a deviating value here.
  2855. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2856. :group 'org-agenda
  2857. :group 'org-time
  2858. :version "24.1"
  2859. :type '(choice
  2860. (const :tag "Use org-read-date-prefer-future"
  2861. org-read-date-prefer-future)
  2862. (const :tag "Never" nil)
  2863. (const :tag "Always" t)))
  2864. (defcustom org-read-date-force-compatible-dates t
  2865. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2866. Depending on the system Emacs is running on, certain dates cannot
  2867. be represented with the type used internally to represent time.
  2868. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2869. correctly. Some systems allow for earlier dates, some for later,
  2870. some for both. One way to find out it to insert any date into an
  2871. Org buffer, putting the cursor on the year and hitting S-up and
  2872. S-down to test the range.
  2873. When this variable is set to t, the date/time prompt will not let
  2874. you specify dates outside the 1970-2037 range, so it is certain that
  2875. these dates will work in whatever version of Emacs you are
  2876. running, and also that you can move a file from one Emacs implementation
  2877. to another. WHenever Org is forcing the year for you, it will display
  2878. a message and beep.
  2879. When this variable is nil, Org will check if the date is
  2880. representable in the specific Emacs implementation you are using.
  2881. If not, it will force a year, usually the current year, and beep
  2882. to remind you. Currently this setting is not recommended because
  2883. the likelihood that you will open your Org files in an Emacs that
  2884. has limited date range is not negligible.
  2885. A workaround for this problem is to use diary sexp dates for time
  2886. stamps outside of this range."
  2887. :group 'org-time
  2888. :version "24.1"
  2889. :type 'boolean)
  2890. (defcustom org-read-date-display-live t
  2891. "Non-nil means display current interpretation of date prompt live.
  2892. This display will be in an overlay, in the minibuffer."
  2893. :group 'org-time
  2894. :type 'boolean)
  2895. (defcustom org-read-date-popup-calendar t
  2896. "Non-nil means pop up a calendar when prompting for a date.
  2897. In the calendar, the date can be selected with mouse-1. However, the
  2898. minibuffer will also be active, and you can simply enter the date as well.
  2899. When nil, only the minibuffer will be available."
  2900. :group 'org-time
  2901. :type 'boolean)
  2902. (defvaralias 'org-popup-calendar-for-date-prompt
  2903. 'org-read-date-popup-calendar)
  2904. (defcustom org-extend-today-until 0
  2905. "The hour when your day really ends. Must be an integer.
  2906. This has influence for the following applications:
  2907. - When switching the agenda to \"today\". It it is still earlier than
  2908. the time given here, the day recognized as TODAY is actually yesterday.
  2909. - When a date is read from the user and it is still before the time given
  2910. here, the current date and time will be assumed to be yesterday, 23:59.
  2911. Also, timestamps inserted in capture templates follow this rule.
  2912. IMPORTANT: This is a feature whose implementation is and likely will
  2913. remain incomplete. Really, it is only here because past midnight seems to
  2914. be the favorite working time of John Wiegley :-)"
  2915. :group 'org-time
  2916. :type 'integer)
  2917. (defcustom org-use-effective-time nil
  2918. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2919. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2920. \"effective time\" of any timestamps between midnight and 8am will be
  2921. 23:59 of the previous day."
  2922. :group 'org-time
  2923. :version "24.1"
  2924. :type 'boolean)
  2925. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2926. "When non-nil, use the last clock out time for `org-todo'.
  2927. Note that this option has precedence over the combined use of
  2928. `org-use-effective-time' and `org-extend-today-until'."
  2929. :group 'org-time
  2930. :version "24.4"
  2931. :package-version '(Org . "8.0")
  2932. :type 'boolean)
  2933. (defcustom org-edit-timestamp-down-means-later nil
  2934. "Non-nil means S-down will increase the time in a time stamp.
  2935. When nil, S-up will increase."
  2936. :group 'org-time
  2937. :type 'boolean)
  2938. (defcustom org-calendar-follow-timestamp-change t
  2939. "Non-nil means make the calendar window follow timestamp changes.
  2940. When a timestamp is modified and the calendar window is visible, it will be
  2941. moved to the new date."
  2942. :group 'org-time
  2943. :type 'boolean)
  2944. (defgroup org-tags nil
  2945. "Options concerning tags in Org mode."
  2946. :tag "Org Tags"
  2947. :group 'org)
  2948. (defcustom org-tag-alist nil
  2949. "Default tags available in Org files.
  2950. The value of this variable is an alist. Associations either:
  2951. (TAG)
  2952. (TAG . SELECT)
  2953. (SPECIAL)
  2954. where TAG is a tag as a string, SELECT is character, used to
  2955. select that tag through the fast tag selection interface, and
  2956. SPECIAL is one of the following keywords: `:startgroup',
  2957. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2958. `:newline'. These keywords are used to define a hierarchy of
  2959. tags. See manual for details.
  2960. When this variable is nil, Org mode bases tag input on what is
  2961. already in the buffer. The value can be overridden locally by
  2962. using a TAGS keyword, e.g.,
  2963. #+TAGS: tag1 tag2
  2964. See also `org-tag-persistent-alist' to sidestep this behavior."
  2965. :group 'org-tags
  2966. :type '(repeat
  2967. (choice
  2968. (cons (string :tag "Tag name")
  2969. (character :tag "Access char"))
  2970. (const :tag "Start radio group" (:startgroup))
  2971. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2972. (const :tag "Group tags delimiter" (:grouptags))
  2973. (const :tag "End radio group" (:endgroup))
  2974. (const :tag "End tag group, non distinct" (:endgrouptag))
  2975. (const :tag "New line" (:newline)))))
  2976. (defcustom org-tag-persistent-alist nil
  2977. "Tags always available in Org files.
  2978. The value of this variable is an alist. Associations either:
  2979. (TAG)
  2980. (TAG . SELECT)
  2981. (SPECIAL)
  2982. where TAG is a tag as a string, SELECT is a character, used to
  2983. select that tag through the fast tag selection interface, and
  2984. SPECIAL is one of the following keywords: `:startgroup',
  2985. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2986. `:newline'. These keywords are used to define a hierarchy of
  2987. tags. See manual for details.
  2988. Unlike to `org-tag-alist', tags defined in this variable do not
  2989. depend on a local TAGS keyword. Instead, to disable these tags
  2990. on a per-file basis, insert anywhere in the file:
  2991. #+STARTUP: noptag"
  2992. :group 'org-tags
  2993. :type '(repeat
  2994. (choice
  2995. (cons (string :tag "Tag name")
  2996. (character :tag "Access char"))
  2997. (const :tag "Start radio group" (:startgroup))
  2998. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2999. (const :tag "Group tags delimiter" (:grouptags))
  3000. (const :tag "End radio group" (:endgroup))
  3001. (const :tag "End tag group, non distinct" (:endgrouptag))
  3002. (const :tag "New line" (:newline)))))
  3003. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3004. "If non-nil, always offer completion for all tags of all agenda files.
  3005. Instead of customizing this variable directly, you might want to
  3006. set it locally for capture buffers, because there no list of
  3007. tags in that file can be created dynamically (there are none).
  3008. (add-hook \\='org-capture-mode-hook
  3009. (lambda ()
  3010. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3011. :group 'org-tags
  3012. :version "24.1"
  3013. :type 'boolean)
  3014. (defvar org-file-tags nil
  3015. "List of tags that can be inherited by all entries in the file.
  3016. The tags will be inherited if the variable `org-use-tag-inheritance'
  3017. says they should be.
  3018. This variable is populated from #+FILETAGS lines.")
  3019. (defcustom org-use-fast-tag-selection 'auto
  3020. "Non-nil means use fast tag selection scheme.
  3021. This is a special interface to select and deselect tags with single keys.
  3022. When nil, fast selection is never used.
  3023. When the symbol `auto', fast selection is used if and only if selection
  3024. characters for tags have been configured, either through the variable
  3025. `org-tag-alist' or through a #+TAGS line in the buffer.
  3026. When t, fast selection is always used and selection keys are assigned
  3027. automatically if necessary."
  3028. :group 'org-tags
  3029. :type '(choice
  3030. (const :tag "Always" t)
  3031. (const :tag "Never" nil)
  3032. (const :tag "When selection characters are configured" auto)))
  3033. (defcustom org-fast-tag-selection-single-key nil
  3034. "Non-nil means fast tag selection exits after first change.
  3035. When nil, you have to press RET to exit it.
  3036. During fast tag selection, you can toggle this flag with `C-c'.
  3037. This variable can also have the value `expert'. In this case, the window
  3038. displaying the tags menu is not even shown, until you press C-c again."
  3039. :group 'org-tags
  3040. :type '(choice
  3041. (const :tag "No" nil)
  3042. (const :tag "Yes" t)
  3043. (const :tag "Expert" expert)))
  3044. (defvar org-fast-tag-selection-include-todo nil
  3045. "Non-nil means fast tags selection interface will also offer TODO states.
  3046. This is an undocumented feature, you should not rely on it.")
  3047. (defcustom org-tags-column -77
  3048. "The column to which tags should be indented in a headline.
  3049. If this number is positive, it specifies the column. If it is negative,
  3050. it means that the tags should be flushright to that column. For example,
  3051. -80 works well for a normal 80 character screen.
  3052. When 0, place tags directly after headline text, with only one space in
  3053. between."
  3054. :group 'org-tags
  3055. :type 'integer)
  3056. (defcustom org-auto-align-tags t
  3057. "Non-nil keeps tags aligned when modifying headlines.
  3058. Some operations (i.e. demoting) change the length of a headline and
  3059. therefore shift the tags around. With this option turned on, after
  3060. each such operation the tags are again aligned to `org-tags-column'."
  3061. :group 'org-tags
  3062. :type 'boolean)
  3063. (defcustom org-use-tag-inheritance t
  3064. "Non-nil means tags in levels apply also for sublevels.
  3065. When nil, only the tags directly given in a specific line apply there.
  3066. This may also be a list of tags that should be inherited, or a regexp that
  3067. matches tags that should be inherited. Additional control is possible
  3068. with the variable `org-tags-exclude-from-inheritance' which gives an
  3069. explicit list of tags to be excluded from inheritance, even if the value of
  3070. `org-use-tag-inheritance' would select it for inheritance.
  3071. If this option is t, a match early-on in a tree can lead to a large
  3072. number of matches in the subtree when constructing the agenda or creating
  3073. a sparse tree. If you only want to see the first match in a tree during
  3074. a search, check out the variable `org-tags-match-list-sublevels'."
  3075. :group 'org-tags
  3076. :type '(choice
  3077. (const :tag "Not" nil)
  3078. (const :tag "Always" t)
  3079. (repeat :tag "Specific tags" (string :tag "Tag"))
  3080. (regexp :tag "Tags matched by regexp")))
  3081. (defcustom org-tags-exclude-from-inheritance nil
  3082. "List of tags that should never be inherited.
  3083. This is a way to exclude a few tags from inheritance. For way to do
  3084. the opposite, to actively allow inheritance for selected tags,
  3085. see the variable `org-use-tag-inheritance'."
  3086. :group 'org-tags
  3087. :type '(repeat (string :tag "Tag")))
  3088. (defun org-tag-inherit-p (tag)
  3089. "Check if TAG is one that should be inherited."
  3090. (cond
  3091. ((member tag org-tags-exclude-from-inheritance) nil)
  3092. ((eq org-use-tag-inheritance t) t)
  3093. ((not org-use-tag-inheritance) nil)
  3094. ((stringp org-use-tag-inheritance)
  3095. (string-match org-use-tag-inheritance tag))
  3096. ((listp org-use-tag-inheritance)
  3097. (member tag org-use-tag-inheritance))
  3098. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3099. (defcustom org-tags-match-list-sublevels t
  3100. "Non-nil means list also sublevels of headlines matching a search.
  3101. This variable applies to tags/property searches, and also to stuck
  3102. projects because this search is based on a tags match as well.
  3103. When set to the symbol `indented', sublevels are indented with
  3104. leading dots.
  3105. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3106. the sublevels of a headline matching a tag search often also match
  3107. the same search. Listing all of them can create very long lists.
  3108. Setting this variable to nil causes subtrees of a match to be skipped.
  3109. This variable is semi-obsolete and probably should always be true. It
  3110. is better to limit inheritance to certain tags using the variables
  3111. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3112. :group 'org-tags
  3113. :type '(choice
  3114. (const :tag "No, don't list them" nil)
  3115. (const :tag "Yes, do list them" t)
  3116. (const :tag "List them, indented with leading dots" indented)))
  3117. (defcustom org-tags-sort-function nil
  3118. "When set, tags are sorted using this function as a comparator."
  3119. :group 'org-tags
  3120. :type '(choice
  3121. (const :tag "No sorting" nil)
  3122. (const :tag "Alphabetical" string<)
  3123. (const :tag "Reverse alphabetical" string>)
  3124. (function :tag "Custom function" nil)))
  3125. (defvar org-tags-history nil
  3126. "History of minibuffer reads for tags.")
  3127. (defvar org-last-tags-completion-table nil
  3128. "The last used completion table for tags.")
  3129. (defvar org-after-tags-change-hook nil
  3130. "Hook that is run after the tags in a line have changed.")
  3131. (defgroup org-properties nil
  3132. "Options concerning properties in Org mode."
  3133. :tag "Org Properties"
  3134. :group 'org)
  3135. (defcustom org-property-format "%-10s %s"
  3136. "How property key/value pairs should be formatted by `indent-line'.
  3137. When `indent-line' hits a property definition, it will format the line
  3138. according to this format, mainly to make sure that the values are
  3139. lined-up with respect to each other."
  3140. :group 'org-properties
  3141. :type 'string)
  3142. (defcustom org-properties-postprocess-alist nil
  3143. "Alist of properties and functions to adjust inserted values.
  3144. Elements of this alist must be of the form
  3145. ([string] [function])
  3146. where [string] must be a property name and [function] must be a
  3147. lambda expression: this lambda expression must take one argument,
  3148. the value to adjust, and return the new value as a string.
  3149. For example, this element will allow the property \"Remaining\"
  3150. to be updated wrt the relation between the \"Effort\" property
  3151. and the clock summary:
  3152. ((\"Remaining\" (lambda(value)
  3153. (let ((clocksum (org-clock-sum-current-item))
  3154. (effort (org-duration-to-minutes
  3155. (org-entry-get (point) \"Effort\"))))
  3156. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3157. :group 'org-properties
  3158. :version "24.1"
  3159. :type '(alist :key-type (string :tag "Property")
  3160. :value-type (function :tag "Function")))
  3161. (defcustom org-use-property-inheritance nil
  3162. "Non-nil means properties apply also for sublevels.
  3163. This setting is chiefly used during property searches. Turning it on can
  3164. cause significant overhead when doing a search, which is why it is not
  3165. on by default.
  3166. When nil, only the properties directly given in the current entry count.
  3167. When t, every property is inherited. The value may also be a list of
  3168. properties that should have inheritance, or a regular expression matching
  3169. properties that should be inherited.
  3170. However, note that some special properties use inheritance under special
  3171. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3172. and the properties ending in \"_ALL\" when they are used as descriptor
  3173. for valid values of a property.
  3174. Note for programmers:
  3175. When querying an entry with `org-entry-get', you can control if inheritance
  3176. should be used. By default, `org-entry-get' looks only at the local
  3177. properties. You can request inheritance by setting the inherit argument
  3178. to t (to force inheritance) or to `selective' (to respect the setting
  3179. in this variable)."
  3180. :group 'org-properties
  3181. :type '(choice
  3182. (const :tag "Not" nil)
  3183. (const :tag "Always" t)
  3184. (repeat :tag "Specific properties" (string :tag "Property"))
  3185. (regexp :tag "Properties matched by regexp")))
  3186. (defun org-property-inherit-p (property)
  3187. "Return a non-nil value if PROPERTY should be inherited."
  3188. (cond
  3189. ((eq org-use-property-inheritance t) t)
  3190. ((not org-use-property-inheritance) nil)
  3191. ((stringp org-use-property-inheritance)
  3192. (string-match org-use-property-inheritance property))
  3193. ((listp org-use-property-inheritance)
  3194. (member-ignore-case property org-use-property-inheritance))
  3195. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3196. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3197. "The default column format, if no other format has been defined.
  3198. This variable can be set on the per-file basis by inserting a line
  3199. #+COLUMNS: %25ITEM ....."
  3200. :group 'org-properties
  3201. :type 'string)
  3202. (defcustom org-columns-ellipses ".."
  3203. "The ellipses to be used when a field in column view is truncated.
  3204. When this is the empty string, as many characters as possible are shown,
  3205. but then there will be no visual indication that the field has been truncated.
  3206. When this is a string of length N, the last N characters of a truncated
  3207. field are replaced by this string. If the column is narrower than the
  3208. ellipses string, only part of the ellipses string will be shown."
  3209. :group 'org-properties
  3210. :type 'string)
  3211. (defconst org-global-properties-fixed
  3212. '(("VISIBILITY_ALL" . "folded children content all")
  3213. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3214. "List of property/value pairs that can be inherited by any entry.
  3215. These are fixed values, for the preset properties. The user variable
  3216. that can be used to add to this list is `org-global-properties'.
  3217. The entries in this list are cons cells where the car is a property
  3218. name and cdr is a string with the value. If the value represents
  3219. multiple items like an \"_ALL\" property, separate the items by
  3220. spaces.")
  3221. (defcustom org-global-properties nil
  3222. "List of property/value pairs that can be inherited by any entry.
  3223. This list will be combined with the constant `org-global-properties-fixed'.
  3224. The entries in this list are cons cells where the car is a property
  3225. name and cdr is a string with the value.
  3226. You can set buffer-local values for the same purpose in the variable
  3227. `org-file-properties' this by adding lines like
  3228. #+PROPERTY: NAME VALUE"
  3229. :group 'org-properties
  3230. :type '(repeat
  3231. (cons (string :tag "Property")
  3232. (string :tag "Value"))))
  3233. (defvar-local org-file-properties nil
  3234. "List of property/value pairs that can be inherited by any entry.
  3235. Valid for the current buffer.
  3236. This variable is populated from #+PROPERTY lines.")
  3237. (defgroup org-agenda nil
  3238. "Options concerning agenda views in Org mode."
  3239. :tag "Org Agenda"
  3240. :group 'org)
  3241. (defvar-local org-category nil
  3242. "Variable used by org files to set a category for agenda display.
  3243. Such files should use a file variable to set it, for example
  3244. # -*- mode: org; org-category: \"ELisp\"
  3245. or contain a special line
  3246. #+CATEGORY: ELisp
  3247. If the file does not specify a category, then file's base name
  3248. is used instead.")
  3249. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3250. (defcustom org-agenda-files nil
  3251. "The files to be used for agenda display.
  3252. If an entry is a directory, all files in that directory that are matched
  3253. by `org-agenda-file-regexp' will be part of the file list.
  3254. If the value of the variable is not a list but a single file name, then
  3255. the list of agenda files is actually stored and maintained in that file,
  3256. one agenda file per line. In this file paths can be given relative to
  3257. `org-directory'. Tilde expansion and environment variable substitution
  3258. are also made.
  3259. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3260. and removed with `\\[org-remove-file]'."
  3261. :group 'org-agenda
  3262. :type '(choice
  3263. (repeat :tag "List of files and directories" file)
  3264. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3265. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3266. "Regular expression to match files for `org-agenda-files'.
  3267. If any element in the list in that variable contains a directory instead
  3268. of a normal file, all files in that directory that are matched by this
  3269. regular expression will be included."
  3270. :group 'org-agenda
  3271. :type 'regexp)
  3272. (defcustom org-agenda-text-search-extra-files nil
  3273. "List of extra files to be searched by text search commands.
  3274. These files will be searched in addition to the agenda files by the
  3275. commands `org-search-view' (`\\[org-agenda] s') \
  3276. and `org-occur-in-agenda-files'.
  3277. Note that these files will only be searched for text search commands,
  3278. not for the other agenda views like todo lists, tag searches or the weekly
  3279. agenda. This variable is intended to list notes and possibly archive files
  3280. that should also be searched by these two commands.
  3281. In fact, if the first element in the list is the symbol `agenda-archives',
  3282. then all archive files of all agenda files will be added to the search
  3283. scope."
  3284. :group 'org-agenda
  3285. :type '(set :greedy t
  3286. (const :tag "Agenda Archives" agenda-archives)
  3287. (repeat :inline t (file))))
  3288. (defvaralias 'org-agenda-multi-occur-extra-files
  3289. 'org-agenda-text-search-extra-files)
  3290. (defcustom org-agenda-skip-unavailable-files nil
  3291. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3292. A nil value means to remove them, after a query, from the list."
  3293. :group 'org-agenda
  3294. :type 'boolean)
  3295. (defcustom org-calendar-to-agenda-key [?c]
  3296. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3297. The command `org-calendar-goto-agenda' will be bound to this key. The
  3298. default is the character `c' because then `c' can be used to switch back and
  3299. forth between agenda and calendar."
  3300. :group 'org-agenda
  3301. :type 'sexp)
  3302. (defcustom org-calendar-insert-diary-entry-key [?i]
  3303. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3304. This option is irrelevant until `org-agenda-diary-file' has been configured
  3305. to point to an Org file. When that is the case, the command
  3306. `org-agenda-diary-entry' will be bound to the key given here, by default
  3307. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3308. if you want to continue doing this, you need to change this to a different
  3309. key."
  3310. :group 'org-agenda
  3311. :type 'sexp)
  3312. (defcustom org-agenda-diary-file 'diary-file
  3313. "File to which to add new entries with the `i' key in agenda and calendar.
  3314. When this is the symbol `diary-file', the functionality in the Emacs
  3315. calendar will be used to add entries to the `diary-file'. But when this
  3316. points to a file, `org-agenda-diary-entry' will be used instead."
  3317. :group 'org-agenda
  3318. :type '(choice
  3319. (const :tag "The standard Emacs diary file" diary-file)
  3320. (file :tag "Special Org file diary entries")))
  3321. (eval-after-load "calendar"
  3322. '(progn
  3323. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3324. 'org-calendar-goto-agenda)
  3325. (add-hook 'calendar-mode-hook
  3326. (lambda ()
  3327. (unless (eq org-agenda-diary-file 'diary-file)
  3328. (define-key calendar-mode-map
  3329. org-calendar-insert-diary-entry-key
  3330. 'org-agenda-diary-entry))))))
  3331. (defgroup org-latex nil
  3332. "Options for embedding LaTeX code into Org mode."
  3333. :tag "Org LaTeX"
  3334. :group 'org)
  3335. (defcustom org-format-latex-options
  3336. '(:foreground default :background default :scale 1.0
  3337. :html-foreground "Black" :html-background "Transparent"
  3338. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3339. "Options for creating images from LaTeX fragments.
  3340. This is a property list with the following properties:
  3341. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3342. `default' means use the foreground of the default face.
  3343. `auto' means use the foreground from the text face.
  3344. :background the background color, or \"Transparent\".
  3345. `default' means use the background of the default face.
  3346. `auto' means use the background from the text face.
  3347. :scale a scaling factor for the size of the images, to get more pixels
  3348. :html-foreground, :html-background, :html-scale
  3349. the same numbers for HTML export.
  3350. :matchers a list indicating which matchers should be used to
  3351. find LaTeX fragments. Valid members of this list are:
  3352. \"begin\" find environments
  3353. \"$1\" find single characters surrounded by $.$
  3354. \"$\" find math expressions surrounded by $...$
  3355. \"$$\" find math expressions surrounded by $$....$$
  3356. \"\\(\" find math expressions surrounded by \\(...\\)
  3357. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3358. :group 'org-latex
  3359. :type 'plist)
  3360. (defcustom org-format-latex-signal-error t
  3361. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3362. When nil, just push out a message."
  3363. :group 'org-latex
  3364. :version "24.1"
  3365. :type 'boolean)
  3366. (defcustom org-latex-to-mathml-jar-file nil
  3367. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3368. Use this to specify additional executable file say a jar file.
  3369. When using MathToWeb as the converter, specify the full-path to
  3370. your mathtoweb.jar file."
  3371. :group 'org-latex
  3372. :version "24.1"
  3373. :type '(choice
  3374. (const :tag "None" nil)
  3375. (file :tag "JAR file" :must-match t)))
  3376. (defcustom org-latex-to-mathml-convert-command nil
  3377. "Command to convert LaTeX fragments to MathML.
  3378. Replace format-specifiers in the command as noted below and use
  3379. `shell-command' to convert LaTeX to MathML.
  3380. %j: Executable file in fully expanded form as specified by
  3381. `org-latex-to-mathml-jar-file'.
  3382. %I: Input LaTeX file in fully expanded form.
  3383. %i: The latex fragment to be converted.
  3384. %o: Output MathML file.
  3385. This command is used by `org-create-math-formula'.
  3386. When using MathToWeb as the converter, set this option to
  3387. \"java -jar %j -unicode -force -df %o %I\".
  3388. When using LaTeXML set this option to
  3389. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3390. :group 'org-latex
  3391. :version "24.1"
  3392. :type '(choice
  3393. (const :tag "None" nil)
  3394. (string :tag "\nShell command")))
  3395. (defcustom org-preview-latex-default-process 'dvipng
  3396. "The default process to convert LaTeX fragments to image files.
  3397. All available processes and theirs documents can be found in
  3398. `org-preview-latex-process-alist', which see."
  3399. :group 'org-latex
  3400. :version "26.1"
  3401. :package-version '(Org . "9.0")
  3402. :type 'symbol)
  3403. (defcustom org-preview-latex-process-alist
  3404. '((dvipng
  3405. :programs ("latex" "dvipng")
  3406. :description "dvi > png"
  3407. :message "you need to install the programs: latex and dvipng."
  3408. :image-input-type "dvi"
  3409. :image-output-type "png"
  3410. :image-size-adjust (1.0 . 1.0)
  3411. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3412. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3413. (dvisvgm
  3414. :programs ("latex" "dvisvgm")
  3415. :description "dvi > svg"
  3416. :message "you need to install the programs: latex and dvisvgm."
  3417. :use-xcolor t
  3418. :image-input-type "dvi"
  3419. :image-output-type "svg"
  3420. :image-size-adjust (1.7 . 1.5)
  3421. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3422. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3423. (imagemagick
  3424. :programs ("latex" "convert")
  3425. :description "pdf > png"
  3426. :message "you need to install the programs: latex and imagemagick."
  3427. :use-xcolor t
  3428. :image-input-type "pdf"
  3429. :image-output-type "png"
  3430. :image-size-adjust (1.0 . 1.0)
  3431. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3432. :image-converter
  3433. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3434. "Definitions of external processes for LaTeX previewing.
  3435. Org mode can use some external commands to generate TeX snippet's images for
  3436. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3437. `org-create-formula-image' how to call them.
  3438. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3439. PROPERTIES accepts the following attributes:
  3440. :programs list of strings, required programs.
  3441. :description string, describe the process.
  3442. :message string, message it when required programs cannot be found.
  3443. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3444. :image-output-type string, output file type of image converter (e.g., \"png\").
  3445. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3446. deal with background and foreground color of image.
  3447. Otherwise, dvipng style background and foreground color
  3448. format are generated. You may then refer to them in
  3449. command options with \"%F\" and \"%B\".
  3450. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3451. image size showed in buffer and the cdr element is for
  3452. HTML file. This option is only useful for process
  3453. developers, users should use variable
  3454. `org-format-latex-options' instead.
  3455. :post-clean list of strings, files matched are to be cleaned up once
  3456. the image is generated. When nil, the files with \".dvi\",
  3457. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3458. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3459. be cleaned up.
  3460. :latex-header list of strings, the LaTeX header of the snippet file.
  3461. When nil, the fallback value is used instead, which is
  3462. controlled by `org-format-latex-header',
  3463. `org-latex-default-packages-alist' and
  3464. `org-latex-packages-alist', which see.
  3465. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3466. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3467. replaced with values defined below.
  3468. :image-converter list of image converter commands strings. Each of them is
  3469. given to the shell and supports any of the following
  3470. place-holders defined below.
  3471. Place-holders used by `:image-converter' and `:latex-compiler':
  3472. %f input file name
  3473. %b base name of input file
  3474. %o base directory of input file
  3475. %O absolute output file name
  3476. Place-holders only used by `:image-converter':
  3477. %F foreground of image
  3478. %B background of image
  3479. %D dpi, which is used to adjust image size by some processing commands.
  3480. %S the image size scale ratio, which is used to adjust image size by some
  3481. processing commands."
  3482. :group 'org-latex
  3483. :version "26.1"
  3484. :package-version '(Org . "9.0")
  3485. :type '(alist :tag "LaTeX to image backends"
  3486. :value-type (plist)))
  3487. (defcustom org-preview-latex-image-directory "ltximg/"
  3488. "Path to store latex preview images.
  3489. A relative path here creates many directories relative to the
  3490. processed org files paths. An absolute path puts all preview
  3491. images at the same place."
  3492. :group 'org-latex
  3493. :version "26.1"
  3494. :package-version '(Org . "9.0")
  3495. :type 'string)
  3496. (defun org-format-latex-mathml-available-p ()
  3497. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3498. (save-match-data
  3499. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3500. org-latex-to-mathml-convert-command)
  3501. (let ((executable (car (split-string
  3502. org-latex-to-mathml-convert-command))))
  3503. (when (executable-find executable)
  3504. (if (string-match
  3505. "%j" org-latex-to-mathml-convert-command)
  3506. (file-readable-p org-latex-to-mathml-jar-file)
  3507. t))))))
  3508. (defcustom org-format-latex-header "\\documentclass{article}
  3509. \\usepackage[usenames]{color}
  3510. \[PACKAGES]
  3511. \[DEFAULT-PACKAGES]
  3512. \\pagestyle{empty} % do not remove
  3513. % The settings below are copied from fullpage.sty
  3514. \\setlength{\\textwidth}{\\paperwidth}
  3515. \\addtolength{\\textwidth}{-3cm}
  3516. \\setlength{\\oddsidemargin}{1.5cm}
  3517. \\addtolength{\\oddsidemargin}{-2.54cm}
  3518. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3519. \\setlength{\\textheight}{\\paperheight}
  3520. \\addtolength{\\textheight}{-\\headheight}
  3521. \\addtolength{\\textheight}{-\\headsep}
  3522. \\addtolength{\\textheight}{-\\footskip}
  3523. \\addtolength{\\textheight}{-3cm}
  3524. \\setlength{\\topmargin}{1.5cm}
  3525. \\addtolength{\\topmargin}{-2.54cm}"
  3526. "The document header used for processing LaTeX fragments.
  3527. It is imperative that this header make sure that no page number
  3528. appears on the page. The package defined in the variables
  3529. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3530. will either replace the placeholder \"[PACKAGES]\" in this
  3531. header, or they will be appended."
  3532. :group 'org-latex
  3533. :type 'string)
  3534. (defun org-set-packages-alist (var val)
  3535. "Set the packages alist and make sure it has 3 elements per entry."
  3536. (set var (mapcar (lambda (x)
  3537. (if (and (consp x) (= (length x) 2))
  3538. (list (car x) (nth 1 x) t)
  3539. x))
  3540. val)))
  3541. (defun org-get-packages-alist (var)
  3542. "Get the packages alist and make sure it has 3 elements per entry."
  3543. (mapcar (lambda (x)
  3544. (if (and (consp x) (= (length x) 2))
  3545. (list (car x) (nth 1 x) t)
  3546. x))
  3547. (default-value var)))
  3548. (defcustom org-latex-default-packages-alist
  3549. '(("AUTO" "inputenc" t ("pdflatex"))
  3550. ("T1" "fontenc" t ("pdflatex"))
  3551. ("" "graphicx" t)
  3552. ("" "grffile" t)
  3553. ("" "longtable" nil)
  3554. ("" "wrapfig" nil)
  3555. ("" "rotating" nil)
  3556. ("normalem" "ulem" t)
  3557. ("" "amsmath" t)
  3558. ("" "textcomp" t)
  3559. ("" "amssymb" t)
  3560. ("" "capt-of" nil)
  3561. ("" "hyperref" nil))
  3562. "Alist of default packages to be inserted in the header.
  3563. Change this only if one of the packages here causes an
  3564. incompatibility with another package you are using.
  3565. The packages in this list are needed by one part or another of
  3566. Org mode to function properly:
  3567. - inputenc, fontenc: for basic font and character selection
  3568. - graphicx: for including images
  3569. - grffile: allow periods and spaces in graphics file names
  3570. - longtable: For multipage tables
  3571. - wrapfig: for figure placement
  3572. - rotating: for sideways figures and tables
  3573. - ulem: for underline and strike-through
  3574. - amsmath: for subscript and superscript and math environments
  3575. - textcomp, amssymb: for various symbols used
  3576. for interpreting the entities in `org-entities'. You can skip
  3577. some of these packages if you don't use any of their symbols.
  3578. - capt-of: for captions outside of floats
  3579. - hyperref: for cross references
  3580. Therefore you should not modify this variable unless you know
  3581. what you are doing. The one reason to change it anyway is that
  3582. you might be loading some other package that conflicts with one
  3583. of the default packages. Each element is either a cell or
  3584. a string.
  3585. A cell is of the format
  3586. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3587. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3588. when compiling LaTeX snippets into images for inclusion into
  3589. non-LaTeX output. COMPILERS is a list of compilers that should
  3590. include the package, see `org-latex-compiler'. If the document
  3591. compiler is not in the list, and the list is non-nil, the package
  3592. will not be inserted in the final document.
  3593. A string will be inserted as-is in the header of the document."
  3594. :group 'org-latex
  3595. :group 'org-export-latex
  3596. :set 'org-set-packages-alist
  3597. :get 'org-get-packages-alist
  3598. :version "26.1"
  3599. :package-version '(Org . "8.3")
  3600. :type '(repeat
  3601. (choice
  3602. (list :tag "options/package pair"
  3603. (string :tag "options")
  3604. (string :tag "package")
  3605. (boolean :tag "Snippet"))
  3606. (string :tag "A line of LaTeX"))))
  3607. (defcustom org-latex-packages-alist nil
  3608. "Alist of packages to be inserted in every LaTeX header.
  3609. These will be inserted after `org-latex-default-packages-alist'.
  3610. Each element is either a cell or a string.
  3611. A cell is of the format:
  3612. (\"options\" \"package\" SNIPPET-FLAG)
  3613. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3614. needed when turning LaTeX snippets into images for inclusion into
  3615. non-LaTeX output.
  3616. A string will be inserted as-is in the header of the document.
  3617. Make sure that you only list packages here which:
  3618. - you want in every file;
  3619. - do not conflict with the setup in `org-format-latex-header';
  3620. - do not conflict with the default packages in
  3621. `org-latex-default-packages-alist'."
  3622. :group 'org-latex
  3623. :group 'org-export-latex
  3624. :set 'org-set-packages-alist
  3625. :get 'org-get-packages-alist
  3626. :type '(repeat
  3627. (choice
  3628. (list :tag "options/package pair"
  3629. (string :tag "options")
  3630. (string :tag "package")
  3631. (boolean :tag "Snippet"))
  3632. (string :tag "A line of LaTeX"))))
  3633. (defgroup org-appearance nil
  3634. "Settings for Org mode appearance."
  3635. :tag "Org Appearance"
  3636. :group 'org)
  3637. (defcustom org-level-color-stars-only nil
  3638. "Non-nil means fontify only the stars in each headline.
  3639. When nil, the entire headline is fontified.
  3640. Changing it requires restart of `font-lock-mode' to become effective
  3641. also in regions already fontified."
  3642. :group 'org-appearance
  3643. :type 'boolean)
  3644. (defcustom org-hide-leading-stars nil
  3645. "Non-nil means hide the first N-1 stars in a headline.
  3646. This works by using the face `org-hide' for these stars. This
  3647. face is white for a light background, and black for a dark
  3648. background. You may have to customize the face `org-hide' to
  3649. make this work.
  3650. Changing it requires restart of `font-lock-mode' to become effective
  3651. also in regions already fontified.
  3652. You may also set this on a per-file basis by adding one of the following
  3653. lines to the buffer:
  3654. #+STARTUP: hidestars
  3655. #+STARTUP: showstars"
  3656. :group 'org-appearance
  3657. :type 'boolean)
  3658. (defcustom org-hidden-keywords nil
  3659. "List of symbols corresponding to keywords to be hidden the org buffer.
  3660. For example, a value \\='(title) for this list will make the document's title
  3661. appear in the buffer without the initial #+TITLE: keyword."
  3662. :group 'org-appearance
  3663. :version "24.1"
  3664. :type '(set (const :tag "#+AUTHOR" author)
  3665. (const :tag "#+DATE" date)
  3666. (const :tag "#+EMAIL" email)
  3667. (const :tag "#+TITLE" title)))
  3668. (defcustom org-custom-properties nil
  3669. "List of properties (as strings) with a special meaning.
  3670. The default use of these custom properties is to let the user
  3671. hide them with `org-toggle-custom-properties-visibility'."
  3672. :group 'org-properties
  3673. :group 'org-appearance
  3674. :version "24.3"
  3675. :type '(repeat (string :tag "Property Name")))
  3676. (defcustom org-fontify-done-headline nil
  3677. "Non-nil means change the face of a headline if it is marked DONE.
  3678. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3679. When this is non-nil, the headline after the keyword is set to the
  3680. `org-headline-done' as an additional indication."
  3681. :group 'org-appearance
  3682. :type 'boolean)
  3683. (defcustom org-fontify-emphasized-text t
  3684. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3685. Changing this variable requires a restart of Emacs to take effect."
  3686. :group 'org-appearance
  3687. :type 'boolean)
  3688. (defcustom org-fontify-whole-heading-line nil
  3689. "Non-nil means fontify the whole line for headings.
  3690. This is useful when setting a background color for the
  3691. org-level-* faces."
  3692. :group 'org-appearance
  3693. :type 'boolean)
  3694. (defcustom org-highlight-latex-and-related nil
  3695. "Non-nil means highlight LaTeX related syntax in the buffer.
  3696. When non nil, the value should be a list containing any of the
  3697. following symbols:
  3698. `latex' Highlight LaTeX snippets and environments.
  3699. `script' Highlight subscript and superscript.
  3700. `entities' Highlight entities."
  3701. :group 'org-appearance
  3702. :version "24.4"
  3703. :package-version '(Org . "8.0")
  3704. :type '(choice
  3705. (const :tag "No highlighting" nil)
  3706. (set :greedy t :tag "Highlight"
  3707. (const :tag "LaTeX snippets and environments" latex)
  3708. (const :tag "Subscript and superscript" script)
  3709. (const :tag "Entities" entities))))
  3710. (defcustom org-hide-emphasis-markers nil
  3711. "Non-nil mean font-lock should hide the emphasis marker characters."
  3712. :group 'org-appearance
  3713. :type 'boolean)
  3714. (defcustom org-hide-macro-markers nil
  3715. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3716. :group 'org-appearance
  3717. :type 'boolean)
  3718. (defcustom org-pretty-entities nil
  3719. "Non-nil means show entities as UTF8 characters.
  3720. When nil, the \\name form remains in the buffer."
  3721. :group 'org-appearance
  3722. :version "24.1"
  3723. :type 'boolean)
  3724. (defcustom org-pretty-entities-include-sub-superscripts t
  3725. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3726. :group 'org-appearance
  3727. :version "24.1"
  3728. :type 'boolean)
  3729. (defvar org-emph-re nil
  3730. "Regular expression for matching emphasis.
  3731. After a match, the match groups contain these elements:
  3732. 0 The match of the full regular expression, including the characters
  3733. before and after the proper match
  3734. 1 The character before the proper match, or empty at beginning of line
  3735. 2 The proper match, including the leading and trailing markers
  3736. 3 The leading marker like * or /, indicating the type of highlighting
  3737. 4 The text between the emphasis markers, not including the markers
  3738. 5 The character after the match, empty at the end of a line")
  3739. (defvar org-verbatim-re nil
  3740. "Regular expression for matching verbatim text.")
  3741. (defvar org-emphasis-regexp-components) ; defined just below
  3742. (defvar org-emphasis-alist) ; defined just below
  3743. (defun org-set-emph-re (var val)
  3744. "Set variable and compute the emphasis regular expression."
  3745. (set var val)
  3746. (when (and (boundp 'org-emphasis-alist)
  3747. (boundp 'org-emphasis-regexp-components)
  3748. org-emphasis-alist org-emphasis-regexp-components)
  3749. (pcase-let*
  3750. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3751. (body (if (<= nl 0) body
  3752. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3753. (template
  3754. (format (concat "\\([%s]\\|^\\)" ;before markers
  3755. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3756. "\\([%s]\\|$\\)") ;after markers
  3757. pre border border body border post)))
  3758. (setq org-emph-re (format template "*/_+"))
  3759. (setq org-verbatim-re (format template "=~")))))
  3760. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3761. ;; set this option proved cumbersome. See this message/thread:
  3762. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3763. (defvar org-emphasis-regexp-components
  3764. '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3765. "Components used to build the regular expression for emphasis.
  3766. This is a list with five entries. Terminology: In an emphasis string
  3767. like \" *strong word* \", we call the initial space PREMATCH, the final
  3768. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3769. and \"trong wor\" is the body. The different components in this variable
  3770. specify what is allowed/forbidden in each part:
  3771. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3772. post Chars allowed as postmatch. End of line will be allowed too.
  3773. border The chars *forbidden* as border characters.
  3774. body-regexp A regexp like \".\" to match a body character. Don't use
  3775. non-shy groups here, and don't allow newline here.
  3776. newline The maximum number of newlines allowed in an emphasis exp.
  3777. You need to reload Org or to restart Emacs after customizing this.")
  3778. (defcustom org-emphasis-alist
  3779. '(("*" bold)
  3780. ("/" italic)
  3781. ("_" underline)
  3782. ("=" org-verbatim verbatim)
  3783. ("~" org-code verbatim)
  3784. ("+" (:strike-through t)))
  3785. "Alist of characters and faces to emphasize text.
  3786. Text starting and ending with a special character will be emphasized,
  3787. for example *bold*, _underlined_ and /italic/. This variable sets the
  3788. marker characters and the face to be used by font-lock for highlighting
  3789. in Org buffers.
  3790. You need to reload Org or to restart Emacs after customizing this."
  3791. :group 'org-appearance
  3792. :set 'org-set-emph-re
  3793. :version "24.4"
  3794. :package-version '(Org . "8.0")
  3795. :type '(repeat
  3796. (list
  3797. (string :tag "Marker character")
  3798. (choice
  3799. (face :tag "Font-lock-face")
  3800. (plist :tag "Face property list"))
  3801. (option (const verbatim)))))
  3802. (defvar org-protecting-blocks '("src" "example" "export")
  3803. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3804. This is needed for font-lock setup.")
  3805. ;;; Functions and variables from their packages
  3806. ;; Declared here to avoid compiler warnings
  3807. (defvar mark-active)
  3808. ;; Various packages
  3809. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3810. (declare-function calendar-forward-day "cal-move" (arg))
  3811. (declare-function calendar-goto-date "cal-move" (date))
  3812. (declare-function calendar-goto-today "cal-move" ())
  3813. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3814. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3815. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3816. (declare-function cdlatex-tab "ext:cdlatex" ())
  3817. (declare-function dired-get-filename
  3818. "dired"
  3819. (&optional localp no-error-if-not-filep))
  3820. (declare-function iswitchb-read-buffer
  3821. "iswitchb"
  3822. (prompt &optional
  3823. default require-match _predicate start matches-set))
  3824. (declare-function org-agenda-change-all-lines
  3825. "org-agenda"
  3826. (newhead hdmarker &optional fixface just-this))
  3827. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3828. "org-agenda"
  3829. (&optional end))
  3830. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3831. (declare-function org-agenda-format-item
  3832. "org-agenda"
  3833. (extra txt &optional level category tags dotime
  3834. remove-re habitp))
  3835. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3836. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3837. (declare-function org-agenda-save-markers-for-cut-and-paste
  3838. "org-agenda"
  3839. (beg end))
  3840. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3841. (declare-function org-agenda-skip "org-agenda" ())
  3842. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3843. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3844. (declare-function org-indent-mode "org-indent" (&optional arg))
  3845. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3846. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3847. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3848. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3849. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3850. (declare-function parse-time-string "parse-time" (string))
  3851. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3852. (defvar align-mode-rules-list)
  3853. (defvar calc-embedded-close-formula)
  3854. (defvar calc-embedded-open-formula)
  3855. (defvar calc-embedded-open-mode)
  3856. (defvar font-lock-unfontify-region-function)
  3857. (defvar iswitchb-temp-buflist)
  3858. (defvar org-agenda-tags-todo-honor-ignore-options)
  3859. (defvar remember-data-file)
  3860. (defvar texmathp-why)
  3861. ;;;###autoload
  3862. (defun turn-on-orgtbl ()
  3863. "Unconditionally turn on `orgtbl-mode'."
  3864. (require 'org-table)
  3865. (orgtbl-mode 1))
  3866. (defun org-at-table-p (&optional table-type)
  3867. "Non-nil if the cursor is inside an Org table.
  3868. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3869. If `org-enable-table-editor' is nil, return nil unconditionally."
  3870. (and
  3871. org-enable-table-editor
  3872. (save-excursion
  3873. (beginning-of-line)
  3874. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3875. (or (not (derived-mode-p 'org-mode))
  3876. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3877. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3878. (defun org-at-table.el-p ()
  3879. "Non-nil when point is at a table.el table."
  3880. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3881. (let ((element (org-element-at-point)))
  3882. (and (eq (org-element-type element) 'table)
  3883. (eq (org-element-property :type element) 'table.el)))))
  3884. (defun org-at-table-hline-p ()
  3885. "Non-nil when point is inside a hline in a table.
  3886. Assume point is already in a table. If `org-enable-table-editor'
  3887. is nil, return nil unconditionally."
  3888. (and org-enable-table-editor
  3889. (save-excursion
  3890. (beginning-of-line)
  3891. (looking-at org-table-hline-regexp))))
  3892. (defun org-table-map-tables (function &optional quietly)
  3893. "Apply FUNCTION to the start of all tables in the buffer."
  3894. (org-with-wide-buffer
  3895. (goto-char (point-min))
  3896. (while (re-search-forward org-table-any-line-regexp nil t)
  3897. (unless quietly
  3898. (message "Mapping tables: %d%%"
  3899. (floor (* 100.0 (point)) (buffer-size))))
  3900. (beginning-of-line 1)
  3901. (when (and (looking-at org-table-line-regexp)
  3902. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3903. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3904. (save-excursion (funcall function))
  3905. (or (looking-at org-table-line-regexp)
  3906. (forward-char 1)))
  3907. (re-search-forward org-table-any-border-regexp nil 1)))
  3908. (unless quietly (message "Mapping tables: done")))
  3909. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3910. (declare-function org-clock-update-mode-line "org-clock" ())
  3911. (declare-function org-resolve-clocks "org-clock"
  3912. (&optional also-non-dangling-p prompt last-valid))
  3913. (defun org-at-TBLFM-p (&optional pos)
  3914. "Non-nil when point (or POS) is in #+TBLFM line."
  3915. (save-excursion
  3916. (goto-char (or pos (point)))
  3917. (beginning-of-line)
  3918. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3919. (eq (org-element-type (org-element-at-point)) 'table))))
  3920. (defvar org-clock-start-time)
  3921. (defvar org-clock-marker (make-marker)
  3922. "Marker recording the last clock-in.")
  3923. (defvar org-clock-hd-marker (make-marker)
  3924. "Marker recording the last clock-in, but the headline position.")
  3925. (defvar org-clock-heading ""
  3926. "The heading of the current clock entry.")
  3927. (defun org-clock-is-active ()
  3928. "Return the buffer where the clock is currently running.
  3929. Return nil if no clock is running."
  3930. (marker-buffer org-clock-marker))
  3931. (defun org-check-running-clock ()
  3932. "Check if the current buffer contains the running clock.
  3933. If yes, offer to stop it and to save the buffer with the changes."
  3934. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3935. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3936. (buffer-name))))
  3937. (org-clock-out)
  3938. (when (y-or-n-p "Save changed buffer?")
  3939. (save-buffer))))
  3940. (defun org-clocktable-try-shift (dir n)
  3941. "Check if this line starts a clock table, if yes, shift the time block."
  3942. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3943. (org-clocktable-shift dir n)))
  3944. ;;;###autoload
  3945. (defun org-clock-persistence-insinuate ()
  3946. "Set up hooks for clock persistence."
  3947. (require 'org-clock)
  3948. (add-hook 'org-mode-hook 'org-clock-load)
  3949. (add-hook 'kill-emacs-hook 'org-clock-save))
  3950. (defgroup org-archive nil
  3951. "Options concerning archiving in Org mode."
  3952. :tag "Org Archive"
  3953. :group 'org-structure)
  3954. (defcustom org-archive-location "%s_archive::"
  3955. "The location where subtrees should be archived.
  3956. The value of this variable is a string, consisting of two parts,
  3957. separated by a double-colon. The first part is a filename and
  3958. the second part is a headline.
  3959. When the filename is omitted, archiving happens in the same file.
  3960. %s in the filename will be replaced by the current file
  3961. name (without the directory part). Archiving to a different file
  3962. is useful to keep archived entries from contributing to the
  3963. Org Agenda.
  3964. The archived entries will be filed as subtrees of the specified
  3965. headline. When the headline is omitted, the subtrees are simply
  3966. filed away at the end of the file, as top-level entries. Also in
  3967. the heading you can use %s to represent the file name, this can be
  3968. useful when using the same archive for a number of different files.
  3969. Here are a few examples:
  3970. \"%s_archive::\"
  3971. If the current file is Projects.org, archive in file
  3972. Projects.org_archive, as top-level trees. This is the default.
  3973. \"::* Archived Tasks\"
  3974. Archive in the current file, under the top-level headline
  3975. \"* Archived Tasks\".
  3976. \"~/org/archive.org::\"
  3977. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3978. \"~/org/archive.org::* From %s\"
  3979. Archive in file ~/org/archive.org (absolute path), under headlines
  3980. \"From FILENAME\" where file name is the current file name.
  3981. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3982. The \"datetree/\" string is special, signifying to archive
  3983. items to the datetree. Items are placed in either the CLOSED
  3984. date of the item, or the current date if there is no CLOSED date.
  3985. The heading will be a subentry to the current date. There doesn't
  3986. need to be a heading, but there always needs to be a slash after
  3987. datetree. For example, to store archived items directly in the
  3988. datetree, use \"~/org/datetree.org::datetree/\".
  3989. \"basement::** Finished Tasks\"
  3990. Archive in file ./basement (relative path), as level 3 trees
  3991. below the level 2 heading \"** Finished Tasks\".
  3992. You may set this option on a per-file basis by adding to the buffer a
  3993. line like
  3994. #+ARCHIVE: basement::** Finished Tasks
  3995. You may also define it locally for a subtree by setting an ARCHIVE property
  3996. in the entry. If such a property is found in an entry, or anywhere up
  3997. the hierarchy, it will be used."
  3998. :group 'org-archive
  3999. :type 'string)
  4000. (defcustom org-agenda-skip-archived-trees t
  4001. "Non-nil means the agenda will skip any items located in archived trees.
  4002. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4003. variable is no longer recommended, you should leave it at the value t.
  4004. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4005. :group 'org-archive
  4006. :group 'org-agenda-skip
  4007. :type 'boolean)
  4008. (defcustom org-columns-skip-archived-trees t
  4009. "Non-nil means ignore archived trees when creating column view."
  4010. :group 'org-archive
  4011. :group 'org-properties
  4012. :type 'boolean)
  4013. (defcustom org-cycle-open-archived-trees nil
  4014. "Non-nil means `org-cycle' will open archived trees.
  4015. An archived tree is a tree marked with the tag ARCHIVE.
  4016. When nil, archived trees will stay folded. You can still open them with
  4017. normal outline commands like `show-all', but not with the cycling commands."
  4018. :group 'org-archive
  4019. :group 'org-cycle
  4020. :type 'boolean)
  4021. (defcustom org-sparse-tree-open-archived-trees nil
  4022. "Non-nil means sparse tree construction shows matches in archived trees.
  4023. When nil, matches in these trees are highlighted, but the trees are kept in
  4024. collapsed state."
  4025. :group 'org-archive
  4026. :group 'org-sparse-trees
  4027. :type 'boolean)
  4028. (defcustom org-sparse-tree-default-date-type nil
  4029. "The default date type when building a sparse tree.
  4030. When this is nil, a date is a scheduled or a deadline timestamp.
  4031. Otherwise, these types are allowed:
  4032. all: all timestamps
  4033. active: only active timestamps (<...>)
  4034. inactive: only inactive timestamps ([...])
  4035. scheduled: only scheduled timestamps
  4036. deadline: only deadline timestamps"
  4037. :type '(choice (const :tag "Scheduled or deadline" nil)
  4038. (const :tag "All timestamps" all)
  4039. (const :tag "Only active timestamps" active)
  4040. (const :tag "Only inactive timestamps" inactive)
  4041. (const :tag "Only scheduled timestamps" scheduled)
  4042. (const :tag "Only deadline timestamps" deadline)
  4043. (const :tag "Only closed timestamps" closed))
  4044. :version "26.1"
  4045. :package-version '(Org . "8.3")
  4046. :group 'org-sparse-trees)
  4047. (defun org-cycle-hide-archived-subtrees (state)
  4048. "Re-hide all archived subtrees after a visibility state change.
  4049. STATE should be one of the symbols listed in the docstring of
  4050. `org-cycle-hook'."
  4051. (when (and (not org-cycle-open-archived-trees)
  4052. (not (memq state '(overview folded))))
  4053. (save-excursion
  4054. (let* ((globalp (memq state '(contents all)))
  4055. (beg (if globalp (point-min) (point)))
  4056. (end (if globalp (point-max) (org-end-of-subtree t))))
  4057. (org-hide-archived-subtrees beg end)
  4058. (goto-char beg)
  4059. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4060. (message "%s" (substitute-command-keys
  4061. "Subtree is archived and stays closed. Use \
  4062. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4063. (defun org-force-cycle-archived ()
  4064. "Cycle subtree even if it is archived."
  4065. (interactive)
  4066. (setq this-command 'org-cycle)
  4067. (let ((org-cycle-open-archived-trees t))
  4068. (call-interactively 'org-cycle)))
  4069. (defun org-hide-archived-subtrees (beg end)
  4070. "Re-hide all archived subtrees after a visibility state change."
  4071. (org-with-wide-buffer
  4072. (let ((case-fold-search nil)
  4073. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4074. (goto-char beg)
  4075. ;; Include headline point is currently on.
  4076. (beginning-of-line)
  4077. (while (and (< (point) end) (re-search-forward re end t))
  4078. (when (member org-archive-tag (org-get-tags))
  4079. (org-flag-subtree t)
  4080. (org-end-of-subtree t))))))
  4081. (declare-function outline-end-of-heading "outline" ())
  4082. (declare-function outline-flag-region "outline" (from to flag))
  4083. (defun org-flag-subtree (flag)
  4084. (save-excursion
  4085. (org-back-to-heading t)
  4086. (outline-end-of-heading)
  4087. (outline-flag-region (point)
  4088. (progn (org-end-of-subtree t) (point))
  4089. flag)))
  4090. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4091. ;; Declare Column View Code
  4092. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4093. (declare-function org-columns-compute "org-colview" (property))
  4094. ;; Declare ID code
  4095. (declare-function org-id-store-link "org-id")
  4096. (declare-function org-id-locations-load "org-id")
  4097. (declare-function org-id-locations-save "org-id")
  4098. (defvar org-id-track-globally)
  4099. ;;; Variables for pre-computed regular expressions, all buffer local
  4100. (defvar-local org-todo-regexp nil
  4101. "Matches any of the TODO state keywords.
  4102. Since TODO keywords are case-sensitive, `case-fold-search' is
  4103. expected to be bound to nil when matching against this regexp.")
  4104. (defvar-local org-not-done-regexp nil
  4105. "Matches any of the TODO state keywords except the last one.
  4106. Since TODO keywords are case-sensitive, `case-fold-search' is
  4107. expected to be bound to nil when matching against this regexp.")
  4108. (defvar-local org-not-done-heading-regexp nil
  4109. "Matches a TODO headline that is not done.
  4110. Since TODO keywords are case-sensitive, `case-fold-search' is
  4111. expected to be bound to nil when matching against this regexp.")
  4112. (defvar-local org-todo-line-regexp nil
  4113. "Matches a headline and puts TODO state into group 2 if present.
  4114. Since TODO keywords are case-sensitive, `case-fold-search' is
  4115. expected to be bound to nil when matching against this regexp.")
  4116. (defvar-local org-complex-heading-regexp nil
  4117. "Matches a headline and puts everything into groups:
  4118. group 1: Stars
  4119. group 2: The TODO keyword, maybe
  4120. group 3: Priority cookie
  4121. group 4: True headline
  4122. group 5: Tags
  4123. Since TODO keywords are case-sensitive, `case-fold-search' is
  4124. expected to be bound to nil when matching against this regexp.")
  4125. (defvar-local org-complex-heading-regexp-format nil
  4126. "Printf format to make regexp to match an exact headline.
  4127. This regexp will match the headline of any node which has the
  4128. exact headline text that is put into the format, but may have any
  4129. TODO state, priority and tags.")
  4130. (defvar-local org-todo-line-tags-regexp nil
  4131. "Matches a headline and puts TODO state into group 2 if present.
  4132. Also put tags into group 4 if tags are present.")
  4133. (defconst org-plain-time-of-day-regexp
  4134. (concat
  4135. "\\(\\<[012]?[0-9]"
  4136. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4137. "\\(--?"
  4138. "\\(\\<[012]?[0-9]"
  4139. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4140. "\\)?")
  4141. "Regular expression to match a plain time or time range.
  4142. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4143. groups carry important information:
  4144. 0 the full match
  4145. 1 the first time, range or not
  4146. 8 the second time, if it is a range.")
  4147. (defconst org-plain-time-extension-regexp
  4148. (concat
  4149. "\\(\\<[012]?[0-9]"
  4150. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4151. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4152. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4153. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4154. groups carry important information:
  4155. 0 the full match
  4156. 7 hours of duration
  4157. 9 minutes of duration")
  4158. (defconst org-stamp-time-of-day-regexp
  4159. (concat
  4160. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4161. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4162. "\\(--?"
  4163. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4164. "Regular expression to match a timestamp time or time range.
  4165. After a match, the following groups carry important information:
  4166. 0 the full match
  4167. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4168. 2 the first time, range or not
  4169. 4 the second time, if it is a range.")
  4170. (defconst org-startup-options
  4171. '(("fold" org-startup-folded t)
  4172. ("overview" org-startup-folded t)
  4173. ("nofold" org-startup-folded nil)
  4174. ("showall" org-startup-folded nil)
  4175. ("showeverything" org-startup-folded showeverything)
  4176. ("content" org-startup-folded content)
  4177. ("indent" org-startup-indented t)
  4178. ("noindent" org-startup-indented nil)
  4179. ("hidestars" org-hide-leading-stars t)
  4180. ("showstars" org-hide-leading-stars nil)
  4181. ("odd" org-odd-levels-only t)
  4182. ("oddeven" org-odd-levels-only nil)
  4183. ("align" org-startup-align-all-tables t)
  4184. ("noalign" org-startup-align-all-tables nil)
  4185. ("inlineimages" org-startup-with-inline-images t)
  4186. ("noinlineimages" org-startup-with-inline-images nil)
  4187. ("latexpreview" org-startup-with-latex-preview t)
  4188. ("nolatexpreview" org-startup-with-latex-preview nil)
  4189. ("customtime" org-display-custom-times t)
  4190. ("logdone" org-log-done time)
  4191. ("lognotedone" org-log-done note)
  4192. ("nologdone" org-log-done nil)
  4193. ("lognoteclock-out" org-log-note-clock-out t)
  4194. ("nolognoteclock-out" org-log-note-clock-out nil)
  4195. ("logrepeat" org-log-repeat state)
  4196. ("lognoterepeat" org-log-repeat note)
  4197. ("logdrawer" org-log-into-drawer t)
  4198. ("nologdrawer" org-log-into-drawer nil)
  4199. ("logstatesreversed" org-log-states-order-reversed t)
  4200. ("nologstatesreversed" org-log-states-order-reversed nil)
  4201. ("nologrepeat" org-log-repeat nil)
  4202. ("logreschedule" org-log-reschedule time)
  4203. ("lognotereschedule" org-log-reschedule note)
  4204. ("nologreschedule" org-log-reschedule nil)
  4205. ("logredeadline" org-log-redeadline time)
  4206. ("lognoteredeadline" org-log-redeadline note)
  4207. ("nologredeadline" org-log-redeadline nil)
  4208. ("logrefile" org-log-refile time)
  4209. ("lognoterefile" org-log-refile note)
  4210. ("nologrefile" org-log-refile nil)
  4211. ("fninline" org-footnote-define-inline t)
  4212. ("nofninline" org-footnote-define-inline nil)
  4213. ("fnlocal" org-footnote-section nil)
  4214. ("fnauto" org-footnote-auto-label t)
  4215. ("fnprompt" org-footnote-auto-label nil)
  4216. ("fnconfirm" org-footnote-auto-label confirm)
  4217. ("fnplain" org-footnote-auto-label plain)
  4218. ("fnadjust" org-footnote-auto-adjust t)
  4219. ("nofnadjust" org-footnote-auto-adjust nil)
  4220. ("constcgs" constants-unit-system cgs)
  4221. ("constSI" constants-unit-system SI)
  4222. ("noptag" org-tag-persistent-alist nil)
  4223. ("hideblocks" org-hide-block-startup t)
  4224. ("nohideblocks" org-hide-block-startup nil)
  4225. ("beamer" org-startup-with-beamer-mode t)
  4226. ("entitiespretty" org-pretty-entities t)
  4227. ("entitiesplain" org-pretty-entities nil))
  4228. "Variable associated with STARTUP options for org-mode.
  4229. Each element is a list of three items: the startup options (as written
  4230. in the #+STARTUP line), the corresponding variable, and the value to set
  4231. this variable to if the option is found. An optional forth element PUSH
  4232. means to push this value onto the list in the variable.")
  4233. (defcustom org-group-tags t
  4234. "When non-nil (the default), use group tags.
  4235. This can be turned on/off through `org-toggle-tags-groups'."
  4236. :group 'org-tags
  4237. :group 'org-startup
  4238. :type 'boolean)
  4239. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4240. (defun org-toggle-tags-groups ()
  4241. "Toggle support for group tags.
  4242. Support for group tags is controlled by the option
  4243. `org-group-tags', which is non-nil by default."
  4244. (interactive)
  4245. (setq org-group-tags (not org-group-tags))
  4246. (cond ((and (derived-mode-p 'org-agenda-mode)
  4247. org-group-tags)
  4248. (org-agenda-redo))
  4249. ((derived-mode-p 'org-mode)
  4250. (let ((org-inhibit-startup t)) (org-mode))))
  4251. (message "Groups tags support has been turned %s"
  4252. (if org-group-tags "on" "off")))
  4253. (defun org-set-regexps-and-options (&optional tags-only)
  4254. "Precompute regular expressions used in the current buffer.
  4255. When optional argument TAGS-ONLY is non-nil, only compute tags
  4256. related expressions."
  4257. (when (derived-mode-p 'org-mode)
  4258. (let ((alist (org--setup-collect-keywords
  4259. (org-make-options-regexp
  4260. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4261. (and (not tags-only)
  4262. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4263. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4264. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4265. ;; Startup options. Get this early since it does change
  4266. ;; behavior for other options (e.g., tags).
  4267. (let ((startup (cdr (assq 'startup alist))))
  4268. (dolist (option startup)
  4269. (let ((entry (assoc-string option org-startup-options t)))
  4270. (when entry
  4271. (let ((var (nth 1 entry))
  4272. (val (nth 2 entry)))
  4273. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4274. (unless (listp (symbol-value var))
  4275. (set (make-local-variable var) nil))
  4276. (add-to-list var val)))))))
  4277. (setq-local org-file-tags
  4278. (mapcar #'org-add-prop-inherited
  4279. (cdr (assq 'filetags alist))))
  4280. (setq org-current-tag-alist
  4281. (append org-tag-persistent-alist
  4282. (let ((tags (cdr (assq 'tags alist))))
  4283. (if tags (org-tag-string-to-alist tags)
  4284. org-tag-alist))))
  4285. (setq org-tag-groups-alist
  4286. (org-tag-alist-to-groups org-current-tag-alist))
  4287. (unless tags-only
  4288. ;; File properties.
  4289. (setq-local org-file-properties (cdr (assq 'property alist)))
  4290. ;; Archive location.
  4291. (let ((archive (cdr (assq 'archive alist))))
  4292. (when archive (setq-local org-archive-location archive)))
  4293. ;; Category.
  4294. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4295. (when cat
  4296. (setq-local org-category (intern cat))
  4297. (setq-local org-file-properties
  4298. (org--update-property-plist
  4299. "CATEGORY" cat org-file-properties))))
  4300. ;; Columns.
  4301. (let ((column (cdr (assq 'columns alist))))
  4302. (when column (setq-local org-columns-default-format column)))
  4303. ;; Constants.
  4304. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4305. ;; Link abbreviations.
  4306. (let ((links (cdr (assq 'link alist))))
  4307. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4308. ;; Priorities.
  4309. (let ((priorities (cdr (assq 'priorities alist))))
  4310. (when priorities
  4311. (setq-local org-highest-priority (nth 0 priorities))
  4312. (setq-local org-lowest-priority (nth 1 priorities))
  4313. (setq-local org-default-priority (nth 2 priorities))))
  4314. ;; Scripts.
  4315. (let ((scripts (assq 'scripts alist)))
  4316. (when scripts
  4317. (setq-local org-use-sub-superscripts (cdr scripts))))
  4318. ;; TODO keywords.
  4319. (setq-local org-todo-kwd-alist nil)
  4320. (setq-local org-todo-key-alist nil)
  4321. (setq-local org-todo-key-trigger nil)
  4322. (setq-local org-todo-keywords-1 nil)
  4323. (setq-local org-done-keywords nil)
  4324. (setq-local org-todo-heads nil)
  4325. (setq-local org-todo-sets nil)
  4326. (setq-local org-todo-log-states nil)
  4327. (let ((todo-sequences
  4328. (or (nreverse (cdr (assq 'todo alist)))
  4329. (let ((d (default-value 'org-todo-keywords)))
  4330. (if (not (stringp (car d))) d
  4331. ;; XXX: Backward compatibility code.
  4332. (list (cons org-todo-interpretation d)))))))
  4333. (dolist (sequence todo-sequences)
  4334. (let* ((sequence (or (run-hook-with-args-until-success
  4335. 'org-todo-setup-filter-hook sequence)
  4336. sequence))
  4337. (sequence-type (car sequence))
  4338. (keywords (cdr sequence))
  4339. (sep (member "|" keywords))
  4340. names alist)
  4341. (dolist (k (remove "|" keywords))
  4342. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4343. k)
  4344. (error "Invalid TODO keyword %s" k))
  4345. (let ((name (match-string 1 k))
  4346. (key (match-string 2 k))
  4347. (log (org-extract-log-state-settings k)))
  4348. (push name names)
  4349. (push (cons name (and key (string-to-char key))) alist)
  4350. (when log (push log org-todo-log-states))))
  4351. (let* ((names (nreverse names))
  4352. (done (if sep (org-remove-keyword-keys (cdr sep))
  4353. (last names)))
  4354. (head (car names))
  4355. (tail (list sequence-type head (car done) (org-last done))))
  4356. (add-to-list 'org-todo-heads head 'append)
  4357. (push names org-todo-sets)
  4358. (setq org-done-keywords (append org-done-keywords done nil))
  4359. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4360. (setq org-todo-key-alist
  4361. (append org-todo-key-alist
  4362. (and alist
  4363. (append '((:startgroup))
  4364. (nreverse alist)
  4365. '((:endgroup))))))
  4366. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4367. (setq org-todo-sets (nreverse org-todo-sets)
  4368. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4369. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4370. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4371. ;; Compute the regular expressions and other local variables.
  4372. ;; Using `org-outline-regexp-bol' would complicate them much,
  4373. ;; because of the fixed white space at the end of that string.
  4374. (unless org-done-keywords
  4375. (setq org-done-keywords
  4376. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4377. (setq org-not-done-keywords
  4378. (org-delete-all org-done-keywords
  4379. (copy-sequence org-todo-keywords-1))
  4380. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4381. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4382. org-not-done-heading-regexp
  4383. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4384. org-todo-line-regexp
  4385. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4386. org-complex-heading-regexp
  4387. (concat "^\\(\\*+\\)"
  4388. "\\(?: +" org-todo-regexp "\\)?"
  4389. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4390. "\\(?: +\\(.*?\\)\\)??"
  4391. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4392. "[ \t]*$")
  4393. org-complex-heading-regexp-format
  4394. (concat "^\\(\\*+\\)"
  4395. "\\(?: +" org-todo-regexp "\\)?"
  4396. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4397. "\\(?: +"
  4398. ;; Stats cookies can be stuck to body.
  4399. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4400. "\\(%s\\)"
  4401. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4402. "\\)"
  4403. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4404. "[ \t]*$")
  4405. org-todo-line-tags-regexp
  4406. (concat "^\\(\\*+\\)"
  4407. "\\(?: +" org-todo-regexp "\\)?"
  4408. "\\(?: +\\(.*?\\)\\)??"
  4409. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4410. "[ \t]*$"))
  4411. (org-compute-latex-and-related-regexp)))))
  4412. (defun org--setup-collect-keywords (regexp &optional files alist)
  4413. "Return setup keywords values as an alist.
  4414. REGEXP matches a subset of setup keywords. FILES is a list of
  4415. file names already visited. It is used to avoid circular setup
  4416. files. ALIST, when non-nil, is the alist computed so far.
  4417. Return value contains the following keys: `archive', `category',
  4418. `columns', `constants', `filetags', `link', `priorities',
  4419. `property', `scripts', `startup', `tags' and `todo'."
  4420. (org-with-wide-buffer
  4421. (goto-char (point-min))
  4422. (let ((case-fold-search t))
  4423. (while (re-search-forward regexp nil t)
  4424. (let ((element (org-element-at-point)))
  4425. (when (eq (org-element-type element) 'keyword)
  4426. (let ((key (org-element-property :key element))
  4427. (value (org-element-property :value element)))
  4428. (cond
  4429. ((equal key "ARCHIVE")
  4430. (when (org-string-nw-p value)
  4431. (push (cons 'archive value) alist)))
  4432. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4433. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4434. ((equal key "CONSTANTS")
  4435. (let* ((constants (assq 'constants alist))
  4436. (store (cdr constants)))
  4437. (dolist (pair (org-split-string value))
  4438. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4439. pair)
  4440. (let* ((name (match-string 1 pair))
  4441. (value (match-string 2 pair))
  4442. (old (assoc name store)))
  4443. (if old (setcdr old value)
  4444. (push (cons name value) store)))))
  4445. (if constants (setcdr constants store)
  4446. (push (cons 'constants store) alist))))
  4447. ((equal key "FILETAGS")
  4448. (when (org-string-nw-p value)
  4449. (let ((old (assq 'filetags alist))
  4450. (new (apply #'nconc
  4451. (mapcar (lambda (x) (org-split-string x ":"))
  4452. (org-split-string value)))))
  4453. (if old (setcdr old (append new (cdr old)))
  4454. (push (cons 'filetags new) alist)))))
  4455. ((equal key "LINK")
  4456. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4457. (let ((links (assq 'link alist))
  4458. (pair (cons (match-string-no-properties 1 value)
  4459. (match-string-no-properties 2 value))))
  4460. (if links (push pair (cdr links))
  4461. (push (list 'link pair) alist)))))
  4462. ((equal key "OPTIONS")
  4463. (when (and (org-string-nw-p value)
  4464. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4465. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4466. ((equal key "PRIORITIES")
  4467. (push (cons 'priorities
  4468. (let ((prio (org-split-string value)))
  4469. (if (< (length prio) 3) '(?A ?C ?B)
  4470. (mapcar #'string-to-char prio))))
  4471. alist))
  4472. ((equal key "PROPERTY")
  4473. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4474. (let* ((property (assq 'property alist))
  4475. (value (org--update-property-plist
  4476. (match-string-no-properties 1 value)
  4477. (match-string-no-properties 2 value)
  4478. (cdr property))))
  4479. (if property (setcdr property value)
  4480. (push (cons 'property value) alist)))))
  4481. ((equal key "STARTUP")
  4482. (let ((startup (assq 'startup alist)))
  4483. (if startup
  4484. (setcdr startup
  4485. (append (cdr startup) (org-split-string value)))
  4486. (push (cons 'startup (org-split-string value)) alist))))
  4487. ((equal key "TAGS")
  4488. (let ((tag-cell (assq 'tags alist)))
  4489. (if tag-cell
  4490. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4491. (push (cons 'tags value) alist))))
  4492. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4493. (let ((todo (assq 'todo alist))
  4494. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4495. (org-split-string value))))
  4496. (if todo (push value (cdr todo))
  4497. (push (list 'todo value) alist))))
  4498. ((equal key "SETUPFILE")
  4499. (unless buffer-read-only ; Do not check in Gnus messages.
  4500. (let ((f (and (org-string-nw-p value)
  4501. (expand-file-name
  4502. (org-unbracket-string "\"" "\"" value)))))
  4503. (when (and f (file-readable-p f) (not (member f files)))
  4504. (with-temp-buffer
  4505. (setq default-directory (file-name-directory f))
  4506. (insert-file-contents f)
  4507. (setq alist
  4508. ;; Fake Org mode to benefit from cache
  4509. ;; without recurring needlessly.
  4510. (let ((major-mode 'org-mode))
  4511. (org--setup-collect-keywords
  4512. regexp (cons f files) alist)))))))))))))))
  4513. alist)
  4514. (defun org-tag-string-to-alist (s)
  4515. "Return tag alist associated to string S.
  4516. S is a value for TAGS keyword or produced with
  4517. `org-tag-alist-to-string'. Return value is an alist suitable for
  4518. `org-tag-alist' or `org-tag-persistent-alist'."
  4519. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4520. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4521. "\\|{.+?}\\)" ; regular expression
  4522. "\\(?:(\\(.\\))\\)?\\'"))
  4523. alist group-flag)
  4524. (dolist (tokens lines (cdr (nreverse alist)))
  4525. (push '(:newline) alist)
  4526. (while tokens
  4527. (let ((token (pop tokens)))
  4528. (pcase token
  4529. ("{"
  4530. (push '(:startgroup) alist)
  4531. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4532. ("}"
  4533. (push '(:endgroup) alist)
  4534. (setq group-flag nil))
  4535. ("["
  4536. (push '(:startgrouptag) alist)
  4537. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4538. ("]"
  4539. (push '(:endgrouptag) alist)
  4540. (setq group-flag nil))
  4541. (":"
  4542. (push '(:grouptags) alist))
  4543. ((guard (string-match tag-re token))
  4544. (let ((tag (match-string 1 token))
  4545. (key (and (match-beginning 2)
  4546. (string-to-char (match-string 2 token)))))
  4547. ;; Push all tags in groups, no matter if they already
  4548. ;; appear somewhere else in the list.
  4549. (when (or group-flag (not (assoc tag alist)))
  4550. (push (cons tag key) alist))))))))))
  4551. (defun org-tag-alist-to-string (alist &optional skip-key)
  4552. "Return tag string associated to ALIST.
  4553. ALIST is an alist, as defined in `org-tag-alist' or
  4554. `org-tag-persistent-alist', or produced with
  4555. `org-tag-string-to-alist'.
  4556. Return value is a string suitable as a value for \"TAGS\"
  4557. keyword.
  4558. When optional argument SKIP-KEY is non-nil, skip selection keys
  4559. next to tags."
  4560. (mapconcat (lambda (token)
  4561. (pcase token
  4562. (`(:startgroup) "{")
  4563. (`(:endgroup) "}")
  4564. (`(:startgrouptag) "[")
  4565. (`(:endgrouptag) "]")
  4566. (`(:grouptags) ":")
  4567. (`(:newline) "\\n")
  4568. ((and
  4569. (guard (not skip-key))
  4570. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4571. (format "%s(%c)" tag key))
  4572. (`(,(and tag (pred stringp)) . ,_) tag)
  4573. (_ (user-error "Invalid tag token: %S" token))))
  4574. alist
  4575. " "))
  4576. (defun org-tag-alist-to-groups (alist)
  4577. "Return group alist from tag ALIST.
  4578. ALIST is an alist, as defined in `org-tag-alist' or
  4579. `org-tag-persistent-alist', or produced with
  4580. `org-tag-string-to-alist'. Return value is an alist following
  4581. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4582. a string, summarizing TAGS, as a list of strings."
  4583. (let (groups group-status current-group)
  4584. (dolist (token alist (nreverse groups))
  4585. (pcase token
  4586. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4587. (`(,(or :endgroup :endgrouptag))
  4588. (when (eq group-status 'append)
  4589. (push (nreverse current-group) groups))
  4590. (setq group-status nil))
  4591. (`(:grouptags) (setq group-status 'append))
  4592. ((and `(,tag . ,_) (guard group-status))
  4593. (if (eq group-status 'append) (push tag current-group)
  4594. (setq current-group (list tag))))
  4595. (_ nil)))))
  4596. (defvar org--file-cache (make-hash-table :test #'equal)
  4597. "Hash table to store contents of files referenced via a URL.
  4598. This is the cache of file URLs read using `org-file-contents'.")
  4599. (defun org-reset-file-cache ()
  4600. "Reset the cache of files downloaded by `org-file-contents'."
  4601. (clrhash org--file-cache))
  4602. (defun org-file-url-p (file)
  4603. "Non-nil if FILE is a URL."
  4604. (require 'ffap)
  4605. (string-match-p ffap-url-regexp file))
  4606. (defun org-file-contents (file &optional noerror nocache)
  4607. "Return the contents of FILE, as a string.
  4608. FILE can be a file name or URL.
  4609. If FILE is a URL, download the contents. If the URL contents are
  4610. already cached in the `org--file-cache' hash table, the download step
  4611. is skipped.
  4612. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4613. from file or URL.
  4614. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4615. is available. This option applies only if FILE is a URL."
  4616. (let* ((is-url (org-file-url-p file))
  4617. (cache (and is-url
  4618. (not nocache)
  4619. (gethash file org--file-cache))))
  4620. (cond
  4621. (cache)
  4622. (is-url
  4623. (with-current-buffer (url-retrieve-synchronously file)
  4624. (goto-char (point-min))
  4625. ;; Move point to after the url-retrieve header.
  4626. (search-forward "\n\n" nil :move)
  4627. ;; Search for the success code only in the url-retrieve header.
  4628. (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4629. ;; Update the cache `org--file-cache' and return contents.
  4630. (puthash file
  4631. (buffer-substring-no-properties (point) (point-max))
  4632. org--file-cache)
  4633. (funcall (if noerror #'message #'user-error)
  4634. "Unable to fetch file from %S"
  4635. file))))
  4636. (t
  4637. (with-temp-buffer
  4638. (condition-case err
  4639. (progn
  4640. (insert-file-contents file)
  4641. (buffer-string))
  4642. (file-error
  4643. (funcall (if noerror #'message #'user-error)
  4644. (error-message-string err)))))))))
  4645. (defun org-extract-log-state-settings (x)
  4646. "Extract the log state setting from a TODO keyword string.
  4647. This will extract info from a string like \"WAIT(w@/!)\"."
  4648. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4649. (let ((kw (match-string 1 x))
  4650. (log1 (and (match-end 3) (match-string 3 x)))
  4651. (log2 (and (match-end 4) (match-string 4 x))))
  4652. (and (or log1 log2)
  4653. (list kw
  4654. (and log1 (if (equal log1 "!") 'time 'note))
  4655. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4656. (defun org-remove-keyword-keys (list)
  4657. "Remove a pair of parenthesis at the end of each string in LIST."
  4658. (mapcar (lambda (x)
  4659. (if (string-match "(.*)$" x)
  4660. (substring x 0 (match-beginning 0))
  4661. x))
  4662. list))
  4663. (defun org-assign-fast-keys (alist)
  4664. "Assign fast keys to a keyword-key alist.
  4665. Respect keys that are already there."
  4666. (let (new e (alt ?0))
  4667. (while (setq e (pop alist))
  4668. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4669. (cdr e)) ;; Key already assigned.
  4670. (push e new)
  4671. (let ((clist (string-to-list (downcase (car e))))
  4672. (used (append new alist)))
  4673. (when (= (car clist) ?@)
  4674. (pop clist))
  4675. (while (and clist (rassoc (car clist) used))
  4676. (pop clist))
  4677. (unless clist
  4678. (while (rassoc alt used)
  4679. (cl-incf alt)))
  4680. (push (cons (car e) (or (car clist) alt)) new))))
  4681. (nreverse new)))
  4682. ;;; Some variables used in various places
  4683. (defvar org-window-configuration nil
  4684. "Used in various places to store a window configuration.")
  4685. (defvar org-selected-window nil
  4686. "Used in various places to store a window configuration.")
  4687. (defvar org-finish-function nil
  4688. "Function to be called when `C-c C-c' is used.
  4689. This is for getting out of special buffers like capture.")
  4690. (defvar org-last-state)
  4691. ;; Defined somewhere in this file, but used before definition.
  4692. (defvar org-entities) ;; defined in org-entities.el
  4693. (defvar org-struct-menu)
  4694. (defvar org-org-menu)
  4695. (defvar org-tbl-menu)
  4696. ;;;; Define the Org mode
  4697. ;; We use a before-change function to check if a table might need
  4698. ;; an update.
  4699. (defvar org-table-may-need-update t
  4700. "Indicates that a table might need an update.
  4701. This variable is set by `org-before-change-function'.
  4702. `org-table-align' sets it back to nil.")
  4703. (defun org-before-change-function (_beg _end)
  4704. "Every change indicates that a table might need an update."
  4705. (setq org-table-may-need-update t))
  4706. (defvar org-mode-map)
  4707. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4708. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4709. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4710. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4711. (defvar org-table-buffer-is-an nil)
  4712. (defvar bidi-paragraph-direction)
  4713. (defvar buffer-face-mode-face)
  4714. (require 'outline)
  4715. ;; Other stuff we need.
  4716. (require 'time-date)
  4717. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4718. (require 'easymenu)
  4719. (autoload 'easy-menu-add "easymenu")
  4720. (require 'overlay)
  4721. ;; (require 'org-macs) moved higher up in the file before it is first used
  4722. (require 'org-entities)
  4723. ;; (require 'org-compat) moved higher up in the file before it is first used
  4724. (require 'org-faces)
  4725. (require 'org-list)
  4726. (require 'org-pcomplete)
  4727. (require 'org-src)
  4728. (require 'org-footnote)
  4729. (require 'org-macro)
  4730. ;; babel
  4731. (require 'ob)
  4732. ;;;###autoload
  4733. (define-derived-mode org-mode outline-mode "Org"
  4734. "Outline-based notes management and organizer, alias
  4735. \"Carsten's outline-mode for keeping track of everything.\"
  4736. Org mode develops organizational tasks around a NOTES file which
  4737. contains information about projects as plain text. Org mode is
  4738. implemented on top of Outline mode, which is ideal to keep the content
  4739. of large files well structured. It supports ToDo items, deadlines and
  4740. time stamps, which magically appear in the diary listing of the Emacs
  4741. calendar. Tables are easily created with a built-in table editor.
  4742. Plain text URL-like links connect to websites, emails (VM), Usenet
  4743. messages (Gnus), BBDB entries, and any files related to the project.
  4744. For printing and sharing of notes, an Org file (or a part of it)
  4745. can be exported as a structured ASCII or HTML file.
  4746. The following commands are available:
  4747. \\{org-mode-map}"
  4748. ;; Get rid of Outline menus, they are not needed
  4749. ;; Need to do this here because define-derived-mode sets up
  4750. ;; the keymap so late. Still, it is a waste to call this each time
  4751. ;; we switch another buffer into Org mode.
  4752. (define-key org-mode-map [menu-bar headings] 'undefined)
  4753. (define-key org-mode-map [menu-bar hide] 'undefined)
  4754. (define-key org-mode-map [menu-bar show] 'undefined)
  4755. (org-load-modules-maybe)
  4756. (org-install-agenda-files-menu)
  4757. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4758. (add-to-invisibility-spec '(org-cwidth))
  4759. (add-to-invisibility-spec '(org-hide-block . t))
  4760. (setq-local outline-regexp org-outline-regexp)
  4761. (setq-local outline-level 'org-outline-level)
  4762. (setq bidi-paragraph-direction 'left-to-right)
  4763. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4764. (unless org-display-table
  4765. (setq org-display-table (make-display-table)))
  4766. (set-display-table-slot
  4767. org-display-table 4
  4768. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4769. org-ellipsis)))
  4770. (setq buffer-display-table org-display-table))
  4771. (org-set-regexps-and-options)
  4772. (org-set-font-lock-defaults)
  4773. (when (and org-tag-faces (not org-tags-special-faces-re))
  4774. ;; tag faces set outside customize.... force initialization.
  4775. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4776. ;; Calc embedded
  4777. (setq-local calc-embedded-open-mode "# ")
  4778. ;; Modify a few syntax entries
  4779. (modify-syntax-entry ?@ "w")
  4780. (modify-syntax-entry ?\" "\"")
  4781. (modify-syntax-entry ?\\ "_")
  4782. (modify-syntax-entry ?~ "_")
  4783. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4784. ;; Activate before-change-function
  4785. (setq-local org-table-may-need-update t)
  4786. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4787. ;; Check for running clock before killing a buffer
  4788. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4789. ;; Initialize macros templates.
  4790. (org-macro-initialize-templates)
  4791. ;; Initialize radio targets.
  4792. (org-update-radio-target-regexp)
  4793. ;; Indentation.
  4794. (setq-local indent-line-function 'org-indent-line)
  4795. (setq-local indent-region-function 'org-indent-region)
  4796. ;; Filling and auto-filling.
  4797. (org-setup-filling)
  4798. ;; Comments.
  4799. (org-setup-comments-handling)
  4800. ;; Initialize cache.
  4801. (org-element-cache-reset)
  4802. ;; Beginning/end of defun
  4803. (setq-local beginning-of-defun-function 'org-backward-element)
  4804. (setq-local end-of-defun-function
  4805. (lambda ()
  4806. (if (not (org-at-heading-p))
  4807. (org-forward-element)
  4808. (org-forward-element)
  4809. (forward-char -1))))
  4810. ;; Next error for sparse trees
  4811. (setq-local next-error-function 'org-occur-next-match)
  4812. ;; Make sure dependence stuff works reliably, even for users who set it
  4813. ;; too late :-(
  4814. (if org-enforce-todo-dependencies
  4815. (add-hook 'org-blocker-hook
  4816. 'org-block-todo-from-children-or-siblings-or-parent)
  4817. (remove-hook 'org-blocker-hook
  4818. 'org-block-todo-from-children-or-siblings-or-parent))
  4819. (if org-enforce-todo-checkbox-dependencies
  4820. (add-hook 'org-blocker-hook
  4821. 'org-block-todo-from-checkboxes)
  4822. (remove-hook 'org-blocker-hook
  4823. 'org-block-todo-from-checkboxes))
  4824. ;; Align options lines
  4825. (setq-local
  4826. align-mode-rules-list
  4827. '((org-in-buffer-settings
  4828. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4829. (modes . '(org-mode)))))
  4830. ;; Imenu
  4831. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4832. ;; Make isearch reveal context
  4833. (setq-local outline-isearch-open-invisible-function
  4834. (lambda (&rest _) (org-show-context 'isearch)))
  4835. ;; Setup the pcomplete hooks
  4836. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4837. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4838. (setq-local pcomplete-default-completion-function 'ignore)
  4839. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4840. (setq-local pcomplete-termination-string "")
  4841. (setq-local buffer-face-mode-face 'org-default)
  4842. ;; If empty file that did not turn on Org mode automatically, make
  4843. ;; it to.
  4844. (when (and org-insert-mode-line-in-empty-file
  4845. (called-interactively-p 'any)
  4846. (= (point-min) (point-max)))
  4847. (insert "# -*- mode: org -*-\n\n"))
  4848. (unless org-inhibit-startup
  4849. (org-unmodified
  4850. (when org-startup-with-beamer-mode (org-beamer-mode))
  4851. (when org-startup-align-all-tables
  4852. (org-table-map-tables #'org-table-align t))
  4853. (when org-startup-with-inline-images (org-display-inline-images))
  4854. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4855. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4856. (when org-startup-truncated (setq truncate-lines t))
  4857. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4858. (org-refresh-effort-properties)))
  4859. ;; Try to set `org-hide' face correctly.
  4860. (let ((foreground (org-find-invisible-foreground)))
  4861. (when foreground
  4862. (set-face-foreground 'org-hide foreground))))
  4863. ;; Update `customize-package-emacs-version-alist'
  4864. (add-to-list 'customize-package-emacs-version-alist
  4865. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4866. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4867. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4868. ("9.0" . "26.1")))
  4869. (defvar org-mode-transpose-word-syntax-table
  4870. (let ((st (make-syntax-table text-mode-syntax-table)))
  4871. (dolist (c org-emphasis-alist st)
  4872. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4873. (when (fboundp 'abbrev-table-put)
  4874. (abbrev-table-put org-mode-abbrev-table
  4875. :parents (list text-mode-abbrev-table)))
  4876. (defun org-find-invisible-foreground ()
  4877. (let ((candidates (remove
  4878. "unspecified-bg"
  4879. (nconc
  4880. (list (face-background 'default)
  4881. (face-background 'org-default))
  4882. (mapcar
  4883. (lambda (alist)
  4884. (when (boundp alist)
  4885. (cdr (assq 'background-color (symbol-value alist)))))
  4886. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4887. (list (face-foreground 'org-hide))))))
  4888. (car (remove nil candidates))))
  4889. (defun org-current-time (&optional rounding-minutes past)
  4890. "Current time, possibly rounded to ROUNDING-MINUTES.
  4891. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4892. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4893. the rounding returns a past time."
  4894. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4895. (car org-time-stamp-rounding-minutes)))
  4896. (time (decode-time)) res)
  4897. (if (< r 1)
  4898. (current-time)
  4899. (setq res
  4900. (apply 'encode-time
  4901. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4902. (nthcdr 2 time))))
  4903. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4904. (seconds-to-time (- (float-time res) (* r 60)))
  4905. res))))
  4906. (defun org-today ()
  4907. "Return today date, considering `org-extend-today-until'."
  4908. (time-to-days
  4909. (time-subtract (current-time)
  4910. (list 0 (* 3600 org-extend-today-until) 0))))
  4911. ;;;; Font-Lock stuff, including the activators
  4912. (defvar org-mouse-map (make-sparse-keymap))
  4913. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4914. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4915. (when org-mouse-1-follows-link
  4916. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4917. (when org-tab-follows-link
  4918. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4919. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4920. (require 'font-lock)
  4921. (defconst org-non-link-chars "]\t\n\r<>")
  4922. (defvar org-link-types-re nil
  4923. "Matches a link that has a url-like prefix like \"http:\"")
  4924. (defvar org-link-re-with-space nil
  4925. "Matches a link with spaces, optional angular brackets around it.")
  4926. (defvar org-link-re-with-space2 nil
  4927. "Matches a link with spaces, optional angular brackets around it.")
  4928. (defvar org-link-re-with-space3 nil
  4929. "Matches a link with spaces, only for internal part in bracket links.")
  4930. (defvar org-angle-link-re nil
  4931. "Matches link with angular brackets, spaces are allowed.")
  4932. (defvar org-plain-link-re nil
  4933. "Matches plain link, without spaces.")
  4934. (defvar org-bracket-link-regexp nil
  4935. "Matches a link in double brackets.")
  4936. (defvar org-bracket-link-analytic-regexp nil
  4937. "Regular expression used to analyze links.
  4938. Here is what the match groups contain after a match:
  4939. 1: http:
  4940. 2: http
  4941. 3: path
  4942. 4: [desc]
  4943. 5: desc")
  4944. (defvar org-bracket-link-analytic-regexp++ nil
  4945. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4946. (defvar org-any-link-re nil
  4947. "Regular expression matching any link.")
  4948. (defconst org-match-sexp-depth 3
  4949. "Number of stacked braces for sub/superscript matching.")
  4950. (defun org-create-multibrace-regexp (left right n)
  4951. "Create a regular expression which will match a balanced sexp.
  4952. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4953. as single character strings.
  4954. The regexp returned will match the entire expression including the
  4955. delimiters. It will also define a single group which contains the
  4956. match except for the outermost delimiters. The maximum depth of
  4957. stacked delimiters is N. Escaping delimiters is not possible."
  4958. (let* ((nothing (concat "[^" left right "]*?"))
  4959. (or "\\|")
  4960. (re nothing)
  4961. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4962. (while (> n 1)
  4963. (setq n (1- n)
  4964. re (concat re or next)
  4965. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4966. (concat left "\\(" re "\\)" right)))
  4967. (defconst org-match-substring-regexp
  4968. (concat
  4969. "\\(\\S-\\)\\([_^]\\)\\("
  4970. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4971. "\\|"
  4972. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4973. "\\|"
  4974. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4975. "The regular expression matching a sub- or superscript.")
  4976. (defconst org-match-substring-with-braces-regexp
  4977. (concat
  4978. "\\(\\S-\\)\\([_^]\\)"
  4979. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4980. "The regular expression matching a sub- or superscript, forcing braces.")
  4981. (defun org-make-link-regexps ()
  4982. "Update the link regular expressions.
  4983. This should be called after the variable `org-link-parameters' has changed."
  4984. (let ((types-re (regexp-opt (org-link-types) t)))
  4985. (setq org-link-types-re
  4986. (concat "\\`" types-re ":")
  4987. org-link-re-with-space
  4988. (concat "<?" types-re ":"
  4989. "\\([^" org-non-link-chars " ]"
  4990. "[^" org-non-link-chars "]*"
  4991. "[^" org-non-link-chars " ]\\)>?")
  4992. org-link-re-with-space2
  4993. (concat "<?" types-re ":"
  4994. "\\([^" org-non-link-chars " ]"
  4995. "[^\t\n\r]*"
  4996. "[^" org-non-link-chars " ]\\)>?")
  4997. org-link-re-with-space3
  4998. (concat "<?" types-re ":"
  4999. "\\([^" org-non-link-chars " ]"
  5000. "[^\t\n\r]*\\)")
  5001. org-angle-link-re
  5002. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5003. types-re)
  5004. org-plain-link-re
  5005. (concat
  5006. "\\<" types-re ":"
  5007. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5008. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5009. org-bracket-link-regexp
  5010. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5011. org-bracket-link-analytic-regexp
  5012. (concat
  5013. "\\[\\["
  5014. "\\(" types-re ":\\)?"
  5015. "\\([^]]+\\)"
  5016. "\\]"
  5017. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5018. "\\]")
  5019. org-bracket-link-analytic-regexp++
  5020. (concat
  5021. "\\[\\["
  5022. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5023. "\\([^]]+\\)"
  5024. "\\]"
  5025. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5026. "\\]")
  5027. org-any-link-re
  5028. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5029. org-angle-link-re "\\)\\|\\("
  5030. org-plain-link-re "\\)"))))
  5031. (org-make-link-regexps)
  5032. (defvar org-emph-face nil)
  5033. (defun org-do-emphasis-faces (limit)
  5034. "Run through the buffer and emphasize strings."
  5035. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5036. (car org-emphasis-regexp-components))))
  5037. (catch :exit
  5038. (while (re-search-forward quick-re limit t)
  5039. (let* ((marker (match-string 2))
  5040. (verbatim? (member marker '("~" "="))))
  5041. (when (save-excursion
  5042. (goto-char (match-beginning 0))
  5043. ;; Do not match headline stars. Do not consider
  5044. ;; stars of a headline as closing marker for bold
  5045. ;; markup either. Do not match table hlines.
  5046. (and
  5047. (not (looking-at-p org-outline-regexp-bol))
  5048. (not (and (equal marker "+")
  5049. (org-match-line
  5050. "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5051. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5052. (not (string-match-p
  5053. (concat org-outline-regexp-bol "\\'")
  5054. (match-string 0)))))
  5055. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5056. (font-lock-prepend-text-property
  5057. (match-beginning 2) (match-end 2) 'face face)
  5058. (when verbatim?
  5059. (org-remove-flyspell-overlays-in
  5060. (match-beginning 0) (match-end 0)))
  5061. (add-text-properties (match-beginning 2) (match-end 2)
  5062. '(font-lock-multiline t org-emphasis t))
  5063. (when org-hide-emphasis-markers
  5064. (add-text-properties (match-end 4) (match-beginning 5)
  5065. '(invisible org-link))
  5066. (add-text-properties (match-beginning 3) (match-end 3)
  5067. '(invisible org-link)))
  5068. (throw :exit t))))))))
  5069. (defun org-emphasize (&optional char)
  5070. "Insert or change an emphasis, i.e. a font like bold or italic.
  5071. If there is an active region, change that region to a new emphasis.
  5072. If there is no region, just insert the marker characters and position
  5073. the cursor between them.
  5074. CHAR should be the marker character. If it is a space, it means to
  5075. remove the emphasis of the selected region.
  5076. If CHAR is not given (for example in an interactive call) it will be
  5077. prompted for."
  5078. (interactive)
  5079. (let ((erc org-emphasis-regexp-components)
  5080. (string "") beg end move s)
  5081. (if (org-region-active-p)
  5082. (setq beg (region-beginning)
  5083. end (region-end)
  5084. string (buffer-substring beg end))
  5085. (setq move t))
  5086. (unless char
  5087. (message "Emphasis marker or tag: [%s]"
  5088. (mapconcat #'car org-emphasis-alist ""))
  5089. (setq char (read-char-exclusive)))
  5090. (if (equal char ?\s)
  5091. (setq s ""
  5092. move nil)
  5093. (unless (assoc (char-to-string char) org-emphasis-alist)
  5094. (user-error "No such emphasis marker: \"%c\"" char))
  5095. (setq s (char-to-string char)))
  5096. (while (and (> (length string) 1)
  5097. (equal (substring string 0 1) (substring string -1))
  5098. (assoc (substring string 0 1) org-emphasis-alist))
  5099. (setq string (substring string 1 -1)))
  5100. (setq string (concat s string s))
  5101. (when beg (delete-region beg end))
  5102. (unless (or (bolp)
  5103. (string-match (concat "[" (nth 0 erc) "\n]")
  5104. (char-to-string (char-before (point)))))
  5105. (insert " "))
  5106. (unless (or (eobp)
  5107. (string-match (concat "[" (nth 1 erc) "\n]")
  5108. (char-to-string (char-after (point)))))
  5109. (insert " ") (backward-char 1))
  5110. (insert string)
  5111. (and move (backward-char 1))))
  5112. (defconst org-nonsticky-props
  5113. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5114. (defsubst org-rear-nonsticky-at (pos)
  5115. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5116. (defun org-activate-links (limit)
  5117. "Add link properties to links.
  5118. This includes angle, plain, and bracket links."
  5119. (catch :exit
  5120. (while (re-search-forward org-any-link-re limit t)
  5121. (let* ((start (match-beginning 0))
  5122. (end (match-end 0))
  5123. (style (cond ((eq ?< (char-after start)) 'angle)
  5124. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5125. (t 'plain))))
  5126. (when (and (memq style org-highlight-links)
  5127. ;; Do not confuse plain links with tags.
  5128. (not (and (eq style 'plain)
  5129. (let ((face (get-text-property
  5130. (max (1- start) (point-min)) 'face)))
  5131. (if (consp face) (memq 'org-tag face)
  5132. (eq 'org-tag face))))))
  5133. (let* ((link-object (save-excursion
  5134. (goto-char start)
  5135. (save-match-data (org-element-link-parser))))
  5136. (link (org-element-property :raw-link link-object))
  5137. (type (org-element-property :type link-object))
  5138. (path (org-element-property :path link-object))
  5139. (properties ;for link's visible part
  5140. (list
  5141. 'face (pcase (org-link-get-parameter type :face)
  5142. ((and (pred functionp) face) (funcall face path))
  5143. ((and (pred facep) face) face)
  5144. ((and (pred consp) face) face) ;anonymous
  5145. (_ 'org-link))
  5146. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5147. 'highlight)
  5148. 'keymap (or (org-link-get-parameter type :keymap)
  5149. org-mouse-map)
  5150. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5151. ((and (pred stringp) echo) echo)
  5152. ((and (pred functionp) echo) echo)
  5153. (_ (concat "LINK: " link)))
  5154. 'htmlize-link (pcase (org-link-get-parameter type
  5155. :htmlize-link)
  5156. ((and (pred functionp) f) (funcall f))
  5157. (_ `(:uri ,link)))
  5158. 'font-lock-multiline t)))
  5159. (org-remove-flyspell-overlays-in start end)
  5160. (org-rear-nonsticky-at end)
  5161. (if (not (eq 'bracket style))
  5162. (add-text-properties start end properties)
  5163. ;; Handle invisible parts in bracket links.
  5164. (remove-text-properties start end '(invisible nil))
  5165. (let ((hidden
  5166. (append `(invisible
  5167. ,(or (org-link-get-parameter type :display)
  5168. 'org-link))
  5169. properties))
  5170. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5171. (visible-end (or (match-end 4) (match-end 2))))
  5172. (add-text-properties start visible-start hidden)
  5173. (add-text-properties visible-start visible-end properties)
  5174. (add-text-properties visible-end end hidden)
  5175. (org-rear-nonsticky-at visible-start)
  5176. (org-rear-nonsticky-at visible-end)))
  5177. (let ((f (org-link-get-parameter type :activate-func)))
  5178. (when (functionp f)
  5179. (funcall f start end path (eq style 'bracket))))
  5180. (throw :exit t))))) ;signal success
  5181. nil))
  5182. (defun org-activate-code (limit)
  5183. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5184. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5185. (remove-text-properties (match-beginning 0) (match-end 0)
  5186. '(display t invisible t intangible t))
  5187. t))
  5188. (defcustom org-src-fontify-natively t
  5189. "When non-nil, fontify code in code blocks.
  5190. See also the `org-block' face."
  5191. :type 'boolean
  5192. :version "24.4"
  5193. :package-version '(Org . "8.3")
  5194. :group 'org-appearance
  5195. :group 'org-babel)
  5196. (defcustom org-allow-promoting-top-level-subtree nil
  5197. "When non-nil, allow promoting a top level subtree.
  5198. The leading star of the top level headline will be replaced
  5199. by a #."
  5200. :type 'boolean
  5201. :version "24.1"
  5202. :group 'org-appearance)
  5203. (defun org-fontify-meta-lines-and-blocks (limit)
  5204. (condition-case nil
  5205. (org-fontify-meta-lines-and-blocks-1 limit)
  5206. (error (message "org-mode fontification error in %S at %d"
  5207. (current-buffer)
  5208. (line-number-at-pos)))))
  5209. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5210. "Fontify #+ lines and blocks."
  5211. (let ((case-fold-search t))
  5212. (when (re-search-forward
  5213. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5214. limit t)
  5215. (let ((beg (match-beginning 0))
  5216. (block-start (match-end 0))
  5217. (block-end nil)
  5218. (lang (match-string 7))
  5219. (beg1 (line-beginning-position 2))
  5220. (dc1 (downcase (match-string 2)))
  5221. (dc3 (downcase (match-string 3)))
  5222. end end1 quoting block-type)
  5223. (cond
  5224. ((and (match-end 4) (equal dc3 "+begin"))
  5225. ;; Truly a block
  5226. (setq block-type (downcase (match-string 5))
  5227. quoting (member block-type org-protecting-blocks))
  5228. (when (re-search-forward
  5229. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5230. nil t) ;; on purpose, we look further than LIMIT
  5231. (setq end (min (point-max) (match-end 0))
  5232. end1 (min (point-max) (1- (match-beginning 0))))
  5233. (setq block-end (match-beginning 0))
  5234. (when quoting
  5235. (org-remove-flyspell-overlays-in beg1 end1)
  5236. (remove-text-properties beg end
  5237. '(display t invisible t intangible t)))
  5238. (add-text-properties
  5239. beg end '(font-lock-fontified t font-lock-multiline t))
  5240. (add-text-properties beg beg1 '(face org-meta-line))
  5241. (org-remove-flyspell-overlays-in beg beg1)
  5242. (add-text-properties ; For end_src
  5243. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5244. (org-remove-flyspell-overlays-in end1 end)
  5245. (cond
  5246. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5247. (org-src-font-lock-fontify-block lang block-start block-end)
  5248. (add-text-properties beg1 block-end '(src-block t)))
  5249. (quoting
  5250. (add-text-properties beg1 (min (point-max) (1+ end1))
  5251. (list 'face
  5252. (list :inherit
  5253. (let ((face-name
  5254. (intern (format "org-block-%s" lang))))
  5255. (append (and (facep face-name) (list face-name))
  5256. '(org-block))))))) ; end of source block
  5257. ((not org-fontify-quote-and-verse-blocks))
  5258. ((string= block-type "quote")
  5259. (add-face-text-property
  5260. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5261. ((string= block-type "verse")
  5262. (add-face-text-property
  5263. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5264. (add-text-properties beg beg1 '(face org-block-begin-line))
  5265. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5266. '(face org-block-end-line))
  5267. t))
  5268. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5269. (org-remove-flyspell-overlays-in
  5270. (match-beginning 0)
  5271. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5272. (add-text-properties
  5273. beg (match-end 3)
  5274. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5275. '(font-lock-fontified t invisible t)
  5276. '(font-lock-fontified t face org-document-info-keyword)))
  5277. (add-text-properties
  5278. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5279. (if (string-equal dc1 "+title:")
  5280. '(font-lock-fontified t face org-document-title)
  5281. '(font-lock-fontified t face org-document-info))))
  5282. ((string-prefix-p "+caption" dc1)
  5283. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5284. (remove-text-properties (match-beginning 0) (match-end 0)
  5285. '(display t invisible t intangible t))
  5286. ;; Handle short captions.
  5287. (save-excursion
  5288. (beginning-of-line)
  5289. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5290. (add-text-properties (line-beginning-position) (match-end 1)
  5291. '(font-lock-fontified t face org-meta-line))
  5292. (add-text-properties (match-end 0) (line-end-position)
  5293. '(font-lock-fontified t face org-block))
  5294. t)
  5295. ((member dc3 '(" " ""))
  5296. (org-remove-flyspell-overlays-in beg (match-end 0))
  5297. (add-text-properties
  5298. beg (match-end 0)
  5299. '(font-lock-fontified t face font-lock-comment-face)))
  5300. (t ;; just any other in-buffer setting, but not indented
  5301. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5302. (remove-text-properties (match-beginning 0) (match-end 0)
  5303. '(display t invisible t intangible t))
  5304. (add-text-properties beg (match-end 0)
  5305. '(font-lock-fontified t face org-meta-line))
  5306. t))))))
  5307. (defun org-fontify-drawers (limit)
  5308. "Fontify drawers."
  5309. (when (re-search-forward org-drawer-regexp limit t)
  5310. (add-text-properties
  5311. (match-beginning 0) (match-end 0)
  5312. '(font-lock-fontified t face org-special-keyword))
  5313. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5314. t))
  5315. (defun org-fontify-macros (limit)
  5316. "Fontify macros."
  5317. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5318. (add-text-properties
  5319. (match-beginning 0) (match-end 0)
  5320. '(font-lock-fontified t face org-macro))
  5321. (when org-hide-macro-markers
  5322. (add-text-properties (match-end 2) (match-beginning 2)
  5323. '(invisible t))
  5324. (add-text-properties (match-beginning 1) (match-end 1)
  5325. '(invisible t)))
  5326. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5327. t))
  5328. (defun org-activate-footnote-links (limit)
  5329. "Add text properties for footnotes."
  5330. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5331. (when fn
  5332. (let* ((beg (nth 1 fn))
  5333. (end (nth 2 fn))
  5334. (label (car fn))
  5335. (referencep (/= (line-beginning-position) beg)))
  5336. (when (and referencep (nth 3 fn))
  5337. (save-excursion
  5338. (goto-char beg)
  5339. (search-forward (or label "fn:"))
  5340. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5341. (add-text-properties beg end
  5342. (list 'mouse-face 'highlight
  5343. 'keymap org-mouse-map
  5344. 'help-echo
  5345. (if referencep "Footnote reference"
  5346. "Footnote definition")
  5347. 'font-lock-fontified t
  5348. 'font-lock-multiline t
  5349. 'face 'org-footnote))))))
  5350. (defun org-activate-dates (limit)
  5351. "Add text properties for dates."
  5352. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5353. (not (equal (char-before (match-beginning 0)) 91)))
  5354. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5355. (add-text-properties (match-beginning 0) (match-end 0)
  5356. (list 'mouse-face 'highlight
  5357. 'keymap org-mouse-map))
  5358. (org-rear-nonsticky-at (match-end 0))
  5359. (when org-display-custom-times
  5360. ;; If it's a date range, activate custom time for second date.
  5361. (when (match-end 3)
  5362. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5363. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5364. t))
  5365. (defvar-local org-target-link-regexp nil
  5366. "Regular expression matching radio targets in plain text.")
  5367. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5368. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5369. border border border))
  5370. "Regular expression matching a link target.")
  5371. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5372. "Regular expression matching a radio target.")
  5373. (defconst org-any-target-regexp
  5374. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5375. "Regular expression matching any target.")
  5376. (defun org-activate-target-links (limit)
  5377. "Add text properties for target matches."
  5378. (when org-target-link-regexp
  5379. (let ((case-fold-search t))
  5380. (when (re-search-forward org-target-link-regexp limit t)
  5381. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5382. (add-text-properties (match-beginning 1) (match-end 1)
  5383. (list 'mouse-face 'highlight
  5384. 'keymap org-mouse-map
  5385. 'help-echo "Radio target link"
  5386. 'org-linked-text t))
  5387. (org-rear-nonsticky-at (match-end 1))
  5388. t))))
  5389. (defun org-update-radio-target-regexp ()
  5390. "Find all radio targets in this file and update the regular expression.
  5391. Also refresh fontification if needed."
  5392. (interactive)
  5393. (let ((old-regexp org-target-link-regexp)
  5394. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5395. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5396. (targets
  5397. (org-with-wide-buffer
  5398. (goto-char (point-min))
  5399. (let (rtn)
  5400. (while (re-search-forward org-radio-target-regexp nil t)
  5401. ;; Make sure point is really within the object.
  5402. (backward-char)
  5403. (let ((obj (org-element-context)))
  5404. (when (eq (org-element-type obj) 'radio-target)
  5405. (cl-pushnew (org-element-property :value obj) rtn
  5406. :test #'equal))))
  5407. rtn))))
  5408. (setq org-target-link-regexp
  5409. (and targets
  5410. (concat before-re
  5411. (mapconcat
  5412. (lambda (x)
  5413. (replace-regexp-in-string
  5414. " +" "\\s-+" (regexp-quote x) t t))
  5415. targets
  5416. "\\|")
  5417. after-re)))
  5418. (unless (equal old-regexp org-target-link-regexp)
  5419. ;; Clean-up cache.
  5420. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5421. ((not org-target-link-regexp) old-regexp)
  5422. (t
  5423. (concat before-re
  5424. (mapconcat
  5425. (lambda (re)
  5426. (substring re (length before-re)
  5427. (- (length after-re))))
  5428. (list old-regexp org-target-link-regexp)
  5429. "\\|")
  5430. after-re)))))
  5431. (org-with-wide-buffer
  5432. (goto-char (point-min))
  5433. (while (re-search-forward regexp nil t)
  5434. (org-element-cache-refresh (match-beginning 1)))))
  5435. ;; Re fontify buffer.
  5436. (when (memq 'radio org-highlight-links)
  5437. (org-restart-font-lock)))))
  5438. (defun org-hide-wide-columns (limit)
  5439. (let (s e)
  5440. (setq s (text-property-any (point) (or limit (point-max))
  5441. 'org-cwidth t))
  5442. (when s
  5443. (setq e (next-single-property-change s 'org-cwidth))
  5444. (add-text-properties s e '(invisible org-cwidth))
  5445. (goto-char e)
  5446. t)))
  5447. (defvar org-latex-and-related-regexp nil
  5448. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5449. (defun org-compute-latex-and-related-regexp ()
  5450. "Compute regular expression for LaTeX, entities and sub/superscript.
  5451. Result depends on variable `org-highlight-latex-and-related'."
  5452. (setq-local
  5453. org-latex-and-related-regexp
  5454. (let* ((re-sub
  5455. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5456. ((eq org-use-sub-superscripts '{})
  5457. (list org-match-substring-with-braces-regexp))
  5458. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5459. (re-latex
  5460. (when (memq 'latex org-highlight-latex-and-related)
  5461. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5462. (delq nil
  5463. (mapcar (lambda (x)
  5464. (and (member (car x) matchers) (nth 1 x)))
  5465. org-latex-regexps)))))
  5466. (re-entities
  5467. (when (memq 'entities org-highlight-latex-and-related)
  5468. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5469. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5470. (defun org-do-latex-and-related (limit)
  5471. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5472. LIMIT bounds the search for syntax to highlight. Stop at first
  5473. highlighted object, if any. Return t if some highlighting was
  5474. done, nil otherwise."
  5475. (when (org-string-nw-p org-latex-and-related-regexp)
  5476. (catch 'found
  5477. (while (re-search-forward org-latex-and-related-regexp limit t)
  5478. (unless
  5479. (cl-some
  5480. (lambda (f)
  5481. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5482. (save-excursion
  5483. (goto-char (1+ (match-beginning 0)))
  5484. (face-at-point nil t)))
  5485. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5486. '(?_ ?^))
  5487. 1
  5488. 0)))
  5489. (font-lock-prepend-text-property
  5490. (+ offset (match-beginning 0)) (match-end 0)
  5491. 'face 'org-latex-and-related)
  5492. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5493. '(font-lock-multiline t)))
  5494. (throw 'found t)))
  5495. nil)))
  5496. (defun org-restart-font-lock ()
  5497. "Restart `font-lock-mode', to force refontification."
  5498. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5499. (font-lock-mode -1)
  5500. (font-lock-mode 1)))
  5501. (defun org-activate-tags (limit)
  5502. (when (re-search-forward
  5503. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5504. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5505. (add-text-properties (match-beginning 1) (match-end 1)
  5506. (list 'mouse-face 'highlight
  5507. 'keymap org-mouse-map))
  5508. (org-rear-nonsticky-at (match-end 1))
  5509. t))
  5510. (defun org-outline-level ()
  5511. "Compute the outline level of the heading at point.
  5512. If this is called at a normal headline, the level is the number
  5513. of stars. Use `org-reduced-level' to remove the effect of
  5514. `org-odd-levels'. Unlike to `org-current-level', this function
  5515. takes into consideration inlinetasks."
  5516. (org-with-wide-buffer
  5517. (end-of-line)
  5518. (if (re-search-backward org-outline-regexp-bol nil t)
  5519. (1- (- (match-end 0) (match-beginning 0)))
  5520. 0)))
  5521. (defvar org-font-lock-keywords nil)
  5522. (defsubst org-re-property (property &optional literal allow-null value)
  5523. "Return a regexp matching a PROPERTY line.
  5524. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5525. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5526. non-nil, match properties even without a value.
  5527. Match group 3 is set to the value when it exists. If there is no
  5528. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5529. With optional argument VALUE, match only property lines with
  5530. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5531. unless LITERAL is non-nil."
  5532. (concat
  5533. "^\\(?4:[ \t]*\\)"
  5534. (format "\\(?1::\\(?2:%s\\):\\)"
  5535. (if literal property (regexp-quote property)))
  5536. (cond (value
  5537. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5538. (if literal value (regexp-quote value))))
  5539. (allow-null
  5540. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5541. (t
  5542. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5543. (defconst org-property-re
  5544. (org-re-property "\\S-+" 'literal t)
  5545. "Regular expression matching a property line.
  5546. There are four matching groups:
  5547. 1: :PROPKEY: including the leading and trailing colon,
  5548. 2: PROPKEY without the leading and trailing colon,
  5549. 3: PROPVAL without leading or trailing spaces,
  5550. 4: the indentation of the current line,
  5551. 5: trailing whitespace.")
  5552. (defvar org-font-lock-hook nil
  5553. "Functions to be called for special font lock stuff.")
  5554. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5555. (defvar org-font-lock-set-keywords-hook nil
  5556. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5557. This is called after `org-font-lock-extra-keywords' is defined, but before
  5558. it is installed to be used by font lock. This can be useful if something
  5559. needs to be inserted at a specific position in the font-lock sequence.")
  5560. (defun org-font-lock-hook (limit)
  5561. "Run `org-font-lock-hook' within LIMIT."
  5562. (run-hook-with-args 'org-font-lock-hook limit))
  5563. (defun org-set-font-lock-defaults ()
  5564. "Set font lock defaults for the current buffer."
  5565. (let* ((em org-fontify-emphasized-text)
  5566. (lk org-highlight-links)
  5567. (org-font-lock-extra-keywords
  5568. (list
  5569. ;; Call the hook
  5570. '(org-font-lock-hook)
  5571. ;; Headlines
  5572. `(,(if org-fontify-whole-heading-line
  5573. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5574. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5575. (1 (org-get-level-face 1))
  5576. (2 (org-get-level-face 2))
  5577. (3 (org-get-level-face 3)))
  5578. ;; Table lines
  5579. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5580. (1 'org-table t))
  5581. ;; Table internals
  5582. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5583. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5584. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5585. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5586. ;; Drawers
  5587. '(org-fontify-drawers)
  5588. ;; Properties
  5589. (list org-property-re
  5590. '(1 'org-special-keyword t)
  5591. '(3 'org-property-value t))
  5592. ;; Link related fontification.
  5593. '(org-activate-links)
  5594. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5595. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5596. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5597. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5598. ;; Targets.
  5599. (list org-any-target-regexp '(0 'org-target t))
  5600. ;; Diary sexps.
  5601. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5602. ;; Macro
  5603. '(org-fontify-macros)
  5604. '(org-hide-wide-columns (0 nil append))
  5605. ;; TODO keyword
  5606. (list (format org-heading-keyword-regexp-format
  5607. org-todo-regexp)
  5608. '(2 (org-get-todo-face 2) t))
  5609. ;; DONE
  5610. (if org-fontify-done-headline
  5611. (list (format org-heading-keyword-regexp-format
  5612. (concat
  5613. "\\(?:"
  5614. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5615. "\\)"))
  5616. '(2 'org-headline-done t))
  5617. nil)
  5618. ;; Priorities
  5619. '(org-font-lock-add-priority-faces)
  5620. ;; Tags
  5621. '(org-font-lock-add-tag-faces)
  5622. ;; Tags groups
  5623. (when (and org-group-tags org-tag-groups-alist)
  5624. (list (concat org-outline-regexp-bol ".+\\(:"
  5625. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5626. ":\\).*$")
  5627. '(1 'org-tag-group prepend)))
  5628. ;; Special keywords
  5629. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5630. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5631. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5632. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5633. ;; Emphasis
  5634. (when em '(org-do-emphasis-faces))
  5635. ;; Checkboxes
  5636. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5637. 1 'org-checkbox prepend)
  5638. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5639. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5640. (0 (org-get-checkbox-statistics-face) t)))
  5641. ;; Description list items
  5642. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5643. 1 'org-list-dt prepend)
  5644. ;; ARCHIVEd headings
  5645. (list (concat
  5646. org-outline-regexp-bol
  5647. "\\(.*:" org-archive-tag ":.*\\)")
  5648. '(1 'org-archived prepend))
  5649. ;; Specials
  5650. '(org-do-latex-and-related)
  5651. '(org-fontify-entities)
  5652. '(org-raise-scripts)
  5653. ;; Code
  5654. '(org-activate-code (1 'org-code t))
  5655. ;; COMMENT
  5656. (list (format
  5657. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5658. org-todo-regexp
  5659. org-comment-string)
  5660. '(9 'org-special-keyword t))
  5661. ;; Blocks and meta lines
  5662. '(org-fontify-meta-lines-and-blocks))))
  5663. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5664. (run-hooks 'org-font-lock-set-keywords-hook)
  5665. ;; Now set the full font-lock-keywords
  5666. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5667. (setq-local font-lock-defaults
  5668. '(org-font-lock-keywords t nil nil backward-paragraph))
  5669. (kill-local-variable 'font-lock-keywords)
  5670. nil))
  5671. (defun org-toggle-pretty-entities ()
  5672. "Toggle the composition display of entities as UTF8 characters."
  5673. (interactive)
  5674. (setq-local org-pretty-entities (not org-pretty-entities))
  5675. (org-restart-font-lock)
  5676. (if org-pretty-entities
  5677. (message "Entities are now displayed as UTF8 characters")
  5678. (save-restriction
  5679. (widen)
  5680. (decompose-region (point-min) (point-max))
  5681. (message "Entities are now displayed as plain text"))))
  5682. (defvar-local org-custom-properties-overlays nil
  5683. "List of overlays used for custom properties.")
  5684. (defun org-toggle-custom-properties-visibility ()
  5685. "Display or hide properties in `org-custom-properties'."
  5686. (interactive)
  5687. (if org-custom-properties-overlays
  5688. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5689. (setq org-custom-properties-overlays nil))
  5690. (when org-custom-properties
  5691. (org-with-wide-buffer
  5692. (goto-char (point-min))
  5693. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5694. (while (re-search-forward regexp nil t)
  5695. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5696. (when (and end (< (point) end))
  5697. ;; Hide first custom property in current drawer.
  5698. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5699. (overlay-put o 'invisible t)
  5700. (overlay-put o 'org-custom-property t)
  5701. (push o org-custom-properties-overlays))
  5702. ;; Hide additional custom properties in the same drawer.
  5703. (while (re-search-forward regexp end t)
  5704. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5705. (overlay-put o 'invisible t)
  5706. (overlay-put o 'org-custom-property t)
  5707. (push o org-custom-properties-overlays)))))
  5708. ;; Each entry is limited to a single property drawer.
  5709. (outline-next-heading)))))))
  5710. (defun org-fontify-entities (limit)
  5711. "Find an entity to fontify."
  5712. (let (ee)
  5713. (when org-pretty-entities
  5714. (catch 'match
  5715. ;; "\_ "-family is left out on purpose. Only the first one,
  5716. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5717. ;; confusing when adding a second white space character.
  5718. (while (re-search-forward
  5719. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5720. limit t)
  5721. (when (and (not (org-at-comment-p))
  5722. (setq ee (org-entity-get (match-string 1)))
  5723. (= (length (nth 6 ee)) 1))
  5724. (let* ((end (if (equal (match-string 2) "{}")
  5725. (match-end 2)
  5726. (match-end 1))))
  5727. (add-text-properties
  5728. (match-beginning 0) end
  5729. (list 'font-lock-fontified t))
  5730. (compose-region (match-beginning 0) end
  5731. (nth 6 ee) nil)
  5732. (backward-char 1)
  5733. (throw 'match t))))
  5734. nil))))
  5735. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5736. "Fontify string S like in Org mode."
  5737. (with-temp-buffer
  5738. (insert s)
  5739. (let ((org-odd-levels-only odd-levels))
  5740. (org-mode)
  5741. (org-font-lock-ensure)
  5742. (buffer-string))))
  5743. (defvar org-m nil)
  5744. (defvar org-l nil)
  5745. (defvar org-f nil)
  5746. (defun org-get-level-face (n)
  5747. "Get the right face for match N in font-lock matching of headlines."
  5748. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5749. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5750. (if org-cycle-level-faces
  5751. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5752. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5753. (cond
  5754. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5755. ((eq n 2) org-f)
  5756. (t (unless org-level-color-stars-only org-f))))
  5757. (defun org-face-from-face-or-color (context inherit face-or-color)
  5758. "Create a face list that inherits INHERIT, but sets the foreground color.
  5759. When FACE-OR-COLOR is not a string, just return it."
  5760. (if (stringp face-or-color)
  5761. (list :inherit inherit
  5762. (cdr (assoc context org-faces-easy-properties))
  5763. face-or-color)
  5764. face-or-color))
  5765. (defun org-get-todo-face (kwd)
  5766. "Get the right face for a TODO keyword KWD.
  5767. If KWD is a number, get the corresponding match group."
  5768. (when (numberp kwd) (setq kwd (match-string kwd)))
  5769. (or (org-face-from-face-or-color
  5770. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5771. (and (member kwd org-done-keywords) 'org-done)
  5772. 'org-todo))
  5773. (defun org-get-priority-face (priority)
  5774. "Get the right face for PRIORITY.
  5775. PRIORITY is a character."
  5776. (or (org-face-from-face-or-color
  5777. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5778. 'org-priority))
  5779. (defun org-get-tag-face (tag)
  5780. "Get the right face for TAG.
  5781. If TAG is a number, get the corresponding match group."
  5782. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5783. (or (org-face-from-face-or-color
  5784. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5785. 'org-tag)))
  5786. (defun org-font-lock-add-priority-faces (limit)
  5787. "Add the special priority faces."
  5788. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5789. (add-text-properties
  5790. (match-beginning 1) (match-end 1)
  5791. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5792. 'font-lock-fontified t))))
  5793. (defun org-font-lock-add-tag-faces (limit)
  5794. "Add the special tag faces."
  5795. (when (and org-tag-faces org-tags-special-faces-re)
  5796. (while (re-search-forward org-tags-special-faces-re limit t)
  5797. (add-text-properties (match-beginning 1) (match-end 1)
  5798. (list 'face (org-get-tag-face 1)
  5799. 'font-lock-fontified t))
  5800. (backward-char 1))))
  5801. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5802. "Remove fontification and activation overlays from links."
  5803. (font-lock-default-unfontify-region beg end)
  5804. (let* ((buffer-undo-list t)
  5805. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5806. (inhibit-modification-hooks t)
  5807. deactivate-mark buffer-file-name buffer-file-truename)
  5808. (decompose-region beg end)
  5809. (remove-text-properties beg end
  5810. '(mouse-face t keymap t org-linked-text t
  5811. invisible t intangible t
  5812. org-emphasis t))
  5813. (org-remove-font-lock-display-properties beg end)))
  5814. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5815. ((raise 0.3) (height 0.7))
  5816. ((raise -0.5))
  5817. ((raise 0.5)))
  5818. "Display properties for showing superscripts and subscripts.")
  5819. (defun org-remove-font-lock-display-properties (beg end)
  5820. "Remove specific display properties that have been added by font lock.
  5821. The will remove the raise properties that are used to show superscripts
  5822. and subscripts."
  5823. (let (next prop)
  5824. (while (< beg end)
  5825. (setq next (next-single-property-change beg 'display nil end)
  5826. prop (get-text-property beg 'display))
  5827. (when (member prop org-script-display)
  5828. (put-text-property beg next 'display nil))
  5829. (setq beg next))))
  5830. (defun org-raise-scripts (limit)
  5831. "Add raise properties to sub/superscripts."
  5832. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5833. (re-search-forward
  5834. (if (eq org-use-sub-superscripts t)
  5835. org-match-substring-regexp
  5836. org-match-substring-with-braces-regexp)
  5837. limit t))
  5838. (let* ((pos (point)) table-p comment-p
  5839. (mpos (match-beginning 3))
  5840. (emph-p (get-text-property mpos 'org-emphasis))
  5841. (link-p (get-text-property mpos 'mouse-face))
  5842. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5843. (goto-char (point-at-bol))
  5844. (setq table-p (looking-at-p org-table-dataline-regexp)
  5845. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5846. (goto-char pos)
  5847. ;; Handle a_b^c
  5848. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5849. (unless (or comment-p emph-p link-p keyw-p)
  5850. (put-text-property (match-beginning 3) (match-end 0)
  5851. 'display
  5852. (if (equal (char-after (match-beginning 2)) ?^)
  5853. (nth (if table-p 3 1) org-script-display)
  5854. (nth (if table-p 2 0) org-script-display)))
  5855. (add-text-properties (match-beginning 2) (match-end 2)
  5856. (list 'invisible t))
  5857. (when (and (eq (char-after (match-beginning 3)) ?{)
  5858. (eq (char-before (match-end 3)) ?}))
  5859. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5860. (list 'invisible t))
  5861. (add-text-properties (1- (match-end 3)) (match-end 3)
  5862. (list 'invisible t))))
  5863. t)))
  5864. ;;;; Visibility cycling, including org-goto and indirect buffer
  5865. ;;; Cycling
  5866. (defvar-local org-cycle-global-status nil)
  5867. (put 'org-cycle-global-status 'org-state t)
  5868. (defvar-local org-cycle-subtree-status nil)
  5869. (put 'org-cycle-subtree-status 'org-state t)
  5870. (defvar org-inlinetask-min-level)
  5871. (defun org-unlogged-message (&rest args)
  5872. "Display a message, but avoid logging it in the *Messages* buffer."
  5873. (let ((message-log-max nil))
  5874. (apply 'message args)))
  5875. ;;;###autoload
  5876. (defun org-cycle (&optional arg)
  5877. "TAB-action and visibility cycling for Org mode.
  5878. This is the command invoked in Org mode by the `TAB' key. Its main
  5879. purpose is outline visibility cycling, but it also invokes other actions
  5880. in special contexts.
  5881. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5882. the entire
  5883. buffer through 3 states (global cycling)
  5884. 1. OVERVIEW: Show only top-level headlines.
  5885. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5886. 3. SHOW ALL: Show everything.
  5887. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5888. switch to the startup visibility,
  5889. determined by the variable `org-startup-folded', and by any VISIBILITY
  5890. properties in the buffer.
  5891. With a `\\[universal-argument] \\[universal-argument] \
  5892. \\[universal-argument]' prefix argument, show the entire buffer, including
  5893. any drawers.
  5894. When inside a table, re-align the table and move to the next field.
  5895. When point is at the beginning of a headline, rotate the subtree started
  5896. by this line through 3 different states (local cycling)
  5897. 1. FOLDED: Only the main headline is shown.
  5898. 2. CHILDREN: The main headline and the direct children are shown.
  5899. From this state, you can move to one of the children
  5900. and zoom in further.
  5901. 3. SUBTREE: Show the entire subtree, including body text.
  5902. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5903. When point is at the beginning of an empty headline and the variable
  5904. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5905. of the headline by demoting and promoting it to likely levels. This
  5906. speeds up creation document structure by pressing `TAB' once or several
  5907. times right after creating a new headline.
  5908. When there is a numeric prefix, go up to a heading with level ARG, do
  5909. a `show-subtree' and return to the previous cursor position. If ARG
  5910. is negative, go up that many levels.
  5911. When point is not at the beginning of a headline, execute the global
  5912. binding for `TAB', which is re-indenting the line. See the option
  5913. `org-cycle-emulate-tab' for details.
  5914. As a special case, if point is at the beginning of the buffer and there is
  5915. no headline in line 1, this function will act as if called with prefix arg
  5916. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5917. prefix arg, but only
  5918. if the variable `org-cycle-global-at-bob' is t."
  5919. (interactive "P")
  5920. (org-load-modules-maybe)
  5921. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5922. (and org-cycle-level-after-item/entry-creation
  5923. (or (org-cycle-level)
  5924. (org-cycle-item-indentation))))
  5925. (let* ((limit-level
  5926. (or org-cycle-max-level
  5927. (and (boundp 'org-inlinetask-min-level)
  5928. org-inlinetask-min-level
  5929. (1- org-inlinetask-min-level))))
  5930. (nstars (and limit-level
  5931. (if org-odd-levels-only
  5932. (and limit-level (1- (* limit-level 2)))
  5933. limit-level)))
  5934. (org-outline-regexp
  5935. (if (not (derived-mode-p 'org-mode))
  5936. outline-regexp
  5937. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5938. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5939. (not (looking-at org-outline-regexp))))
  5940. (org-cycle-hook
  5941. (if bob-special
  5942. (delq 'org-optimize-window-after-visibility-change
  5943. (copy-sequence org-cycle-hook))
  5944. org-cycle-hook))
  5945. (pos (point)))
  5946. (cond
  5947. ((equal arg '(16))
  5948. (setq last-command 'dummy)
  5949. (org-set-startup-visibility)
  5950. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5951. ((equal arg '(64))
  5952. (outline-show-all)
  5953. (org-unlogged-message "Entire buffer visible, including drawers"))
  5954. ((equal arg '(4)) (org-cycle-internal-global))
  5955. ;; Try hiding block at point.
  5956. ((org-hide-block-toggle-maybe))
  5957. ;; Try cdlatex TAB completion
  5958. ((org-try-cdlatex-tab))
  5959. ;; Table: enter it or move to the next field.
  5960. ((org-at-table-p 'any)
  5961. (if (org-at-table.el-p)
  5962. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5963. Use `\\[org-edit-special]' to edit table.el tables"))
  5964. (if arg (org-table-edit-field t)
  5965. (org-table-justify-field-maybe)
  5966. (call-interactively 'org-table-next-field))))
  5967. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5968. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5969. (bob-special (org-cycle-internal-global))
  5970. ;; Drawers: delegate to `org-flag-drawer'.
  5971. ((save-excursion
  5972. (beginning-of-line 1)
  5973. (looking-at org-drawer-regexp))
  5974. (org-flag-drawer ; toggle block visibility
  5975. (not (get-char-property (match-end 0) 'invisible))))
  5976. ;; Show-subtree, ARG levels up from here.
  5977. ((integerp arg)
  5978. (save-excursion
  5979. (org-back-to-heading)
  5980. (outline-up-heading (if (< arg 0) (- arg)
  5981. (- (funcall outline-level) arg)))
  5982. (org-show-subtree)))
  5983. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5984. ((and (featurep 'org-inlinetask)
  5985. (org-inlinetask-at-task-p)
  5986. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5987. (org-inlinetask-toggle-visibility))
  5988. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5989. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5990. (save-excursion (move-beginning-of-line 1)
  5991. (looking-at org-outline-regexp)))
  5992. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5993. (org-cycle-internal-local))
  5994. ;; From there: TAB emulation and template completion.
  5995. (buffer-read-only (org-back-to-heading))
  5996. ((run-hook-with-args-until-success
  5997. 'org-tab-after-check-for-cycling-hook))
  5998. ((org-try-structure-completion))
  5999. ((run-hook-with-args-until-success
  6000. 'org-tab-before-tab-emulation-hook))
  6001. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6002. (or (not (bolp))
  6003. (not (looking-at org-outline-regexp))))
  6004. (call-interactively (global-key-binding "\t")))
  6005. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6006. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6007. (or (and (eq org-cycle-emulate-tab 'white)
  6008. (= (match-end 0) (point-at-eol)))
  6009. (and (eq org-cycle-emulate-tab 'whitestart)
  6010. (>= (match-end 0) pos))))
  6011. t
  6012. (eq org-cycle-emulate-tab t))
  6013. (call-interactively (global-key-binding "\t")))
  6014. (t (save-excursion
  6015. (org-back-to-heading)
  6016. (org-cycle)))))))
  6017. (defun org-cycle-internal-global ()
  6018. "Do the global cycling action."
  6019. ;; Hack to avoid display of messages for .org attachments in Gnus
  6020. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6021. (cond
  6022. ((and (eq last-command this-command)
  6023. (eq org-cycle-global-status 'overview))
  6024. ;; We just created the overview - now do table of contents
  6025. ;; This can be slow in very large buffers, so indicate action
  6026. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6027. (unless ga (org-unlogged-message "CONTENTS..."))
  6028. (org-content)
  6029. (unless ga (org-unlogged-message "CONTENTS...done"))
  6030. (setq org-cycle-global-status 'contents)
  6031. (run-hook-with-args 'org-cycle-hook 'contents))
  6032. ((and (eq last-command this-command)
  6033. (eq org-cycle-global-status 'contents))
  6034. ;; We just showed the table of contents - now show everything
  6035. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6036. (outline-show-all)
  6037. (unless ga (org-unlogged-message "SHOW ALL"))
  6038. (setq org-cycle-global-status 'all)
  6039. (run-hook-with-args 'org-cycle-hook 'all))
  6040. (t
  6041. ;; Default action: go to overview
  6042. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6043. (org-overview)
  6044. (unless ga (org-unlogged-message "OVERVIEW"))
  6045. (setq org-cycle-global-status 'overview)
  6046. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6047. (defvar org-called-with-limited-levels nil
  6048. "Non-nil when `org-with-limited-levels' is currently active.")
  6049. (defun org-invisible-p (&optional pos)
  6050. "Non-nil if the character after POS is invisible.
  6051. If POS is nil, use `point' instead."
  6052. (get-char-property (or pos (point)) 'invisible))
  6053. (defun org-cycle-internal-local ()
  6054. "Do the local cycling action."
  6055. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6056. ;; First, determine end of headline (EOH), end of subtree or item
  6057. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6058. (save-excursion
  6059. (if (org-at-item-p)
  6060. (progn
  6061. (beginning-of-line)
  6062. (setq struct (org-list-struct))
  6063. (setq eoh (point-at-eol))
  6064. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6065. (setq has-children (org-list-has-child-p (point) struct)))
  6066. (org-back-to-heading)
  6067. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6068. (setq eos (save-excursion (org-end-of-subtree t t)
  6069. (when (bolp) (backward-char)) (point)))
  6070. (setq has-children
  6071. (or (save-excursion
  6072. (let ((level (funcall outline-level)))
  6073. (outline-next-heading)
  6074. (and (org-at-heading-p t)
  6075. (> (funcall outline-level) level))))
  6076. (save-excursion
  6077. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6078. ;; Determine end invisible part of buffer (EOL)
  6079. (beginning-of-line 2)
  6080. (while (and (not (eobp)) ;This is like `next-line'.
  6081. (get-char-property (1- (point)) 'invisible))
  6082. (goto-char (next-single-char-property-change (point) 'invisible))
  6083. (and (eolp) (beginning-of-line 2)))
  6084. (setq eol (point)))
  6085. ;; Find out what to do next and set `this-command'
  6086. (cond
  6087. ((= eos eoh)
  6088. ;; Nothing is hidden behind this heading
  6089. (unless (org-before-first-heading-p)
  6090. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6091. (org-unlogged-message "EMPTY ENTRY")
  6092. (setq org-cycle-subtree-status nil)
  6093. (save-excursion
  6094. (goto-char eos)
  6095. (outline-next-heading)
  6096. (when (org-invisible-p) (org-flag-heading nil))))
  6097. ((and (or (>= eol eos)
  6098. (not (string-match "\\S-" (buffer-substring eol eos))))
  6099. (or has-children
  6100. (not (setq children-skipped
  6101. org-cycle-skip-children-state-if-no-children))))
  6102. ;; Entire subtree is hidden in one line: children view
  6103. (unless (org-before-first-heading-p)
  6104. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6105. (if (org-at-item-p)
  6106. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6107. (org-show-entry)
  6108. (org-with-limited-levels (org-show-children))
  6109. ;; FIXME: This slows down the func way too much.
  6110. ;; How keep drawers hidden in subtree anyway?
  6111. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6112. ;; (org-cycle-hide-drawers 'subtree))
  6113. ;; Fold every list in subtree to top-level items.
  6114. (when (eq org-cycle-include-plain-lists 'integrate)
  6115. (save-excursion
  6116. (org-back-to-heading)
  6117. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6118. (beginning-of-line 1)
  6119. (let* ((struct (org-list-struct))
  6120. (prevs (org-list-prevs-alist struct))
  6121. (end (org-list-get-bottom-point struct)))
  6122. (dolist (e (org-list-get-all-items (point) struct prevs))
  6123. (org-list-set-item-visibility e struct 'folded))
  6124. (goto-char (if (< end eos) end eos)))))))
  6125. (org-unlogged-message "CHILDREN")
  6126. (save-excursion
  6127. (goto-char eos)
  6128. (outline-next-heading)
  6129. (when (org-invisible-p) (org-flag-heading nil)))
  6130. (setq org-cycle-subtree-status 'children)
  6131. (unless (org-before-first-heading-p)
  6132. (run-hook-with-args 'org-cycle-hook 'children)))
  6133. ((or children-skipped
  6134. (and (eq last-command this-command)
  6135. (eq org-cycle-subtree-status 'children)))
  6136. ;; We just showed the children, or no children are there,
  6137. ;; now show everything.
  6138. (unless (org-before-first-heading-p)
  6139. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6140. (outline-flag-region eoh eos nil)
  6141. (org-unlogged-message
  6142. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6143. (setq org-cycle-subtree-status 'subtree)
  6144. (unless (org-before-first-heading-p)
  6145. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6146. (t
  6147. ;; Default action: hide the subtree.
  6148. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6149. (outline-flag-region eoh eos t)
  6150. (org-unlogged-message "FOLDED")
  6151. (setq org-cycle-subtree-status 'folded)
  6152. (unless (org-before-first-heading-p)
  6153. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6154. ;;;###autoload
  6155. (defun org-global-cycle (&optional arg)
  6156. "Cycle the global visibility. For details see `org-cycle'.
  6157. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6158. With a numeric prefix, show all headlines up to that level."
  6159. (interactive "P")
  6160. (let ((org-cycle-include-plain-lists
  6161. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6162. (cond
  6163. ((integerp arg)
  6164. (outline-show-all)
  6165. (outline-hide-sublevels arg)
  6166. (setq org-cycle-global-status 'contents))
  6167. ((equal arg '(4))
  6168. (org-set-startup-visibility)
  6169. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6170. (t
  6171. (org-cycle '(4))))))
  6172. (defun org-set-startup-visibility ()
  6173. "Set the visibility required by startup options and properties."
  6174. (cond
  6175. ((eq org-startup-folded t)
  6176. (org-overview))
  6177. ((eq org-startup-folded 'content)
  6178. (org-content))
  6179. ((or (eq org-startup-folded 'showeverything)
  6180. (eq org-startup-folded nil))
  6181. (outline-show-all)))
  6182. (unless (eq org-startup-folded 'showeverything)
  6183. (when org-hide-block-startup (org-hide-block-all))
  6184. (org-set-visibility-according-to-property 'no-cleanup)
  6185. (org-cycle-hide-archived-subtrees 'all)
  6186. (org-cycle-hide-drawers 'all)
  6187. (org-cycle-show-empty-lines t)))
  6188. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6189. "Switch subtree visibilities according to :VISIBILITY: property."
  6190. (interactive)
  6191. (org-with-wide-buffer
  6192. (goto-char (point-min))
  6193. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6194. (if (not (org-at-property-p)) (outline-next-heading)
  6195. (let ((state (match-string 3)))
  6196. (save-excursion
  6197. (org-back-to-heading t)
  6198. (outline-hide-subtree)
  6199. (org-reveal)
  6200. (cond
  6201. ((equal state "folded")
  6202. (outline-hide-subtree))
  6203. ((equal state "children")
  6204. (org-show-hidden-entry)
  6205. (org-show-children))
  6206. ((equal state "content")
  6207. (save-excursion
  6208. (save-restriction
  6209. (org-narrow-to-subtree)
  6210. (org-content))))
  6211. ((member state '("all" "showall"))
  6212. (outline-show-subtree)))))))
  6213. (unless no-cleanup
  6214. (org-cycle-hide-archived-subtrees 'all)
  6215. (org-cycle-hide-drawers 'all)
  6216. (org-cycle-show-empty-lines 'all))))
  6217. ;; This function uses outline-regexp instead of the more fundamental
  6218. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6219. ;; buffers, where outline-regexp is needed.
  6220. (defun org-overview ()
  6221. "Switch to overview mode, showing only top-level headlines.
  6222. This shows all headlines with a level equal or greater than the level
  6223. of the first headline in the buffer. This is important, because if the
  6224. first headline is not level one, then (hide-sublevels 1) gives confusing
  6225. results."
  6226. (interactive)
  6227. (save-excursion
  6228. (let ((level
  6229. (save-excursion
  6230. (goto-char (point-min))
  6231. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6232. (goto-char (match-beginning 0))
  6233. (funcall outline-level)))))
  6234. (and level (outline-hide-sublevels level)))))
  6235. (defun org-content (&optional arg)
  6236. "Show all headlines in the buffer, like a table of contents.
  6237. With numerical argument N, show content up to level N."
  6238. (interactive "P")
  6239. (org-overview)
  6240. (save-excursion
  6241. ;; Visit all headings and show their offspring
  6242. (and (integerp arg) (org-overview))
  6243. (goto-char (point-max))
  6244. (catch 'exit
  6245. (while (and (progn (condition-case nil
  6246. (outline-previous-visible-heading 1)
  6247. (error (goto-char (point-min))))
  6248. t)
  6249. (looking-at org-outline-regexp))
  6250. (if (integerp arg)
  6251. (org-show-children (1- arg))
  6252. (outline-show-branches))
  6253. (when (bobp) (throw 'exit nil))))))
  6254. (defun org-optimize-window-after-visibility-change (state)
  6255. "Adjust the window after a change in outline visibility.
  6256. This function is the default value of the hook `org-cycle-hook'."
  6257. (when (get-buffer-window (current-buffer))
  6258. (cond
  6259. ((eq state 'content) nil)
  6260. ((eq state 'all) nil)
  6261. ((eq state 'folded) nil)
  6262. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6263. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6264. (defun org-remove-empty-overlays-at (pos)
  6265. "Remove outline overlays that do not contain non-white stuff."
  6266. (dolist (o (overlays-at pos))
  6267. (and (eq 'outline (overlay-get o 'invisible))
  6268. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6269. (overlay-end o))))
  6270. (delete-overlay o))))
  6271. (defun org-clean-visibility-after-subtree-move ()
  6272. "Fix visibility issues after moving a subtree."
  6273. ;; First, find a reasonable region to look at:
  6274. ;; Start two siblings above, end three below
  6275. (let* ((beg (save-excursion
  6276. (and (org-get-last-sibling)
  6277. (org-get-last-sibling))
  6278. (point)))
  6279. (end (save-excursion
  6280. (and (org-get-next-sibling)
  6281. (org-get-next-sibling)
  6282. (org-get-next-sibling))
  6283. (if (org-at-heading-p)
  6284. (point-at-eol)
  6285. (point))))
  6286. (level (looking-at "\\*+"))
  6287. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6288. (save-excursion
  6289. (save-restriction
  6290. (narrow-to-region beg end)
  6291. (when re
  6292. ;; Properly fold already folded siblings
  6293. (goto-char (point-min))
  6294. (while (re-search-forward re nil t)
  6295. (when (and (not (org-invisible-p))
  6296. (save-excursion
  6297. (goto-char (point-at-eol)) (org-invisible-p)))
  6298. (outline-hide-entry))))
  6299. (org-cycle-show-empty-lines 'overview)
  6300. (org-cycle-hide-drawers 'overview)))))
  6301. (defun org-cycle-show-empty-lines (state)
  6302. "Show empty lines above all visible headlines.
  6303. The region to be covered depends on STATE when called through
  6304. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6305. entire buffer covered. Note that an empty line is only shown if there
  6306. are at least `org-cycle-separator-lines' empty lines before the headline."
  6307. (when (/= org-cycle-separator-lines 0)
  6308. (save-excursion
  6309. (let* ((n (abs org-cycle-separator-lines))
  6310. (re (cond
  6311. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6312. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6313. (t (let ((ns (number-to-string (- n 2))))
  6314. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6315. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6316. beg end)
  6317. (cond
  6318. ((memq state '(overview contents t))
  6319. (setq beg (point-min) end (point-max)))
  6320. ((memq state '(children folded))
  6321. (setq beg (point)
  6322. end (progn (org-end-of-subtree t t)
  6323. (line-beginning-position 2)))))
  6324. (when beg
  6325. (goto-char beg)
  6326. (while (re-search-forward re end t)
  6327. (unless (get-char-property (match-end 1) 'invisible)
  6328. (let ((e (match-end 1))
  6329. (b (if (>= org-cycle-separator-lines 0)
  6330. (match-beginning 1)
  6331. (save-excursion
  6332. (goto-char (match-beginning 0))
  6333. (skip-chars-backward " \t\n")
  6334. (line-end-position)))))
  6335. (outline-flag-region b e nil))))))))
  6336. ;; Never hide empty lines at the end of the file.
  6337. (save-excursion
  6338. (goto-char (point-max))
  6339. (outline-previous-heading)
  6340. (outline-end-of-heading)
  6341. (when (and (looking-at "[ \t\n]+")
  6342. (= (match-end 0) (point-max)))
  6343. (outline-flag-region (point) (match-end 0) nil))))
  6344. (defun org-show-empty-lines-in-parent ()
  6345. "Move to the parent and re-show empty lines before visible headlines."
  6346. (save-excursion
  6347. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6348. (org-cycle-show-empty-lines context))))
  6349. (defun org-files-list ()
  6350. "Return `org-agenda-files' list, plus all open Org files.
  6351. This is useful for operations that need to scan all of a user's
  6352. open and agenda-wise Org files."
  6353. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6354. (dolist (buf (buffer-list))
  6355. (with-current-buffer buf
  6356. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6357. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6358. files))
  6359. (defsubst org-entry-beginning-position ()
  6360. "Return the beginning position of the current entry."
  6361. (save-excursion (org-back-to-heading t) (point)))
  6362. (defsubst org-entry-end-position ()
  6363. "Return the end position of the current entry."
  6364. (save-excursion (outline-next-heading) (point)))
  6365. (defun org-cycle-hide-drawers (state &optional exceptions)
  6366. "Re-hide all drawers after a visibility state change.
  6367. STATE should be one of the symbols listed in the docstring of
  6368. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6369. a list of strings specifying which drawers should not be hidden."
  6370. (when (and (derived-mode-p 'org-mode)
  6371. (not (memq state '(overview folded contents))))
  6372. (save-excursion
  6373. (let* ((globalp (eq state 'all))
  6374. (beg (if globalp (point-min) (point)))
  6375. (end (if globalp (point-max)
  6376. (if (eq state 'children)
  6377. (save-excursion (outline-next-heading) (point))
  6378. (org-end-of-subtree t)))))
  6379. (goto-char beg)
  6380. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6381. (unless (member-ignore-case (match-string 1) exceptions)
  6382. (let ((drawer (org-element-at-point)))
  6383. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6384. (org-flag-drawer t drawer)
  6385. ;; Make sure to skip drawer entirely or we might flag
  6386. ;; it another time when matching its ending line with
  6387. ;; `org-drawer-regexp'.
  6388. (goto-char (org-element-property :end drawer))))))))))
  6389. (defun org-flag-drawer (flag &optional element)
  6390. "When FLAG is non-nil, hide the drawer we are at.
  6391. Otherwise make it visible. When optional argument ELEMENT is
  6392. a parsed drawer, as returned by `org-element-at-point', hide or
  6393. show that drawer instead."
  6394. (let ((drawer (or element
  6395. (and (save-excursion
  6396. (beginning-of-line)
  6397. (looking-at-p org-drawer-regexp))
  6398. (org-element-at-point)))))
  6399. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6400. (let ((post (org-element-property :post-affiliated drawer)))
  6401. (save-excursion
  6402. (outline-flag-region
  6403. (progn (goto-char post) (line-end-position))
  6404. (progn (goto-char (org-element-property :end drawer))
  6405. (skip-chars-backward " \r\t\n")
  6406. (line-end-position))
  6407. flag))
  6408. ;; When the drawer is hidden away, make sure point lies in
  6409. ;; a visible part of the buffer.
  6410. (when (and flag (> (line-beginning-position) post))
  6411. (goto-char post))))))
  6412. (defun org-subtree-end-visible-p ()
  6413. "Is the end of the current subtree visible?"
  6414. (pos-visible-in-window-p
  6415. (save-excursion (org-end-of-subtree t) (point))))
  6416. (defun org-first-headline-recenter ()
  6417. "Move cursor to the first headline and recenter the headline."
  6418. (let ((window (get-buffer-window)))
  6419. (when window
  6420. (goto-char (point-min))
  6421. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6422. (set-window-start window (line-beginning-position))))))
  6423. ;;; Saving and restoring visibility
  6424. (defun org-outline-overlay-data (&optional use-markers)
  6425. "Return a list of the locations of all outline overlays.
  6426. These are overlays with the `invisible' property value `outline'.
  6427. The return value is a list of cons cells, with start and stop
  6428. positions for each overlay.
  6429. If USE-MARKERS is set, return the positions as markers."
  6430. (let (beg end)
  6431. (org-with-wide-buffer
  6432. (delq nil
  6433. (mapcar (lambda (o)
  6434. (when (eq (overlay-get o 'invisible) 'outline)
  6435. (setq beg (overlay-start o)
  6436. end (overlay-end o))
  6437. (and beg end (> end beg)
  6438. (if use-markers
  6439. (cons (copy-marker beg)
  6440. (copy-marker end t))
  6441. (cons beg end)))))
  6442. (overlays-in (point-min) (point-max)))))))
  6443. (defun org-set-outline-overlay-data (data)
  6444. "Create visibility overlays for all positions in DATA.
  6445. DATA should have been made by `org-outline-overlay-data'."
  6446. (org-with-wide-buffer
  6447. (outline-show-all)
  6448. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6449. ;;; Folding of blocks
  6450. (defvar-local org-hide-block-overlays nil
  6451. "Overlays hiding blocks.")
  6452. (defun org-block-map (function &optional start end)
  6453. "Call FUNCTION at the head of all source blocks in the current buffer.
  6454. Optional arguments START and END can be used to limit the range."
  6455. (let ((start (or start (point-min)))
  6456. (end (or end (point-max))))
  6457. (save-excursion
  6458. (goto-char start)
  6459. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6460. (save-excursion
  6461. (save-match-data
  6462. (goto-char (match-beginning 0))
  6463. (funcall function)))))))
  6464. (defun org-hide-block-toggle-all ()
  6465. "Toggle the visibility of all blocks in the current buffer."
  6466. (org-block-map 'org-hide-block-toggle))
  6467. (defun org-hide-block-all ()
  6468. "Fold all blocks in the current buffer."
  6469. (interactive)
  6470. (org-show-block-all)
  6471. (org-block-map 'org-hide-block-toggle-maybe))
  6472. (defun org-show-block-all ()
  6473. "Unfold all blocks in the current buffer."
  6474. (interactive)
  6475. (mapc #'delete-overlay org-hide-block-overlays)
  6476. (setq org-hide-block-overlays nil))
  6477. (defun org-hide-block-toggle-maybe ()
  6478. "Toggle visibility of block at point.
  6479. Unlike to `org-hide-block-toggle', this function does not throw
  6480. an error. Return a non-nil value when toggling is successful."
  6481. (interactive)
  6482. (ignore-errors (org-hide-block-toggle)))
  6483. (defun org-hide-block-toggle (&optional force)
  6484. "Toggle the visibility of the current block.
  6485. When optional argument FORCE is `off', make block visible. If it
  6486. is non-nil, hide it unconditionally. Throw an error when not at
  6487. a block. Return a non-nil value when toggling is successful."
  6488. (interactive)
  6489. (let ((element (org-element-at-point)))
  6490. (unless (memq (org-element-type element)
  6491. '(center-block comment-block dynamic-block example-block
  6492. export-block quote-block special-block
  6493. src-block verse-block))
  6494. (user-error "Not at a block"))
  6495. (let* ((start (save-excursion
  6496. (goto-char (org-element-property :post-affiliated element))
  6497. (line-end-position)))
  6498. (end (save-excursion
  6499. (goto-char (org-element-property :end element))
  6500. (skip-chars-backward " \r\t\n")
  6501. (line-end-position)))
  6502. (overlays (overlays-at start)))
  6503. (cond
  6504. ;; Do nothing when not before or at the block opening line or
  6505. ;; at the block closing line.
  6506. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6507. ((and (not (eq force 'off))
  6508. (not (memq t (mapcar
  6509. (lambda (o)
  6510. (eq (overlay-get o 'invisible) 'org-hide-block))
  6511. overlays))))
  6512. (let ((ov (make-overlay start end)))
  6513. (overlay-put ov 'invisible 'org-hide-block)
  6514. ;; Make the block accessible to `isearch'.
  6515. (overlay-put
  6516. ov 'isearch-open-invisible
  6517. (lambda (ov)
  6518. (when (memq ov org-hide-block-overlays)
  6519. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6520. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6521. (delete-overlay ov))))
  6522. (push ov org-hide-block-overlays)
  6523. ;; When the block is hidden away, make sure point is left in
  6524. ;; a visible part of the buffer.
  6525. (when (> (line-beginning-position) start)
  6526. (goto-char start)
  6527. (beginning-of-line))
  6528. ;; Signal successful toggling.
  6529. t))
  6530. ((or (not force) (eq force 'off))
  6531. (dolist (ov overlays t)
  6532. (when (memq ov org-hide-block-overlays)
  6533. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6534. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6535. (delete-overlay ov))))))))
  6536. ;; Remove overlays when changing major mode
  6537. (add-hook 'org-mode-hook
  6538. (lambda () (add-hook 'change-major-mode-hook
  6539. 'org-show-block-all 'append 'local)))
  6540. ;;; Org-goto
  6541. (defvar org-goto-window-configuration nil)
  6542. (defvar org-goto-marker nil)
  6543. (defvar org-goto-map)
  6544. (defun org-goto-map ()
  6545. "Set the keymap `org-goto'."
  6546. (setq org-goto-map
  6547. (let ((map (make-sparse-keymap)))
  6548. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6549. mouse-drag-region universal-argument org-occur)))
  6550. (dolist (cmd cmds)
  6551. (substitute-key-definition cmd cmd map global-map)))
  6552. (suppress-keymap map)
  6553. (org-defkey map "\C-m" 'org-goto-ret)
  6554. (org-defkey map [(return)] 'org-goto-ret)
  6555. (org-defkey map [(left)] 'org-goto-left)
  6556. (org-defkey map [(right)] 'org-goto-right)
  6557. (org-defkey map [(control ?g)] 'org-goto-quit)
  6558. (org-defkey map "\C-i" 'org-cycle)
  6559. (org-defkey map [(tab)] 'org-cycle)
  6560. (org-defkey map [(down)] 'outline-next-visible-heading)
  6561. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6562. (if org-goto-auto-isearch
  6563. (if (fboundp 'define-key-after)
  6564. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6565. nil)
  6566. (org-defkey map "q" 'org-goto-quit)
  6567. (org-defkey map "n" 'outline-next-visible-heading)
  6568. (org-defkey map "p" 'outline-previous-visible-heading)
  6569. (org-defkey map "f" 'outline-forward-same-level)
  6570. (org-defkey map "b" 'outline-backward-same-level)
  6571. (org-defkey map "u" 'outline-up-heading))
  6572. (org-defkey map "/" 'org-occur)
  6573. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6574. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6575. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6576. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6577. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6578. map)))
  6579. (defconst org-goto-help
  6580. "Browse buffer copy, to find location or copy text.%s
  6581. RET=jump to location C-g=quit and return to previous location
  6582. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6583. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6584. (defun org-goto (&optional alternative-interface)
  6585. "Look up a different location in the current file, keeping current visibility.
  6586. When you want look-up or go to a different location in a
  6587. document, the fastest way is often to fold the entire buffer and
  6588. then dive into the tree. This method has the disadvantage, that
  6589. the previous location will be folded, which may not be what you
  6590. want.
  6591. This command works around this by showing a copy of the current
  6592. buffer in an indirect buffer, in overview mode. You can dive
  6593. into the tree in that copy, use org-occur and incremental search
  6594. to find a location. When pressing RET or `Q', the command
  6595. returns to the original buffer in which the visibility is still
  6596. unchanged. After RET it will also jump to the location selected
  6597. in the indirect buffer and expose the headline hierarchy above.
  6598. With a prefix argument, use the alternative interface: e.g., if
  6599. `org-goto-interface' is `outline' use `outline-path-completion'."
  6600. (interactive "P")
  6601. (org-goto-map)
  6602. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6603. (org-refile-use-outline-path t)
  6604. (org-refile-target-verify-function nil)
  6605. (interface
  6606. (if (not alternative-interface)
  6607. org-goto-interface
  6608. (if (eq org-goto-interface 'outline)
  6609. 'outline-path-completion
  6610. 'outline)))
  6611. (org-goto-start-pos (point))
  6612. (selected-point
  6613. (if (eq interface 'outline)
  6614. (car (org-get-location (current-buffer) org-goto-help))
  6615. (let ((pa (org-refile-get-location "Goto")))
  6616. (org-refile-check-position pa)
  6617. (nth 3 pa)))))
  6618. (if selected-point
  6619. (progn
  6620. (org-mark-ring-push org-goto-start-pos)
  6621. (goto-char selected-point)
  6622. (when (or (org-invisible-p) (org-invisible-p2))
  6623. (org-show-context 'org-goto)))
  6624. (message "Quit"))))
  6625. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6626. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6627. (defvar org-goto-local-auto-isearch-map) ; defined below
  6628. (defun org-get-location (_buf help)
  6629. "Let the user select a location in current buffer.
  6630. This function uses a recursive edit. It returns the selected position
  6631. or nil."
  6632. (org-no-popups
  6633. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6634. (isearch-hide-immediately nil)
  6635. (isearch-search-fun-function
  6636. (lambda () 'org-goto-local-search-headings))
  6637. (org-goto-selected-point org-goto-exit-command))
  6638. (save-excursion
  6639. (save-window-excursion
  6640. (delete-other-windows)
  6641. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6642. (pop-to-buffer-same-window
  6643. (condition-case nil
  6644. (make-indirect-buffer (current-buffer) "*org-goto*")
  6645. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6646. (with-output-to-temp-buffer "*Org Help*"
  6647. (princ (format help (if org-goto-auto-isearch
  6648. " Just type for auto-isearch."
  6649. " n/p/f/b/u to navigate, q to quit."))))
  6650. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6651. (setq buffer-read-only nil)
  6652. (let ((org-startup-truncated t)
  6653. (org-startup-folded nil)
  6654. (org-startup-align-all-tables nil))
  6655. (org-mode)
  6656. (org-overview))
  6657. (setq buffer-read-only t)
  6658. (if (and (boundp 'org-goto-start-pos)
  6659. (integer-or-marker-p org-goto-start-pos))
  6660. (progn (goto-char org-goto-start-pos)
  6661. (when (org-invisible-p)
  6662. (org-show-set-visibility 'lineage)))
  6663. (goto-char (point-min)))
  6664. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6665. (message "Select location and press RET")
  6666. (use-local-map org-goto-map)
  6667. (recursive-edit)))
  6668. (kill-buffer "*org-goto*")
  6669. (cons org-goto-selected-point org-goto-exit-command))))
  6670. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6671. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6672. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6673. (if (fboundp 'isearch-other-control-char)
  6674. (progn
  6675. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6676. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6677. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6678. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6679. (define-key org-goto-local-auto-isearch-map [return] nil))
  6680. (defun org-goto-local-search-headings (string bound noerror)
  6681. "Search and make sure that any matches are in headlines."
  6682. (catch 'return
  6683. (while (if isearch-forward
  6684. (search-forward string bound noerror)
  6685. (search-backward string bound noerror))
  6686. (when (save-match-data
  6687. (and (save-excursion
  6688. (beginning-of-line)
  6689. (looking-at org-complex-heading-regexp))
  6690. (or (not (match-beginning 5))
  6691. (< (point) (match-beginning 5)))))
  6692. (throw 'return (point))))))
  6693. (defun org-goto-local-auto-isearch ()
  6694. "Start isearch."
  6695. (interactive)
  6696. (goto-char (point-min))
  6697. (let ((keys (this-command-keys)))
  6698. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6699. (isearch-mode t)
  6700. (isearch-process-search-char (string-to-char keys)))))
  6701. (defun org-goto-ret (&optional _arg)
  6702. "Finish `org-goto' by going to the new location."
  6703. (interactive "P")
  6704. (setq org-goto-selected-point (point))
  6705. (setq org-goto-exit-command 'return)
  6706. (throw 'exit nil))
  6707. (defun org-goto-left ()
  6708. "Finish `org-goto' by going to the new location."
  6709. (interactive)
  6710. (if (org-at-heading-p)
  6711. (progn
  6712. (beginning-of-line 1)
  6713. (setq org-goto-selected-point (point)
  6714. org-goto-exit-command 'left)
  6715. (throw 'exit nil))
  6716. (user-error "Not on a heading")))
  6717. (defun org-goto-right ()
  6718. "Finish `org-goto' by going to the new location."
  6719. (interactive)
  6720. (if (org-at-heading-p)
  6721. (progn
  6722. (setq org-goto-selected-point (point)
  6723. org-goto-exit-command 'right)
  6724. (throw 'exit nil))
  6725. (user-error "Not on a heading")))
  6726. (defun org-goto-quit ()
  6727. "Finish `org-goto' without cursor motion."
  6728. (interactive)
  6729. (setq org-goto-selected-point nil)
  6730. (setq org-goto-exit-command 'quit)
  6731. (throw 'exit nil))
  6732. ;;; Indirect buffer display of subtrees
  6733. (defvar org-indirect-dedicated-frame nil
  6734. "This is the frame being used for indirect tree display.")
  6735. (defvar org-last-indirect-buffer nil)
  6736. (defun org-tree-to-indirect-buffer (&optional arg)
  6737. "Create indirect buffer and narrow it to current subtree.
  6738. With a numerical prefix ARG, go up to this level and then take that tree.
  6739. If ARG is negative, go up that many levels.
  6740. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6741. indirect buffer previously made with this command, to avoid proliferation of
  6742. indirect buffers. However, when you call the command with a \
  6743. `\\[universal-argument]' prefix, or
  6744. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6745. so that you can work with several indirect buffers at the same time. If
  6746. `org-indirect-buffer-display' is `dedicated-frame', the \
  6747. `\\[universal-argument]' prefix also
  6748. requests that a new frame be made for the new buffer, so that the dedicated
  6749. frame is not changed."
  6750. (interactive "P")
  6751. (let ((cbuf (current-buffer))
  6752. (cwin (selected-window))
  6753. (pos (point))
  6754. beg end level heading ibuf)
  6755. (save-excursion
  6756. (org-back-to-heading t)
  6757. (when (numberp arg)
  6758. (setq level (org-outline-level))
  6759. (when (< arg 0) (setq arg (+ level arg)))
  6760. (while (> (setq level (org-outline-level)) arg)
  6761. (org-up-heading-safe)))
  6762. (setq beg (point)
  6763. heading (org-get-heading 'no-tags))
  6764. (org-end-of-subtree t t)
  6765. (when (org-at-heading-p) (backward-char 1))
  6766. (setq end (point)))
  6767. (when (and (buffer-live-p org-last-indirect-buffer)
  6768. (not (eq org-indirect-buffer-display 'new-frame))
  6769. (not arg))
  6770. (kill-buffer org-last-indirect-buffer))
  6771. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6772. org-last-indirect-buffer ibuf)
  6773. (cond
  6774. ((or (eq org-indirect-buffer-display 'new-frame)
  6775. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6776. (select-frame (make-frame))
  6777. (delete-other-windows)
  6778. (pop-to-buffer-same-window ibuf)
  6779. (org-set-frame-title heading))
  6780. ((eq org-indirect-buffer-display 'dedicated-frame)
  6781. (raise-frame
  6782. (select-frame (or (and org-indirect-dedicated-frame
  6783. (frame-live-p org-indirect-dedicated-frame)
  6784. org-indirect-dedicated-frame)
  6785. (setq org-indirect-dedicated-frame (make-frame)))))
  6786. (delete-other-windows)
  6787. (pop-to-buffer-same-window ibuf)
  6788. (org-set-frame-title (concat "Indirect: " heading)))
  6789. ((eq org-indirect-buffer-display 'current-window)
  6790. (pop-to-buffer-same-window ibuf))
  6791. ((eq org-indirect-buffer-display 'other-window)
  6792. (pop-to-buffer ibuf))
  6793. (t (error "Invalid value")))
  6794. (narrow-to-region beg end)
  6795. (outline-show-all)
  6796. (goto-char pos)
  6797. (run-hook-with-args 'org-cycle-hook 'all)
  6798. (and (window-live-p cwin) (select-window cwin))))
  6799. (defun org-get-indirect-buffer (&optional buffer heading)
  6800. (setq buffer (or buffer (current-buffer)))
  6801. (let ((n 1) (base (buffer-name buffer)) bname)
  6802. (while (buffer-live-p
  6803. (get-buffer
  6804. (setq bname
  6805. (concat base "-"
  6806. (if heading (concat heading "-" (number-to-string n))
  6807. (number-to-string n))))))
  6808. (setq n (1+ n)))
  6809. (condition-case nil
  6810. (make-indirect-buffer buffer bname 'clone)
  6811. (error (make-indirect-buffer buffer bname)))))
  6812. (defun org-set-frame-title (title)
  6813. "Set the title of the current frame to the string TITLE."
  6814. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6815. ;;;; Structure editing
  6816. ;;; Inserting headlines
  6817. (defun org--line-empty-p (n)
  6818. "Is the Nth next line empty?
  6819. Counts the current line as N = 1 and the previous line as N = 0;
  6820. see `beginning-of-line'."
  6821. (save-excursion
  6822. (and (not (bobp))
  6823. (or (beginning-of-line n) t)
  6824. (save-match-data
  6825. (looking-at "[ \t]*$")))))
  6826. (defun org-previous-line-empty-p ()
  6827. "Is the previous line a blank line?
  6828. When NEXT is non-nil, check the next line instead."
  6829. (org--line-empty-p 0))
  6830. (defun org-next-line-empty-p ()
  6831. "Is the previous line a blank line?
  6832. When NEXT is non-nil, check the next line instead."
  6833. (org--line-empty-p 2))
  6834. (defun org--blank-before-heading-p (&optional parent)
  6835. "Non-nil when an empty line should precede a new heading here.
  6836. When optional argument PARENT is non-nil, consider parent
  6837. headline instead of current one."
  6838. (pcase (assq 'heading org-blank-before-new-entry)
  6839. (`(heading . auto)
  6840. (save-excursion
  6841. (org-with-limited-levels
  6842. (unless (and (org-before-first-heading-p)
  6843. (not (outline-next-heading)))
  6844. (org-back-to-heading t)
  6845. (when parent (org-up-heading-safe))
  6846. (cond ((not (bobp))
  6847. (org-previous-line-empty-p))
  6848. ((outline-next-heading)
  6849. (org-previous-line-empty-p))
  6850. ;; Ignore trailing spaces on last buffer line.
  6851. ((progn (skip-chars-backward " \t") (bolp))
  6852. (org-previous-line-empty-p))
  6853. (t nil))))))
  6854. (`(heading . ,value) value)
  6855. (_ nil)))
  6856. (defun org-insert-heading (&optional arg invisible-ok top)
  6857. "Insert a new heading or an item with the same depth at point.
  6858. If point is at the beginning of a heading, insert a new heading
  6859. or a new headline above the current one. When at the beginning
  6860. of a regular line of text, turn it into a heading.
  6861. If point is in the middle of a line, split it and create a new
  6862. headline with the text in the current line after point (see
  6863. `org-M-RET-may-split-line' on how to modify this behavior). As
  6864. a special case, on a headline, splitting can only happen on the
  6865. title itself. E.g., this excludes breaking stars or tags.
  6866. With a `\\[universal-argument]' prefix, set \
  6867. `org-insert-heading-respect-content' to
  6868. a non-nil value for the duration of the command. This forces the
  6869. insertion of a heading after the current subtree, independently
  6870. on the location of point.
  6871. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6872. insert the heading at the end of the tree
  6873. above the current heading. For example, if point is within a
  6874. 2nd-level heading, then it will insert a 2nd-level heading at
  6875. the end of the 1st-level parent subtree.
  6876. When INVISIBLE-OK is set, stop at invisible headlines when going
  6877. back. This is important for non-interactive uses of the
  6878. command.
  6879. When optional argument TOP is non-nil, insert a level 1 heading,
  6880. unconditionally."
  6881. (interactive "P")
  6882. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6883. (level (org-current-level))
  6884. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6885. (cond
  6886. ((or org-insert-heading-respect-content
  6887. (member arg '((4) (16)))
  6888. (and (not invisible-ok)
  6889. (invisible-p (max (1- (point)) (point-min)))))
  6890. ;; Position point at the location of insertion.
  6891. (if (not level) ;before first headline
  6892. (org-with-limited-levels (outline-next-heading))
  6893. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6894. ;; is nil.
  6895. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6896. (cond ((equal arg '(16))
  6897. (org-up-heading-safe)
  6898. (org-end-of-subtree t t))
  6899. (t
  6900. (org-end-of-subtree t t))))
  6901. (unless (bolp) (insert "\n")) ;ensure final newline
  6902. (unless (and blank? (org-previous-line-empty-p))
  6903. (org-N-empty-lines-before-current (if blank? 1 0)))
  6904. (insert stars " \n")
  6905. (forward-char -1))
  6906. ;; At a headline...
  6907. ((org-at-heading-p)
  6908. (cond ((bolp)
  6909. (when blank? (save-excursion (insert "\n")))
  6910. (save-excursion (insert stars " \n"))
  6911. (unless (and blank? (org-previous-line-empty-p))
  6912. (org-N-empty-lines-before-current (if blank? 1 0)))
  6913. (end-of-line))
  6914. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6915. (org-match-line org-complex-heading-regexp)
  6916. (org-pos-in-match-range (point) 4))
  6917. ;; Grab the text that should moved to the new headline.
  6918. ;; Preserve tags.
  6919. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6920. (if (looking-at "[ \t]*$") (replace-match "")
  6921. (org-set-tags nil t))
  6922. (end-of-line)
  6923. (when blank? (insert "\n"))
  6924. (insert "\n" stars " ")
  6925. (when (org-string-nw-p split) (insert split))
  6926. (when (eobp) (save-excursion (insert "\n")))))
  6927. (t
  6928. (end-of-line)
  6929. (when blank? (insert "\n"))
  6930. (insert "\n" stars " ")
  6931. (when (eobp) (save-excursion (insert "\n"))))))
  6932. ;; On regular text, turn line into a headline or split, if
  6933. ;; appropriate.
  6934. ((bolp)
  6935. (insert stars " ")
  6936. (unless (and blank? (org-previous-line-empty-p))
  6937. (org-N-empty-lines-before-current (if blank? 1 0))))
  6938. (t
  6939. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6940. (end-of-line))
  6941. (insert "\n" stars " ")
  6942. (unless (and blank? (org-previous-line-empty-p))
  6943. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6944. (run-hooks 'org-insert-heading-hook))
  6945. (defun org-N-empty-lines-before-current (n)
  6946. "Make the number of empty lines before current exactly N.
  6947. So this will delete or add empty lines."
  6948. (let ((column (current-column)))
  6949. (beginning-of-line)
  6950. (unless (bobp)
  6951. (let ((start (save-excursion
  6952. (skip-chars-backward " \r\t\n")
  6953. (line-end-position))))
  6954. (delete-region start (line-end-position 0))))
  6955. (insert (make-string n ?\n))
  6956. (move-to-column column)))
  6957. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6958. "Return the heading of the current entry, without the stars.
  6959. When NO-TAGS is non-nil, don't include tags.
  6960. When NO-TODO is non-nil, don't include TODO keywords.
  6961. When NO-PRIORITY is non-nil, don't include priority cookie.
  6962. When NO-COMMENT is non-nil, don't include COMMENT string."
  6963. (save-excursion
  6964. (org-back-to-heading t)
  6965. (let ((case-fold-search nil))
  6966. (looking-at org-complex-heading-regexp)
  6967. (let ((todo (and (not no-todo) (match-string 2)))
  6968. (priority (and (not no-priority) (match-string 3)))
  6969. (headline (pcase (match-string 4)
  6970. (`nil "")
  6971. ((and (guard no-comment) h)
  6972. (replace-regexp-in-string
  6973. (eval-when-compile
  6974. (format "\\`%s[ \t]+" org-comment-string))
  6975. "" h))
  6976. (h h)))
  6977. (tags (and (not no-tags) (match-string 5))))
  6978. (mapconcat #'identity
  6979. (delq nil (list todo priority headline tags))
  6980. " ")))))
  6981. (defvar orgstruct-mode) ; defined below
  6982. (defun org-heading-components ()
  6983. "Return the components of the current heading.
  6984. This is a list with the following elements:
  6985. - the level as an integer
  6986. - the reduced level, different if `org-odd-levels-only' is set.
  6987. - the TODO keyword, or nil
  6988. - the priority character, like ?A, or nil if no priority is given
  6989. - the headline text itself, or the tags string if no headline text
  6990. - the tags string, or nil."
  6991. (save-excursion
  6992. (org-back-to-heading t)
  6993. (when (let (case-fold-search)
  6994. (looking-at
  6995. (if orgstruct-mode
  6996. org-heading-regexp
  6997. org-complex-heading-regexp)))
  6998. (if orgstruct-mode
  6999. (list (length (match-string 1))
  7000. (org-reduced-level (length (match-string 1)))
  7001. nil
  7002. nil
  7003. (match-string 2)
  7004. nil)
  7005. (list (length (match-string 1))
  7006. (org-reduced-level (length (match-string 1)))
  7007. (match-string-no-properties 2)
  7008. (and (match-end 3) (aref (match-string 3) 2))
  7009. (match-string-no-properties 4)
  7010. (match-string-no-properties 5))))))
  7011. (defun org-get-entry ()
  7012. "Get the entry text, after heading, entire subtree."
  7013. (save-excursion
  7014. (org-back-to-heading t)
  7015. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7016. (defun org-edit-headline (&optional heading)
  7017. "Edit the current headline.
  7018. Set it to HEADING when provided."
  7019. (interactive)
  7020. (org-with-wide-buffer
  7021. (org-back-to-heading t)
  7022. (let ((case-fold-search nil))
  7023. (when (looking-at org-complex-heading-regexp)
  7024. (let* ((old (match-string-no-properties 4))
  7025. (new (save-match-data
  7026. (org-trim (or heading (read-string "Edit: " old))))))
  7027. (unless (equal old new)
  7028. (if old (replace-match new t t nil 4)
  7029. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7030. (insert " " new))
  7031. (org-set-tags nil t)
  7032. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7033. (defun org-insert-heading-after-current ()
  7034. "Insert a new heading with same level as current, after current subtree."
  7035. (interactive)
  7036. (org-back-to-heading)
  7037. (org-insert-heading)
  7038. (org-move-subtree-down)
  7039. (end-of-line 1))
  7040. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7041. "Insert heading with `org-insert-heading-respect-content' set to t."
  7042. (interactive)
  7043. (org-insert-heading '(4) invisible-ok))
  7044. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7045. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7046. (interactive)
  7047. (org-insert-todo-heading force-state '(4)))
  7048. (defun org-insert-todo-heading (arg &optional force-heading)
  7049. "Insert a new heading with the same level and TODO state as current heading.
  7050. If the heading has no TODO state, or if the state is DONE, use
  7051. the first state (TODO by default). Also with one prefix arg,
  7052. force first state. With two prefix args, force inserting at the
  7053. end of the parent subtree.
  7054. When called at a plain list item, insert a new item with an
  7055. unchecked check box."
  7056. (interactive "P")
  7057. (when (or force-heading (not (org-insert-item 'checkbox)))
  7058. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7059. force-heading))
  7060. (save-excursion
  7061. (org-back-to-heading)
  7062. (outline-previous-heading)
  7063. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7064. (let* ((new-mark-x
  7065. (if (or (equal arg '(4))
  7066. (not (match-beginning 2))
  7067. (member (match-string 2) org-done-keywords))
  7068. (car org-todo-keywords-1)
  7069. (match-string 2)))
  7070. (new-mark
  7071. (or
  7072. (run-hook-with-args-until-success
  7073. 'org-todo-get-default-hook new-mark-x nil)
  7074. new-mark-x)))
  7075. (beginning-of-line 1)
  7076. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7077. (if org-treat-insert-todo-heading-as-state-change
  7078. (org-todo new-mark)
  7079. (insert new-mark " "))))
  7080. (when org-provide-todo-statistics
  7081. (org-update-parent-todo-statistics))))
  7082. (defun org-insert-subheading (arg)
  7083. "Insert a new subheading and demote it.
  7084. Works for outline headings and for plain lists alike."
  7085. (interactive "P")
  7086. (org-insert-heading arg)
  7087. (cond
  7088. ((org-at-heading-p) (org-do-demote))
  7089. ((org-at-item-p) (org-indent-item))))
  7090. (defun org-insert-todo-subheading (arg)
  7091. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7092. Works for outline headings and for plain lists alike."
  7093. (interactive "P")
  7094. (org-insert-todo-heading arg)
  7095. (cond
  7096. ((org-at-heading-p) (org-do-demote))
  7097. ((org-at-item-p) (org-indent-item))))
  7098. ;;; Promotion and Demotion
  7099. (defvar org-after-demote-entry-hook nil
  7100. "Hook run after an entry has been demoted.
  7101. The cursor will be at the beginning of the entry.
  7102. When a subtree is being demoted, the hook will be called for each node.")
  7103. (defvar org-after-promote-entry-hook nil
  7104. "Hook run after an entry has been promoted.
  7105. The cursor will be at the beginning of the entry.
  7106. When a subtree is being promoted, the hook will be called for each node.")
  7107. (defun org-promote-subtree ()
  7108. "Promote the entire subtree.
  7109. See also `org-promote'."
  7110. (interactive)
  7111. (save-excursion
  7112. (org-with-limited-levels (org-map-tree 'org-promote)))
  7113. (org-fix-position-after-promote))
  7114. (defun org-demote-subtree ()
  7115. "Demote the entire subtree.
  7116. See `org-demote' and `org-promote'."
  7117. (interactive)
  7118. (save-excursion
  7119. (org-with-limited-levels (org-map-tree 'org-demote)))
  7120. (org-fix-position-after-promote))
  7121. (defun org-do-promote ()
  7122. "Promote the current heading higher up the tree.
  7123. If the region is active in `transient-mark-mode', promote all
  7124. headings in the region."
  7125. (interactive)
  7126. (save-excursion
  7127. (if (org-region-active-p)
  7128. (org-map-region 'org-promote (region-beginning) (region-end))
  7129. (org-promote)))
  7130. (org-fix-position-after-promote))
  7131. (defun org-do-demote ()
  7132. "Demote the current heading lower down the tree.
  7133. If the region is active in `transient-mark-mode', demote all
  7134. headings in the region."
  7135. (interactive)
  7136. (save-excursion
  7137. (if (org-region-active-p)
  7138. (org-map-region 'org-demote (region-beginning) (region-end))
  7139. (org-demote)))
  7140. (org-fix-position-after-promote))
  7141. (defun org-fix-position-after-promote ()
  7142. "Fix cursor position and indentation after demoting/promoting."
  7143. (let ((pos (point)))
  7144. (when (save-excursion
  7145. (beginning-of-line)
  7146. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7147. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7148. (cond ((eobp) (insert " "))
  7149. ((eolp) (insert " "))
  7150. ((equal (char-after) ?\s) (forward-char 1))))))
  7151. (defun org-current-level ()
  7152. "Return the level of the current entry, or nil if before the first headline.
  7153. The level is the number of stars at the beginning of the
  7154. headline. Use `org-reduced-level' to remove the effect of
  7155. `org-odd-levels'. Unlike to `org-outline-level', this function
  7156. ignores inlinetasks."
  7157. (let ((level (org-with-limited-levels (org-outline-level))))
  7158. (and (> level 0) level)))
  7159. (defun org-get-previous-line-level ()
  7160. "Return the outline depth of the last headline before the current line.
  7161. Returns 0 for the first headline in the buffer, and nil if before the
  7162. first headline."
  7163. (and (org-current-level)
  7164. (or (and (/= (line-beginning-position) (point-min))
  7165. (save-excursion (beginning-of-line 0) (org-current-level)))
  7166. 0)))
  7167. (defun org-reduced-level (l)
  7168. "Compute the effective level of a heading.
  7169. This takes into account the setting of `org-odd-levels-only'."
  7170. (cond
  7171. ((zerop l) 0)
  7172. (org-odd-levels-only (1+ (floor (/ l 2))))
  7173. (t l)))
  7174. (defun org-level-increment ()
  7175. "Return the number of stars that will be added or removed at a
  7176. time to headlines when structure editing, based on the value of
  7177. `org-odd-levels-only'."
  7178. (if org-odd-levels-only 2 1))
  7179. (defun org-get-valid-level (level &optional change)
  7180. "Rectify a level change under the influence of `org-odd-levels-only'.
  7181. LEVEL is a current level, CHANGE is by how much the level should
  7182. be modified. Even if CHANGE is nil, LEVEL may be returned
  7183. modified because even level numbers will become the next higher
  7184. odd number. Returns values greater than 0."
  7185. (if org-odd-levels-only
  7186. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7187. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7188. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7189. (max 1 (+ level (or change 0)))))
  7190. (defun org-promote ()
  7191. "Promote the current heading higher up the tree."
  7192. (org-with-wide-buffer
  7193. (org-back-to-heading t)
  7194. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7195. after-change-functions))
  7196. (level (save-match-data (funcall outline-level)))
  7197. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7198. (diff (abs (- level (length up-head) -1))))
  7199. (cond
  7200. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7201. (replace-match "# " nil t))
  7202. ((= level 1)
  7203. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7204. (t (replace-match up-head nil t)))
  7205. (unless (= level 1)
  7206. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7207. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7208. (run-hooks 'org-after-promote-entry-hook))))
  7209. (defun org-demote ()
  7210. "Demote the current heading lower down the tree."
  7211. (org-with-wide-buffer
  7212. (org-back-to-heading t)
  7213. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7214. after-change-functions))
  7215. (level (save-match-data (funcall outline-level)))
  7216. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7217. (diff (abs (- level (length down-head) -1))))
  7218. (replace-match down-head nil t)
  7219. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7220. (when org-adapt-indentation (org-fixup-indentation diff))
  7221. (run-hooks 'org-after-demote-entry-hook))))
  7222. (defun org-cycle-level ()
  7223. "Cycle the level of an empty headline through possible states.
  7224. This goes first to child, then to parent, level, then up the hierarchy.
  7225. After top level, it switches back to sibling level."
  7226. (interactive)
  7227. (let ((org-adapt-indentation nil))
  7228. (when (org-point-at-end-of-empty-headline)
  7229. (setq this-command 'org-cycle-level) ; Only needed for caching
  7230. (let ((cur-level (org-current-level))
  7231. (prev-level (org-get-previous-line-level)))
  7232. (cond
  7233. ;; If first headline in file, promote to top-level.
  7234. ((= prev-level 0)
  7235. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7236. do (org-do-promote)))
  7237. ;; If same level as prev, demote one.
  7238. ((= prev-level cur-level)
  7239. (org-do-demote))
  7240. ;; If parent is top-level, promote to top level if not already.
  7241. ((= prev-level 1)
  7242. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7243. do (org-do-promote)))
  7244. ;; If top-level, return to prev-level.
  7245. ((= cur-level 1)
  7246. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7247. do (org-do-demote)))
  7248. ;; If less than prev-level, promote one.
  7249. ((< cur-level prev-level)
  7250. (org-do-promote))
  7251. ;; If deeper than prev-level, promote until higher than
  7252. ;; prev-level.
  7253. ((> cur-level prev-level)
  7254. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7255. do (org-do-promote))))
  7256. t))))
  7257. (defun org-map-tree (fun)
  7258. "Call FUN for every heading underneath the current one."
  7259. (org-back-to-heading t)
  7260. (let ((level (funcall outline-level)))
  7261. (save-excursion
  7262. (funcall fun)
  7263. (while (and (progn
  7264. (outline-next-heading)
  7265. (> (funcall outline-level) level))
  7266. (not (eobp)))
  7267. (funcall fun)))))
  7268. (defun org-map-region (fun beg end)
  7269. "Call FUN for every heading between BEG and END."
  7270. (let ((org-ignore-region t))
  7271. (save-excursion
  7272. (setq end (copy-marker end))
  7273. (goto-char beg)
  7274. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7275. (< (point) end))
  7276. (funcall fun))
  7277. (while (and (progn
  7278. (outline-next-heading)
  7279. (< (point) end))
  7280. (not (eobp)))
  7281. (funcall fun)))))
  7282. (defun org-fixup-indentation (diff)
  7283. "Change the indentation in the current entry by DIFF.
  7284. DIFF is an integer. Indentation is done according to the
  7285. following rules:
  7286. - Planning information and property drawers are always indented
  7287. according to the new level of the headline;
  7288. - Footnote definitions and their contents are ignored;
  7289. - Inlinetasks' boundaries are not shifted;
  7290. - Empty lines are ignored;
  7291. - Other lines' indentation are shifted by DIFF columns, unless
  7292. it would introduce a structural change in the document, in
  7293. which case no shifting is done at all.
  7294. Assume point is at a heading or an inlinetask beginning."
  7295. (org-with-wide-buffer
  7296. (narrow-to-region (line-beginning-position)
  7297. (save-excursion
  7298. (if (org-with-limited-levels (org-at-heading-p))
  7299. (org-with-limited-levels (outline-next-heading))
  7300. (org-inlinetask-goto-end))
  7301. (point)))
  7302. (forward-line)
  7303. ;; Indent properly planning info and property drawer.
  7304. (when (looking-at-p org-planning-line-re)
  7305. (org-indent-line)
  7306. (forward-line))
  7307. (when (looking-at org-property-drawer-re)
  7308. (goto-char (match-end 0))
  7309. (forward-line)
  7310. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7311. (catch 'no-shift
  7312. (when (zerop diff) (throw 'no-shift nil))
  7313. ;; If DIFF is negative, first check if a shift is possible at all
  7314. ;; (e.g., it doesn't break structure). This can only happen if
  7315. ;; some contents are not properly indented.
  7316. (let ((case-fold-search t))
  7317. (when (< diff 0)
  7318. (let ((diff (- diff))
  7319. (forbidden-re (concat org-outline-regexp
  7320. "\\|"
  7321. (substring org-footnote-definition-re 1))))
  7322. (save-excursion
  7323. (while (not (eobp))
  7324. (cond
  7325. ((looking-at-p "[ \t]*$") (forward-line))
  7326. ((and (looking-at-p org-footnote-definition-re)
  7327. (let ((e (org-element-at-point)))
  7328. (and (eq (org-element-type e) 'footnote-definition)
  7329. (goto-char (org-element-property :end e))))))
  7330. ((looking-at-p org-outline-regexp) (forward-line))
  7331. ;; Give up if shifting would move before column 0 or
  7332. ;; if it would introduce a headline or a footnote
  7333. ;; definition.
  7334. (t
  7335. (skip-chars-forward " \t")
  7336. (let ((ind (current-column)))
  7337. (when (or (< ind diff)
  7338. (and (= ind diff) (looking-at-p forbidden-re)))
  7339. (throw 'no-shift nil)))
  7340. ;; Ignore contents of example blocks and source
  7341. ;; blocks if their indentation is meant to be
  7342. ;; preserved. Jump to block's closing line.
  7343. (beginning-of-line)
  7344. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7345. (let ((e (org-element-at-point)))
  7346. (and (memq (org-element-type e)
  7347. '(example-block src-block))
  7348. (or org-src-preserve-indentation
  7349. (org-element-property :preserve-indent e))
  7350. (goto-char (org-element-property :end e))
  7351. (progn (skip-chars-backward " \r\t\n")
  7352. (beginning-of-line)
  7353. t))))
  7354. (forward-line))))))))
  7355. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7356. ;; by DIFF. Also skip contents of source or example blocks
  7357. ;; when indentation is meant to be preserved.
  7358. (while (not (eobp))
  7359. (cond
  7360. ((and (looking-at-p org-footnote-definition-re)
  7361. (let ((e (org-element-at-point)))
  7362. (and (eq (org-element-type e) 'footnote-definition)
  7363. (goto-char (org-element-property :end e))))))
  7364. ((looking-at-p org-outline-regexp) (forward-line))
  7365. ((looking-at-p "[ \t]*$") (forward-line))
  7366. (t
  7367. (indent-line-to (+ (org-get-indentation) diff))
  7368. (beginning-of-line)
  7369. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7370. (let ((e (org-element-at-point)))
  7371. (and (memq (org-element-type e)
  7372. '(example-block src-block))
  7373. (or org-src-preserve-indentation
  7374. (org-element-property :preserve-indent e))
  7375. (goto-char (org-element-property :end e))
  7376. (progn (skip-chars-backward " \r\t\n")
  7377. (beginning-of-line)
  7378. t))))
  7379. (forward-line)))))))))
  7380. (defun org-convert-to-odd-levels ()
  7381. "Convert an Org file with all levels allowed to one with odd levels.
  7382. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7383. level 5 etc."
  7384. (interactive)
  7385. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7386. (let ((outline-level 'org-outline-level)
  7387. (org-odd-levels-only nil) n)
  7388. (save-excursion
  7389. (goto-char (point-min))
  7390. (while (re-search-forward "^\\*\\*+ " nil t)
  7391. (setq n (- (length (match-string 0)) 2))
  7392. (while (>= (setq n (1- n)) 0)
  7393. (org-demote))
  7394. (end-of-line 1))))))
  7395. (defun org-convert-to-oddeven-levels ()
  7396. "Convert an Org file with only odd levels to one with odd/even levels.
  7397. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7398. file contains a section with an even level, conversion would
  7399. destroy the structure of the file. An error is signaled in this
  7400. case."
  7401. (interactive)
  7402. (goto-char (point-min))
  7403. ;; First check if there are no even levels
  7404. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7405. (org-show-set-visibility 'canonical)
  7406. (error "Not all levels are odd in this file. Conversion not possible"))
  7407. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7408. (let ((outline-regexp org-outline-regexp)
  7409. (outline-level 'org-outline-level)
  7410. (org-odd-levels-only nil) n)
  7411. (save-excursion
  7412. (goto-char (point-min))
  7413. (while (re-search-forward "^\\*\\*+ " nil t)
  7414. (setq n (/ (1- (length (match-string 0))) 2))
  7415. (while (>= (setq n (1- n)) 0)
  7416. (org-promote))
  7417. (end-of-line 1))))))
  7418. (defun org-tr-level (n)
  7419. "Make N odd if required."
  7420. (if org-odd-levels-only (1+ (/ n 2)) n))
  7421. ;;; Vertical tree motion, cutting and pasting of subtrees
  7422. (defun org-move-subtree-up (&optional arg)
  7423. "Move the current subtree up past ARG headlines of the same level."
  7424. (interactive "p")
  7425. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7426. (defun org-move-subtree-down (&optional arg)
  7427. "Move the current subtree down past ARG headlines of the same level."
  7428. (interactive "p")
  7429. (setq arg (prefix-numeric-value arg))
  7430. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7431. 'org-get-last-sibling))
  7432. (ins-point (make-marker))
  7433. (cnt (abs arg))
  7434. (col (current-column))
  7435. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7436. ;; Select the tree
  7437. (org-back-to-heading)
  7438. (setq beg0 (point))
  7439. (save-excursion
  7440. (setq ne-beg (org-back-over-empty-lines))
  7441. (setq beg (point)))
  7442. (save-match-data
  7443. (save-excursion (outline-end-of-heading)
  7444. (setq folded (org-invisible-p)))
  7445. (progn (org-end-of-subtree nil t)
  7446. (unless (eobp) (backward-char))))
  7447. (outline-next-heading)
  7448. (setq ne-end (org-back-over-empty-lines))
  7449. (setq end (point))
  7450. (goto-char beg0)
  7451. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7452. ;; include less whitespace
  7453. (save-excursion
  7454. (goto-char beg)
  7455. (forward-line (- ne-beg ne-end))
  7456. (setq beg (point))))
  7457. ;; Find insertion point, with error handling
  7458. (while (> cnt 0)
  7459. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7460. (progn (goto-char beg0)
  7461. (user-error "Cannot move past superior level or buffer limit")))
  7462. (setq cnt (1- cnt)))
  7463. (when (> arg 0)
  7464. ;; Moving forward - still need to move over subtree
  7465. (org-end-of-subtree t t)
  7466. (save-excursion
  7467. (org-back-over-empty-lines)
  7468. (or (bolp) (newline))))
  7469. (setq ne-ins (org-back-over-empty-lines))
  7470. (move-marker ins-point (point))
  7471. (setq txt (buffer-substring beg end))
  7472. (org-save-markers-in-region beg end)
  7473. (delete-region beg end)
  7474. (org-remove-empty-overlays-at beg)
  7475. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7476. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7477. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7478. (let ((bbb (point)))
  7479. (insert-before-markers txt)
  7480. (org-reinstall-markers-in-region bbb)
  7481. (move-marker ins-point bbb))
  7482. (or (bolp) (insert "\n"))
  7483. (setq ins-end (point))
  7484. (goto-char ins-point)
  7485. (org-skip-whitespace)
  7486. (when (and (< arg 0)
  7487. (org-first-sibling-p)
  7488. (> ne-ins ne-beg))
  7489. ;; Move whitespace back to beginning
  7490. (save-excursion
  7491. (goto-char ins-end)
  7492. (let ((kill-whole-line t))
  7493. (kill-line (- ne-ins ne-beg)) (point)))
  7494. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7495. (move-marker ins-point nil)
  7496. (if folded
  7497. (outline-hide-subtree)
  7498. (org-show-entry)
  7499. (org-show-children)
  7500. (org-cycle-hide-drawers 'children))
  7501. (org-clean-visibility-after-subtree-move)
  7502. ;; move back to the initial column we were at
  7503. (move-to-column col)))
  7504. (defvar org-subtree-clip ""
  7505. "Clipboard for cut and paste of subtrees.
  7506. This is actually only a copy of the kill, because we use the normal kill
  7507. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7508. (defvar org-subtree-clip-folded nil
  7509. "Was the last copied subtree folded?
  7510. This is used to fold the tree back after pasting.")
  7511. (defun org-cut-subtree (&optional n)
  7512. "Cut the current subtree into the clipboard.
  7513. With prefix arg N, cut this many sequential subtrees.
  7514. This is a short-hand for marking the subtree and then cutting it."
  7515. (interactive "p")
  7516. (org-copy-subtree n 'cut))
  7517. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7518. "Copy the current subtree it in the clipboard.
  7519. With prefix arg N, copy this many sequential subtrees.
  7520. This is a short-hand for marking the subtree and then copying it.
  7521. If CUT is non-nil, actually cut the subtree.
  7522. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7523. of some markers in the region, even if CUT is non-nil. This is
  7524. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7525. (interactive "p")
  7526. (let (beg end folded (beg0 (point)))
  7527. (if (called-interactively-p 'any)
  7528. (org-back-to-heading nil) ; take what looks like a subtree
  7529. (org-back-to-heading t)) ; take what is really there
  7530. (setq beg (point))
  7531. (skip-chars-forward " \t\r\n")
  7532. (save-match-data
  7533. (if nosubtrees
  7534. (outline-next-heading)
  7535. (save-excursion (outline-end-of-heading)
  7536. (setq folded (org-invisible-p)))
  7537. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7538. (org-end-of-subtree t t)))
  7539. ;; Include the end of an inlinetask
  7540. (when (and (featurep 'org-inlinetask)
  7541. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7542. "END[ \t]*$")))
  7543. (end-of-line))
  7544. (setq end (point))
  7545. (goto-char beg0)
  7546. (when (> end beg)
  7547. (setq org-subtree-clip-folded folded)
  7548. (when (or cut force-store-markers)
  7549. (org-save-markers-in-region beg end))
  7550. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7551. (setq org-subtree-clip (current-kill 0))
  7552. (message "%s: Subtree(s) with %d characters"
  7553. (if cut "Cut" "Copied")
  7554. (length org-subtree-clip)))))
  7555. (defun org-paste-subtree (&optional level tree for-yank remove)
  7556. "Paste the clipboard as a subtree, with modification of headline level.
  7557. The entire subtree is promoted or demoted in order to match a new headline
  7558. level.
  7559. If the cursor is at the beginning of a headline, the same level as
  7560. that headline is used to paste the tree.
  7561. If not, the new level is derived from the *visible* headings
  7562. before and after the insertion point, and taken to be the inferior headline
  7563. level of the two. So if the previous visible heading is level 3 and the
  7564. next is level 4 (or vice versa), level 4 will be used for insertion.
  7565. This makes sure that the subtree remains an independent subtree and does
  7566. not swallow low level entries.
  7567. You can also force a different level, either by using a numeric prefix
  7568. argument, or by inserting the heading marker by hand. For example, if the
  7569. cursor is after \"*****\", then the tree will be shifted to level 5.
  7570. If optional TREE is given, use this text instead of the kill ring.
  7571. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7572. move back over whitespace before inserting, and move point to the end of
  7573. the inserted text when done.
  7574. When REMOVE is non-nil, remove the subtree from the clipboard."
  7575. (interactive "P")
  7576. (setq tree (or tree (and kill-ring (current-kill 0))))
  7577. (unless (org-kill-is-subtree-p tree)
  7578. (user-error "%s"
  7579. (substitute-command-keys
  7580. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7581. (org-with-limited-levels
  7582. (let* ((visp (not (org-invisible-p)))
  7583. (txt tree)
  7584. (^re_ "\\(\\*+\\)[ \t]*")
  7585. (old-level (if (string-match org-outline-regexp-bol txt)
  7586. (- (match-end 0) (match-beginning 0) 1)
  7587. -1))
  7588. (force-level (cond (level (prefix-numeric-value level))
  7589. ((and (looking-at "[ \t]*$")
  7590. (string-match
  7591. "^\\*+$" (buffer-substring
  7592. (point-at-bol) (point))))
  7593. (- (match-end 0) (match-beginning 0)))
  7594. ((and (bolp)
  7595. (looking-at org-outline-regexp))
  7596. (- (match-end 0) (point) 1))))
  7597. (previous-level (save-excursion
  7598. (condition-case nil
  7599. (progn
  7600. (outline-previous-visible-heading 1)
  7601. (if (looking-at ^re_)
  7602. (- (match-end 0) (match-beginning 0) 1)
  7603. 1))
  7604. (error 1))))
  7605. (next-level (save-excursion
  7606. (condition-case nil
  7607. (progn
  7608. (or (looking-at org-outline-regexp)
  7609. (outline-next-visible-heading 1))
  7610. (if (looking-at ^re_)
  7611. (- (match-end 0) (match-beginning 0) 1)
  7612. 1))
  7613. (error 1))))
  7614. (new-level (or force-level (max previous-level next-level)))
  7615. (shift (if (or (= old-level -1)
  7616. (= new-level -1)
  7617. (= old-level new-level))
  7618. 0
  7619. (- new-level old-level)))
  7620. (delta (if (> shift 0) -1 1))
  7621. (func (if (> shift 0) 'org-demote 'org-promote))
  7622. (org-odd-levels-only nil)
  7623. beg end newend)
  7624. ;; Remove the forced level indicator
  7625. (when force-level
  7626. (delete-region (point-at-bol) (point)))
  7627. ;; Paste
  7628. (beginning-of-line (if (bolp) 1 2))
  7629. (setq beg (point))
  7630. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7631. (insert-before-markers txt)
  7632. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7633. (setq newend (point))
  7634. (org-reinstall-markers-in-region beg)
  7635. (setq end (point))
  7636. (goto-char beg)
  7637. (skip-chars-forward " \t\n\r")
  7638. (setq beg (point))
  7639. (when (and (org-invisible-p) visp)
  7640. (save-excursion (outline-show-heading)))
  7641. ;; Shift if necessary
  7642. (unless (= shift 0)
  7643. (save-restriction
  7644. (narrow-to-region beg end)
  7645. (while (not (= shift 0))
  7646. (org-map-region func (point-min) (point-max))
  7647. (setq shift (+ delta shift)))
  7648. (goto-char (point-min))
  7649. (setq newend (point-max))))
  7650. (when (or (called-interactively-p 'interactive) for-yank)
  7651. (message "Clipboard pasted as level %d subtree" new-level))
  7652. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7653. kill-ring
  7654. (eq org-subtree-clip (current-kill 0))
  7655. org-subtree-clip-folded)
  7656. ;; The tree was folded before it was killed/copied
  7657. (outline-hide-subtree))
  7658. (and for-yank (goto-char newend))
  7659. (and remove (setq kill-ring (cdr kill-ring))))))
  7660. (defun org-kill-is-subtree-p (&optional txt)
  7661. "Check if the current kill is an outline subtree, or a set of trees.
  7662. Returns nil if kill does not start with a headline, or if the first
  7663. headline level is not the largest headline level in the tree.
  7664. So this will actually accept several entries of equal levels as well,
  7665. which is OK for `org-paste-subtree'.
  7666. If optional TXT is given, check this string instead of the current kill."
  7667. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7668. (re (org-get-limited-outline-regexp))
  7669. (^re (concat "^" re))
  7670. (start-level (and kill
  7671. (string-match
  7672. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7673. kill)
  7674. (- (match-end 2) (match-beginning 2) 1)))
  7675. (start (1+ (or (match-beginning 2) -1))))
  7676. (if (not start-level)
  7677. (progn
  7678. nil) ;; does not even start with a heading
  7679. (catch 'exit
  7680. (while (setq start (string-match ^re kill (1+ start)))
  7681. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7682. (throw 'exit nil)))
  7683. t))))
  7684. (defvar org-markers-to-move nil
  7685. "Markers that should be moved with a cut-and-paste operation.
  7686. Those markers are stored together with their positions relative to
  7687. the start of the region.")
  7688. (defun org-save-markers-in-region (beg end)
  7689. "Check markers in region.
  7690. If these markers are between BEG and END, record their position relative
  7691. to BEG, so that after moving the block of text, we can put the markers back
  7692. into place.
  7693. This function gets called just before an entry or tree gets cut from the
  7694. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7695. called immediately, to move the markers with the entries."
  7696. (setq org-markers-to-move nil)
  7697. (when (featurep 'org-clock)
  7698. (org-clock-save-markers-for-cut-and-paste beg end))
  7699. (when (featurep 'org-agenda)
  7700. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7701. (defun org-check-and-save-marker (marker beg end)
  7702. "Check if MARKER is between BEG and END.
  7703. If yes, remember the marker and the distance to BEG."
  7704. (when (and (marker-buffer marker)
  7705. (equal (marker-buffer marker) (current-buffer))
  7706. (>= marker beg) (< marker end))
  7707. (push (cons marker (- marker beg)) org-markers-to-move)))
  7708. (defun org-reinstall-markers-in-region (beg)
  7709. "Move all remembered markers to their position relative to BEG."
  7710. (dolist (x org-markers-to-move)
  7711. (move-marker (car x) (+ beg (cdr x))))
  7712. (setq org-markers-to-move nil))
  7713. (defun org-narrow-to-subtree ()
  7714. "Narrow buffer to the current subtree."
  7715. (interactive)
  7716. (save-excursion
  7717. (save-match-data
  7718. (org-with-limited-levels
  7719. (narrow-to-region
  7720. (progn (org-back-to-heading t) (point))
  7721. (progn (org-end-of-subtree t t)
  7722. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7723. (point)))))))
  7724. (defun org-narrow-to-block ()
  7725. "Narrow buffer to the current block."
  7726. (interactive)
  7727. (let* ((case-fold-search t)
  7728. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7729. "^[ \t]*#\\+end_.*")))
  7730. (if blockp
  7731. (narrow-to-region (car blockp) (cdr blockp))
  7732. (user-error "Not in a block"))))
  7733. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7734. "Clone the task (subtree) at point N times.
  7735. The clones will be inserted as siblings.
  7736. In interactive use, the user will be prompted for the number of
  7737. clones to be produced. If the entry has a timestamp, the user
  7738. will also be prompted for a time shift, which may be a repeater
  7739. as used in time stamps, for example `+3d'. To disable this,
  7740. you can call the function with a universal prefix argument.
  7741. When a valid repeater is given and the entry contains any time
  7742. stamps, the clones will become a sequence in time, with time
  7743. stamps in the subtree shifted for each clone produced. If SHIFT
  7744. is nil or the empty string, time stamps will be left alone. The
  7745. ID property of the original subtree is removed.
  7746. In each clone, all the CLOCK entries will be removed. This
  7747. prevents Org from considering that the clocked times overlap.
  7748. If the original subtree did contain time stamps with a repeater,
  7749. the following will happen:
  7750. - the repeater will be removed in each clone
  7751. - an additional clone will be produced, with the current, unshifted
  7752. date(s) in the entry.
  7753. - the original entry will be placed *after* all the clones, with
  7754. repeater intact.
  7755. - the start days in the repeater in the original entry will be shifted
  7756. to past the last clone.
  7757. In this way you can spell out a number of instances of a repeating task,
  7758. and still retain the repeater to cover future instances of the task.
  7759. As described above, N+1 clones are produced when the original
  7760. subtree has a repeater. Setting N to 0, then, can be used to
  7761. remove the repeater from a subtree and create a shifted clone
  7762. with the original repeater."
  7763. (interactive "nNumber of clones to produce: ")
  7764. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7765. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7766. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7767. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7768. (shift
  7769. (or shift
  7770. (if (and (not (equal current-prefix-arg '(4)))
  7771. (save-excursion
  7772. (goto-char beg)
  7773. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7774. (read-from-minibuffer
  7775. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7776. ""))) ;No time shift
  7777. (doshift
  7778. (and (org-string-nw-p shift)
  7779. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7780. shift)
  7781. (user-error "Invalid shift specification %s" shift)))))
  7782. (goto-char end-of-tree)
  7783. (unless (bolp) (insert "\n"))
  7784. (let* ((end (point))
  7785. (template (buffer-substring beg end))
  7786. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7787. (shift-what (pcase (and doshift (match-string 2 shift))
  7788. (`nil nil)
  7789. ("d" 'day)
  7790. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7791. ("m" 'month)
  7792. ("y" 'year)
  7793. (_ (error "Unsupported time unit"))))
  7794. (nmin 1)
  7795. (nmax n)
  7796. (n-no-remove -1)
  7797. (idprop (org-entry-get nil "ID")))
  7798. (when (and doshift
  7799. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7800. template))
  7801. (delete-region beg end)
  7802. (setq end beg)
  7803. (setq nmin 0)
  7804. (setq nmax (1+ nmax))
  7805. (setq n-no-remove nmax))
  7806. (goto-char end)
  7807. (cl-loop for n from nmin to nmax do
  7808. (insert
  7809. ;; Prepare clone.
  7810. (with-temp-buffer
  7811. (insert template)
  7812. (org-mode)
  7813. (goto-char (point-min))
  7814. (org-show-subtree)
  7815. (and idprop (if org-clone-delete-id
  7816. (org-entry-delete nil "ID")
  7817. (org-id-get-create t)))
  7818. (unless (= n 0)
  7819. (while (re-search-forward org-clock-line-re nil t)
  7820. (delete-region (line-beginning-position)
  7821. (line-beginning-position 2)))
  7822. (goto-char (point-min))
  7823. (while (re-search-forward org-drawer-regexp nil t)
  7824. (org-remove-empty-drawer-at (point))))
  7825. (goto-char (point-min))
  7826. (when doshift
  7827. (while (re-search-forward org-ts-regexp-both nil t)
  7828. (org-timestamp-change (* n shift-n) shift-what))
  7829. (unless (= n n-no-remove)
  7830. (goto-char (point-min))
  7831. (while (re-search-forward org-ts-regexp nil t)
  7832. (save-excursion
  7833. (goto-char (match-beginning 0))
  7834. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7835. (delete-region (match-beginning 1) (match-end 1)))))))
  7836. (buffer-string)))))
  7837. (goto-char beg)))
  7838. ;;; Outline Sorting
  7839. (defun org-sort (&optional with-case)
  7840. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7841. Optional argument WITH-CASE means sort case-sensitively."
  7842. (interactive "P")
  7843. (org-call-with-arg
  7844. (cond ((org-at-table-p) #'org-table-sort-lines)
  7845. ((org-at-item-p) #'org-sort-list)
  7846. (t #'org-sort-entries))
  7847. with-case))
  7848. (defun org-sort-remove-invisible (s)
  7849. "Remove invisible part of links and emphasis markers from string S."
  7850. (remove-text-properties 0 (length s) org-rm-props s)
  7851. (replace-regexp-in-string
  7852. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7853. (replace-regexp-in-string
  7854. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7855. (org-link-display-format s)
  7856. t t) t t))
  7857. (defvar org-priority-regexp) ; defined later in the file
  7858. (defvar org-after-sorting-entries-or-items-hook nil
  7859. "Hook that is run after a bunch of entries or items have been sorted.
  7860. When children are sorted, the cursor is in the parent line when this
  7861. hook gets called. When a region or a plain list is sorted, the cursor
  7862. will be in the first entry of the sorted region/list.")
  7863. (defun org-sort-entries
  7864. (&optional with-case sorting-type getkey-func compare-func property
  7865. interactive?)
  7866. "Sort entries on a certain level of an outline tree.
  7867. If there is an active region, the entries in the region are sorted.
  7868. Else, if the cursor is before the first entry, sort the top-level items.
  7869. Else, the children of the entry at point are sorted.
  7870. Sorting can be alphabetically, numerically, by date/time as given by
  7871. a time stamp, by a property, by priority order, or by a custom function.
  7872. The command prompts for the sorting type unless it has been given to the
  7873. function through the SORTING-TYPE argument, which needs to be a character,
  7874. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7875. the precise meaning of each character:
  7876. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7877. c By creation time, which is assumed to be the first inactive time stamp
  7878. at the beginning of a line.
  7879. d By deadline date/time.
  7880. k By clocking time.
  7881. n Numerically, by converting the beginning of the entry/item to a number.
  7882. o By order of TODO keywords.
  7883. p By priority according to the cookie.
  7884. r By the value of a property.
  7885. s By scheduled date/time.
  7886. t By date/time, either the first active time stamp in the entry, or, if
  7887. none exist, by the first inactive one.
  7888. Capital letters will reverse the sort order.
  7889. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7890. called with point at the beginning of the record. It must return a
  7891. value that is compatible with COMPARE-FUNC, the function used to
  7892. compare entries.
  7893. Comparing entries ignores case by default. However, with an optional argument
  7894. WITH-CASE, the sorting considers case as well.
  7895. Sorting is done against the visible part of the headlines, it ignores hidden
  7896. links.
  7897. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7898. A non-nil value for INTERACTIVE? is used to signal that this
  7899. function is being called interactively."
  7900. (interactive (list current-prefix-arg nil nil nil nil t))
  7901. (let ((case-func (if with-case 'identity 'downcase))
  7902. start beg end stars re re2
  7903. txt what tmp)
  7904. ;; Find beginning and end of region to sort
  7905. (cond
  7906. ((org-region-active-p)
  7907. ;; we will sort the region
  7908. (setq end (region-end)
  7909. what "region")
  7910. (goto-char (region-beginning))
  7911. (unless (org-at-heading-p) (outline-next-heading))
  7912. (setq start (point)))
  7913. ((or (org-at-heading-p)
  7914. (ignore-errors (progn (org-back-to-heading) t)))
  7915. ;; we will sort the children of the current headline
  7916. (org-back-to-heading)
  7917. (setq start (point)
  7918. end (progn (org-end-of-subtree t t)
  7919. (or (bolp) (insert "\n"))
  7920. (when (>= (org-back-over-empty-lines) 1)
  7921. (forward-line 1))
  7922. (point))
  7923. what "children")
  7924. (goto-char start)
  7925. (outline-show-subtree)
  7926. (outline-next-heading))
  7927. (t
  7928. ;; we will sort the top-level entries in this file
  7929. (goto-char (point-min))
  7930. (or (org-at-heading-p) (outline-next-heading))
  7931. (setq start (point))
  7932. (goto-char (point-max))
  7933. (beginning-of-line 1)
  7934. (when (looking-at ".*?\\S-")
  7935. ;; File ends in a non-white line
  7936. (end-of-line 1)
  7937. (insert "\n"))
  7938. (setq end (point-max))
  7939. (setq what "top-level")
  7940. (goto-char start)
  7941. (outline-show-all)))
  7942. (setq beg (point))
  7943. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7944. (looking-at "\\(\\*+\\)")
  7945. (setq stars (match-string 1)
  7946. re (concat "^" (regexp-quote stars) " +")
  7947. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7948. txt (buffer-substring beg end))
  7949. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7950. (when (and (not (equal stars "*")) (string-match re2 txt))
  7951. (user-error "Region to sort contains a level above the first entry"))
  7952. (unless sorting-type
  7953. (message
  7954. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7955. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7956. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7957. what)
  7958. (setq sorting-type (read-char-exclusive)))
  7959. (unless getkey-func
  7960. (and (= (downcase sorting-type) ?f)
  7961. (setq getkey-func
  7962. (or (and interactive?
  7963. (org-read-function
  7964. "Function for extracting keys: "))
  7965. (error "Missing key extractor")))))
  7966. (and (= (downcase sorting-type) ?r)
  7967. (not property)
  7968. (setq property
  7969. (completing-read "Property: "
  7970. (mapcar #'list (org-buffer-property-keys t))
  7971. nil t)))
  7972. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7973. (message "Sorting entries...")
  7974. (save-restriction
  7975. (narrow-to-region start end)
  7976. (let ((restore-clock?
  7977. ;; The clock marker is lost when using `sort-subr'; mark
  7978. ;; the clock with temporary `:org-clock-marker-backup'
  7979. ;; text property.
  7980. (when (and (eq (org-clocking-buffer) (current-buffer))
  7981. (<= start (marker-position org-clock-marker))
  7982. (>= end (marker-position org-clock-marker)))
  7983. (org-with-silent-modifications
  7984. (put-text-property (1- org-clock-marker) org-clock-marker
  7985. :org-clock-marker-backup t))
  7986. t))
  7987. (dcst (downcase sorting-type))
  7988. (case-fold-search nil)
  7989. (now (current-time)))
  7990. (sort-subr
  7991. (/= dcst sorting-type)
  7992. ;; This function moves to the beginning character of the "record" to
  7993. ;; be sorted.
  7994. (lambda nil
  7995. (if (re-search-forward re nil t)
  7996. (goto-char (match-beginning 0))
  7997. (goto-char (point-max))))
  7998. ;; This function moves to the last character of the "record" being
  7999. ;; sorted.
  8000. (lambda nil
  8001. (save-match-data
  8002. (condition-case nil
  8003. (outline-forward-same-level 1)
  8004. (error
  8005. (goto-char (point-max))))))
  8006. ;; This function returns the value that gets sorted against.
  8007. (lambda nil
  8008. (cond
  8009. ((= dcst ?n)
  8010. (if (looking-at org-complex-heading-regexp)
  8011. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8012. nil))
  8013. ((= dcst ?a)
  8014. (if (looking-at org-complex-heading-regexp)
  8015. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8016. nil))
  8017. ((= dcst ?k)
  8018. (or (get-text-property (point) :org-clock-minutes) 0))
  8019. ((= dcst ?t)
  8020. (let ((end (save-excursion (outline-next-heading) (point))))
  8021. (if (or (re-search-forward org-ts-regexp end t)
  8022. (re-search-forward org-ts-regexp-both end t))
  8023. (org-time-string-to-seconds (match-string 0))
  8024. (float-time now))))
  8025. ((= dcst ?c)
  8026. (let ((end (save-excursion (outline-next-heading) (point))))
  8027. (if (re-search-forward
  8028. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8029. end t)
  8030. (org-time-string-to-seconds (match-string 0))
  8031. (float-time now))))
  8032. ((= dcst ?s)
  8033. (let ((end (save-excursion (outline-next-heading) (point))))
  8034. (if (re-search-forward org-scheduled-time-regexp end t)
  8035. (org-time-string-to-seconds (match-string 1))
  8036. (float-time now))))
  8037. ((= dcst ?d)
  8038. (let ((end (save-excursion (outline-next-heading) (point))))
  8039. (if (re-search-forward org-deadline-time-regexp end t)
  8040. (org-time-string-to-seconds (match-string 1))
  8041. (float-time now))))
  8042. ((= dcst ?p)
  8043. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8044. (string-to-char (match-string 2))
  8045. org-default-priority))
  8046. ((= dcst ?r)
  8047. (or (org-entry-get nil property) ""))
  8048. ((= dcst ?o)
  8049. (when (looking-at org-complex-heading-regexp)
  8050. (let* ((m (match-string 2))
  8051. (s (if (member m org-done-keywords) '- '+)))
  8052. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8053. ((= dcst ?f)
  8054. (if getkey-func
  8055. (progn
  8056. (setq tmp (funcall getkey-func))
  8057. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8058. tmp)
  8059. (error "Invalid key function `%s'" getkey-func)))
  8060. (t (error "Invalid sorting type `%c'" sorting-type))))
  8061. nil
  8062. (cond
  8063. ((= dcst ?a) 'string<)
  8064. ((= dcst ?f)
  8065. (or compare-func
  8066. (and interactive?
  8067. (org-read-function
  8068. (concat "Function for comparing keys "
  8069. "(empty for default `sort-subr' predicate): ")
  8070. 'allow-empty))))
  8071. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  8072. (when restore-clock?
  8073. (move-marker org-clock-marker
  8074. (1+ (next-single-property-change
  8075. start :org-clock-marker-backup)))
  8076. (remove-text-properties (1- org-clock-marker) org-clock-marker
  8077. '(:org-clock-marker-backup t)))))
  8078. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8079. (message "Sorting entries...done")))
  8080. ;;; The orgstruct minor mode
  8081. ;; Define a minor mode which can be used in other modes in order to
  8082. ;; integrate the Org mode structure editing commands.
  8083. ;; This is really a hack, because the Org mode structure commands use
  8084. ;; keys which normally belong to the major mode. Here is how it
  8085. ;; works: The minor mode defines all the keys necessary to operate the
  8086. ;; structure commands, but wraps the commands into a function which
  8087. ;; tests if the cursor is currently at a headline or a plain list
  8088. ;; item. If that is the case, the structure command is used,
  8089. ;; temporarily setting many Org mode variables like regular
  8090. ;; expressions for filling etc. However, when any of those keys is
  8091. ;; used at a different location, function uses `key-binding' to look
  8092. ;; up if the key has an associated command in another currently active
  8093. ;; keymap (minor modes, major mode, global), and executes that
  8094. ;; command. There might be problems if any of the keys is otherwise
  8095. ;; used as a prefix key.
  8096. (defcustom orgstruct-heading-prefix-regexp ""
  8097. "Regexp that matches the custom prefix of Org headlines in
  8098. orgstruct(++)-mode."
  8099. :group 'org
  8100. :version "24.4"
  8101. :package-version '(Org . "8.3")
  8102. :type 'regexp)
  8103. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8104. (defcustom orgstruct-setup-hook nil
  8105. "Hook run after orgstruct-mode-map is filled."
  8106. :group 'org
  8107. :version "24.4"
  8108. :package-version '(Org . "8.0")
  8109. :type 'hook)
  8110. (defvar orgstruct-initialized nil)
  8111. (defvar org-local-vars nil
  8112. "List of local variables, for use by `orgstruct-mode'.")
  8113. ;;;###autoload
  8114. (define-minor-mode orgstruct-mode
  8115. "Toggle the minor mode `orgstruct-mode'.
  8116. This mode is for using Org mode structure commands in other
  8117. modes. The following keys behave as if Org mode were active, if
  8118. the cursor is on a headline, or on a plain list item (both as
  8119. defined by Org mode)."
  8120. nil " OrgStruct" (make-sparse-keymap)
  8121. (funcall (if orgstruct-mode
  8122. 'add-to-invisibility-spec
  8123. 'remove-from-invisibility-spec)
  8124. '(outline . t))
  8125. (when orgstruct-mode
  8126. (org-load-modules-maybe)
  8127. (unless orgstruct-initialized
  8128. (orgstruct-setup)
  8129. (setq orgstruct-initialized t))))
  8130. ;;;###autoload
  8131. (defun turn-on-orgstruct ()
  8132. "Unconditionally turn on `orgstruct-mode'."
  8133. (orgstruct-mode 1))
  8134. (defvar-local orgstruct-is-++ nil
  8135. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8136. (defvar-local org-fb-vars nil)
  8137. (defun orgstruct++-mode (&optional arg)
  8138. "Toggle `orgstruct-mode', the enhanced version of it.
  8139. In addition to setting orgstruct-mode, this also exports all
  8140. indentation and autofilling variables from Org mode into the
  8141. buffer. It will also recognize item context in multiline items."
  8142. (interactive "P")
  8143. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8144. (if (< arg 1)
  8145. (progn (orgstruct-mode -1)
  8146. (dolist (v org-fb-vars)
  8147. (set (make-local-variable (car v))
  8148. (if (eq (car-safe (cadr v)) 'quote)
  8149. (cl-cadadr v)
  8150. (nth 1 v)))))
  8151. (orgstruct-mode 1)
  8152. (setq org-fb-vars nil)
  8153. (unless org-local-vars
  8154. (setq org-local-vars (org-get-local-variables)))
  8155. (let (var val)
  8156. (dolist (x org-local-vars)
  8157. (when (string-match
  8158. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8159. \\|fill-prefix\\|indent-\\)"
  8160. (symbol-name (car x)))
  8161. (setq var (car x) val (nth 1 x))
  8162. (push (list var `(quote ,(eval var))) org-fb-vars)
  8163. (set (make-local-variable var)
  8164. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8165. (setq-local orgstruct-is-++ t))))
  8166. ;;;###autoload
  8167. (defun turn-on-orgstruct++ ()
  8168. "Unconditionally turn on `orgstruct++-mode'."
  8169. (orgstruct++-mode 1))
  8170. (defun orgstruct-error ()
  8171. "Error when there is no default binding for a structure key."
  8172. (interactive)
  8173. (funcall (if (fboundp 'user-error)
  8174. 'user-error
  8175. 'error)
  8176. "This key has no function outside structure elements"))
  8177. (defun orgstruct-setup ()
  8178. "Setup orgstruct keymap."
  8179. (dolist (cell '((org-demote . t)
  8180. (org-metaleft . t)
  8181. (org-metaright . t)
  8182. (org-promote . t)
  8183. (org-shiftmetaleft . t)
  8184. (org-shiftmetaright . t)
  8185. org-backward-element
  8186. org-backward-heading-same-level
  8187. org-ctrl-c-ret
  8188. org-ctrl-c-minus
  8189. org-ctrl-c-star
  8190. org-cycle
  8191. org-force-cycle-archived
  8192. org-forward-heading-same-level
  8193. org-insert-heading
  8194. org-insert-heading-respect-content
  8195. org-kill-note-or-show-branches
  8196. org-mark-subtree
  8197. org-meta-return
  8198. org-metadown
  8199. org-metaup
  8200. org-narrow-to-subtree
  8201. org-promote-subtree
  8202. org-reveal
  8203. org-shiftdown
  8204. org-shiftleft
  8205. org-shiftmetadown
  8206. org-shiftmetaup
  8207. org-shiftright
  8208. org-shifttab
  8209. org-shifttab
  8210. org-shiftup
  8211. org-show-children
  8212. org-show-subtree
  8213. org-sort
  8214. org-up-element
  8215. outline-demote
  8216. outline-next-visible-heading
  8217. outline-previous-visible-heading
  8218. outline-promote
  8219. outline-up-heading))
  8220. (let ((f (or (car-safe cell) cell))
  8221. (disable-when-heading-prefix (cdr-safe cell)))
  8222. (when (fboundp f)
  8223. (let ((new-bindings))
  8224. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8225. (where-is-internal f outline-mode-map)))
  8226. (push binding new-bindings)
  8227. ;; TODO use local-function-key-map
  8228. (dolist (rep '(("<tab>" . "TAB")
  8229. ("<return>" . "RET")
  8230. ("<escape>" . "ESC")
  8231. ("<delete>" . "DEL")))
  8232. (setq binding (read-kbd-macro
  8233. (let ((case-fold-search))
  8234. (replace-regexp-in-string
  8235. (regexp-quote (cdr rep))
  8236. (car rep)
  8237. (key-description binding)))))
  8238. (cl-pushnew binding new-bindings :test 'equal)))
  8239. (dolist (binding new-bindings)
  8240. (let ((key (lookup-key orgstruct-mode-map binding)))
  8241. (when (or (not key) (numberp key))
  8242. (ignore-errors
  8243. (org-defkey orgstruct-mode-map
  8244. binding
  8245. (orgstruct-make-binding
  8246. f binding disable-when-heading-prefix))))))))))
  8247. (run-hooks 'orgstruct-setup-hook))
  8248. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8249. "Create a function for binding in the structure minor mode.
  8250. FUN is the command to call inside a table. KEY is the key that
  8251. should be checked in for a command to execute outside of tables.
  8252. Non-nil `disable-when-heading-prefix' means to disable the command
  8253. if `orgstruct-heading-prefix-regexp' is not empty."
  8254. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8255. (let ((nname name)
  8256. (i 0))
  8257. (while (fboundp (intern nname))
  8258. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8259. (setq name (intern nname)))
  8260. (eval
  8261. (let ((bindings '((org-heading-regexp
  8262. (concat "^"
  8263. orgstruct-heading-prefix-regexp
  8264. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8265. (org-outline-regexp
  8266. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8267. (org-outline-regexp-bol
  8268. (concat "^" org-outline-regexp))
  8269. (outline-regexp org-outline-regexp)
  8270. (outline-heading-end-regexp "\n")
  8271. (outline-level 'org-outline-level)
  8272. (outline-heading-alist))))
  8273. `(defun ,name (arg)
  8274. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8275. "Outside of structure, run the binding of `"
  8276. (key-description key) "'."
  8277. (when disable-when-heading-prefix
  8278. (concat
  8279. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8280. "back to the default binding due to limitations of Org's implementation of\n"
  8281. "`" (symbol-name fun) "'.")))
  8282. (interactive "p")
  8283. (let* ((disable
  8284. ,(and disable-when-heading-prefix
  8285. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8286. (fallback
  8287. (or disable
  8288. (not
  8289. (let* ,bindings
  8290. (org-context-p 'headline 'item
  8291. ,(when (memq fun
  8292. '(org-insert-heading
  8293. org-insert-heading-respect-content
  8294. org-meta-return))
  8295. '(when orgstruct-is-++
  8296. 'item-body))))))))
  8297. (if fallback
  8298. (let* ((orgstruct-mode)
  8299. (binding
  8300. (let ((key ,key))
  8301. (catch 'exit
  8302. (dolist
  8303. (rep
  8304. '(nil
  8305. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8306. ("<\\([^>]*\\)return>" . "\\1RET")
  8307. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8308. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8309. nil)
  8310. (when rep
  8311. (setq key (read-kbd-macro
  8312. (let ((case-fold-search))
  8313. (replace-regexp-in-string
  8314. (car rep)
  8315. (cdr rep)
  8316. (key-description key))))))
  8317. (when (key-binding key)
  8318. (throw 'exit (key-binding key))))))))
  8319. (if (keymapp binding)
  8320. (org-set-transient-map binding)
  8321. (let ((func (or binding
  8322. (unless disable
  8323. 'orgstruct-error))))
  8324. (when func
  8325. (call-interactively func)))))
  8326. (org-run-like-in-org-mode
  8327. (lambda ()
  8328. (interactive)
  8329. (let* ,bindings
  8330. (call-interactively ',fun)))))))))
  8331. name))
  8332. (defun org-contextualize-keys (alist contexts)
  8333. "Return valid elements in ALIST depending on CONTEXTS.
  8334. `org-agenda-custom-commands' or `org-capture-templates' are the
  8335. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8336. or `org-capture-templates-contexts' are the associated contexts
  8337. definitions."
  8338. (let ((contexts
  8339. ;; normalize contexts
  8340. (mapcar
  8341. (lambda(c) (cond ((listp (cadr c))
  8342. (list (car c) (car c) (nth 1 c)))
  8343. ((string= "" (cadr c))
  8344. (list (car c) (car c) (nth 2 c)))
  8345. (t c)))
  8346. contexts))
  8347. (a alist) r s)
  8348. ;; loop over all commands or templates
  8349. (dolist (c a)
  8350. (let (vrules repl)
  8351. (cond
  8352. ((not (assoc (car c) contexts))
  8353. (push c r))
  8354. ((and (assoc (car c) contexts)
  8355. (setq vrules (org-contextualize-validate-key
  8356. (car c) contexts)))
  8357. (mapc (lambda (vr)
  8358. (unless (equal (car vr) (cadr vr))
  8359. (setq repl vr)))
  8360. vrules)
  8361. (if (not repl) (push c r)
  8362. (push (cadr repl) s)
  8363. (push
  8364. (cons (car c)
  8365. (cdr (or (assoc (cadr repl) alist)
  8366. (error "Undefined key `%s' as contextual replacement for `%s'"
  8367. (cadr repl) (car c)))))
  8368. r))))))
  8369. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8370. (delq
  8371. nil
  8372. (delete-dups
  8373. (mapcar (lambda (x)
  8374. (let ((tpl (car x)))
  8375. (unless (delq
  8376. nil
  8377. (mapcar (lambda (y)
  8378. (equal y tpl))
  8379. s))
  8380. x)))
  8381. (reverse r))))))
  8382. (defun org-contextualize-validate-key (key contexts)
  8383. "Check CONTEXTS for agenda or capture KEY."
  8384. (let (res)
  8385. (dolist (r contexts)
  8386. (dolist (rr (car (last r)))
  8387. (when
  8388. (and (equal key (car r))
  8389. (if (functionp rr) (funcall rr)
  8390. (or (and (eq (car rr) 'in-file)
  8391. (buffer-file-name)
  8392. (string-match (cdr rr) (buffer-file-name)))
  8393. (and (eq (car rr) 'in-mode)
  8394. (string-match (cdr rr) (symbol-name major-mode)))
  8395. (and (eq (car rr) 'in-buffer)
  8396. (string-match (cdr rr) (buffer-name)))
  8397. (when (and (eq (car rr) 'not-in-file)
  8398. (buffer-file-name))
  8399. (not (string-match (cdr rr) (buffer-file-name))))
  8400. (when (eq (car rr) 'not-in-mode)
  8401. (not (string-match (cdr rr) (symbol-name major-mode))))
  8402. (when (eq (car rr) 'not-in-buffer)
  8403. (not (string-match (cdr rr) (buffer-name)))))))
  8404. (push r res))))
  8405. (delete-dups (delq nil res))))
  8406. (defun org-context-p (&rest contexts)
  8407. "Check if local context is any of CONTEXTS.
  8408. Possible values in the list of contexts are `table', `headline', and `item'."
  8409. (let ((pos (point)))
  8410. (goto-char (point-at-bol))
  8411. (prog1 (or (and (memq 'table contexts)
  8412. (looking-at "[ \t]*|"))
  8413. (and (memq 'headline contexts)
  8414. (looking-at org-outline-regexp))
  8415. (and (memq 'item contexts)
  8416. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8417. (and (memq 'item-body contexts)
  8418. (org-in-item-p)))
  8419. (goto-char pos))))
  8420. ;;;###autoload
  8421. (defun org-run-like-in-org-mode (cmd)
  8422. "Run a command, pretending that the current buffer is in Org mode.
  8423. This will temporarily bind local variables that are typically bound in
  8424. Org mode to the values they have in Org mode, and then interactively
  8425. call CMD."
  8426. (org-load-modules-maybe)
  8427. (unless org-local-vars
  8428. (setq org-local-vars (org-get-local-variables)))
  8429. (let (binds)
  8430. (dolist (var org-local-vars)
  8431. (when (or (not (boundp (car var)))
  8432. (eq (symbol-value (car var))
  8433. (default-value (car var))))
  8434. (push (list (car var) `(quote ,(cadr var))) binds)))
  8435. (eval `(let ,binds
  8436. (call-interactively (quote ,cmd))))))
  8437. (defun org-get-category (&optional pos force-refresh)
  8438. "Get the category applying to position POS."
  8439. (save-match-data
  8440. (when force-refresh (org-refresh-category-properties))
  8441. (let ((pos (or pos (point))))
  8442. (or (get-text-property pos 'org-category)
  8443. (progn (org-refresh-category-properties)
  8444. (get-text-property pos 'org-category))))))
  8445. ;;; Refresh properties
  8446. (defun org-refresh-properties (dprop tprop)
  8447. "Refresh buffer text properties.
  8448. DPROP is the drawer property and TPROP is either the
  8449. corresponding text property to set, or an alist with each element
  8450. being a text property (as a symbol) and a function to apply to
  8451. the value of the drawer property."
  8452. (let* ((case-fold-search t)
  8453. (inhibit-read-only t)
  8454. (inherit? (org-property-inherit-p dprop))
  8455. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8456. (global (and inherit? (org--property-global-value dprop nil))))
  8457. (org-with-silent-modifications
  8458. (org-with-point-at 1
  8459. ;; Set global values (e.g., values defined through
  8460. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8461. (when global (put-text-property (point-min) (point-max) tprop global))
  8462. ;; Set local values.
  8463. (while (re-search-forward property-re nil t)
  8464. (when (org-at-property-p)
  8465. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8466. (outline-next-heading))))))
  8467. (defun org-refresh-property (tprop p &optional inherit)
  8468. "Refresh the buffer text property TPROP from the drawer property P.
  8469. The refresh happens only for the current headline, or the whole
  8470. sub-tree if optional argument INHERIT is non-nil."
  8471. (unless (org-before-first-heading-p)
  8472. (save-excursion
  8473. (org-back-to-heading t)
  8474. (let ((start (point))
  8475. (end (save-excursion
  8476. (if inherit (org-end-of-subtree t t)
  8477. (or (outline-next-heading) (point-max))))))
  8478. (if (symbolp tprop)
  8479. ;; TPROP is a text property symbol.
  8480. (put-text-property start end tprop p)
  8481. ;; TPROP is an alist with (property . function) elements.
  8482. (pcase-dolist (`(,prop . ,f) tprop)
  8483. (put-text-property start end prop (funcall f p))))))))
  8484. (defun org-refresh-category-properties ()
  8485. "Refresh category text properties in the buffer."
  8486. (let ((case-fold-search t)
  8487. (inhibit-read-only t)
  8488. (default-category
  8489. (cond ((null org-category)
  8490. (if buffer-file-name
  8491. (file-name-sans-extension
  8492. (file-name-nondirectory buffer-file-name))
  8493. "???"))
  8494. ((symbolp org-category) (symbol-name org-category))
  8495. (t org-category))))
  8496. (org-with-silent-modifications
  8497. (org-with-wide-buffer
  8498. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8499. ;; This is the default category for the buffer. If none is
  8500. ;; found, fall-back to `org-category' or buffer file name.
  8501. (put-text-property
  8502. (point-min) (point-max)
  8503. 'org-category
  8504. (catch 'buffer-category
  8505. (goto-char (point-max))
  8506. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8507. (let ((element (org-element-at-point)))
  8508. (when (eq (org-element-type element) 'keyword)
  8509. (throw 'buffer-category
  8510. (org-element-property :value element)))))
  8511. default-category))
  8512. ;; Set sub-tree specific categories.
  8513. (goto-char (point-min))
  8514. (let ((regexp (org-re-property "CATEGORY")))
  8515. (while (re-search-forward regexp nil t)
  8516. (let ((value (match-string-no-properties 3)))
  8517. (when (org-at-property-p)
  8518. (put-text-property
  8519. (save-excursion (org-back-to-heading t) (point))
  8520. (save-excursion (org-end-of-subtree t t) (point))
  8521. 'org-category
  8522. value)))))))))
  8523. (defun org-refresh-stats-properties ()
  8524. "Refresh stats text properties in the buffer."
  8525. (org-with-silent-modifications
  8526. (org-with-point-at 1
  8527. (let ((regexp (concat org-outline-regexp-bol
  8528. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8529. (while (re-search-forward regexp nil t)
  8530. (let* ((numerator (string-to-number (match-string 1)))
  8531. (denominator (and (match-end 2)
  8532. (string-to-number (match-string 2))))
  8533. (stats (cond ((not denominator) numerator) ;percent
  8534. ((= denominator 0) 0)
  8535. (t (/ (* numerator 100) denominator)))))
  8536. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8537. 'org-stats stats)))))))
  8538. (defun org-refresh-effort-properties ()
  8539. "Refresh effort properties"
  8540. (org-refresh-properties
  8541. org-effort-property
  8542. '((effort . identity)
  8543. (effort-minutes . org-duration-to-minutes))))
  8544. ;;;; Link Stuff
  8545. ;;; Link abbreviations
  8546. (defun org-link-expand-abbrev (link)
  8547. "Apply replacements as defined in `org-link-abbrev-alist'."
  8548. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8549. (let* ((key (match-string 1 link))
  8550. (as (or (assoc key org-link-abbrev-alist-local)
  8551. (assoc key org-link-abbrev-alist)))
  8552. (tag (and (match-end 2) (match-string 3 link)))
  8553. rpl)
  8554. (if (not as)
  8555. link
  8556. (setq rpl (cdr as))
  8557. (cond
  8558. ((symbolp rpl) (funcall rpl tag))
  8559. ((string-match "%(\\([^)]+\\))" rpl)
  8560. (replace-match
  8561. (save-match-data
  8562. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8563. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8564. ((string-match "%h" rpl)
  8565. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8566. (t (concat rpl tag)))))
  8567. link))
  8568. ;;; Storing and inserting links
  8569. (defvar org-insert-link-history nil
  8570. "Minibuffer history for links inserted with `org-insert-link'.")
  8571. (defvar org-stored-links nil
  8572. "Contains the links stored with `org-store-link'.")
  8573. (defvar org-store-link-plist nil
  8574. "Plist with info about the most recently link created with `org-store-link'.")
  8575. (defun org-store-link-functions ()
  8576. "Return a list of functions that are called to create and store a link.
  8577. The functions defined in the :store property of
  8578. `org-link-parameters'.
  8579. Each function will be called in turn until one returns a non-nil
  8580. value. Each function should check if it is responsible for
  8581. creating this link (for example by looking at the major mode).
  8582. If not, it must exit and return nil. If yes, it should return
  8583. a non-nil value after calling `org-store-link-props' with a list
  8584. of properties and values. Special properties are:
  8585. :type The link prefix, like \"http\". This must be given.
  8586. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8587. This is obligatory as well.
  8588. :description Optional default description for the second pair
  8589. of brackets in an Org mode link. The user can still change
  8590. this when inserting this link into an Org mode buffer.
  8591. In addition to these, any additional properties can be specified
  8592. and then used in capture templates."
  8593. (cl-loop for link in org-link-parameters
  8594. with store-func
  8595. do (setq store-func (org-link-get-parameter (car link) :store))
  8596. if store-func
  8597. collect store-func))
  8598. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8599. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8600. ;;;###autoload
  8601. (defun org-store-link (arg)
  8602. "Store an org-link to the current location.
  8603. \\<org-mode-map>
  8604. This link is added to `org-stored-links' and can later be inserted
  8605. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8606. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8607. A single
  8608. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8609. `org-gnus-prefer-web-links' for links to Usenet articles.
  8610. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8611. skipping storing functions that are not
  8612. part of Org core.
  8613. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8614. prefix ARG forces storing a link for each line in the
  8615. active region."
  8616. (interactive "P")
  8617. (org-load-modules-maybe)
  8618. (if (and (equal arg '(64)) (org-region-active-p))
  8619. (save-excursion
  8620. (let ((end (region-end)))
  8621. (goto-char (region-beginning))
  8622. (set-mark (point))
  8623. (while (< (point-at-eol) end)
  8624. (move-end-of-line 1) (activate-mark)
  8625. (let (current-prefix-arg)
  8626. (call-interactively 'org-store-link))
  8627. (move-beginning-of-line 2)
  8628. (set-mark (point)))))
  8629. (setq org-store-link-plist nil)
  8630. (let (link cpltxt desc description search
  8631. txt custom-id agenda-link sfuns sfunsn)
  8632. (cond
  8633. ;; Store a link using an external link type
  8634. ((and (not (equal arg '(16)))
  8635. (setq sfuns
  8636. (delq
  8637. nil (mapcar (lambda (f)
  8638. (let (fs) (if (funcall f) (push f fs))))
  8639. (org-store-link-functions)))
  8640. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8641. (or (and (cdr sfuns)
  8642. (funcall (intern
  8643. (completing-read
  8644. "Which function for creating the link? "
  8645. sfunsn nil t (car sfunsn)))))
  8646. (funcall (caar sfuns)))
  8647. (setq link (plist-get org-store-link-plist :link)
  8648. desc (or (plist-get org-store-link-plist
  8649. :description)
  8650. link))))
  8651. ;; Store a link from a source code buffer.
  8652. ((org-src-edit-buffer-p)
  8653. (let ((coderef-format (org-src-coderef-format)))
  8654. (cond ((save-excursion
  8655. (beginning-of-line)
  8656. (looking-at (org-src-coderef-regexp coderef-format)))
  8657. (setq link (format "(%s)" (match-string-no-properties 3))))
  8658. ((called-interactively-p 'any)
  8659. (let ((label (read-string "Code line label: ")))
  8660. (end-of-line)
  8661. (setq link (format coderef-format label))
  8662. (let ((gc (- 79 (length link))))
  8663. (if (< (current-column) gc)
  8664. (org-move-to-column gc t)
  8665. (insert " ")))
  8666. (insert link)
  8667. (setq link (concat "(" label ")"))
  8668. (setq desc nil)))
  8669. (t (setq link nil)))))
  8670. ;; We are in the agenda, link to referenced location
  8671. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8672. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8673. (get-text-property (point) 'org-marker))))
  8674. (when m
  8675. (org-with-point-at m
  8676. (setq agenda-link
  8677. (if (called-interactively-p 'any)
  8678. (call-interactively 'org-store-link)
  8679. (org-store-link nil)))))))
  8680. ((eq major-mode 'calendar-mode)
  8681. (let ((cd (calendar-cursor-to-date)))
  8682. (setq link
  8683. (format-time-string
  8684. (car org-time-stamp-formats)
  8685. (apply 'encode-time
  8686. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8687. nil nil nil))))
  8688. (org-store-link-props :type "calendar" :date cd)))
  8689. ((eq major-mode 'help-mode)
  8690. (setq link (concat "help:" (save-excursion
  8691. (goto-char (point-min))
  8692. (looking-at "^[^ ]+")
  8693. (match-string 0))))
  8694. (org-store-link-props :type "help"))
  8695. ((eq major-mode 'w3-mode)
  8696. (setq cpltxt (if (and (buffer-name)
  8697. (not (string-match "Untitled" (buffer-name))))
  8698. (buffer-name)
  8699. (url-view-url t))
  8700. link (url-view-url t))
  8701. (org-store-link-props :type "w3" :url (url-view-url t)))
  8702. ((eq major-mode 'image-mode)
  8703. (setq cpltxt (concat "file:"
  8704. (abbreviate-file-name buffer-file-name))
  8705. link cpltxt)
  8706. (org-store-link-props :type "image" :file buffer-file-name))
  8707. ;; In dired, store a link to the file of the current line
  8708. ((derived-mode-p 'dired-mode)
  8709. (let ((file (dired-get-filename nil t)))
  8710. (setq file (if file
  8711. (abbreviate-file-name
  8712. (expand-file-name (dired-get-filename nil t)))
  8713. ;; otherwise, no file so use current directory.
  8714. default-directory))
  8715. (setq cpltxt (concat "file:" file)
  8716. link cpltxt)))
  8717. ((setq search (run-hook-with-args-until-success
  8718. 'org-create-file-search-functions))
  8719. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8720. "::" search))
  8721. (setq cpltxt (or description link)))
  8722. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8723. (org-with-limited-levels
  8724. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8725. (cond
  8726. ;; Store a link using the target at point
  8727. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8728. (setq cpltxt
  8729. (concat "file:"
  8730. (abbreviate-file-name
  8731. (buffer-file-name (buffer-base-buffer)))
  8732. "::" (match-string 1))
  8733. link cpltxt))
  8734. ((and (featurep 'org-id)
  8735. (or (eq org-id-link-to-org-use-id t)
  8736. (and (called-interactively-p 'any)
  8737. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8738. (and (eq org-id-link-to-org-use-id
  8739. 'create-if-interactive-and-no-custom-id)
  8740. (not custom-id))))
  8741. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8742. ;; Store a link using the ID at point
  8743. (setq link (condition-case nil
  8744. (prog1 (org-id-store-link)
  8745. (setq desc (or (plist-get org-store-link-plist
  8746. :description)
  8747. "")))
  8748. (error
  8749. ;; Probably before first headline, link only to file
  8750. (concat "file:"
  8751. (abbreviate-file-name
  8752. (buffer-file-name (buffer-base-buffer))))))))
  8753. (t
  8754. ;; Just link to current headline
  8755. (setq cpltxt (concat "file:"
  8756. (abbreviate-file-name
  8757. (buffer-file-name (buffer-base-buffer)))))
  8758. ;; Add a context search string
  8759. (when (org-xor org-context-in-file-links
  8760. (equal arg '(4)))
  8761. (let* ((element (org-element-at-point))
  8762. (name (org-element-property :name element)))
  8763. (setq txt (cond
  8764. ((org-at-heading-p) nil)
  8765. (name)
  8766. ((org-region-active-p)
  8767. (buffer-substring (region-beginning) (region-end)))))
  8768. (when (or (null txt) (string-match "\\S-" txt))
  8769. (setq cpltxt
  8770. (concat cpltxt "::"
  8771. (condition-case nil
  8772. (org-make-org-heading-search-string txt)
  8773. (error "")))
  8774. desc (or name
  8775. (nth 4 (ignore-errors (org-heading-components)))
  8776. "NONE")))))
  8777. (when (string-match "::\\'" cpltxt)
  8778. (setq cpltxt (substring cpltxt 0 -2)))
  8779. (setq link cpltxt)))))
  8780. ((buffer-file-name (buffer-base-buffer))
  8781. ;; Just link to this file here.
  8782. (setq cpltxt (concat "file:"
  8783. (abbreviate-file-name
  8784. (buffer-file-name (buffer-base-buffer)))))
  8785. ;; Add a context string.
  8786. (when (org-xor org-context-in-file-links
  8787. (equal arg '(4)))
  8788. (setq txt (if (org-region-active-p)
  8789. (buffer-substring (region-beginning) (region-end))
  8790. (buffer-substring (point-at-bol) (point-at-eol))))
  8791. ;; Only use search option if there is some text.
  8792. (when (string-match "\\S-" txt)
  8793. (setq cpltxt
  8794. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8795. desc "NONE")))
  8796. (setq link cpltxt))
  8797. ((called-interactively-p 'interactive)
  8798. (user-error "No method for storing a link from this buffer"))
  8799. (t (setq link nil)))
  8800. ;; We're done setting link and desc, clean up
  8801. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8802. (setq link (or link cpltxt)
  8803. desc (or desc cpltxt))
  8804. (cond ((not desc))
  8805. ((equal desc "NONE") (setq desc nil))
  8806. (t (setq desc
  8807. (replace-regexp-in-string
  8808. org-bracket-link-analytic-regexp
  8809. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8810. desc))))
  8811. ;; Return the link
  8812. (if (not (and (or (called-interactively-p 'any)
  8813. executing-kbd-macro)
  8814. link))
  8815. (or agenda-link (and link (org-make-link-string link desc)))
  8816. (push (list link desc) org-stored-links)
  8817. (message "Stored: %s" (or desc link))
  8818. (when custom-id
  8819. (setq link (concat "file:" (abbreviate-file-name
  8820. (buffer-file-name)) "::#" custom-id))
  8821. (push (list link desc) org-stored-links))
  8822. (car org-stored-links)))))
  8823. (defun org-store-link-props (&rest plist)
  8824. "Store link properties, extract names, addresses and dates."
  8825. (let ((x (plist-get plist :from)))
  8826. (when x
  8827. (let ((adr (mail-extract-address-components x)))
  8828. (setq plist (plist-put plist :fromname (car adr)))
  8829. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8830. (let ((x (plist-get plist :to)))
  8831. (when x
  8832. (let ((adr (mail-extract-address-components x)))
  8833. (setq plist (plist-put plist :toname (car adr)))
  8834. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8835. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8836. (when x
  8837. (setq plist (plist-put plist :date-timestamp
  8838. (format-time-string
  8839. (org-time-stamp-format t) x)))
  8840. (setq plist (plist-put plist :date-timestamp-inactive
  8841. (format-time-string
  8842. (org-time-stamp-format t t) x)))))
  8843. (let ((from (plist-get plist :from))
  8844. (to (plist-get plist :to)))
  8845. (when (and from to org-from-is-user-regexp)
  8846. (setq plist
  8847. (plist-put plist :fromto
  8848. (if (string-match org-from-is-user-regexp from)
  8849. (concat "to %t")
  8850. (concat "from %f"))))))
  8851. (setq org-store-link-plist plist))
  8852. (defun org-add-link-props (&rest plist)
  8853. "Add these properties to the link property list."
  8854. (let (key value)
  8855. (while plist
  8856. (setq key (pop plist) value (pop plist))
  8857. (setq org-store-link-plist
  8858. (plist-put org-store-link-plist key value)))))
  8859. (defun org-email-link-description (&optional fmt)
  8860. "Return the description part of an email link.
  8861. This takes information from `org-store-link-plist' and formats it
  8862. according to FMT (default from `org-email-link-description-format')."
  8863. (setq fmt (or fmt org-email-link-description-format))
  8864. (let* ((p org-store-link-plist)
  8865. (to (plist-get p :toaddress))
  8866. (from (plist-get p :fromaddress))
  8867. (table
  8868. (list
  8869. (cons "%c" (plist-get p :fromto))
  8870. (cons "%F" (plist-get p :from))
  8871. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8872. (cons "%T" (plist-get p :to))
  8873. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8874. (cons "%s" (plist-get p :subject))
  8875. (cons "%d" (plist-get p :date))
  8876. (cons "%m" (plist-get p :message-id)))))
  8877. (when (string-match "%c" fmt)
  8878. ;; Check if the user wrote this message
  8879. (if (and org-from-is-user-regexp from to
  8880. (save-match-data (string-match org-from-is-user-regexp from)))
  8881. (setq fmt (replace-match "to %t" t t fmt))
  8882. (setq fmt (replace-match "from %f" t t fmt))))
  8883. (org-replace-escapes fmt table)))
  8884. (defun org-make-org-heading-search-string (&optional string)
  8885. "Make search string for the current headline or STRING."
  8886. (let ((s (or string
  8887. (and (derived-mode-p 'org-mode)
  8888. (save-excursion
  8889. (org-back-to-heading t)
  8890. (org-element-property :raw-value (org-element-at-point))))))
  8891. (lines org-context-in-file-links))
  8892. (or string (setq s (concat "*" s))) ; Add * for headlines
  8893. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8894. (when (and string (integerp lines) (> lines 0))
  8895. (let ((slines (org-split-string s "\n")))
  8896. (when (< lines (length slines))
  8897. (setq s (mapconcat
  8898. 'identity
  8899. (reverse (nthcdr (- (length slines) lines)
  8900. (reverse slines))) "\n")))))
  8901. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8902. (defun org-make-link-string (link &optional description)
  8903. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8904. (unless (org-string-nw-p link) (error "Empty link"))
  8905. (let ((uri (cond ((string-match org-link-types-re link)
  8906. (concat (match-string 1 link)
  8907. (org-link-escape (substring link (match-end 1)))))
  8908. ;; For readability, url-encode internal links only
  8909. ;; when absolutely needed (i.e, when they contain
  8910. ;; square brackets). File links however, are
  8911. ;; encoded since, e.g., spaces are significant.
  8912. ((or (file-name-absolute-p link)
  8913. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8914. (org-link-escape link))
  8915. (t link)))
  8916. (description
  8917. (and (org-string-nw-p description)
  8918. ;; Remove brackets from description, as they are fatal.
  8919. (replace-regexp-in-string
  8920. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8921. (org-trim description)))))
  8922. (format "[[%s]%s]"
  8923. uri
  8924. (if description (format "[%s]" description) ""))))
  8925. (defconst org-link-escape-chars
  8926. ;;%20 %5B %5D %25
  8927. '(?\s ?\[ ?\] ?%)
  8928. "List of characters that should be escaped in a link when stored to Org.
  8929. This is the list that is used for internal purposes.")
  8930. (defun org-link-escape (text &optional table merge)
  8931. "Return percent escaped representation of TEXT.
  8932. TEXT is a string with the text to escape.
  8933. Optional argument TABLE is a list with characters that should be
  8934. escaped. When nil, `org-link-escape-chars' is used.
  8935. If optional argument MERGE is set, merge TABLE into
  8936. `org-link-escape-chars'."
  8937. (let ((characters-to-encode
  8938. (cond ((null table) org-link-escape-chars)
  8939. (merge (append org-link-escape-chars table))
  8940. (t table))))
  8941. (mapconcat
  8942. (lambda (c)
  8943. (if (or (memq c characters-to-encode)
  8944. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8945. (mapconcat (lambda (e) (format "%%%.2X" e))
  8946. (or (encode-coding-char c 'utf-8)
  8947. (error "Unable to percent escape character: %c" c))
  8948. "")
  8949. (char-to-string c)))
  8950. text "")))
  8951. (defun org-link-unescape (str)
  8952. "Unhex hexified Unicode parts in string STR.
  8953. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8954. reciprocal of `org-link-escape', which see."
  8955. (if (org-string-nw-p str)
  8956. (replace-regexp-in-string
  8957. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8958. str))
  8959. (defun org-link-unescape-compound (hex)
  8960. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8961. Note: this function also decodes single byte encodings like
  8962. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8963. (save-match-data
  8964. (let* ((bytes (cdr (split-string hex "%")))
  8965. (ret "")
  8966. (eat 0)
  8967. (sum 0))
  8968. (while bytes
  8969. (let* ((val (string-to-number (pop bytes) 16))
  8970. (shift-xor
  8971. (if (= 0 eat)
  8972. (cond
  8973. ((>= val 252) (cons 6 252))
  8974. ((>= val 248) (cons 5 248))
  8975. ((>= val 240) (cons 4 240))
  8976. ((>= val 224) (cons 3 224))
  8977. ((>= val 192) (cons 2 192))
  8978. (t (cons 0 0)))
  8979. (cons 6 128))))
  8980. (when (>= val 192) (setq eat (car shift-xor)))
  8981. (setq val (logxor val (cdr shift-xor)))
  8982. (setq sum (+ (lsh sum (car shift-xor)) val))
  8983. (when (> eat 0) (setq eat (- eat 1)))
  8984. (cond
  8985. ((= 0 eat) ;multi byte
  8986. (setq ret (concat ret (char-to-string sum)))
  8987. (setq sum 0))
  8988. ((not bytes) ; single byte(s)
  8989. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8990. ret)))
  8991. (defun org-link-unescape-single-byte-sequence (hex)
  8992. "Unhexify hex-encoded single byte character sequences."
  8993. (mapconcat (lambda (byte)
  8994. (char-to-string (string-to-number byte 16)))
  8995. (cdr (split-string hex "%")) ""))
  8996. (defun org-xor (a b)
  8997. "Exclusive or."
  8998. (if a (not b) b))
  8999. (defun org-fixup-message-id-for-http (s)
  9000. "Replace special characters in a message id, so it can be used in an http query."
  9001. (when (string-match "%" s)
  9002. (setq s (mapconcat (lambda (c)
  9003. (if (eq c ?%)
  9004. "%25"
  9005. (char-to-string c)))
  9006. s "")))
  9007. (while (string-match "<" s)
  9008. (setq s (replace-match "%3C" t t s)))
  9009. (while (string-match ">" s)
  9010. (setq s (replace-match "%3E" t t s)))
  9011. (while (string-match "@" s)
  9012. (setq s (replace-match "%40" t t s)))
  9013. s)
  9014. (defun org-link-prettify (link)
  9015. "Return a human-readable representation of LINK.
  9016. The car of LINK must be a raw link.
  9017. The cdr of LINK must be either a link description or nil."
  9018. (let ((desc (or (cadr link) "<no description>")))
  9019. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9020. "<" (car link) ">")))
  9021. ;;;###autoload
  9022. (defun org-insert-link-global ()
  9023. "Insert a link like Org mode does.
  9024. This command can be called in any mode to insert a link in Org syntax."
  9025. (interactive)
  9026. (org-load-modules-maybe)
  9027. (org-run-like-in-org-mode 'org-insert-link))
  9028. (defun org-insert-all-links (arg &optional pre post)
  9029. "Insert all links in `org-stored-links'.
  9030. When a universal prefix, do not delete the links from `org-stored-links'.
  9031. When `ARG' is a number, insert the last N link(s).
  9032. `PRE' and `POST' are optional arguments to define a string to
  9033. prepend or to append."
  9034. (interactive "P")
  9035. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9036. (links (copy-sequence org-stored-links))
  9037. (pr (or pre "- "))
  9038. (po (or post "\n"))
  9039. (cnt 1) l)
  9040. (if (null org-stored-links)
  9041. (message "No link to insert")
  9042. (while (and (or (listp arg) (>= arg cnt))
  9043. (setq l (if (listp arg)
  9044. (pop links)
  9045. (pop org-stored-links))))
  9046. (setq cnt (1+ cnt))
  9047. (insert pr)
  9048. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9049. (insert po)))))
  9050. (defun org-insert-last-stored-link (arg)
  9051. "Insert the last link stored in `org-stored-links'."
  9052. (interactive "p")
  9053. (org-insert-all-links arg "" "\n"))
  9054. (defun org-link-fontify-links-to-this-file ()
  9055. "Fontify links to the current file in `org-stored-links'."
  9056. (let ((f (buffer-file-name)) a b)
  9057. (setq a (mapcar (lambda(l)
  9058. (let ((ll (car l)))
  9059. (when (and (string-match "^file:\\(.+\\)::" ll)
  9060. (equal f (expand-file-name (match-string 1 ll))))
  9061. ll)))
  9062. org-stored-links))
  9063. (when (featurep 'org-id)
  9064. (setq b (mapcar (lambda(l)
  9065. (let ((ll (car l)))
  9066. (when (and (string-match "^id:\\(.+\\)$" ll)
  9067. (equal f (expand-file-name
  9068. (or (org-id-find-id-file
  9069. (match-string 1 ll)) ""))))
  9070. ll)))
  9071. org-stored-links)))
  9072. (mapcar (lambda(l)
  9073. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9074. (delq nil (append a b)))))
  9075. (defvar org--links-history nil)
  9076. (defun org-insert-link (&optional complete-file link-location default-description)
  9077. "Insert a link. At the prompt, enter the link.
  9078. Completion can be used to insert any of the link protocol prefixes in use.
  9079. The history can be used to select a link previously stored with
  9080. `org-store-link'. When the empty string is entered (i.e. if you just
  9081. press `RET' at the prompt), the link defaults to the most recently
  9082. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9083. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9084. You will also be prompted for a description, and if one is given, it will
  9085. be displayed in the buffer instead of the link.
  9086. If there is already a link at point, this command will allow you to edit
  9087. link and description parts.
  9088. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9089. file name can be
  9090. selected using completion. The path to the file will be relative to the
  9091. current directory if the file is in the current directory or a subdirectory.
  9092. Otherwise, the link will be the absolute path as completed in the minibuffer
  9093. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9094. option `org-link-file-path-type'.
  9095. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9096. absolute path even if the file is in
  9097. the current directory or below.
  9098. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9099. prefix negates `org-keep-stored-link-after-insertion'.
  9100. If `org-make-link-description-function' is non-nil, this function will be
  9101. called with the link target, and the result will be the default
  9102. link description.
  9103. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9104. the link location instead of reading one interactively.
  9105. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9106. as the default description."
  9107. (interactive "P")
  9108. (let* ((wcf (current-window-configuration))
  9109. (origbuf (current-buffer))
  9110. (region (when (org-region-active-p)
  9111. (buffer-substring (region-beginning) (region-end))))
  9112. (remove (and region (list (region-beginning) (region-end))))
  9113. (desc region)
  9114. (link link-location)
  9115. (abbrevs org-link-abbrev-alist-local)
  9116. entry all-prefixes auto-desc)
  9117. (cond
  9118. (link-location) ; specified by arg, just use it.
  9119. ((org-in-regexp org-bracket-link-regexp 1)
  9120. ;; We do have a link at point, and we are going to edit it.
  9121. (setq remove (list (match-beginning 0) (match-end 0)))
  9122. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9123. (setq link (read-string "Link: "
  9124. (org-link-unescape
  9125. (match-string-no-properties 1)))))
  9126. ((or (org-in-regexp org-angle-link-re)
  9127. (org-in-regexp org-plain-link-re))
  9128. ;; Convert to bracket link
  9129. (setq remove (list (match-beginning 0) (match-end 0))
  9130. link (read-string "Link: "
  9131. (org-unbracket-string "<" ">" (match-string 0)))))
  9132. ((member complete-file '((4) (16)))
  9133. ;; Completing read for file names.
  9134. (setq link (org-file-complete-link complete-file)))
  9135. (t
  9136. ;; Read link, with completion for stored links.
  9137. (org-link-fontify-links-to-this-file)
  9138. (org-switch-to-buffer-other-window "*Org Links*")
  9139. (with-current-buffer "*Org Links*"
  9140. (erase-buffer)
  9141. (insert "Insert a link.
  9142. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9143. (when org-stored-links
  9144. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9145. (insert (mapconcat 'org-link-prettify
  9146. (reverse org-stored-links) "\n")))
  9147. (goto-char (point-min)))
  9148. (let ((cw (selected-window)))
  9149. (select-window (get-buffer-window "*Org Links*" 'visible))
  9150. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9151. (unless (pos-visible-in-window-p (point-max))
  9152. (org-fit-window-to-buffer))
  9153. (and (window-live-p cw) (select-window cw)))
  9154. (setq all-prefixes (append (mapcar 'car abbrevs)
  9155. (mapcar 'car org-link-abbrev-alist)
  9156. (org-link-types)))
  9157. (unwind-protect
  9158. ;; Fake a link history, containing the stored links.
  9159. (let ((org--links-history
  9160. (append (mapcar #'car org-stored-links)
  9161. org-insert-link-history)))
  9162. (setq link
  9163. (org-completing-read
  9164. "Link: "
  9165. (append
  9166. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9167. (mapcar #'car org-stored-links))
  9168. nil nil nil
  9169. 'org--links-history
  9170. (caar org-stored-links)))
  9171. (unless (org-string-nw-p link) (user-error "No link selected"))
  9172. (dolist (l org-stored-links)
  9173. (when (equal link (cadr l))
  9174. (setq link (car l))
  9175. (setq auto-desc t)))
  9176. (when (or (member link all-prefixes)
  9177. (and (equal ":" (substring link -1))
  9178. (member (substring link 0 -1) all-prefixes)
  9179. (setq link (substring link 0 -1))))
  9180. (setq link (with-current-buffer origbuf
  9181. (org-link-try-special-completion link)))))
  9182. (set-window-configuration wcf)
  9183. (kill-buffer "*Org Links*"))
  9184. (setq entry (assoc link org-stored-links))
  9185. (or entry (push link org-insert-link-history))
  9186. (setq desc (or desc (nth 1 entry)))))
  9187. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9188. (not org-keep-stored-link-after-insertion))
  9189. (setq org-stored-links (delq (assoc link org-stored-links)
  9190. org-stored-links)))
  9191. (when (and (string-match org-plain-link-re link)
  9192. (not (string-match org-ts-regexp link)))
  9193. ;; URL-like link, normalize the use of angular brackets.
  9194. (setq link (org-unbracket-string "<" ">" link)))
  9195. ;; Check if we are linking to the current file with a search
  9196. ;; option If yes, simplify the link by using only the search
  9197. ;; option.
  9198. (when (and buffer-file-name
  9199. (let ((case-fold-search nil))
  9200. (string-match "\\`file:\\(.+?\\)::" link)))
  9201. (let ((path (match-string-no-properties 1 link))
  9202. (search (substring-no-properties link (match-end 0))))
  9203. (save-match-data
  9204. (when (equal (file-truename buffer-file-name) (file-truename path))
  9205. ;; We are linking to this same file, with a search option
  9206. (setq link search)))))
  9207. ;; Check if we can/should use a relative path. If yes, simplify the link
  9208. (let ((case-fold-search nil))
  9209. (when (string-match "\\`\\(file\\|docview\\):" link)
  9210. (let* ((type (match-string-no-properties 0 link))
  9211. (path (substring-no-properties link (match-end 0)))
  9212. (origpath path))
  9213. (cond
  9214. ((or (eq org-link-file-path-type 'absolute)
  9215. (equal complete-file '(16)))
  9216. (setq path (abbreviate-file-name (expand-file-name path))))
  9217. ((eq org-link-file-path-type 'noabbrev)
  9218. (setq path (expand-file-name path)))
  9219. ((eq org-link-file-path-type 'relative)
  9220. (setq path (file-relative-name path)))
  9221. (t
  9222. (save-match-data
  9223. (if (string-match (concat "^" (regexp-quote
  9224. (expand-file-name
  9225. (file-name-as-directory
  9226. default-directory))))
  9227. (expand-file-name path))
  9228. ;; We are linking a file with relative path name.
  9229. (setq path (substring (expand-file-name path)
  9230. (match-end 0)))
  9231. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9232. (setq link (concat type path))
  9233. (when (equal desc origpath)
  9234. (setq desc path)))))
  9235. (if org-make-link-description-function
  9236. (setq desc
  9237. (or (condition-case nil
  9238. (funcall org-make-link-description-function link desc)
  9239. (error (progn (message "Can't get link description from `%s'"
  9240. (symbol-name org-make-link-description-function))
  9241. (sit-for 2) nil)))
  9242. (read-string "Description: " default-description)))
  9243. (if default-description (setq desc default-description)
  9244. (setq desc (or (and auto-desc desc)
  9245. (read-string "Description: " desc)))))
  9246. (unless (string-match "\\S-" desc) (setq desc nil))
  9247. (when remove (apply 'delete-region remove))
  9248. (insert (org-make-link-string link desc))
  9249. ;; Redisplay so as the new link has proper invisible characters.
  9250. (sit-for 0)))
  9251. (defun org-link-try-special-completion (type)
  9252. "If there is completion support for link type TYPE, offer it."
  9253. (let ((fun (org-link-get-parameter type :complete)))
  9254. (if (functionp fun)
  9255. (funcall fun)
  9256. (read-string "Link (no completion support): " (concat type ":")))))
  9257. (defun org-file-complete-link (&optional arg)
  9258. "Create a file link using completion."
  9259. (let ((file (read-file-name "File: "))
  9260. (pwd (file-name-as-directory (expand-file-name ".")))
  9261. (pwd1 (file-name-as-directory (abbreviate-file-name
  9262. (expand-file-name ".")))))
  9263. (cond ((equal arg '(16))
  9264. (concat "file:"
  9265. (abbreviate-file-name (expand-file-name file))))
  9266. ((string-match
  9267. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9268. (concat "file:" (match-string 1 file)))
  9269. ((string-match
  9270. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9271. (expand-file-name file))
  9272. (concat "file:"
  9273. (match-string 1 (expand-file-name file))))
  9274. (t (concat "file:" file)))))
  9275. (defun org-completing-read (&rest args)
  9276. "Completing-read with SPACE being a normal character."
  9277. (let ((enable-recursive-minibuffers t)
  9278. (minibuffer-local-completion-map
  9279. (copy-keymap minibuffer-local-completion-map)))
  9280. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9281. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9282. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9283. 'org-time-stamp-inactive)
  9284. (apply #'completing-read args)))
  9285. ;;; Opening/following a link
  9286. (defvar org-link-search-failed nil)
  9287. (defvar org-open-link-functions nil
  9288. "Hook for functions finding a plain text link.
  9289. These functions must take a single argument, the link content.
  9290. They will be called for links that look like [[link text][description]]
  9291. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9292. like a filename (e.g. \"./blue.png\").
  9293. These functions will be called *before* Org attempts to resolve the
  9294. link by doing text searches in the current buffer - so if you want a
  9295. link \"[[target]]\" to still find \"<<target>>\", your function should
  9296. handle this as a special case.
  9297. When the function does handle the link, it must return a non-nil value.
  9298. If it decides that it is not responsible for this link, it must return
  9299. nil to indicate that that Org can continue with other options like
  9300. exact and fuzzy text search.")
  9301. (defun org-next-link (&optional search-backward)
  9302. "Move forward to the next link.
  9303. If the link is in hidden text, expose it."
  9304. (interactive "P")
  9305. (when (and org-link-search-failed (eq this-command last-command))
  9306. (goto-char (point-min))
  9307. (message "Link search wrapped back to beginning of buffer"))
  9308. (setq org-link-search-failed nil)
  9309. (let* ((pos (point))
  9310. (ct (org-context))
  9311. (a (assq :link ct))
  9312. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9313. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9314. ((looking-at org-any-link-re)
  9315. ;; Don't stay stuck at link without an org-link face
  9316. (forward-char (if search-backward -1 1))))
  9317. (if (funcall srch-fun org-any-link-re nil t)
  9318. (progn
  9319. (goto-char (match-beginning 0))
  9320. (when (org-invisible-p) (org-show-context)))
  9321. (goto-char pos)
  9322. (setq org-link-search-failed t)
  9323. (message "No further link found"))))
  9324. (defun org-previous-link ()
  9325. "Move backward to the previous link.
  9326. If the link is in hidden text, expose it."
  9327. (interactive)
  9328. (funcall 'org-next-link t))
  9329. (defun org-translate-link (s)
  9330. "Translate a link string if a translation function has been defined."
  9331. (with-temp-buffer
  9332. (insert (org-trim s))
  9333. (org-trim (org-element-interpret-data (org-element-context)))))
  9334. (defun org-translate-link-from-planner (type path)
  9335. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9336. This is still an experimental function, your mileage may vary."
  9337. (cond
  9338. ((member type '("http" "https" "news" "ftp"))
  9339. ;; standard Internet links are the same.
  9340. nil)
  9341. ((and (equal type "irc") (string-match "^//" path))
  9342. ;; Planner has two / at the beginning of an irc link, we have 1.
  9343. ;; We should have zero, actually....
  9344. (setq path (substring path 1)))
  9345. ((and (equal type "lisp") (string-match "^/" path))
  9346. ;; Planner has a slash, we do not.
  9347. (setq type "elisp" path (substring path 1)))
  9348. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9349. ;; A typical message link. Planner has the id after the final slash,
  9350. ;; we separate it with a hash mark
  9351. (setq path (concat (match-string 1 path) "#"
  9352. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9353. (cons type path))
  9354. (defun org-find-file-at-mouse (ev)
  9355. "Open file link or URL at mouse."
  9356. (interactive "e")
  9357. (mouse-set-point ev)
  9358. (org-open-at-point 'in-emacs))
  9359. (defun org-open-at-mouse (ev)
  9360. "Open file link or URL at mouse.
  9361. See the docstring of `org-open-file' for details."
  9362. (interactive "e")
  9363. (mouse-set-point ev)
  9364. (when (eq major-mode 'org-agenda-mode)
  9365. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9366. (org-open-at-point))
  9367. (defvar org-window-config-before-follow-link nil
  9368. "The window configuration before following a link.
  9369. This is saved in case the need arises to restore it.")
  9370. ;;;###autoload
  9371. (defun org-open-at-point-global ()
  9372. "Follow a link or time-stamp like Org mode does.
  9373. This command can be called in any mode to follow an external link
  9374. or a time-stamp that has Org mode syntax. Its behavior is
  9375. undefined when called on internal links (e.g., fuzzy links).
  9376. Raise an error when there is nothing to follow. "
  9377. (interactive)
  9378. (cond ((org-in-regexp org-any-link-re)
  9379. (org-open-link-from-string (match-string-no-properties 0)))
  9380. ((or (org-in-regexp org-ts-regexp-both nil t)
  9381. (org-in-regexp org-tsr-regexp-both nil t))
  9382. (org-follow-timestamp-link))
  9383. (t (user-error "No link found"))))
  9384. ;;;###autoload
  9385. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9386. "Open a link in the string S, as if it was in Org mode."
  9387. (interactive "sLink: \nP")
  9388. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9389. (with-temp-buffer
  9390. (let ((org-inhibit-startup (not reference-buffer)))
  9391. (org-mode)
  9392. (insert s)
  9393. (goto-char (point-min))
  9394. (when reference-buffer
  9395. (setq org-link-abbrev-alist-local
  9396. (with-current-buffer reference-buffer
  9397. org-link-abbrev-alist-local)))
  9398. (org-open-at-point arg reference-buffer)))))
  9399. (defvar org-open-at-point-functions nil
  9400. "Hook that is run when following a link at point.
  9401. Functions in this hook must return t if they identify and follow
  9402. a link at point. If they don't find anything interesting at point,
  9403. they must return nil.")
  9404. (defvar org-link-search-inhibit-query nil)
  9405. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9406. (defun org--open-doi-link (path)
  9407. "Open a \"doi\" type link.
  9408. PATH is a the path to search for, as a string."
  9409. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9410. (defun org--open-elisp-link (path)
  9411. "Open a \"elisp\" type link.
  9412. PATH is the sexp to evaluate, as a string."
  9413. (let ((cmd path))
  9414. (if (or (and (org-string-nw-p
  9415. org-confirm-elisp-link-not-regexp)
  9416. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9417. (not org-confirm-elisp-link-function)
  9418. (funcall org-confirm-elisp-link-function
  9419. (format "Execute \"%s\" as elisp? "
  9420. (org-add-props cmd nil 'face 'org-warning))))
  9421. (message "%s => %s" cmd
  9422. (if (eq (string-to-char cmd) ?\()
  9423. (eval (read cmd))
  9424. (call-interactively (read cmd))))
  9425. (user-error "Abort"))))
  9426. (defun org--open-help-link (path)
  9427. "Open a \"help\" type link.
  9428. PATH is a symbol name, as a string."
  9429. (pcase (intern path)
  9430. ((and (pred fboundp) variable) (describe-function variable))
  9431. ((and (pred boundp) function) (describe-variable function))
  9432. (name (user-error "Unknown function or variable: %s" name))))
  9433. (defun org--open-shell-link (path)
  9434. "Open a \"shell\" type link.
  9435. PATH is the command to execute, as a string."
  9436. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9437. (cmd path))
  9438. (if (or (and (org-string-nw-p
  9439. org-confirm-shell-link-not-regexp)
  9440. (string-match
  9441. org-confirm-shell-link-not-regexp cmd))
  9442. (not org-confirm-shell-link-function)
  9443. (funcall org-confirm-shell-link-function
  9444. (format "Execute \"%s\" in shell? "
  9445. (org-add-props cmd nil
  9446. 'face 'org-warning))))
  9447. (progn
  9448. (message "Executing %s" cmd)
  9449. (shell-command cmd buf)
  9450. (when (featurep 'midnight)
  9451. (setq clean-buffer-list-kill-buffer-names
  9452. (cons (buffer-name buf)
  9453. clean-buffer-list-kill-buffer-names))))
  9454. (user-error "Abort"))))
  9455. (defun org-open-at-point (&optional arg reference-buffer)
  9456. "Open link, timestamp, footnote or tags at point.
  9457. When point is on a link, follow it. Normally, files will be
  9458. opened by an appropriate application. If the optional prefix
  9459. argument ARG is non-nil, Emacs will visit the file. With
  9460. a double prefix argument, try to open outside of Emacs, in the
  9461. application the system uses for this file type.
  9462. When point is on a timestamp, open the agenda at the day
  9463. specified.
  9464. When point is a footnote definition, move to the first reference
  9465. found. If it is on a reference, move to the associated
  9466. definition.
  9467. When point is on a headline, display a list of every link in the
  9468. entry, so it is possible to pick one, or all, of them. If point
  9469. is on a tag, call `org-tags-view' instead.
  9470. When optional argument REFERENCE-BUFFER is non-nil, it should
  9471. specify a buffer from where the link search should happen. This
  9472. is used internally by `org-open-link-from-string'.
  9473. On top of syntactically correct links, this function will also
  9474. try to open links and time-stamps in comments, example
  9475. blocks... i.e., whenever point is on something looking like
  9476. a timestamp or a link."
  9477. (interactive "P")
  9478. ;; On a code block, open block's results.
  9479. (unless (call-interactively 'org-babel-open-src-block-result)
  9480. (org-load-modules-maybe)
  9481. (setq org-window-config-before-follow-link (current-window-configuration))
  9482. (org-remove-occur-highlights nil nil t)
  9483. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9484. (let* ((context
  9485. ;; Only consider supported types, even if they are not
  9486. ;; the closest one.
  9487. (org-element-lineage
  9488. (org-element-context)
  9489. '(clock footnote-definition footnote-reference headline
  9490. inlinetask link timestamp)
  9491. t))
  9492. (type (org-element-type context))
  9493. (value (org-element-property :value context)))
  9494. (cond
  9495. ;; On a headline or an inlinetask, but not on a timestamp,
  9496. ;; a link, a footnote reference or on tags.
  9497. ((and (memq type '(headline inlinetask))
  9498. ;; Not on tags.
  9499. (let ((case-fold-search nil))
  9500. (and (org-match-line org-complex-heading-regexp)
  9501. (or (not (match-beginning 5))
  9502. (< (point) (match-beginning 5))))))
  9503. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9504. (links (car data))
  9505. (links-end (cdr data)))
  9506. (if links
  9507. (dolist (link (if (stringp links) (list links) links))
  9508. (search-forward link nil links-end)
  9509. (goto-char (match-beginning 0))
  9510. (org-open-at-point))
  9511. (require 'org-attach)
  9512. (org-attach-reveal 'if-exists))))
  9513. ;; On a footnote reference or at definition's label.
  9514. ((or (eq type 'footnote-reference)
  9515. (and (eq type 'footnote-definition)
  9516. (save-excursion
  9517. ;; Do not validate action when point is on the
  9518. ;; spaces right after the footnote label, in
  9519. ;; order to be on par with behaviour on links.
  9520. (skip-chars-forward " \t")
  9521. (let ((begin
  9522. (org-element-property :contents-begin context)))
  9523. (if begin (< (point) begin)
  9524. (= (org-element-property :post-affiliated context)
  9525. (line-beginning-position)))))))
  9526. (org-footnote-action))
  9527. ;; No valid context. Ignore catch-all types like `headline'.
  9528. ;; If point is on something looking like a link or
  9529. ;; a time-stamp, try opening it. It may be useful in
  9530. ;; comments, example blocks...
  9531. ((memq type '(footnote-definition headline inlinetask nil))
  9532. (call-interactively #'org-open-at-point-global))
  9533. ;; On a clock line, make sure point is on the timestamp
  9534. ;; before opening it.
  9535. ((and (eq type 'clock)
  9536. value
  9537. (>= (point) (org-element-property :begin value))
  9538. (<= (point) (org-element-property :end value)))
  9539. (org-follow-timestamp-link))
  9540. ;; Do nothing on white spaces after an object.
  9541. ((>= (point)
  9542. (save-excursion
  9543. (goto-char (org-element-property :end context))
  9544. (skip-chars-backward " \t")
  9545. (point)))
  9546. (user-error "No link found"))
  9547. ((eq type 'timestamp) (org-follow-timestamp-link))
  9548. ;; On tags within a headline or an inlinetask.
  9549. ((and (memq type '(headline inlinetask))
  9550. (let ((case-fold-search nil))
  9551. (save-excursion (beginning-of-line)
  9552. (looking-at org-complex-heading-regexp))
  9553. (and (match-beginning 5)
  9554. (>= (point) (match-beginning 5)))))
  9555. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9556. ((eq type 'link)
  9557. (let ((type (org-element-property :type context))
  9558. (path (org-link-unescape (org-element-property :path context))))
  9559. ;; Switch back to REFERENCE-BUFFER needed when called in
  9560. ;; a temporary buffer through `org-open-link-from-string'.
  9561. (with-current-buffer (or reference-buffer (current-buffer))
  9562. (cond
  9563. ((equal type "file")
  9564. (if (string-match "[*?{]" (file-name-nondirectory path))
  9565. (dired path)
  9566. ;; Look into `org-link-parameters' in order to find
  9567. ;; a DEDICATED-FUNCTION to open file. The function
  9568. ;; will be applied on raw link instead of parsed
  9569. ;; link due to the limitation in `org-add-link-type'
  9570. ;; ("open" function called with a single argument).
  9571. ;; If no such function is found, fallback to
  9572. ;; `org-open-file'.
  9573. (let* ((option (org-element-property :search-option context))
  9574. (app (org-element-property :application context))
  9575. (dedicated-function
  9576. (org-link-get-parameter
  9577. (if app (concat type "+" app) type)
  9578. :follow)))
  9579. (if dedicated-function
  9580. (funcall dedicated-function
  9581. (concat path
  9582. (and option (concat "::" option))))
  9583. (apply #'org-open-file
  9584. path
  9585. (cond (arg)
  9586. ((equal app "emacs") 'emacs)
  9587. ((equal app "sys") 'system))
  9588. (cond ((not option) nil)
  9589. ((string-match-p "\\`[0-9]+\\'" option)
  9590. (list (string-to-number option)))
  9591. (t (list nil
  9592. (org-link-unescape option)))))))))
  9593. ((functionp (org-link-get-parameter type :follow))
  9594. (funcall (org-link-get-parameter type :follow) path))
  9595. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9596. (unless (run-hook-with-args-until-success
  9597. 'org-open-link-functions path)
  9598. (if (not arg) (org-mark-ring-push)
  9599. (switch-to-buffer-other-window
  9600. (org-get-buffer-for-internal-link (current-buffer))))
  9601. (let ((destination
  9602. (org-with-wide-buffer
  9603. (if (equal type "radio")
  9604. (org-search-radio-target
  9605. (org-element-property :path context))
  9606. (org-link-search
  9607. (if (member type '("custom-id" "coderef"))
  9608. (org-element-property :raw-link context)
  9609. path)
  9610. ;; Prevent fuzzy links from matching
  9611. ;; themselves.
  9612. (and (equal type "fuzzy")
  9613. (+ 2 (org-element-property :begin context)))))
  9614. (point))))
  9615. (unless (and (<= (point-min) destination)
  9616. (>= (point-max) destination))
  9617. (widen))
  9618. (goto-char destination))))
  9619. (t (browse-url-at-point))))))
  9620. (t (user-error "No link found")))))
  9621. (run-hook-with-args 'org-follow-link-hook)))
  9622. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9623. "Offer links in the current entry and return the selected link.
  9624. If there is only one link, return it.
  9625. If NTH is an integer, return the NTH link found.
  9626. If ZERO is a string, check also this string for a link, and if
  9627. there is one, return it."
  9628. (with-current-buffer buffer
  9629. (org-with-wide-buffer
  9630. (goto-char marker)
  9631. (let ((cnt ?0)
  9632. have-zero end links link c)
  9633. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9634. (push (match-string 0 zero) links)
  9635. (setq cnt (1- cnt) have-zero t))
  9636. (save-excursion
  9637. (org-back-to-heading t)
  9638. (setq end (save-excursion (outline-next-heading) (point)))
  9639. (while (re-search-forward org-any-link-re end t)
  9640. (push (match-string 0) links))
  9641. (setq links (org-uniquify (reverse links))))
  9642. (cond
  9643. ((null links)
  9644. (message "No links"))
  9645. ((equal (length links) 1)
  9646. (setq link (car links)))
  9647. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9648. (setq link (nth (if have-zero nth (1- nth)) links)))
  9649. (t ; we have to select a link
  9650. (save-excursion
  9651. (save-window-excursion
  9652. (delete-other-windows)
  9653. (with-output-to-temp-buffer "*Select Link*"
  9654. (dolist (l links)
  9655. (cond
  9656. ((not (string-match org-bracket-link-regexp l))
  9657. (princ (format "[%c] %s\n" (cl-incf cnt)
  9658. (org-unbracket-string "<" ">" l))))
  9659. ((match-end 3)
  9660. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9661. (match-string 3 l) (match-string 1 l))))
  9662. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9663. (match-string 1 l)))))))
  9664. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9665. (message "Select link to open, RET to open all:")
  9666. (setq c (read-char-exclusive))
  9667. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9668. (when (equal c ?q) (user-error "Abort"))
  9669. (if (equal c ?\C-m)
  9670. (setq link links)
  9671. (setq nth (- c ?0))
  9672. (when have-zero (setq nth (1+ nth)))
  9673. (unless (and (integerp nth) (>= (length links) nth))
  9674. (user-error "Invalid link selection"))
  9675. (setq link (nth (1- nth) links)))))
  9676. (cons link end)))))
  9677. ;; TODO: These functions are deprecated since `org-open-at-point'
  9678. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9679. (defun org-open-file-with-system (path)
  9680. "Open file at PATH using the system way of opening it."
  9681. (org-open-file path 'system))
  9682. (defun org-open-file-with-emacs (path)
  9683. "Open file at PATH in Emacs."
  9684. (org-open-file path 'emacs))
  9685. ;;; File search
  9686. (defvar org-create-file-search-functions nil
  9687. "List of functions to construct the right search string for a file link.
  9688. These functions are called in turn with point at the location to
  9689. which the link should point.
  9690. A function in the hook should first test if it would like to
  9691. handle this file type, for example by checking the `major-mode'
  9692. or the file extension. If it decides not to handle this file, it
  9693. should just return nil to give other functions a chance. If it
  9694. does handle the file, it must return the search string to be used
  9695. when following the link. The search string will be part of the
  9696. file link, given after a double colon, and `org-open-at-point'
  9697. will automatically search for it. If special measures must be
  9698. taken to make the search successful, another function should be
  9699. added to the companion hook `org-execute-file-search-functions',
  9700. which see.
  9701. A function in this hook may also use `setq' to set the variable
  9702. `description' to provide a suggestion for the descriptive text to
  9703. be used for this link when it gets inserted into an Org buffer
  9704. with \\[org-insert-link].")
  9705. (defvar org-execute-file-search-functions nil
  9706. "List of functions to execute a file search triggered by a link.
  9707. Functions added to this hook must accept a single argument, the
  9708. search string that was part of the file link, the part after the
  9709. double colon. The function must first check if it would like to
  9710. handle this search, for example by checking the `major-mode' or
  9711. the file extension. If it decides not to handle this search, it
  9712. should just return nil to give other functions a chance. If it
  9713. does handle the search, it must return a non-nil value to keep
  9714. other functions from trying.
  9715. Each function can access the current prefix argument through the
  9716. variable `current-prefix-arg'. Note that a single prefix is used
  9717. to force opening a link in Emacs, so it may be good to only use a
  9718. numeric or double prefix to guide the search function.
  9719. In case this is needed, a function in this hook can also restore
  9720. the window configuration before `org-open-at-point' was called using:
  9721. (set-window-configuration org-window-config-before-follow-link)")
  9722. (defun org-search-radio-target (target)
  9723. "Search a radio target matching TARGET in current buffer.
  9724. White spaces are not significant."
  9725. (let ((re (format "<<<%s>>>"
  9726. (mapconcat #'regexp-quote
  9727. (org-split-string target "[ \t\n]+")
  9728. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9729. (origin (point)))
  9730. (goto-char (point-min))
  9731. (catch :radio-match
  9732. (while (re-search-forward re nil t)
  9733. (backward-char)
  9734. (let ((object (org-element-context)))
  9735. (when (eq (org-element-type object) 'radio-target)
  9736. (goto-char (org-element-property :begin object))
  9737. (org-show-context 'link-search)
  9738. (throw :radio-match nil))))
  9739. (goto-char origin)
  9740. (user-error "No match for radio target: %s" target))))
  9741. (defun org-link-search (s &optional avoid-pos stealth)
  9742. "Search for a search string S.
  9743. If S starts with \"#\", it triggers a custom ID search.
  9744. If S is enclosed within parenthesis, it initiates a coderef
  9745. search.
  9746. If S is surrounded by forward slashes, it is interpreted as
  9747. a regular expression. In Org mode files, this will create an
  9748. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9749. to list matches. If the current buffer is in `dired-mode', grep
  9750. will be used to search in all files.
  9751. When AVOID-POS is given, ignore matches near that position.
  9752. When optional argument STEALTH is non-nil, do not modify
  9753. visibility around point, thus ignoring `org-show-context-detail'
  9754. variable.
  9755. Search is case-insensitive and ignores white spaces. Return type
  9756. of matched result, which is either `dedicated' or `fuzzy'."
  9757. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9758. (let* ((case-fold-search t)
  9759. (origin (point))
  9760. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9761. (starred (eq (string-to-char normalized) ?*))
  9762. (words (split-string (if starred (substring s 1) s)))
  9763. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9764. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9765. type)
  9766. (cond
  9767. ;; Check if there are any special search functions.
  9768. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9769. ((eq (string-to-char s) ?#)
  9770. ;; Look for a custom ID S if S starts with "#".
  9771. (let* ((id (substring normalized 1))
  9772. (match (org-find-property "CUSTOM_ID" id)))
  9773. (if match (progn (goto-char match) (setf type 'dedicated))
  9774. (error "No match for custom ID: %s" id))))
  9775. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9776. ;; Look for coderef targets if S is enclosed within parenthesis.
  9777. (let ((coderef (match-string-no-properties 1 normalized))
  9778. (re (substring s-single-re 1 -1)))
  9779. (goto-char (point-min))
  9780. (catch :coderef-match
  9781. (while (re-search-forward re nil t)
  9782. (let ((element (org-element-at-point)))
  9783. (when (and (memq (org-element-type element)
  9784. '(example-block src-block))
  9785. ;; Build proper regexp according to current
  9786. ;; block's label format.
  9787. (let ((label-fmt
  9788. (regexp-quote
  9789. (or (org-element-property :label-fmt element)
  9790. org-coderef-label-format))))
  9791. (save-excursion
  9792. (beginning-of-line)
  9793. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9794. (format label-fmt coderef))))))
  9795. (setq type 'dedicated)
  9796. (goto-char (match-beginning 1))
  9797. (throw :coderef-match nil))))
  9798. (goto-char origin)
  9799. (error "No match for coderef: %s" coderef))))
  9800. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9801. ;; Look for a regular expression.
  9802. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9803. (match-string 1 s)))
  9804. ;; From here, we handle fuzzy links.
  9805. ;;
  9806. ;; Look for targets, only if not in a headline search.
  9807. ((and (not starred)
  9808. (let ((target (format "<<%s>>" s-multi-re)))
  9809. (catch :target-match
  9810. (goto-char (point-min))
  9811. (while (re-search-forward target nil t)
  9812. (backward-char)
  9813. (let ((context (org-element-context)))
  9814. (when (eq (org-element-type context) 'target)
  9815. (setq type 'dedicated)
  9816. (goto-char (org-element-property :begin context))
  9817. (throw :target-match t))))
  9818. nil))))
  9819. ;; Look for elements named after S, only if not in a headline
  9820. ;; search.
  9821. ((and (not starred)
  9822. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9823. (catch :name-match
  9824. (goto-char (point-min))
  9825. (while (re-search-forward name nil t)
  9826. (let ((element (org-element-at-point)))
  9827. (when (equal words
  9828. (split-string
  9829. (org-element-property :name element)))
  9830. (setq type 'dedicated)
  9831. (beginning-of-line)
  9832. (throw :name-match t))))
  9833. nil))))
  9834. ;; Regular text search. Prefer headlines in Org mode buffers.
  9835. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9836. ;; statistics cookies and tags.
  9837. ((and (derived-mode-p 'org-mode)
  9838. (let ((title-re
  9839. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9840. org-outline-regexp-bol
  9841. org-comment-string
  9842. (mapconcat #'regexp-quote words ".+")))
  9843. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9844. (comment-re (eval-when-compile
  9845. (format "\\`%s[ \t]+" org-comment-string))))
  9846. (goto-char (point-min))
  9847. (catch :found
  9848. (while (re-search-forward title-re nil t)
  9849. (when (equal words
  9850. (split-string
  9851. (replace-regexp-in-string
  9852. cookie-re ""
  9853. (replace-regexp-in-string
  9854. comment-re "" (org-get-heading t t t)))))
  9855. (throw :found t)))
  9856. nil)))
  9857. (beginning-of-line)
  9858. (setq type 'dedicated))
  9859. ;; Offer to create non-existent headline depending on
  9860. ;; `org-link-search-must-match-exact-headline'.
  9861. ((and (derived-mode-p 'org-mode)
  9862. (not org-link-search-inhibit-query)
  9863. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9864. (yes-or-no-p "No match - create this as a new heading? "))
  9865. (goto-char (point-max))
  9866. (unless (bolp) (newline))
  9867. (org-insert-heading nil t t)
  9868. (insert s "\n")
  9869. (beginning-of-line 0))
  9870. ;; Only headlines are looked after. No need to process
  9871. ;; further: throw an error.
  9872. ((and (derived-mode-p 'org-mode)
  9873. (or starred org-link-search-must-match-exact-headline))
  9874. (goto-char origin)
  9875. (error "No match for fuzzy expression: %s" normalized))
  9876. ;; Regular text search.
  9877. ((catch :fuzzy-match
  9878. (goto-char (point-min))
  9879. (while (re-search-forward s-multi-re nil t)
  9880. ;; Skip match if it contains AVOID-POS or it is included in
  9881. ;; a link with a description but outside the description.
  9882. (unless (or (and avoid-pos
  9883. (<= (match-beginning 0) avoid-pos)
  9884. (> (match-end 0) avoid-pos))
  9885. (and (save-match-data
  9886. (org-in-regexp org-bracket-link-regexp))
  9887. (match-beginning 3)
  9888. (or (> (match-beginning 3) (point))
  9889. (<= (match-end 3) (point)))
  9890. (org-element-lineage
  9891. (save-match-data (org-element-context))
  9892. '(link) t)))
  9893. (goto-char (match-beginning 0))
  9894. (setq type 'fuzzy)
  9895. (throw :fuzzy-match t)))
  9896. nil))
  9897. ;; All failed. Throw an error.
  9898. (t (goto-char origin)
  9899. (error "No match for fuzzy expression: %s" normalized)))
  9900. ;; Disclose surroundings of match, if appropriate.
  9901. (when (and (derived-mode-p 'org-mode) (not stealth))
  9902. (org-show-context 'link-search))
  9903. type))
  9904. (defun org-get-buffer-for-internal-link (buffer)
  9905. "Return a buffer to be used for displaying the link target of internal links."
  9906. (cond
  9907. ((not org-display-internal-link-with-indirect-buffer)
  9908. buffer)
  9909. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9910. (message "Buffer is already a clone, not making another one")
  9911. ;; we also do not modify visibility in this case
  9912. buffer)
  9913. (t ; make a new indirect buffer for displaying the link
  9914. (let* ((bn (buffer-name buffer))
  9915. (ibn (concat bn "(Clone)"))
  9916. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9917. (with-current-buffer ib (org-overview))
  9918. ib))))
  9919. (defun org-do-occur (regexp &optional cleanup)
  9920. "Call the Emacs command `occur'.
  9921. If CLEANUP is non-nil, remove the printout of the regular expression
  9922. in the *Occur* buffer. This is useful if the regex is long and not useful
  9923. to read."
  9924. (occur regexp)
  9925. (when cleanup
  9926. (let ((cwin (selected-window)) win beg end)
  9927. (when (setq win (get-buffer-window "*Occur*"))
  9928. (select-window win))
  9929. (goto-char (point-min))
  9930. (when (re-search-forward "match[a-z]+" nil t)
  9931. (setq beg (match-end 0))
  9932. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9933. (setq end (1- (match-beginning 0)))))
  9934. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9935. (goto-char (point-min))
  9936. (select-window cwin))))
  9937. ;;; The mark ring for links jumps
  9938. (defvar org-mark-ring nil
  9939. "Mark ring for positions before jumps in Org mode.")
  9940. (defvar org-mark-ring-last-goto nil
  9941. "Last position in the mark ring used to go back.")
  9942. ;; Fill and close the ring
  9943. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9944. (dotimes (_ org-mark-ring-length)
  9945. (push (make-marker) org-mark-ring))
  9946. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9947. org-mark-ring)
  9948. (defun org-mark-ring-push (&optional pos buffer)
  9949. "Put the current position or POS into the mark ring and rotate it."
  9950. (interactive)
  9951. (setq pos (or pos (point)))
  9952. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9953. (move-marker (car org-mark-ring)
  9954. (or pos (point))
  9955. (or buffer (current-buffer)))
  9956. (message "%s"
  9957. (substitute-command-keys
  9958. "Position saved to mark ring, go back with \
  9959. `\\[org-mark-ring-goto]'.")))
  9960. (defun org-mark-ring-goto (&optional n)
  9961. "Jump to the previous position in the mark ring.
  9962. With prefix arg N, jump back that many stored positions. When
  9963. called several times in succession, walk through the entire ring.
  9964. Org mode commands jumping to a different position in the current file,
  9965. or to another Org file, automatically push the old position onto the ring."
  9966. (interactive "p")
  9967. (let (p m)
  9968. (if (eq last-command this-command)
  9969. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9970. (setq p org-mark-ring))
  9971. (setq org-mark-ring-last-goto p)
  9972. (setq m (car p))
  9973. (pop-to-buffer-same-window (marker-buffer m))
  9974. (goto-char m)
  9975. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9976. (defun org-add-angle-brackets (s)
  9977. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9978. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9979. s)
  9980. ;;; Following specific links
  9981. (defvar org-agenda-buffer-tmp-name)
  9982. (defvar org-agenda-start-on-weekday)
  9983. (defun org-follow-timestamp-link ()
  9984. "Open an agenda view for the time-stamp date/range at point."
  9985. (cond
  9986. ((org-at-date-range-p t)
  9987. (let ((org-agenda-start-on-weekday)
  9988. (t1 (match-string 1))
  9989. (t2 (match-string 2)) tt1 tt2)
  9990. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9991. tt2 (time-to-days (org-time-string-to-time t2)))
  9992. (let ((org-agenda-buffer-tmp-name
  9993. (format "*Org Agenda(a:%s)"
  9994. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9995. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9996. ((org-at-timestamp-p 'lax)
  9997. (let ((org-agenda-buffer-tmp-name
  9998. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9999. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10000. (substring (match-string 1) 0 10)))
  10001. 1)))
  10002. (t (error "This should not happen"))))
  10003. ;;; Following file links
  10004. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10005. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10006. (declare-function mailcap-mime-info
  10007. "mailcap" (string &optional request no-decode))
  10008. (defvar org-wait nil)
  10009. (defun org-open-file (path &optional in-emacs line search)
  10010. "Open the file at PATH.
  10011. First, this expands any special file name abbreviations. Then the
  10012. configuration variable `org-file-apps' is checked if it contains an
  10013. entry for this file type, and if yes, the corresponding command is launched.
  10014. If no application is found, Emacs simply visits the file.
  10015. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10016. With a double \\[universal-argument] \\[universal-argument] \
  10017. prefix arg, Org tries to avoid opening in Emacs
  10018. and to use an external application to visit the file.
  10019. Optional LINE specifies a line to go to, optional SEARCH a string
  10020. to search for. If LINE or SEARCH is given, the file will be
  10021. opened in Emacs, unless an entry from org-file-apps that makes
  10022. use of groups in a regexp matches.
  10023. If you want to change the way frames are used when following a
  10024. link, please customize `org-link-frame-setup'.
  10025. If the file does not exist, an error is thrown."
  10026. (let* ((file (if (equal path "")
  10027. buffer-file-name
  10028. (substitute-in-file-name (expand-file-name path))))
  10029. (file-apps (append org-file-apps (org-default-apps)))
  10030. (apps (cl-remove-if
  10031. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10032. (apps-dlink (cl-remove-if-not
  10033. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10034. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10035. (dirp (unless remp (file-directory-p file)))
  10036. (file (if (and dirp org-open-directory-means-index-dot-org)
  10037. (concat (file-name-as-directory file) "index.org")
  10038. file))
  10039. (a-m-a-p (assq 'auto-mode apps))
  10040. (dfile (downcase file))
  10041. ;; Reconstruct the original link from the PATH, LINE and
  10042. ;; SEARCH args.
  10043. (link (cond (line (concat file "::" (number-to-string line)))
  10044. (search (concat file "::" search))
  10045. (t file)))
  10046. (dlink (downcase link))
  10047. (ext
  10048. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10049. (match-string 1 dfile)))
  10050. (save-position-maybe
  10051. (let ((old-buffer (current-buffer))
  10052. (old-pos (point))
  10053. (old-mode major-mode))
  10054. (lambda ()
  10055. (and (derived-mode-p 'org-mode)
  10056. (eq old-mode 'org-mode)
  10057. (or (not (eq old-buffer (current-buffer)))
  10058. (not (eq old-pos (point))))
  10059. (org-mark-ring-push old-pos old-buffer)))))
  10060. cmd link-match-data)
  10061. (cond
  10062. ((member in-emacs '((16) system))
  10063. (setq cmd (cdr (assq 'system apps))))
  10064. (in-emacs (setq cmd 'emacs))
  10065. (t
  10066. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10067. (and dirp (cdr (assq 'directory apps)))
  10068. ;; First, try matching against apps-dlink if we
  10069. ;; get a match here, store the match data for
  10070. ;; later.
  10071. (let ((match (assoc-default dlink apps-dlink
  10072. 'string-match)))
  10073. (if match
  10074. (progn (setq link-match-data (match-data))
  10075. match)
  10076. (progn (setq in-emacs (or in-emacs line search))
  10077. nil))) ; if we have no match in apps-dlink,
  10078. ; always open the file in emacs if line or search
  10079. ; is given (for backwards compatibility)
  10080. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10081. 'string-match)
  10082. (cdr (assoc ext apps))
  10083. (cdr (assq t apps))))))
  10084. (when (eq cmd 'system)
  10085. (setq cmd (cdr (assq 'system apps))))
  10086. (when (eq cmd 'default)
  10087. (setq cmd (cdr (assoc t apps))))
  10088. (when (eq cmd 'mailcap)
  10089. (require 'mailcap)
  10090. (mailcap-parse-mailcaps)
  10091. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10092. (command (mailcap-mime-info mime-type)))
  10093. (if (stringp command)
  10094. (setq cmd command)
  10095. (setq cmd 'emacs))))
  10096. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10097. (not (file-exists-p file))
  10098. (not org-open-non-existing-files))
  10099. (user-error "No such file: %s" file))
  10100. (cond
  10101. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10102. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10103. (while (string-match "['\"]%s['\"]" cmd)
  10104. (setq cmd (replace-match "%s" t t cmd)))
  10105. (setq cmd (replace-regexp-in-string
  10106. "%s"
  10107. (shell-quote-argument (convert-standard-filename file))
  10108. cmd
  10109. nil t))
  10110. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10111. (save-match-data
  10112. (let ((match-index 1)
  10113. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10114. (set-match-data link-match-data)
  10115. (while (<= match-index number-of-groups)
  10116. (let ((regex (concat "%" (number-to-string match-index)))
  10117. (replace-with (match-string match-index dlink)))
  10118. (while (string-match regex cmd)
  10119. (setq cmd (replace-match replace-with t t cmd))))
  10120. (setq match-index (+ match-index 1)))))
  10121. (save-window-excursion
  10122. (message "Running %s...done" cmd)
  10123. (start-process-shell-command cmd nil cmd)
  10124. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10125. ((or (stringp cmd)
  10126. (eq cmd 'emacs))
  10127. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10128. (widen)
  10129. (cond (line (org-goto-line line)
  10130. (when (derived-mode-p 'org-mode) (org-reveal)))
  10131. (search (condition-case err
  10132. (org-link-search search)
  10133. ;; Save position before error-ing out so user
  10134. ;; can easily move back to the original buffer.
  10135. (error (funcall save-position-maybe)
  10136. (error (nth 1 err)))))))
  10137. ((functionp cmd)
  10138. (save-match-data
  10139. (set-match-data link-match-data)
  10140. (condition-case nil
  10141. (funcall cmd file link)
  10142. ;; FIXME: Remove this check when most default installations
  10143. ;; of Emacs have at least Org 9.0.
  10144. ((debug wrong-number-of-arguments wrong-type-argument
  10145. invalid-function)
  10146. (user-error "Please see Org News for version 9.0 about \
  10147. `org-file-apps'--Lisp error: %S" cmd)))))
  10148. ((consp cmd)
  10149. ;; FIXME: Remove this check when most default installations of
  10150. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10151. ;; fall back to `org-link-frame-setup' for an old usage of
  10152. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10153. (user-error "Please see Org News for version 9.0 about \
  10154. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10155. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10156. (funcall save-position-maybe)))
  10157. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10158. "This function returns non-nil if `entry' uses a regular
  10159. expression which should be matched against the whole link by
  10160. org-open-file.
  10161. It assumes that is the case when the entry uses a regular
  10162. expression which has at least one grouping construct and the
  10163. action is either a lisp form or a command string containing
  10164. `%1', i.e. using at least one subexpression match as a
  10165. parameter."
  10166. (let ((selector (car entry))
  10167. (action (cdr entry)))
  10168. (if (stringp selector)
  10169. (and (> (regexp-opt-depth selector) 0)
  10170. (or (and (stringp action)
  10171. (string-match "%[0-9]" action))
  10172. (consp action)))
  10173. nil)))
  10174. (defun org-default-apps ()
  10175. "Return the default applications for this operating system."
  10176. (cond
  10177. ((eq system-type 'darwin)
  10178. org-file-apps-defaults-macosx)
  10179. ((eq system-type 'windows-nt)
  10180. org-file-apps-defaults-windowsnt)
  10181. (t org-file-apps-defaults-gnu)))
  10182. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10183. "Convert extensions to regular expressions in the cars of LIST.
  10184. Also, weed out any non-string entries, because the return value is used
  10185. only for regexp matching.
  10186. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10187. point to the symbol `emacs', indicating that the file should
  10188. be opened in Emacs."
  10189. (append
  10190. (delq nil
  10191. (mapcar (lambda (x)
  10192. (unless (not (stringp (car x)))
  10193. (if (string-match "\\W" (car x))
  10194. x
  10195. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10196. list))
  10197. (when add-auto-mode
  10198. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10199. (defvar ange-ftp-name-format)
  10200. (defun org-file-remote-p (file)
  10201. "Test whether FILE specifies a location on a remote system.
  10202. Return non-nil if the location is indeed remote.
  10203. For example, the filename \"/user@host:/foo\" specifies a location
  10204. on the system \"/user@host:\"."
  10205. (cond ((fboundp 'file-remote-p)
  10206. (file-remote-p file))
  10207. ((fboundp 'tramp-handle-file-remote-p)
  10208. (tramp-handle-file-remote-p file))
  10209. ((and (boundp 'ange-ftp-name-format)
  10210. (string-match (car ange-ftp-name-format) file))
  10211. t)))
  10212. ;;;; Refiling
  10213. (defun org-get-org-file ()
  10214. "Read a filename, with default directory `org-directory'."
  10215. (let ((default (or org-default-notes-file remember-data-file)))
  10216. (read-file-name (format "File name [%s]: " default)
  10217. (file-name-as-directory org-directory)
  10218. default)))
  10219. (defun org-notes-order-reversed-p ()
  10220. "Check if the current file should receive notes in reversed order."
  10221. (cond
  10222. ((not org-reverse-note-order) nil)
  10223. ((eq t org-reverse-note-order) t)
  10224. ((not (listp org-reverse-note-order)) nil)
  10225. (t (catch 'exit
  10226. (dolist (entry org-reverse-note-order)
  10227. (when (string-match (car entry) buffer-file-name)
  10228. (throw 'exit (cdr entry))))))))
  10229. (defvar org-refile-target-table nil
  10230. "The list of refile targets, created by `org-refile'.")
  10231. (defvar org-agenda-new-buffers nil
  10232. "Buffers created to visit agenda files.")
  10233. (defvar org-refile-cache nil
  10234. "Cache for refile targets.")
  10235. (defvar org-refile-markers nil
  10236. "All the markers used for caching refile locations.")
  10237. (defun org-refile-marker (pos)
  10238. "Get a new refile marker, but only if caching is in use."
  10239. (if (not org-refile-use-cache)
  10240. pos
  10241. (let ((m (make-marker)))
  10242. (move-marker m pos)
  10243. (push m org-refile-markers)
  10244. m)))
  10245. (defun org-refile-cache-clear ()
  10246. "Clear the refile cache and disable all the markers."
  10247. (dolist (m org-refile-markers) (move-marker m nil))
  10248. (setq org-refile-markers nil)
  10249. (setq org-refile-cache nil)
  10250. (message "Refile cache has been cleared"))
  10251. (defun org-refile-cache-check-set (set)
  10252. "Check if all the markers in the cache still have live buffers."
  10253. (let (marker)
  10254. (catch 'exit
  10255. (while (and set (setq marker (nth 3 (pop set))))
  10256. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10257. (when (and marker (null (marker-buffer marker)))
  10258. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10259. (sit-for 3)
  10260. (throw 'exit nil)))
  10261. t)))
  10262. (defun org-refile-cache-put (set &rest identifiers)
  10263. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10264. (let* ((key (sha1 (prin1-to-string identifiers)))
  10265. (entry (assoc key org-refile-cache)))
  10266. (if entry
  10267. (setcdr entry set)
  10268. (push (cons key set) org-refile-cache))))
  10269. (defun org-refile-cache-get (&rest identifiers)
  10270. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10271. (cond
  10272. ((not org-refile-cache) nil)
  10273. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10274. (t
  10275. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10276. org-refile-cache))))
  10277. (and set (org-refile-cache-check-set set) set)))))
  10278. (defvar org-outline-path-cache nil
  10279. "Alist between buffer positions and outline paths.
  10280. It value is an alist (POSITION . PATH) where POSITION is the
  10281. buffer position at the beginning of an entry and PATH is a list
  10282. of strings describing the outline path for that entry, in reverse
  10283. order.")
  10284. (defun org-refile-get-targets (&optional default-buffer)
  10285. "Produce a table with refile targets."
  10286. (let ((case-fold-search nil)
  10287. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10288. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10289. targets tgs files desc descre)
  10290. (message "Getting targets...")
  10291. (with-current-buffer (or default-buffer (current-buffer))
  10292. (dolist (entry entries)
  10293. (setq files (car entry) desc (cdr entry))
  10294. (cond
  10295. ((null files) (setq files (list (current-buffer))))
  10296. ((eq files 'org-agenda-files)
  10297. (setq files (org-agenda-files 'unrestricted)))
  10298. ((and (symbolp files) (fboundp files))
  10299. (setq files (funcall files)))
  10300. ((and (symbolp files) (boundp files))
  10301. (setq files (symbol-value files))))
  10302. (when (stringp files) (setq files (list files)))
  10303. (cond
  10304. ((eq (car desc) :tag)
  10305. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10306. ((eq (car desc) :todo)
  10307. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10308. ((eq (car desc) :regexp)
  10309. (setq descre (cdr desc)))
  10310. ((eq (car desc) :level)
  10311. (setq descre (concat "^\\*\\{" (number-to-string
  10312. (if org-odd-levels-only
  10313. (1- (* 2 (cdr desc)))
  10314. (cdr desc)))
  10315. "\\}[ \t]")))
  10316. ((eq (car desc) :maxlevel)
  10317. (setq descre (concat "^\\*\\{1," (number-to-string
  10318. (if org-odd-levels-only
  10319. (1- (* 2 (cdr desc)))
  10320. (cdr desc)))
  10321. "\\}[ \t]")))
  10322. (t (error "Bad refiling target description %s" desc)))
  10323. (dolist (f files)
  10324. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10325. (or
  10326. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10327. (progn
  10328. (when (bufferp f)
  10329. (setq f (buffer-file-name (buffer-base-buffer f))))
  10330. (setq f (and f (expand-file-name f)))
  10331. (when (eq org-refile-use-outline-path 'file)
  10332. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10333. (when (eq org-refile-use-outline-path 'buffer-name)
  10334. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10335. (when (eq org-refile-use-outline-path 'full-file-path)
  10336. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10337. (org-with-wide-buffer
  10338. (goto-char (point-min))
  10339. (setq org-outline-path-cache nil)
  10340. (while (re-search-forward descre nil t)
  10341. (beginning-of-line)
  10342. (let ((case-fold-search nil))
  10343. (looking-at org-complex-heading-regexp))
  10344. (let ((begin (point))
  10345. (heading (match-string-no-properties 4)))
  10346. (unless (or (and
  10347. org-refile-target-verify-function
  10348. (not
  10349. (funcall org-refile-target-verify-function)))
  10350. (not heading))
  10351. (let ((re (format org-complex-heading-regexp-format
  10352. (regexp-quote heading)))
  10353. (target
  10354. (if (not org-refile-use-outline-path) heading
  10355. (mapconcat
  10356. #'identity
  10357. (append
  10358. (pcase org-refile-use-outline-path
  10359. (`file (list (file-name-nondirectory
  10360. (buffer-file-name
  10361. (buffer-base-buffer)))))
  10362. (`full-file-path
  10363. (list (buffer-file-name
  10364. (buffer-base-buffer))))
  10365. (`buffer-name
  10366. (list (buffer-name
  10367. (buffer-base-buffer))))
  10368. (_ nil))
  10369. (mapcar (lambda (s) (replace-regexp-in-string
  10370. "/" "\\/" s nil t))
  10371. (org-get-outline-path t t)))
  10372. "/"))))
  10373. (push (list target f re (org-refile-marker (point)))
  10374. tgs)))
  10375. (when (= (point) begin)
  10376. ;; Verification function has not moved point.
  10377. (end-of-line)))))))
  10378. (when org-refile-use-cache
  10379. (org-refile-cache-put tgs (buffer-file-name) descre))
  10380. (setq targets (append tgs targets))))))
  10381. (message "Getting targets...done")
  10382. (delete-dups (nreverse targets))))
  10383. (defun org--get-outline-path-1 (&optional use-cache)
  10384. "Return outline path to current headline.
  10385. Outline path is a list of strings, in reverse order. When
  10386. optional argument USE-CACHE is non-nil, make use of a cache. See
  10387. `org-get-outline-path' for details.
  10388. Assume buffer is widened and point is on a headline."
  10389. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10390. (let ((p (point))
  10391. (heading (let ((case-fold-search nil))
  10392. (looking-at org-complex-heading-regexp)
  10393. (if (not (match-end 4)) ""
  10394. ;; Remove statistics cookies.
  10395. (org-trim
  10396. (org-link-display-format
  10397. (replace-regexp-in-string
  10398. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10399. (match-string-no-properties 4))))))))
  10400. (if (org-up-heading-safe)
  10401. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10402. (when use-cache
  10403. (push (cons p path) org-outline-path-cache))
  10404. path)
  10405. ;; This is a new root node. Since we assume we are moving
  10406. ;; forward, we can drop previous cache so as to limit number
  10407. ;; of associations there.
  10408. (let ((path (list heading)))
  10409. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10410. path)))))
  10411. (defun org-get-outline-path (&optional with-self use-cache)
  10412. "Return the outline path to the current entry.
  10413. An outline path is a list of ancestors for current headline, as
  10414. a list of strings. Statistics cookies are removed and links are
  10415. replaced with their description, if any, or their path otherwise.
  10416. When optional argument WITH-SELF is non-nil, the path also
  10417. includes the current headline.
  10418. When optional argument USE-CACHE is non-nil, cache outline paths
  10419. between calls to this function so as to avoid backtracking. This
  10420. argument is useful when planning to find more than one outline
  10421. path in the same document. In that case, there are two
  10422. conditions to satisfy:
  10423. - `org-outline-path-cache' is set to nil before starting the
  10424. process;
  10425. - outline paths are computed by increasing buffer positions."
  10426. (org-with-wide-buffer
  10427. (and (or (and with-self (org-back-to-heading t))
  10428. (org-up-heading-safe))
  10429. (reverse (org--get-outline-path-1 use-cache)))))
  10430. (defun org-format-outline-path (path &optional width prefix separator)
  10431. "Format the outline path PATH for display.
  10432. WIDTH is the maximum number of characters that is available.
  10433. PREFIX is a prefix to be included in the returned string,
  10434. such as the file name.
  10435. SEPARATOR is inserted between the different parts of the path,
  10436. the default is \"/\"."
  10437. (setq width (or width 79))
  10438. (setq path (delq nil path))
  10439. (unless (> width 0)
  10440. (user-error "Argument `width' must be positive"))
  10441. (setq separator (or separator "/"))
  10442. (let* ((org-odd-levels-only nil)
  10443. (fpath (concat
  10444. prefix (and prefix path separator)
  10445. (mapconcat
  10446. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10447. (cl-loop for head in path
  10448. for n from 0
  10449. collect (org-add-props
  10450. head nil 'face
  10451. (nth (% n org-n-level-faces) org-level-faces)))
  10452. separator))))
  10453. (when (> (length fpath) width)
  10454. (if (< width 7)
  10455. ;; It's unlikely that `width' will be this small, but don't
  10456. ;; waste characters by adding ".." if it is.
  10457. (setq fpath (substring fpath 0 width))
  10458. (setf (substring fpath (- width 2)) "..")))
  10459. fpath))
  10460. (defun org-display-outline-path (&optional file current separator just-return-string)
  10461. "Display the current outline path in the echo area.
  10462. If FILE is non-nil, prepend the output with the file name.
  10463. If CURRENT is non-nil, append the current heading to the output.
  10464. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10465. the different parts of the path and defaults to \"/\".
  10466. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10467. (interactive "P")
  10468. (let* (case-fold-search
  10469. (bfn (buffer-file-name (buffer-base-buffer)))
  10470. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10471. res)
  10472. (when current (setq path (append path
  10473. (save-excursion
  10474. (org-back-to-heading t)
  10475. (when (looking-at org-complex-heading-regexp)
  10476. (list (match-string 4)))))))
  10477. (setq res
  10478. (org-format-outline-path
  10479. path
  10480. (1- (frame-width))
  10481. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10482. separator))
  10483. (if just-return-string
  10484. (org-no-properties res)
  10485. (org-unlogged-message "%s" res))))
  10486. (defvar org-refile-history nil
  10487. "History for refiling operations.")
  10488. (defvar org-after-refile-insert-hook nil
  10489. "Hook run after `org-refile' has inserted its stuff at the new location.
  10490. Note that this is still *before* the stuff will be removed from
  10491. the *old* location.")
  10492. (defvar org-capture-last-stored-marker)
  10493. (defvar org-refile-keep nil
  10494. "Non-nil means `org-refile' will copy instead of refile.")
  10495. (defun org-copy ()
  10496. "Like `org-refile', but copy."
  10497. (interactive)
  10498. (let ((org-refile-keep t))
  10499. (funcall 'org-refile nil nil nil "Copy")))
  10500. (defun org-refile (&optional arg default-buffer rfloc msg)
  10501. "Move the entry or entries at point to another heading.
  10502. The list of target headings is compiled using the information in
  10503. `org-refile-targets', which see.
  10504. At the target location, the entry is filed as a subitem of the
  10505. target heading. Depending on `org-reverse-note-order', the new
  10506. subitem will either be the first or the last subitem.
  10507. If there is an active region, all entries in that region will be
  10508. refiled. However, the region must fulfill the requirement that
  10509. the first heading sets the top-level of the moved text.
  10510. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10511. location
  10512. and not actually move anything.
  10513. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10514. location where the last
  10515. refiling operation has put the subtree.
  10516. With a numeric prefix argument of `2', refile to the running clock.
  10517. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10518. being set to t and copy to the target location, don't move it.
  10519. Beware that keeping refiled entries may result in duplicated ID
  10520. properties.
  10521. RFLOC can be a refile location obtained in a different way.
  10522. MSG is a string to replace \"Refile\" in the default prompt with
  10523. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10524. See also `org-refile-use-outline-path'.
  10525. If you are using target caching (see `org-refile-use-cache'), you
  10526. have to clear the target cache in order to find new targets.
  10527. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10528. prefix argument (`C-u C-u C-u C-c C-w')."
  10529. (interactive "P")
  10530. (if (member arg '(0 (64)))
  10531. (org-refile-cache-clear)
  10532. (let* ((actionmsg (cond (msg msg)
  10533. ((equal arg 3) "Refile (and keep)")
  10534. (t "Refile")))
  10535. (regionp (org-region-active-p))
  10536. (region-start (and regionp (region-beginning)))
  10537. (region-end (and regionp (region-end)))
  10538. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10539. pos it nbuf file level reversed)
  10540. (setq last-command nil)
  10541. (when regionp
  10542. (goto-char region-start)
  10543. (or (bolp) (goto-char (point-at-bol)))
  10544. (setq region-start (point))
  10545. (unless (or (org-kill-is-subtree-p
  10546. (buffer-substring region-start region-end))
  10547. (prog1 org-refile-active-region-within-subtree
  10548. (let ((s (point-at-eol)))
  10549. (org-toggle-heading)
  10550. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10551. (user-error "The region is not a (sequence of) subtree(s)")))
  10552. (if (equal arg '(16))
  10553. (org-refile-goto-last-stored)
  10554. (when (or
  10555. (and (equal arg 2)
  10556. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10557. (prog1
  10558. (setq it (list (or org-clock-heading "running clock")
  10559. (buffer-file-name
  10560. (marker-buffer org-clock-hd-marker))
  10561. ""
  10562. (marker-position org-clock-hd-marker)))
  10563. (setq arg nil)))
  10564. (setq it
  10565. (or rfloc
  10566. (let (heading-text)
  10567. (save-excursion
  10568. (unless (and arg (listp arg))
  10569. (org-back-to-heading t)
  10570. (setq heading-text
  10571. (replace-regexp-in-string
  10572. org-bracket-link-regexp
  10573. "\\3"
  10574. (or (nth 4 (org-heading-components))
  10575. ""))))
  10576. (org-refile-get-location
  10577. (cond ((and arg (listp arg)) "Goto")
  10578. (regionp (concat actionmsg " region to"))
  10579. (t (concat actionmsg " subtree \""
  10580. heading-text "\" to")))
  10581. default-buffer
  10582. (and (not (equal '(4) arg))
  10583. org-refile-allow-creating-parent-nodes)))))))
  10584. (setq file (nth 1 it)
  10585. pos (nth 3 it))
  10586. (when (and (not arg)
  10587. pos
  10588. (equal (buffer-file-name) file)
  10589. (if regionp
  10590. (and (>= pos region-start)
  10591. (<= pos region-end))
  10592. (and (>= pos (point))
  10593. (< pos (save-excursion
  10594. (org-end-of-subtree t t))))))
  10595. (error "Cannot refile to position inside the tree or region"))
  10596. (setq nbuf (or (find-buffer-visiting file)
  10597. (find-file-noselect file)))
  10598. (if (and arg (not (equal arg 3)))
  10599. (progn
  10600. (pop-to-buffer-same-window nbuf)
  10601. (goto-char (cond (pos)
  10602. ((org-notes-order-reversed-p) (point-min))
  10603. (t (point-max))))
  10604. (org-show-context 'org-goto))
  10605. (if regionp
  10606. (progn
  10607. (org-kill-new (buffer-substring region-start region-end))
  10608. (org-save-markers-in-region region-start region-end))
  10609. (org-copy-subtree 1 nil t))
  10610. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10611. (find-file-noselect file)))
  10612. (setq reversed (org-notes-order-reversed-p))
  10613. (org-with-wide-buffer
  10614. (if pos
  10615. (progn
  10616. (goto-char pos)
  10617. (setq level (org-get-valid-level (funcall outline-level) 1))
  10618. (goto-char
  10619. (if reversed
  10620. (or (outline-next-heading) (point-max))
  10621. (or (save-excursion (org-get-next-sibling))
  10622. (org-end-of-subtree t t)
  10623. (point-max)))))
  10624. (setq level 1)
  10625. (if (not reversed)
  10626. (goto-char (point-max))
  10627. (goto-char (point-min))
  10628. (or (outline-next-heading) (goto-char (point-max)))))
  10629. (unless (bolp) (newline))
  10630. (org-paste-subtree level nil nil t)
  10631. (when org-log-refile
  10632. (org-add-log-setup 'refile nil nil org-log-refile)
  10633. (unless (eq org-log-refile 'note)
  10634. (save-excursion (org-add-log-note))))
  10635. (and org-auto-align-tags
  10636. (let ((org-loop-over-headlines-in-active-region nil))
  10637. (org-set-tags nil t)))
  10638. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10639. :last-refile)))
  10640. (when bookmark-name
  10641. (with-demoted-errors
  10642. (bookmark-set bookmark-name))))
  10643. ;; If we are refiling for capture, make sure that the
  10644. ;; last-capture pointers point here
  10645. (when (bound-and-true-p org-capture-is-refiling)
  10646. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10647. :last-capture-marker)))
  10648. (when bookmark-name
  10649. (with-demoted-errors
  10650. (bookmark-set bookmark-name))))
  10651. (move-marker org-capture-last-stored-marker (point)))
  10652. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10653. (run-hooks 'org-after-refile-insert-hook)))
  10654. (unless org-refile-keep
  10655. (if regionp
  10656. (delete-region (point) (+ (point) (- region-end region-start)))
  10657. (delete-region
  10658. (and (org-back-to-heading t) (point))
  10659. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10660. (when (featurep 'org-inlinetask)
  10661. (org-inlinetask-remove-END-maybe))
  10662. (setq org-markers-to-move nil)
  10663. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10664. (defun org-refile-goto-last-stored ()
  10665. "Go to the location where the last refile was stored."
  10666. (interactive)
  10667. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10668. (message "This is the location of the last refile"))
  10669. (defun org-refile--get-location (refloc tbl)
  10670. "When user refile to REFLOC, find the associated target in TBL.
  10671. Also check `org-refile-target-table'."
  10672. (car (delq
  10673. nil
  10674. (mapcar
  10675. (lambda (r) (or (assoc r tbl)
  10676. (assoc r org-refile-target-table)))
  10677. (list (replace-regexp-in-string "/$" "" refloc)
  10678. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10679. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10680. "Prompt the user for a refile location, using PROMPT.
  10681. PROMPT should not be suffixed with a colon and a space, because
  10682. this function appends the default value from
  10683. `org-refile-history' automatically, if that is not empty."
  10684. (let ((org-refile-targets org-refile-targets)
  10685. (org-refile-use-outline-path org-refile-use-outline-path))
  10686. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10687. (unless org-refile-target-table
  10688. (user-error "No refile targets"))
  10689. (let* ((cbuf (current-buffer))
  10690. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10691. (cfunc (if (and org-refile-use-outline-path
  10692. org-outline-path-complete-in-steps)
  10693. #'org-olpath-completing-read
  10694. #'completing-read))
  10695. (extra (if org-refile-use-outline-path "/" ""))
  10696. (cbnex (concat (buffer-name) extra))
  10697. (filename (and cfn (expand-file-name cfn)))
  10698. (tbl (mapcar
  10699. (lambda (x)
  10700. (if (and (not (member org-refile-use-outline-path
  10701. '(file full-file-path)))
  10702. (not (equal filename (nth 1 x))))
  10703. (cons (concat (car x) extra " ("
  10704. (file-name-nondirectory (nth 1 x)) ")")
  10705. (cdr x))
  10706. (cons (concat (car x) extra) (cdr x))))
  10707. org-refile-target-table))
  10708. (completion-ignore-case t)
  10709. cdef
  10710. (prompt (concat prompt
  10711. (or (and (car org-refile-history)
  10712. (concat " (default " (car org-refile-history) ")"))
  10713. (and (assoc cbnex tbl) (setq cdef cbnex)
  10714. (concat " (default " cbnex ")"))) ": "))
  10715. pa answ parent-target child parent old-hist)
  10716. (setq old-hist org-refile-history)
  10717. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10718. nil 'org-refile-history (or cdef (car org-refile-history))))
  10719. (if (setq pa (org-refile--get-location answ tbl))
  10720. (progn
  10721. (org-refile-check-position pa)
  10722. (when (or (not org-refile-history)
  10723. (not (eq old-hist org-refile-history))
  10724. (not (equal (car pa) (car org-refile-history))))
  10725. (setq org-refile-history
  10726. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10727. org-refile-history
  10728. (cdr org-refile-history))))
  10729. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10730. (pop org-refile-history)))
  10731. pa)
  10732. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10733. (progn
  10734. (setq parent (match-string 1 answ)
  10735. child (match-string 2 answ))
  10736. (setq parent-target (org-refile--get-location parent tbl))
  10737. (when (and parent-target
  10738. (or (eq new-nodes t)
  10739. (and (eq new-nodes 'confirm)
  10740. (y-or-n-p (format "Create new node \"%s\"? "
  10741. child)))))
  10742. (org-refile-new-child parent-target child)))
  10743. (user-error "Invalid target location")))))
  10744. (declare-function org-string-nw-p "org-macs" (s))
  10745. (defun org-refile-check-position (refile-pointer)
  10746. "Check if the refile pointer matches the headline to which it points."
  10747. (let* ((file (nth 1 refile-pointer))
  10748. (re (nth 2 refile-pointer))
  10749. (pos (nth 3 refile-pointer))
  10750. buffer)
  10751. (if (and (not (markerp pos)) (not file))
  10752. (user-error "Please indicate a target file in the refile path")
  10753. (when (org-string-nw-p re)
  10754. (setq buffer (if (markerp pos)
  10755. (marker-buffer pos)
  10756. (or (find-buffer-visiting file)
  10757. (find-file-noselect file))))
  10758. (with-current-buffer buffer
  10759. (org-with-wide-buffer
  10760. (goto-char pos)
  10761. (beginning-of-line 1)
  10762. (unless (looking-at-p re)
  10763. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10764. (defun org-refile-new-child (parent-target child)
  10765. "Use refile target PARENT-TARGET to add new CHILD below it."
  10766. (unless parent-target
  10767. (error "Cannot find parent for new node"))
  10768. (let ((file (nth 1 parent-target))
  10769. (pos (nth 3 parent-target))
  10770. level)
  10771. (with-current-buffer (or (find-buffer-visiting file)
  10772. (find-file-noselect file))
  10773. (org-with-wide-buffer
  10774. (if pos
  10775. (goto-char pos)
  10776. (goto-char (point-max))
  10777. (unless (bolp) (newline)))
  10778. (when (looking-at org-outline-regexp)
  10779. (setq level (funcall outline-level))
  10780. (org-end-of-subtree t t))
  10781. (org-back-over-empty-lines)
  10782. (insert "\n" (make-string
  10783. (if pos (org-get-valid-level level 1) 1) ?*)
  10784. " " child "\n")
  10785. (beginning-of-line 0)
  10786. (list (concat (car parent-target) "/" child) file "" (point))))))
  10787. (defun org-olpath-completing-read (prompt collection &rest args)
  10788. "Read an outline path like a file name."
  10789. (let ((thetable collection))
  10790. (apply #'completing-read
  10791. prompt
  10792. (lambda (string predicate &optional flag)
  10793. (cond
  10794. ((eq flag nil) (try-completion string thetable))
  10795. ((eq flag t)
  10796. (let ((l (length string)))
  10797. (mapcar (lambda (x)
  10798. (let ((r (substring x l))
  10799. (f (if (string-match " ([^)]*)$" x)
  10800. (match-string 0 x)
  10801. "")))
  10802. (if (string-match "/" r)
  10803. (concat string (substring r 0 (match-end 0)) f)
  10804. x)))
  10805. (all-completions string thetable predicate))))
  10806. ;; Exact match?
  10807. ((eq flag 'lambda) (assoc string thetable))))
  10808. args)))
  10809. ;;;; Dynamic blocks
  10810. (defun org-find-dblock (name)
  10811. "Find the first dynamic block with name NAME in the buffer.
  10812. If not found, stay at current position and return nil."
  10813. (let ((case-fold-search t) pos)
  10814. (save-excursion
  10815. (goto-char (point-min))
  10816. (setq pos (and (re-search-forward
  10817. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10818. (match-beginning 0))))
  10819. (when pos (goto-char pos))
  10820. pos))
  10821. (defun org-create-dblock (plist)
  10822. "Create a dynamic block section, with parameters taken from PLIST.
  10823. PLIST must contain a :name entry which is used as the name of the block."
  10824. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10825. (end-of-line 1)
  10826. (newline))
  10827. (let ((col (current-column))
  10828. (name (plist-get plist :name)))
  10829. (insert "#+BEGIN: " name)
  10830. (while plist
  10831. (if (eq (car plist) :name)
  10832. (setq plist (cddr plist))
  10833. (insert " " (prin1-to-string (pop plist)))))
  10834. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10835. (beginning-of-line -2)))
  10836. (defun org-prepare-dblock ()
  10837. "Prepare dynamic block for refresh.
  10838. This empties the block, puts the cursor at the insert position and returns
  10839. the property list including an extra property :name with the block name."
  10840. (unless (looking-at org-dblock-start-re)
  10841. (user-error "Not at a dynamic block"))
  10842. (let* ((begdel (1+ (match-end 0)))
  10843. (name (org-no-properties (match-string 1)))
  10844. (params (append (list :name name)
  10845. (read (concat "(" (match-string 3) ")")))))
  10846. (save-excursion
  10847. (beginning-of-line 1)
  10848. (skip-chars-forward " \t")
  10849. (setq params (plist-put params :indentation-column (current-column))))
  10850. (unless (re-search-forward org-dblock-end-re nil t)
  10851. (error "Dynamic block not terminated"))
  10852. (setq params
  10853. (append params
  10854. (list :content (buffer-substring
  10855. begdel (match-beginning 0)))))
  10856. (delete-region begdel (match-beginning 0))
  10857. (goto-char begdel)
  10858. (open-line 1)
  10859. params))
  10860. (defun org-map-dblocks (&optional command)
  10861. "Apply COMMAND to all dynamic blocks in the current buffer.
  10862. If COMMAND is not given, use `org-update-dblock'."
  10863. (let ((cmd (or command 'org-update-dblock)))
  10864. (save-excursion
  10865. (goto-char (point-min))
  10866. (while (re-search-forward org-dblock-start-re nil t)
  10867. (goto-char (match-beginning 0))
  10868. (save-excursion
  10869. (condition-case nil
  10870. (funcall cmd)
  10871. (error (message "Error during update of dynamic block"))))
  10872. (unless (re-search-forward org-dblock-end-re nil t)
  10873. (error "Dynamic block not terminated"))))))
  10874. (defun org-dblock-update (&optional arg)
  10875. "User command for updating dynamic blocks.
  10876. Update the dynamic block at point. With prefix ARG, update all dynamic
  10877. blocks in the buffer."
  10878. (interactive "P")
  10879. (if arg
  10880. (org-update-all-dblocks)
  10881. (or (looking-at org-dblock-start-re)
  10882. (org-beginning-of-dblock))
  10883. (org-update-dblock)))
  10884. (defun org-update-dblock ()
  10885. "Update the dynamic block at point.
  10886. This means to empty the block, parse for parameters and then call
  10887. the correct writing function."
  10888. (interactive)
  10889. (save-excursion
  10890. (let* ((win (selected-window))
  10891. (pos (point))
  10892. (line (org-current-line))
  10893. (params (org-prepare-dblock))
  10894. (name (plist-get params :name))
  10895. (indent (plist-get params :indentation-column))
  10896. (cmd (intern (concat "org-dblock-write:" name))))
  10897. (message "Updating dynamic block `%s' at line %d..." name line)
  10898. (funcall cmd params)
  10899. (message "Updating dynamic block `%s' at line %d...done" name line)
  10900. (goto-char pos)
  10901. (when (and indent (> indent 0))
  10902. (setq indent (make-string indent ?\ ))
  10903. (save-excursion
  10904. (select-window win)
  10905. (org-beginning-of-dblock)
  10906. (forward-line 1)
  10907. (while (not (looking-at org-dblock-end-re))
  10908. (insert indent)
  10909. (beginning-of-line 2))
  10910. (when (looking-at org-dblock-end-re)
  10911. (and (looking-at "[ \t]+")
  10912. (replace-match ""))
  10913. (insert indent)))))))
  10914. (defun org-beginning-of-dblock ()
  10915. "Find the beginning of the dynamic block at point.
  10916. Error if there is no such block at point."
  10917. (let ((pos (point))
  10918. beg)
  10919. (end-of-line 1)
  10920. (if (and (re-search-backward org-dblock-start-re nil t)
  10921. (setq beg (match-beginning 0))
  10922. (re-search-forward org-dblock-end-re nil t)
  10923. (> (match-end 0) pos))
  10924. (goto-char beg)
  10925. (goto-char pos)
  10926. (error "Not in a dynamic block"))))
  10927. (defun org-update-all-dblocks ()
  10928. "Update all dynamic blocks in the buffer.
  10929. This function can be used in a hook."
  10930. (interactive)
  10931. (when (derived-mode-p 'org-mode)
  10932. (org-map-dblocks 'org-update-dblock)))
  10933. ;;;; Completion
  10934. (declare-function org-export-backend-options "ox" (cl-x) t)
  10935. (defun org-get-export-keywords ()
  10936. "Return a list of all currently understood export keywords.
  10937. Export keywords include options, block names, attributes and
  10938. keywords relative to each registered export back-end."
  10939. (let (keywords)
  10940. (dolist (backend
  10941. (bound-and-true-p org-export-registered-backends)
  10942. (delq nil keywords))
  10943. ;; Back-end name (for keywords, like #+LATEX:)
  10944. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10945. (dolist (option-entry (org-export-backend-options backend))
  10946. ;; Back-end options.
  10947. (push (nth 1 option-entry) keywords)))))
  10948. (defconst org-options-keywords
  10949. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10950. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10951. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10952. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10953. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10954. (defcustom org-structure-template-alist
  10955. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10956. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10957. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10958. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10959. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10960. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10961. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10962. ("L" "#+LaTeX: ")
  10963. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10964. ("H" "#+HTML: ")
  10965. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10966. ("A" "#+ASCII: ")
  10967. ("i" "#+INDEX: ?")
  10968. ("I" "#+INCLUDE: %file ?"))
  10969. "Structure completion elements.
  10970. This is a list of abbreviation keys and values. The value gets inserted
  10971. if you type `<' followed by the key and then press the completion key,
  10972. usually `TAB'. %file will be replaced by a file name after prompting
  10973. for the file using completion. The cursor will be placed at the position
  10974. of the `?' in the template.
  10975. There are two templates for each key, the first uses the original Org syntax,
  10976. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10977. the default when the /org-mtags.el/ module has been loaded. See also the
  10978. variable `org-mtags-prefer-muse-templates'."
  10979. :group 'org-completion
  10980. :type '(repeat
  10981. (list
  10982. (string :tag "Key")
  10983. (string :tag "Template")))
  10984. :version "26.1"
  10985. :package-version '(Org . "8.3"))
  10986. (defun org-try-structure-completion ()
  10987. "Try to complete a structure template before point.
  10988. This looks for strings like \"<e\" on an otherwise empty line and
  10989. expands them."
  10990. (let ((l (buffer-substring (point-at-bol) (point)))
  10991. a)
  10992. (when (and (looking-at "[ \t]*$")
  10993. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10994. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10995. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10996. (match-beginning 1)) a)
  10997. t)))
  10998. (defun org-complete-expand-structure-template (start cell)
  10999. "Expand a structure template."
  11000. (let ((rpl (nth 1 cell))
  11001. (ind ""))
  11002. (delete-region start (point))
  11003. (when (string-match "\\`[ \t]*#\\+" rpl)
  11004. (cond
  11005. ((bolp))
  11006. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11007. (setq ind (buffer-substring (point-at-bol) (point))))
  11008. (t (newline))))
  11009. (setq start (point))
  11010. (when (string-match "%file" rpl)
  11011. (setq rpl (replace-match
  11012. (concat
  11013. "\""
  11014. (save-match-data
  11015. (abbreviate-file-name (read-file-name "Include file: ")))
  11016. "\"")
  11017. t t rpl)))
  11018. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11019. (concat "\n" ind)))
  11020. (insert rpl)
  11021. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11022. ;;;; TODO, DEADLINE, Comments
  11023. (defun org-toggle-comment ()
  11024. "Change the COMMENT state of an entry."
  11025. (interactive)
  11026. (save-excursion
  11027. (org-back-to-heading)
  11028. (let ((case-fold-search nil))
  11029. (looking-at org-complex-heading-regexp))
  11030. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11031. (skip-chars-forward " \t")
  11032. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11033. (if (org-in-commented-heading-p t)
  11034. (delete-region (point)
  11035. (progn (search-forward " " (line-end-position) 'move)
  11036. (skip-chars-forward " \t")
  11037. (point)))
  11038. (insert org-comment-string)
  11039. (unless (eolp) (insert " ")))))
  11040. (defvar org-last-todo-state-is-todo nil
  11041. "This is non-nil when the last TODO state change led to a TODO state.
  11042. If the last change removed the TODO tag or switched to DONE, then
  11043. this is nil.")
  11044. (defvar org-setting-tags nil) ; dynamically skipped
  11045. (defvar org-todo-setup-filter-hook nil
  11046. "Hook for functions that pre-filter todo specs.
  11047. Each function takes a todo spec and returns either nil or the spec
  11048. transformed into canonical form." )
  11049. (defvar org-todo-get-default-hook nil
  11050. "Hook for functions that get a default item for todo.
  11051. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11052. nil or a string to be used for the todo mark." )
  11053. (defvar org-agenda-headline-snapshot-before-repeat)
  11054. (defun org-current-effective-time ()
  11055. "Return current time adjusted for `org-extend-today-until' variable."
  11056. (let* ((ct (org-current-time))
  11057. (dct (decode-time ct))
  11058. (ct1
  11059. (cond
  11060. (org-use-last-clock-out-time-as-effective-time
  11061. (or (org-clock-get-last-clock-out-time) ct))
  11062. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11063. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11064. (t ct))))
  11065. ct1))
  11066. (defun org-todo-yesterday (&optional arg)
  11067. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11068. (interactive "P")
  11069. (if (eq major-mode 'org-agenda-mode)
  11070. (apply 'org-agenda-todo-yesterday arg)
  11071. (let* ((org-use-effective-time t)
  11072. (hour (nth 2 (decode-time (org-current-time))))
  11073. (org-extend-today-until (1+ hour)))
  11074. (org-todo arg))))
  11075. (defvar org-block-entry-blocking ""
  11076. "First entry preventing the TODO state change.")
  11077. (defun org-cancel-repeater ()
  11078. "Cancel a repeater by setting its numeric value to zero."
  11079. (interactive)
  11080. (save-excursion
  11081. (org-back-to-heading t)
  11082. (let ((bound1 (point))
  11083. (bound0 (save-excursion (outline-next-heading) (point))))
  11084. (when (and (re-search-forward
  11085. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11086. org-deadline-time-regexp "\\)\\|\\("
  11087. org-ts-regexp "\\)")
  11088. bound0 t)
  11089. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11090. bound1 t))
  11091. (replace-match "0" t nil nil 1)))))
  11092. (defvar org-state)
  11093. (defvar org-blocked-by-checkboxes)
  11094. (defun org-todo (&optional arg)
  11095. "Change the TODO state of an item.
  11096. The state of an item is given by a keyword at the start of the heading,
  11097. like
  11098. *** TODO Write paper
  11099. *** DONE Call mom
  11100. The different keywords are specified in the variable `org-todo-keywords'.
  11101. By default the available states are \"TODO\" and \"DONE\". So, for this
  11102. example: when the item starts with TODO, it is changed to DONE.
  11103. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11104. DONE are present, add TODO at the beginning of the heading.
  11105. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11106. state.
  11107. With numeric prefix ARG, switch to that state.
  11108. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11109. next set of TODO \
  11110. keywords (nextset).
  11111. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11112. prefix, circumvent any state blocking.
  11113. With a numeric prefix arg of 0, inhibit note taking for the change.
  11114. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11115. When called through ELisp, arg is also interpreted in the following way:
  11116. `none' -> empty state
  11117. \"\" -> switch to empty state
  11118. `done' -> switch to DONE
  11119. `nextset' -> switch to the next set of keywords
  11120. `previousset' -> switch to the previous set of keywords
  11121. \"WAITING\" -> switch to the specified keyword, but only if it
  11122. really is a member of `org-todo-keywords'."
  11123. (interactive "P")
  11124. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11125. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11126. 'region-start-level 'region))
  11127. org-loop-over-headlines-in-active-region)
  11128. (org-map-entries
  11129. `(org-todo ,arg)
  11130. org-loop-over-headlines-in-active-region
  11131. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11132. (when (equal arg '(16)) (setq arg 'nextset))
  11133. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11134. (let ((org-blocker-hook org-blocker-hook)
  11135. commentp
  11136. case-fold-search)
  11137. (when (equal arg '(64))
  11138. (setq arg nil org-blocker-hook nil))
  11139. (when (and org-blocker-hook
  11140. (or org-inhibit-blocking
  11141. (org-entry-get nil "NOBLOCKING")))
  11142. (setq org-blocker-hook nil))
  11143. (save-excursion
  11144. (catch 'exit
  11145. (org-back-to-heading t)
  11146. (when (org-in-commented-heading-p t)
  11147. (org-toggle-comment)
  11148. (setq commentp t))
  11149. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11150. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11151. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11152. (let* ((match-data (match-data))
  11153. (startpos (point-at-bol))
  11154. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11155. (org-log-done org-log-done)
  11156. (org-log-repeat org-log-repeat)
  11157. (org-todo-log-states org-todo-log-states)
  11158. (org-inhibit-logging
  11159. (if (equal arg 0)
  11160. (progn (setq arg nil) 'note) org-inhibit-logging))
  11161. (this (match-string 1))
  11162. (hl-pos (match-beginning 0))
  11163. (head (org-get-todo-sequence-head this))
  11164. (ass (assoc head org-todo-kwd-alist))
  11165. (interpret (nth 1 ass))
  11166. (done-word (nth 3 ass))
  11167. (final-done-word (nth 4 ass))
  11168. (org-last-state (or this ""))
  11169. (completion-ignore-case t)
  11170. (member (member this org-todo-keywords-1))
  11171. (tail (cdr member))
  11172. (org-state (cond
  11173. ((and org-todo-key-trigger
  11174. (or (and (equal arg '(4))
  11175. (eq org-use-fast-todo-selection 'prefix))
  11176. (and (not arg) org-use-fast-todo-selection
  11177. (not (eq org-use-fast-todo-selection
  11178. 'prefix)))))
  11179. ;; Use fast selection.
  11180. (org-fast-todo-selection))
  11181. ((and (equal arg '(4))
  11182. (or (not org-use-fast-todo-selection)
  11183. (not org-todo-key-trigger)))
  11184. ;; Read a state with completion.
  11185. (completing-read
  11186. "State: " (mapcar #'list org-todo-keywords-1)
  11187. nil t))
  11188. ((eq arg 'right)
  11189. (if this
  11190. (if tail (car tail) nil)
  11191. (car org-todo-keywords-1)))
  11192. ((eq arg 'left)
  11193. (unless (equal member org-todo-keywords-1)
  11194. (if this
  11195. (nth (- (length org-todo-keywords-1)
  11196. (length tail) 2)
  11197. org-todo-keywords-1)
  11198. (org-last org-todo-keywords-1))))
  11199. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11200. (setq arg nil))) ;hack to fall back to cycling
  11201. (arg
  11202. ;; User or caller requests a specific state.
  11203. (cond
  11204. ((equal arg "") nil)
  11205. ((eq arg 'none) nil)
  11206. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11207. ((eq arg 'nextset)
  11208. (or (car (cdr (member head org-todo-heads)))
  11209. (car org-todo-heads)))
  11210. ((eq arg 'previousset)
  11211. (let ((org-todo-heads (reverse org-todo-heads)))
  11212. (or (car (cdr (member head org-todo-heads)))
  11213. (car org-todo-heads))))
  11214. ((car (member arg org-todo-keywords-1)))
  11215. ((stringp arg)
  11216. (user-error "State `%s' not valid in this file" arg))
  11217. ((nth (1- (prefix-numeric-value arg))
  11218. org-todo-keywords-1))))
  11219. ((null member) (or head (car org-todo-keywords-1)))
  11220. ((equal this final-done-word) nil) ;-> make empty
  11221. ((null tail) nil) ;-> first entry
  11222. ((memq interpret '(type priority))
  11223. (if (eq this-command last-command)
  11224. (car tail)
  11225. (if (> (length tail) 0)
  11226. (or done-word (car org-done-keywords))
  11227. nil)))
  11228. (t
  11229. (car tail))))
  11230. (org-state (or
  11231. (run-hook-with-args-until-success
  11232. 'org-todo-get-default-hook org-state org-last-state)
  11233. org-state))
  11234. (next (if org-state (concat " " org-state " ") " "))
  11235. (change-plist (list :type 'todo-state-change :from this :to org-state
  11236. :position startpos))
  11237. dolog now-done-p)
  11238. (when org-blocker-hook
  11239. (let (org-blocked-by-checkboxes block-reason)
  11240. (setq org-last-todo-state-is-todo
  11241. (not (member this org-done-keywords)))
  11242. (unless (save-excursion
  11243. (save-match-data
  11244. (org-with-wide-buffer
  11245. (run-hook-with-args-until-failure
  11246. 'org-blocker-hook change-plist))))
  11247. (setq block-reason (if org-blocked-by-checkboxes
  11248. "contained checkboxes"
  11249. (format "\"%s\"" org-block-entry-blocking)))
  11250. (if (called-interactively-p 'interactive)
  11251. (user-error "TODO state change from %s to %s blocked (by %s)"
  11252. this org-state block-reason)
  11253. ;; Fail silently.
  11254. (message "TODO state change from %s to %s blocked (by %s)"
  11255. this org-state block-reason)
  11256. (throw 'exit nil)))))
  11257. (store-match-data match-data)
  11258. (replace-match next t t)
  11259. (cond ((equal this org-state)
  11260. (message "TODO state was already %s" (org-trim next)))
  11261. ((not (pos-visible-in-window-p hl-pos))
  11262. (message "TODO state changed to %s" (org-trim next))))
  11263. (unless head
  11264. (setq head (org-get-todo-sequence-head org-state)
  11265. ass (assoc head org-todo-kwd-alist)
  11266. interpret (nth 1 ass)
  11267. done-word (nth 3 ass)
  11268. final-done-word (nth 4 ass)))
  11269. (when (memq arg '(nextset previousset))
  11270. (message "Keyword-Set %d/%d: %s"
  11271. (- (length org-todo-sets) -1
  11272. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11273. (length org-todo-sets)
  11274. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11275. (setq org-last-todo-state-is-todo
  11276. (not (member org-state org-done-keywords)))
  11277. (setq now-done-p (and (member org-state org-done-keywords)
  11278. (not (member this org-done-keywords))))
  11279. (and logging (org-local-logging logging))
  11280. (when (and (or org-todo-log-states org-log-done)
  11281. (not (eq org-inhibit-logging t))
  11282. (not (memq arg '(nextset previousset))))
  11283. ;; We need to look at recording a time and note.
  11284. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11285. (nth 2 (assoc this org-todo-log-states))))
  11286. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11287. (setq dolog 'time))
  11288. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11289. (and org-state
  11290. (member org-state org-not-done-keywords)
  11291. (not (member this org-not-done-keywords))))
  11292. ;; This is now a todo state and was not one before
  11293. ;; If there was a CLOSED time stamp, get rid of it.
  11294. (org-add-planning-info nil nil 'closed))
  11295. (when (and now-done-p org-log-done)
  11296. ;; It is now done, and it was not done before.
  11297. (org-add-planning-info 'closed (org-current-effective-time))
  11298. (when (and (not dolog) (eq 'note org-log-done))
  11299. (org-add-log-setup 'done org-state this 'note)))
  11300. (when (and org-state dolog)
  11301. ;; This is a non-nil state, and we need to log it.
  11302. (org-add-log-setup 'state org-state this dolog)))
  11303. ;; Fixup tag positioning.
  11304. (org-todo-trigger-tag-changes org-state)
  11305. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11306. (when org-provide-todo-statistics
  11307. (org-update-parent-todo-statistics))
  11308. (run-hooks 'org-after-todo-state-change-hook)
  11309. (when (and arg (not (member org-state org-done-keywords)))
  11310. (setq head (org-get-todo-sequence-head org-state)))
  11311. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11312. ;; Do we need to trigger a repeat?
  11313. (when now-done-p
  11314. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11315. ;; This is for the agenda, take a snapshot of the headline.
  11316. (save-match-data
  11317. (setq org-agenda-headline-snapshot-before-repeat
  11318. (org-get-heading))))
  11319. (org-auto-repeat-maybe org-state))
  11320. ;; Fixup cursor location if close to the keyword.
  11321. (when (and (outline-on-heading-p)
  11322. (not (bolp))
  11323. (save-excursion (beginning-of-line 1)
  11324. (looking-at org-todo-line-regexp))
  11325. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11326. (goto-char (or (match-end 2) (match-end 1)))
  11327. (and (looking-at " ") (just-one-space)))
  11328. (when org-trigger-hook
  11329. (save-excursion
  11330. (run-hook-with-args 'org-trigger-hook change-plist)))
  11331. (when commentp (org-toggle-comment))))))))
  11332. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11333. "Block turning an entry into a TODO, using the hierarchy.
  11334. This checks whether the current task should be blocked from state
  11335. changes. Such blocking occurs when:
  11336. 1. The task has children which are not all in a completed state.
  11337. 2. A task has a parent with the property :ORDERED:, and there
  11338. are siblings prior to the current task with incomplete
  11339. status.
  11340. 3. The parent of the task is blocked because it has siblings that should
  11341. be done first, or is child of a block grandparent TODO entry."
  11342. (if (not org-enforce-todo-dependencies)
  11343. t ; if locally turned off don't block
  11344. (catch 'dont-block
  11345. ;; If this is not a todo state change, or if this entry is already DONE,
  11346. ;; do not block
  11347. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11348. (member (plist-get change-plist :from)
  11349. (cons 'done org-done-keywords))
  11350. (member (plist-get change-plist :to)
  11351. (cons 'todo org-not-done-keywords))
  11352. (not (plist-get change-plist :to)))
  11353. (throw 'dont-block t))
  11354. ;; If this task has children, and any are undone, it's blocked
  11355. (save-excursion
  11356. (org-back-to-heading t)
  11357. (let ((this-level (funcall outline-level)))
  11358. (outline-next-heading)
  11359. (let ((child-level (funcall outline-level)))
  11360. (while (and (not (eobp))
  11361. (> child-level this-level))
  11362. ;; this todo has children, check whether they are all
  11363. ;; completed
  11364. (when (and (not (org-entry-is-done-p))
  11365. (org-entry-is-todo-p))
  11366. (setq org-block-entry-blocking (org-get-heading))
  11367. (throw 'dont-block nil))
  11368. (outline-next-heading)
  11369. (setq child-level (funcall outline-level))))))
  11370. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11371. ;; any previous siblings are undone, it's blocked
  11372. (save-excursion
  11373. (org-back-to-heading t)
  11374. (let* ((pos (point))
  11375. (parent-pos (and (org-up-heading-safe) (point)))
  11376. (case-fold-search nil))
  11377. (unless parent-pos (throw 'dont-block t)) ; no parent
  11378. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11379. (forward-line 1)
  11380. (re-search-forward org-not-done-heading-regexp pos t))
  11381. (setq org-block-entry-blocking (match-string 0))
  11382. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11383. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11384. (while t
  11385. (goto-char parent-pos)
  11386. (unless (looking-at org-not-done-heading-regexp)
  11387. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11388. (setq pos (point))
  11389. (setq parent-pos (and (org-up-heading-safe) (point)))
  11390. (unless parent-pos (throw 'dont-block t)) ; no parent
  11391. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11392. (forward-line 1)
  11393. (re-search-forward org-not-done-heading-regexp pos t)
  11394. (setq org-block-entry-blocking (org-get-heading)))
  11395. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11396. (defcustom org-track-ordered-property-with-tag nil
  11397. "Should the ORDERED property also be shown as a tag?
  11398. The ORDERED property decides if an entry should require subtasks to be
  11399. completed in sequence. Since a property is not very visible, setting
  11400. this option means that toggling the ORDERED property with the command
  11401. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11402. not relevant for the behavior, but it makes things more visible.
  11403. Note that toggling the tag with tags commands will not change the property
  11404. and therefore not influence behavior!
  11405. This can be t, meaning the tag ORDERED should be used, It can also be a
  11406. string to select a different tag for this task."
  11407. :group 'org-todo
  11408. :type '(choice
  11409. (const :tag "No tracking" nil)
  11410. (const :tag "Track with ORDERED tag" t)
  11411. (string :tag "Use other tag")))
  11412. (defun org-toggle-ordered-property ()
  11413. "Toggle the ORDERED property of the current entry.
  11414. For better visibility, you can track the value of this property with a tag.
  11415. See variable `org-track-ordered-property-with-tag'."
  11416. (interactive)
  11417. (let* ((t1 org-track-ordered-property-with-tag)
  11418. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11419. (save-excursion
  11420. (org-back-to-heading)
  11421. (if (org-entry-get nil "ORDERED")
  11422. (progn
  11423. (org-delete-property "ORDERED")
  11424. (and tag (org-toggle-tag tag 'off))
  11425. (message "Subtasks can be completed in arbitrary order"))
  11426. (org-entry-put nil "ORDERED" "t")
  11427. (and tag (org-toggle-tag tag 'on))
  11428. (message "Subtasks must be completed in sequence")))))
  11429. (defun org-block-todo-from-checkboxes (change-plist)
  11430. "Block turning an entry into a TODO, using checkboxes.
  11431. This checks whether the current task should be blocked from state
  11432. changes because there are unchecked boxes in this entry."
  11433. (if (not org-enforce-todo-checkbox-dependencies)
  11434. t ; if locally turned off don't block
  11435. (catch 'dont-block
  11436. ;; If this is not a todo state change, or if this entry is already DONE,
  11437. ;; do not block
  11438. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11439. (member (plist-get change-plist :from)
  11440. (cons 'done org-done-keywords))
  11441. (member (plist-get change-plist :to)
  11442. (cons 'todo org-not-done-keywords))
  11443. (not (plist-get change-plist :to)))
  11444. (throw 'dont-block t))
  11445. ;; If this task has checkboxes that are not checked, it's blocked
  11446. (save-excursion
  11447. (org-back-to-heading t)
  11448. (let ((beg (point)) end)
  11449. (outline-next-heading)
  11450. (setq end (point))
  11451. (goto-char beg)
  11452. (when (org-list-search-forward
  11453. (concat (org-item-beginning-re)
  11454. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11455. "\\[[- ]\\]")
  11456. end t)
  11457. (when (boundp 'org-blocked-by-checkboxes)
  11458. (setq org-blocked-by-checkboxes t))
  11459. (throw 'dont-block nil))))
  11460. t))) ; do not block
  11461. (defun org-entry-blocked-p ()
  11462. "Non-nil if entry at point is blocked."
  11463. (and (not (org-entry-get nil "NOBLOCKING"))
  11464. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11465. (not (run-hook-with-args-until-failure
  11466. 'org-blocker-hook
  11467. (list :type 'todo-state-change
  11468. :position (point)
  11469. :from 'todo
  11470. :to 'done)))))
  11471. (defun org-update-statistics-cookies (all)
  11472. "Update the statistics cookie, either from TODO or from checkboxes.
  11473. This should be called with the cursor in a line with a statistics
  11474. cookie. When called with a \\[universal-argument] prefix, update
  11475. all statistics cookies in the buffer."
  11476. (interactive "P")
  11477. (if all
  11478. (progn
  11479. (org-update-checkbox-count 'all)
  11480. (org-map-entries 'org-update-parent-todo-statistics))
  11481. (if (not (org-at-heading-p))
  11482. (org-update-checkbox-count)
  11483. (let ((pos (point-marker))
  11484. end l1 l2)
  11485. (ignore-errors (org-back-to-heading t))
  11486. (if (not (org-at-heading-p))
  11487. (org-update-checkbox-count)
  11488. (setq l1 (org-outline-level))
  11489. (setq end (save-excursion
  11490. (outline-next-heading)
  11491. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11492. (point)))
  11493. (if (and (save-excursion
  11494. (re-search-forward
  11495. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11496. (not (save-excursion (re-search-forward
  11497. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11498. (org-update-checkbox-count)
  11499. (if (and l2 (> l2 l1))
  11500. (progn
  11501. (goto-char end)
  11502. (org-update-parent-todo-statistics))
  11503. (goto-char pos)
  11504. (beginning-of-line 1)
  11505. (while (re-search-forward
  11506. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11507. (point-at-eol) t)
  11508. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11509. (goto-char pos)
  11510. (move-marker pos nil)))))
  11511. (defvar org-entry-property-inherited-from) ;; defined below
  11512. (defun org-update-parent-todo-statistics ()
  11513. "Update any statistics cookie in the parent of the current headline.
  11514. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11515. the entire subtree and this will travel up the hierarchy and update
  11516. statistics everywhere."
  11517. (let* ((prop (save-excursion (org-up-heading-safe)
  11518. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11519. (recursive (or (not org-hierarchical-todo-statistics)
  11520. (and prop (string-match "\\<recursive\\>" prop))))
  11521. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11522. 0))
  11523. (first t)
  11524. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11525. level ltoggle l1 new ndel
  11526. (cnt-all 0) (cnt-done 0) is-percent kwd
  11527. checkbox-beg cookie-present)
  11528. (catch 'exit
  11529. (save-excursion
  11530. (beginning-of-line 1)
  11531. (setq ltoggle (funcall outline-level))
  11532. ;; Three situations are to consider:
  11533. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11534. ;; to the top-level ancestor on the headline;
  11535. ;; 2. If parent has "recursive" property, repeat up to the
  11536. ;; headline setting that property, taking inheritance into
  11537. ;; account;
  11538. ;; 3. Else, move up to direct parent and proceed only once.
  11539. (while (and (setq level (org-up-heading-safe))
  11540. (or recursive first)
  11541. (>= (point) lim))
  11542. (setq first nil cookie-present nil)
  11543. (unless (and level
  11544. (not (string-match
  11545. "\\<checkbox\\>"
  11546. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11547. "")))))
  11548. (throw 'exit nil))
  11549. (while (re-search-forward box-re (point-at-eol) t)
  11550. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11551. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11552. (save-match-data
  11553. (unless (outline-next-heading) (throw 'exit nil))
  11554. (while (and (looking-at org-complex-heading-regexp)
  11555. (> (setq l1 (length (match-string 1))) level))
  11556. (setq kwd (and (or recursive (= l1 ltoggle))
  11557. (match-string 2)))
  11558. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11559. (and (eq org-provide-todo-statistics t)
  11560. (or (member kwd org-done-keywords)))
  11561. (and (listp org-provide-todo-statistics)
  11562. (stringp (car org-provide-todo-statistics))
  11563. (or (member kwd org-provide-todo-statistics)
  11564. (member kwd org-done-keywords)))
  11565. (and (listp org-provide-todo-statistics)
  11566. (listp (car org-provide-todo-statistics))
  11567. (or (member kwd (car org-provide-todo-statistics))
  11568. (and (member kwd org-done-keywords)
  11569. (member kwd (cadr org-provide-todo-statistics))))))
  11570. (setq cnt-all (1+ cnt-all))
  11571. (and (eq org-provide-todo-statistics t)
  11572. kwd
  11573. (setq cnt-all (1+ cnt-all))))
  11574. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11575. (member kwd org-done-keywords))
  11576. (and (listp org-provide-todo-statistics)
  11577. (listp (car org-provide-todo-statistics))
  11578. (member kwd org-done-keywords)
  11579. (member kwd (cadr org-provide-todo-statistics)))
  11580. (and (listp org-provide-todo-statistics)
  11581. (stringp (car org-provide-todo-statistics))
  11582. (member kwd org-done-keywords)))
  11583. (setq cnt-done (1+ cnt-done)))
  11584. (outline-next-heading)))
  11585. (setq new
  11586. (if is-percent
  11587. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11588. (max 1 cnt-all)))
  11589. (format "[%d/%d]" cnt-done cnt-all))
  11590. ndel (- (match-end 0) checkbox-beg))
  11591. (goto-char checkbox-beg)
  11592. (insert new)
  11593. (delete-region (point) (+ (point) ndel))
  11594. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11595. (when cookie-present
  11596. (run-hook-with-args 'org-after-todo-statistics-hook
  11597. cnt-done (- cnt-all cnt-done))))))
  11598. (run-hooks 'org-todo-statistics-hook)))
  11599. (defvar org-after-todo-statistics-hook nil
  11600. "Hook that is called after a TODO statistics cookie has been updated.
  11601. Each function is called with two arguments: the number of not-done entries
  11602. and the number of done entries.
  11603. For example, the following function, when added to this hook, will switch
  11604. an entry to DONE when all children are done, and back to TODO when new
  11605. entries are set to a TODO status. Note that this hook is only called
  11606. when there is a statistics cookie in the headline!
  11607. (defun org-summary-todo (n-done n-not-done)
  11608. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11609. (let (org-log-done org-log-states) ; turn off logging
  11610. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11611. ")
  11612. (defvar org-todo-statistics-hook nil
  11613. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11614. This hook runs even if there is no statistics cookie present, in which case
  11615. `org-after-todo-statistics-hook' would not run.")
  11616. (defun org-todo-trigger-tag-changes (state)
  11617. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11618. (let ((l org-todo-state-tags-triggers)
  11619. changes)
  11620. (when (or (not state) (equal state ""))
  11621. (setq changes (append changes (cdr (assoc "" l)))))
  11622. (when (and (stringp state) (> (length state) 0))
  11623. (setq changes (append changes (cdr (assoc state l)))))
  11624. (when (member state org-not-done-keywords)
  11625. (setq changes (append changes (cdr (assq 'todo l)))))
  11626. (when (member state org-done-keywords)
  11627. (setq changes (append changes (cdr (assq 'done l)))))
  11628. (dolist (c changes)
  11629. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11630. (defun org-local-logging (value)
  11631. "Get logging settings from a property VALUE."
  11632. ;; Directly set the variables, they are already local.
  11633. (setq org-log-done nil
  11634. org-log-repeat nil
  11635. org-todo-log-states nil)
  11636. (dolist (w (org-split-string value))
  11637. (let (a)
  11638. (cond
  11639. ((setq a (assoc w org-startup-options))
  11640. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11641. (set (nth 1 a) (nth 2 a))))
  11642. ((setq a (org-extract-log-state-settings w))
  11643. (and (member (car a) org-todo-keywords-1)
  11644. (push a org-todo-log-states)))))))
  11645. (defun org-get-todo-sequence-head (kwd)
  11646. "Return the head of the TODO sequence to which KWD belongs.
  11647. If KWD is not set, check if there is a text property remembering the
  11648. right sequence."
  11649. (let (p)
  11650. (cond
  11651. ((not kwd)
  11652. (or (get-text-property (point-at-bol) 'org-todo-head)
  11653. (progn
  11654. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11655. nil (point-at-eol)))
  11656. (get-text-property p 'org-todo-head))))
  11657. ((not (member kwd org-todo-keywords-1))
  11658. (car org-todo-keywords-1))
  11659. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11660. (defun org-fast-todo-selection ()
  11661. "Fast TODO keyword selection with single keys.
  11662. Returns the new TODO keyword, or nil if no state change should occur."
  11663. (let* ((fulltable org-todo-key-alist)
  11664. (done-keywords org-done-keywords) ;; needed for the faces.
  11665. (maxlen (apply 'max (mapcar
  11666. (lambda (x)
  11667. (if (stringp (car x)) (string-width (car x)) 0))
  11668. fulltable)))
  11669. (expert nil)
  11670. (fwidth (+ maxlen 3 1 3))
  11671. (ncol (/ (- (window-width) 4) fwidth))
  11672. tg cnt e c tbl
  11673. groups ingroup)
  11674. (save-excursion
  11675. (save-window-excursion
  11676. (if expert
  11677. (set-buffer (get-buffer-create " *Org todo*"))
  11678. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11679. (erase-buffer)
  11680. (setq-local org-done-keywords done-keywords)
  11681. (setq tbl fulltable cnt 0)
  11682. (while (setq e (pop tbl))
  11683. (cond
  11684. ((equal e '(:startgroup))
  11685. (push '() groups) (setq ingroup t)
  11686. (unless (= cnt 0)
  11687. (setq cnt 0)
  11688. (insert "\n"))
  11689. (insert "{ "))
  11690. ((equal e '(:endgroup))
  11691. (setq ingroup nil cnt 0)
  11692. (insert "}\n"))
  11693. ((equal e '(:newline))
  11694. (unless (= cnt 0)
  11695. (setq cnt 0)
  11696. (insert "\n")
  11697. (setq e (car tbl))
  11698. (while (equal (car tbl) '(:newline))
  11699. (insert "\n")
  11700. (setq tbl (cdr tbl)))))
  11701. (t
  11702. (setq tg (car e) c (cdr e))
  11703. (when ingroup (push tg (car groups)))
  11704. (setq tg (org-add-props tg nil 'face
  11705. (org-get-todo-face tg)))
  11706. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11707. (insert "[" c "] " tg (make-string
  11708. (- fwidth 4 (length tg)) ?\ ))
  11709. (when (= (setq cnt (1+ cnt)) ncol)
  11710. (insert "\n")
  11711. (when ingroup (insert " "))
  11712. (setq cnt 0)))))
  11713. (insert "\n")
  11714. (goto-char (point-min))
  11715. (unless expert (org-fit-window-to-buffer))
  11716. (message "[a-z..]:Set [SPC]:clear")
  11717. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11718. (cond
  11719. ((or (= c ?\C-g)
  11720. (and (= c ?q) (not (rassoc c fulltable))))
  11721. (setq quit-flag t))
  11722. ((= c ?\ ) nil)
  11723. ((setq e (rassoc c fulltable) tg (car e))
  11724. tg)
  11725. (t (setq quit-flag t)))))))
  11726. (defun org-entry-is-todo-p ()
  11727. (member (org-get-todo-state) org-not-done-keywords))
  11728. (defun org-entry-is-done-p ()
  11729. (member (org-get-todo-state) org-done-keywords))
  11730. (defun org-get-todo-state ()
  11731. "Return the TODO keyword of the current subtree."
  11732. (save-excursion
  11733. (org-back-to-heading t)
  11734. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11735. (match-end 2)
  11736. (match-string 2))))
  11737. (defun org-at-date-range-p (&optional inactive-ok)
  11738. "Non-nil if point is inside a date range.
  11739. When optional argument INACTIVE-OK is non-nil, also consider
  11740. inactive time ranges.
  11741. When this function returns a non-nil value, match data is set
  11742. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11743. on INACTIVE-OK."
  11744. (interactive)
  11745. (save-excursion
  11746. (catch 'exit
  11747. (let ((pos (point)))
  11748. (skip-chars-backward "^[<\r\n")
  11749. (skip-chars-backward "<[")
  11750. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11751. (>= (match-end 0) pos)
  11752. (throw 'exit t))
  11753. (skip-chars-backward "^<[\r\n")
  11754. (skip-chars-backward "<[")
  11755. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11756. (>= (match-end 0) pos)
  11757. (throw 'exit t)))
  11758. nil)))
  11759. (defun org-get-repeat (&optional timestamp)
  11760. "Check if there is a time-stamp with repeater in this entry.
  11761. Return the repeater, as a string, or nil. Also return nil when
  11762. this function is called before first heading.
  11763. When optional argument TIMESTAMP is a string, extract the
  11764. repeater from there instead."
  11765. (save-match-data
  11766. (cond (timestamp
  11767. (and (string-match org-repeat-re timestamp)
  11768. (match-string-no-properties 1 timestamp)))
  11769. ((org-before-first-heading-p) nil)
  11770. (t
  11771. (save-excursion
  11772. (org-back-to-heading t)
  11773. (let ((end (org-entry-end-position)))
  11774. (catch :repeat
  11775. (while (re-search-forward org-repeat-re end t)
  11776. (when (save-match-data (org-at-timestamp-p 'agenda))
  11777. (throw :repeat (match-string-no-properties 1)))))))))))
  11778. (defvar org-last-changed-timestamp)
  11779. (defvar org-last-inserted-timestamp)
  11780. (defvar org-log-post-message)
  11781. (defvar org-log-note-purpose)
  11782. (defvar org-log-note-how nil)
  11783. (defvar org-log-note-extra)
  11784. (defun org-auto-repeat-maybe (done-word)
  11785. "Check if the current headline contains a repeated time-stamp.
  11786. If yes, set TODO state back to what it was and change the base date
  11787. of repeating deadline/scheduled time stamps to new date.
  11788. This function is run automatically after each state change to a DONE state."
  11789. (let* ((repeat (org-get-repeat))
  11790. (aa (assoc org-last-state org-todo-kwd-alist))
  11791. (interpret (nth 1 aa))
  11792. (head (nth 2 aa))
  11793. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11794. (msg "Entry repeats: ")
  11795. (org-log-done nil)
  11796. (org-todo-log-states nil)
  11797. (end (copy-marker (org-entry-end-position))))
  11798. (unwind-protect
  11799. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11800. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11801. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11802. org-todo-repeat-to-state)))
  11803. (org-todo (cond
  11804. ((and to-state (member to-state org-todo-keywords-1))
  11805. to-state)
  11806. ((eq interpret 'type) org-last-state)
  11807. (head)
  11808. (t 'none))))
  11809. (org-back-to-heading t)
  11810. (org-add-planning-info nil nil 'closed)
  11811. ;; When `org-log-repeat' is non-nil or entry contains
  11812. ;; a clock, set LAST_REPEAT property.
  11813. (when (or org-log-repeat
  11814. (catch :clock
  11815. (while (re-search-forward org-clock-line-re end t)
  11816. (when (org-at-clock-log-p) (throw :clock t)))))
  11817. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11818. (org-time-stamp-format t t)
  11819. (current-time))))
  11820. (when org-log-repeat
  11821. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11822. (memq 'org-add-log-note post-command-hook))
  11823. ;; We are already setup for some record.
  11824. (when (eq org-log-repeat 'note)
  11825. ;; Make sure we take a note, not only a time stamp.
  11826. (setq org-log-note-how 'note))
  11827. ;; Set up for taking a record.
  11828. (org-add-log-setup 'state
  11829. (or done-word (car org-done-keywords))
  11830. org-last-state
  11831. org-log-repeat)))
  11832. (let ((planning-re (regexp-opt
  11833. (list org-scheduled-string org-deadline-string))))
  11834. (while (re-search-forward org-ts-regexp end t)
  11835. (let* ((ts (match-string 0))
  11836. (planning? (org-at-planning-p))
  11837. (type (if (not planning?) "Plain:"
  11838. (save-excursion
  11839. (re-search-backward
  11840. planning-re (line-beginning-position) t)
  11841. (match-string 0)))))
  11842. (cond
  11843. ;; Ignore fake time-stamps (e.g., within comments).
  11844. ((not (org-at-timestamp-p 'agenda)))
  11845. ;; Time-stamps without a repeater are usually
  11846. ;; skipped. However, a SCHEDULED time-stamp without
  11847. ;; one is removed, as they are no longer relevant.
  11848. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11849. ts))
  11850. (when (equal type org-scheduled-string)
  11851. (org-remove-timestamp-with-keyword type)))
  11852. (t
  11853. (let ((n (string-to-number (match-string 2 ts)))
  11854. (what (match-string 3 ts)))
  11855. (when (equal what "w") (setq n (* n 7) what "d"))
  11856. (when (and (equal what "h")
  11857. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11858. ts)))
  11859. (user-error
  11860. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11861. has been set"
  11862. n))
  11863. ;; Preparation, see if we need to modify the start
  11864. ;; date for the change.
  11865. (when (match-end 1)
  11866. (let ((time (save-match-data
  11867. (org-time-string-to-time ts))))
  11868. (cond
  11869. ((equal (match-string 1 ts) ".")
  11870. ;; Shift starting date to today
  11871. (org-timestamp-change
  11872. (- (org-today) (time-to-days time))
  11873. 'day))
  11874. ((equal (match-string 1 ts) "+")
  11875. (let ((nshiftmax 10)
  11876. (nshift 0))
  11877. (while (or (= nshift 0)
  11878. (not (time-less-p (current-time) time)))
  11879. (when (= (cl-incf nshift) nshiftmax)
  11880. (or (y-or-n-p
  11881. (format "%d repeater intervals were not \
  11882. enough to shift date past today. Continue? "
  11883. nshift))
  11884. (user-error "Abort")))
  11885. (org-timestamp-change n (cdr (assoc what whata)))
  11886. (org-in-regexp org-ts-regexp3)
  11887. (setq ts (match-string 1))
  11888. (setq time
  11889. (save-match-data
  11890. (org-time-string-to-time ts)))))
  11891. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11892. ;; Rematch, so that we have everything in place
  11893. ;; for the real shift.
  11894. (org-in-regexp org-ts-regexp3)
  11895. (setq ts (match-string 1))
  11896. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11897. ts)))))
  11898. (save-excursion
  11899. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11900. (setq msg
  11901. (concat
  11902. msg type " " org-last-changed-timestamp " "))))))))
  11903. (setq org-log-post-message msg)
  11904. (message "%s" msg))
  11905. (set-marker end nil))))
  11906. (defun org-show-todo-tree (arg)
  11907. "Make a compact tree which shows all headlines marked with TODO.
  11908. The tree will show the lines where the regexp matches, and all higher
  11909. headlines above the match.
  11910. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11911. With a numeric prefix N, construct a sparse tree for the Nth element
  11912. of `org-todo-keywords-1'."
  11913. (interactive "P")
  11914. (let ((case-fold-search nil)
  11915. (kwd-re
  11916. (cond ((null arg) org-not-done-regexp)
  11917. ((equal arg '(4))
  11918. (let ((kwd
  11919. (completing-read "Keyword (or KWD1|KWD2|...): "
  11920. (mapcar #'list org-todo-keywords-1))))
  11921. (concat "\\("
  11922. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11923. "\\)\\>")))
  11924. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11925. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11926. org-todo-keywords-1)))
  11927. (t (user-error "Invalid prefix argument: %s" arg)))))
  11928. (message "%d TODO entries found"
  11929. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11930. (defun org--deadline-or-schedule (arg type time)
  11931. "Insert DEADLINE or SCHEDULE information in current entry.
  11932. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11933. `org-schedule' for information about ARG and TIME arguments."
  11934. (let* ((deadline? (eq type 'deadline))
  11935. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11936. (log (if deadline? org-log-redeadline org-log-reschedule))
  11937. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11938. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11939. ;; Save repeater cookie from either TIME or current scheduled
  11940. ;; time stamp. We are going to insert it back at the end of
  11941. ;; the process.
  11942. (repeater (or (and (org-string-nw-p time)
  11943. ;; We use `org-repeat-re' because we need
  11944. ;; to tell the difference between a real
  11945. ;; repeater and a time delta, e.g. "+2d".
  11946. (string-match org-repeat-re time)
  11947. (match-string 1 time))
  11948. (and (org-string-nw-p old-date)
  11949. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11950. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11951. old-date)
  11952. (match-string 1 old-date)))))
  11953. (pcase arg
  11954. (`(4)
  11955. (when (and old-date log)
  11956. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11957. nil old-date log))
  11958. (org-remove-timestamp-with-keyword keyword)
  11959. (message (if deadline? "Item no longer has a deadline."
  11960. "Item is no longer scheduled.")))
  11961. (`(16)
  11962. (save-excursion
  11963. (org-back-to-heading t)
  11964. (let ((regexp (if deadline? org-deadline-time-regexp
  11965. org-scheduled-time-regexp)))
  11966. (if (not (re-search-forward regexp (line-end-position 2) t))
  11967. (user-error (if deadline? "No deadline information to update"
  11968. "No scheduled information to update"))
  11969. (let* ((rpl0 (match-string 1))
  11970. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11971. (msg (if deadline? "Warn starting from" "Delay until")))
  11972. (replace-match
  11973. (concat keyword
  11974. " <" rpl
  11975. (format " -%dd"
  11976. (abs (- (time-to-days
  11977. (save-match-data
  11978. (org-read-date
  11979. nil t nil msg old-date-time)))
  11980. (time-to-days old-date-time))))
  11981. ">") t t))))))
  11982. (_
  11983. (org-add-planning-info type time 'closed)
  11984. (when (and old-date
  11985. log
  11986. (not (equal old-date org-last-inserted-timestamp)))
  11987. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11988. org-last-inserted-timestamp
  11989. old-date
  11990. log))
  11991. (when repeater
  11992. (save-excursion
  11993. (org-back-to-heading t)
  11994. (when (re-search-forward
  11995. (concat keyword " " org-last-inserted-timestamp)
  11996. (line-end-position 2)
  11997. t)
  11998. (goto-char (1- (match-end 0)))
  11999. (insert " " repeater)
  12000. (setq org-last-inserted-timestamp
  12001. (concat (substring org-last-inserted-timestamp 0 -1)
  12002. " " repeater
  12003. (substring org-last-inserted-timestamp -1))))))
  12004. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12005. org-last-inserted-timestamp)))))
  12006. (defun org-deadline (arg &optional time)
  12007. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12008. With one universal prefix argument, remove any deadline from the item.
  12009. With two universal prefix arguments, prompt for a warning delay.
  12010. With argument TIME, set the deadline at the corresponding date. TIME
  12011. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12012. (interactive "P")
  12013. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12014. (org-map-entries
  12015. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12016. nil
  12017. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12018. 'region-start-level
  12019. 'region)
  12020. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12021. (org--deadline-or-schedule arg 'deadline time)))
  12022. (defun org-schedule (arg &optional time)
  12023. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12024. With one universal prefix argument, remove any scheduling date from the item.
  12025. With two universal prefix arguments, prompt for a delay cookie.
  12026. With argument TIME, scheduled at the corresponding date. TIME can
  12027. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12028. (interactive "P")
  12029. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12030. (org-map-entries
  12031. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12032. nil
  12033. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12034. 'region-start-level
  12035. 'region)
  12036. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12037. (org--deadline-or-schedule arg 'scheduled time)))
  12038. (defun org-get-scheduled-time (pom &optional inherit)
  12039. "Get the scheduled time as a time tuple, of a format suitable
  12040. for calling org-schedule with, or if there is no scheduling,
  12041. returns nil."
  12042. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12043. (when time
  12044. (apply 'encode-time (org-parse-time-string time)))))
  12045. (defun org-get-deadline-time (pom &optional inherit)
  12046. "Get the deadline as a time tuple, of a format suitable for
  12047. calling org-deadline with, or if there is no scheduling, returns
  12048. nil."
  12049. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12050. (when time
  12051. (apply 'encode-time (org-parse-time-string time)))))
  12052. (defun org-remove-timestamp-with-keyword (keyword)
  12053. "Remove all time stamps with KEYWORD in the current entry."
  12054. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12055. beg)
  12056. (save-excursion
  12057. (org-back-to-heading t)
  12058. (setq beg (point))
  12059. (outline-next-heading)
  12060. (while (re-search-backward re beg t)
  12061. (replace-match "")
  12062. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12063. (equal (char-before) ?\ ))
  12064. (backward-delete-char 1)
  12065. (when (string-match "^[ \t]*$" (buffer-substring
  12066. (point-at-bol) (point-at-eol)))
  12067. (delete-region (point-at-bol)
  12068. (min (point-max) (1+ (point-at-eol))))))))))
  12069. (defvar org-time-was-given) ; dynamically scoped parameter
  12070. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12071. (defun org-at-planning-p ()
  12072. "Non-nil when point is on a planning info line."
  12073. ;; This is as accurate and faster than `org-element-at-point' since
  12074. ;; planning info location is fixed in the section.
  12075. (org-with-wide-buffer
  12076. (beginning-of-line)
  12077. (and (looking-at-p org-planning-line-re)
  12078. (eq (point)
  12079. (ignore-errors
  12080. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12081. (org-back-to-heading t)
  12082. (org-with-limited-levels (org-back-to-heading t)))
  12083. (line-beginning-position 2))))))
  12084. (defun org-add-planning-info (what &optional time &rest remove)
  12085. "Insert new timestamp with keyword in the planning line.
  12086. WHAT indicates what kind of time stamp to add. It is a symbol
  12087. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12088. the time to use. If none is given, the user is prompted for
  12089. a date. REMOVE indicates what kind of entries to remove. An old
  12090. WHAT entry will also be removed."
  12091. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12092. (catch 'exit
  12093. (when (and (memq what '(scheduled deadline))
  12094. (or (not time)
  12095. (and (stringp time)
  12096. (string-match "^[-+]+[0-9]" time))))
  12097. ;; Try to get a default date/time from existing timestamp
  12098. (save-excursion
  12099. (org-back-to-heading t)
  12100. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12101. (when (re-search-forward (if (eq what 'scheduled)
  12102. org-scheduled-time-regexp
  12103. org-deadline-time-regexp)
  12104. end t)
  12105. (setq ts (match-string 1)
  12106. default-time (apply 'encode-time (org-parse-time-string ts))
  12107. default-input (and ts (org-get-compact-tod ts)))))))
  12108. (when what
  12109. (setq time
  12110. (if (stringp time)
  12111. ;; This is a string (relative or absolute), set
  12112. ;; proper date.
  12113. (apply #'encode-time
  12114. (org-read-date-analyze
  12115. time default-time (decode-time default-time)))
  12116. ;; If necessary, get the time from the user
  12117. (or time (org-read-date nil 'to-time nil nil
  12118. default-time default-input)))))
  12119. (org-with-wide-buffer
  12120. (org-back-to-heading t)
  12121. (forward-line)
  12122. (unless (bolp) (insert "\n"))
  12123. (cond ((looking-at-p org-planning-line-re)
  12124. ;; Move to current indentation.
  12125. (skip-chars-forward " \t")
  12126. ;; Check if we have to remove something.
  12127. (dolist (type (if what (cons what remove) remove))
  12128. (save-excursion
  12129. (when (re-search-forward
  12130. (cl-case type
  12131. (closed org-closed-time-regexp)
  12132. (deadline org-deadline-time-regexp)
  12133. (scheduled org-scheduled-time-regexp)
  12134. (otherwise
  12135. (error "Invalid planning type: %s" type)))
  12136. (line-end-position) t)
  12137. ;; Delete until next keyword or end of line.
  12138. (delete-region
  12139. (match-beginning 0)
  12140. (if (re-search-forward org-keyword-time-not-clock-regexp
  12141. (line-end-position)
  12142. t)
  12143. (match-beginning 0)
  12144. (line-end-position))))))
  12145. ;; If there is nothing more to add and no more keyword
  12146. ;; is left, remove the line completely.
  12147. (if (and (looking-at-p "[ \t]*$") (not what))
  12148. (delete-region (line-beginning-position)
  12149. (line-beginning-position 2))
  12150. ;; If we removed last keyword, do not leave trailing
  12151. ;; white space at the end of line.
  12152. (let ((p (point)))
  12153. (save-excursion
  12154. (end-of-line)
  12155. (unless (= (skip-chars-backward " \t" p) 0)
  12156. (delete-region (point) (line-end-position)))))))
  12157. ((not what) (throw 'exit nil)) ; Nothing to do.
  12158. (t (insert-before-markers "\n")
  12159. (backward-char 1)
  12160. (when org-adapt-indentation
  12161. (indent-to-column (1+ (org-outline-level))))))
  12162. (when what
  12163. ;; Insert planning keyword.
  12164. (insert (cl-case what
  12165. (closed org-closed-string)
  12166. (deadline org-deadline-string)
  12167. (scheduled org-scheduled-string)
  12168. (otherwise (error "Invalid planning type: %s" what)))
  12169. " ")
  12170. ;; Insert associated timestamp.
  12171. (let ((ts (org-insert-time-stamp
  12172. time
  12173. (or org-time-was-given
  12174. (and (eq what 'closed) org-log-done-with-time))
  12175. (eq what 'closed)
  12176. nil nil (list org-end-time-was-given))))
  12177. (unless (eolp) (insert " "))
  12178. ts))))))
  12179. (defvar org-log-note-marker (make-marker)
  12180. "Marker pointing at the entry where the note is to be inserted.")
  12181. (defvar org-log-note-purpose nil)
  12182. (defvar org-log-note-state nil)
  12183. (defvar org-log-note-previous-state nil)
  12184. (defvar org-log-note-extra nil)
  12185. (defvar org-log-note-window-configuration nil)
  12186. (defvar org-log-note-return-to (make-marker))
  12187. (defvar org-log-note-effective-time nil
  12188. "Remembered current time so that dynamically scoped
  12189. `org-extend-today-until' affects timestamps in state change log")
  12190. (defvar org-log-post-message nil
  12191. "Message to be displayed after a log note has been stored.
  12192. The auto-repeater uses this.")
  12193. (defun org-add-note ()
  12194. "Add a note to the current entry.
  12195. This is done in the same way as adding a state change note."
  12196. (interactive)
  12197. (org-add-log-setup 'note))
  12198. (defun org-log-beginning (&optional create)
  12199. "Return expected start of log notes in current entry.
  12200. When optional argument CREATE is non-nil, the function creates
  12201. a drawer to store notes, if necessary. Returned position ignores
  12202. narrowing."
  12203. (org-with-wide-buffer
  12204. (let ((drawer (org-log-into-drawer)))
  12205. (cond
  12206. (drawer
  12207. (org-end-of-meta-data)
  12208. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12209. (end (if (org-at-heading-p) (point)
  12210. (save-excursion (outline-next-heading) (point))))
  12211. (case-fold-search t))
  12212. (catch 'exit
  12213. ;; Try to find existing drawer.
  12214. (while (re-search-forward regexp end t)
  12215. (let ((element (org-element-at-point)))
  12216. (when (eq (org-element-type element) 'drawer)
  12217. (let ((cend (org-element-property :contents-end element)))
  12218. (when (and (not org-log-states-order-reversed) cend)
  12219. (goto-char cend)))
  12220. (throw 'exit nil))))
  12221. ;; No drawer found. Create one, if permitted.
  12222. (when create
  12223. (unless (bolp) (insert "\n"))
  12224. (let ((beg (point)))
  12225. (insert ":" drawer ":\n:END:\n")
  12226. (org-indent-region beg (point)))
  12227. (end-of-line -1)))))
  12228. (t
  12229. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12230. (skip-chars-forward " \t\n")
  12231. (beginning-of-line)
  12232. (unless org-log-states-order-reversed
  12233. (org-skip-over-state-notes)
  12234. (skip-chars-backward " \t\n")
  12235. (forward-line)))))
  12236. (if (bolp) (point) (line-beginning-position 2))))
  12237. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12238. "Set up the post command hook to take a note.
  12239. If this is about to TODO state change, the new state is expected in STATE.
  12240. HOW is an indicator what kind of note should be created.
  12241. EXTRA is additional text that will be inserted into the notes buffer."
  12242. (move-marker org-log-note-marker (point))
  12243. (setq org-log-note-purpose purpose
  12244. org-log-note-state state
  12245. org-log-note-previous-state prev-state
  12246. org-log-note-how how
  12247. org-log-note-extra extra
  12248. org-log-note-effective-time (org-current-effective-time))
  12249. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12250. (defun org-skip-over-state-notes ()
  12251. "Skip past the list of State notes in an entry."
  12252. (when (ignore-errors (goto-char (org-in-item-p)))
  12253. (let* ((struct (org-list-struct))
  12254. (prevs (org-list-prevs-alist struct))
  12255. (regexp
  12256. (concat "[ \t]*- +"
  12257. (replace-regexp-in-string
  12258. " +" " +"
  12259. (org-replace-escapes
  12260. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12261. `(("%d" . ,org-ts-regexp-inactive)
  12262. ("%D" . ,org-ts-regexp)
  12263. ("%s" . "\"\\S-+\"")
  12264. ("%S" . "\"\\S-+\"")
  12265. ("%t" . ,org-ts-regexp-inactive)
  12266. ("%T" . ,org-ts-regexp)
  12267. ("%u" . ".*?")
  12268. ("%U" . ".*?")))))))
  12269. (while (looking-at-p regexp)
  12270. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12271. (org-list-get-item-end (point) struct)))))))
  12272. (defun org-add-log-note (&optional _purpose)
  12273. "Pop up a window for taking a note, and add this note later."
  12274. (remove-hook 'post-command-hook 'org-add-log-note)
  12275. (setq org-log-note-window-configuration (current-window-configuration))
  12276. (delete-other-windows)
  12277. (move-marker org-log-note-return-to (point))
  12278. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12279. (goto-char org-log-note-marker)
  12280. (org-switch-to-buffer-other-window "*Org Note*")
  12281. (erase-buffer)
  12282. (if (memq org-log-note-how '(time state))
  12283. (org-store-log-note)
  12284. (let ((org-inhibit-startup t)) (org-mode))
  12285. (insert (format "# Insert note for %s.
  12286. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12287. (cond
  12288. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12289. ((eq org-log-note-purpose 'done) "closed todo item")
  12290. ((eq org-log-note-purpose 'state)
  12291. (format "state change from \"%s\" to \"%s\""
  12292. (or org-log-note-previous-state "")
  12293. (or org-log-note-state "")))
  12294. ((eq org-log-note-purpose 'reschedule)
  12295. "rescheduling")
  12296. ((eq org-log-note-purpose 'delschedule)
  12297. "no longer scheduled")
  12298. ((eq org-log-note-purpose 'redeadline)
  12299. "changing deadline")
  12300. ((eq org-log-note-purpose 'deldeadline)
  12301. "removing deadline")
  12302. ((eq org-log-note-purpose 'refile)
  12303. "refiling")
  12304. ((eq org-log-note-purpose 'note)
  12305. "this entry")
  12306. (t (error "This should not happen")))))
  12307. (when org-log-note-extra (insert org-log-note-extra))
  12308. (setq-local org-finish-function 'org-store-log-note)
  12309. (run-hooks 'org-log-buffer-setup-hook)))
  12310. (defvar org-note-abort nil) ; dynamically scoped
  12311. (defun org-store-log-note ()
  12312. "Finish taking a log note, and insert it to where it belongs."
  12313. (let ((txt (prog1 (buffer-string)
  12314. (kill-buffer)))
  12315. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12316. lines)
  12317. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12318. (setq txt (replace-match "" t t txt)))
  12319. (when (string-match "\\s-+\\'" txt)
  12320. (setq txt (replace-match "" t t txt)))
  12321. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12322. (when (org-string-nw-p note)
  12323. (setq note
  12324. (org-replace-escapes
  12325. note
  12326. (list (cons "%u" (user-login-name))
  12327. (cons "%U" user-full-name)
  12328. (cons "%t" (format-time-string
  12329. (org-time-stamp-format 'long 'inactive)
  12330. org-log-note-effective-time))
  12331. (cons "%T" (format-time-string
  12332. (org-time-stamp-format 'long nil)
  12333. org-log-note-effective-time))
  12334. (cons "%d" (format-time-string
  12335. (org-time-stamp-format nil 'inactive)
  12336. org-log-note-effective-time))
  12337. (cons "%D" (format-time-string
  12338. (org-time-stamp-format nil nil)
  12339. org-log-note-effective-time))
  12340. (cons "%s" (cond
  12341. ((not org-log-note-state) "")
  12342. ((string-match-p org-ts-regexp
  12343. org-log-note-state)
  12344. (format "\"[%s]\""
  12345. (substring org-log-note-state 1 -1)))
  12346. (t (format "\"%s\"" org-log-note-state))))
  12347. (cons "%S"
  12348. (cond
  12349. ((not org-log-note-previous-state) "")
  12350. ((string-match-p org-ts-regexp
  12351. org-log-note-previous-state)
  12352. (format "\"[%s]\""
  12353. (substring
  12354. org-log-note-previous-state 1 -1)))
  12355. (t (format "\"%s\""
  12356. org-log-note-previous-state)))))))
  12357. (when lines (setq note (concat note " \\\\")))
  12358. (push note lines))
  12359. (when (and lines (not org-note-abort))
  12360. (with-current-buffer (marker-buffer org-log-note-marker)
  12361. (org-with-wide-buffer
  12362. ;; Find location for the new note.
  12363. (goto-char org-log-note-marker)
  12364. (set-marker org-log-note-marker nil)
  12365. ;; Note associated to a clock is to be located right after
  12366. ;; the clock. Do not move point.
  12367. (unless (eq org-log-note-purpose 'clock-out)
  12368. (goto-char (org-log-beginning t)))
  12369. ;; Make sure point is at the beginning of an empty line.
  12370. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12371. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12372. ;; In an existing list, add a new item at the top level.
  12373. ;; Otherwise, indent line like a regular one.
  12374. (let ((itemp (org-in-item-p)))
  12375. (if itemp
  12376. (indent-line-to
  12377. (let ((struct (save-excursion
  12378. (goto-char itemp) (org-list-struct))))
  12379. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12380. (org-indent-line)))
  12381. (insert (org-list-bullet-string "-") (pop lines))
  12382. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12383. (dolist (line lines)
  12384. (insert "\n")
  12385. (indent-line-to ind)
  12386. (insert line)))
  12387. (message "Note stored")
  12388. (org-back-to-heading t)
  12389. (org-cycle-hide-drawers 'children))
  12390. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12391. ;; from within `org-add-log-note' because `buffer-undo-list'
  12392. ;; is then modified outside of `org-with-remote-undo'.
  12393. (when (eq this-command 'org-agenda-todo)
  12394. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12395. ;; Don't add undo information when called from `org-agenda-todo'.
  12396. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12397. (set-window-configuration org-log-note-window-configuration)
  12398. (with-current-buffer (marker-buffer org-log-note-return-to)
  12399. (goto-char org-log-note-return-to))
  12400. (move-marker org-log-note-return-to nil)
  12401. (when org-log-post-message (message "%s" org-log-post-message))))
  12402. (defun org-remove-empty-drawer-at (pos)
  12403. "Remove an empty drawer at position POS.
  12404. POS may also be a marker."
  12405. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12406. (org-with-wide-buffer
  12407. (goto-char pos)
  12408. (let ((drawer (org-element-at-point)))
  12409. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12410. (not (org-element-property :contents-begin drawer)))
  12411. (delete-region (org-element-property :begin drawer)
  12412. (progn (goto-char (org-element-property :end drawer))
  12413. (skip-chars-backward " \r\t\n")
  12414. (forward-line)
  12415. (point))))))))
  12416. (defvar org-ts-type nil)
  12417. (defun org-sparse-tree (&optional arg type)
  12418. "Create a sparse tree, prompt for the details.
  12419. This command can create sparse trees. You first need to select the type
  12420. of match used to create the tree:
  12421. t Show all TODO entries.
  12422. T Show entries with a specific TODO keyword.
  12423. m Show entries selected by a tags/property match.
  12424. p Enter a property name and its value (both with completion on existing
  12425. names/values) and show entries with that property.
  12426. r Show entries matching a regular expression (`/' can be used as well).
  12427. b Show deadlines and scheduled items before a date.
  12428. a Show deadlines and scheduled items after a date.
  12429. d Show deadlines due within `org-deadline-warning-days'.
  12430. D Show deadlines and scheduled items between a date range."
  12431. (interactive "P")
  12432. (setq type (or type org-sparse-tree-default-date-type))
  12433. (setq org-ts-type type)
  12434. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12435. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12436. \[c]ycle through date types: %s"
  12437. (cl-case type
  12438. (all "all timestamps")
  12439. (scheduled "only scheduled")
  12440. (deadline "only deadline")
  12441. (active "only active timestamps")
  12442. (inactive "only inactive timestamps")
  12443. (closed "with a closed time-stamp")
  12444. (otherwise "scheduled/deadline")))
  12445. (let ((answer (read-char-exclusive)))
  12446. (cl-case answer
  12447. (?c
  12448. (org-sparse-tree
  12449. arg
  12450. (cadr
  12451. (memq type '(nil all scheduled deadline active inactive closed)))))
  12452. (?d (call-interactively 'org-check-deadlines))
  12453. (?b (call-interactively 'org-check-before-date))
  12454. (?a (call-interactively 'org-check-after-date))
  12455. (?D (call-interactively 'org-check-dates-range))
  12456. (?t (call-interactively 'org-show-todo-tree))
  12457. (?T (org-show-todo-tree '(4)))
  12458. (?m (call-interactively 'org-match-sparse-tree))
  12459. ((?p ?P)
  12460. (let* ((kwd (completing-read
  12461. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12462. (value (completing-read
  12463. "Value: " (mapcar #'list (org-property-values kwd)))))
  12464. (unless (string-match "\\`{.*}\\'" value)
  12465. (setq value (concat "\"" value "\"")))
  12466. (org-match-sparse-tree arg (concat kwd "=" value))))
  12467. ((?r ?R ?/) (call-interactively 'org-occur))
  12468. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12469. (defvar-local org-occur-highlights nil
  12470. "List of overlays used for occur matches.")
  12471. (defvar-local org-occur-parameters nil
  12472. "Parameters of the active org-occur calls.
  12473. This is a list, each call to org-occur pushes as cons cell,
  12474. containing the regular expression and the callback, onto the list.
  12475. The list can contain several entries if `org-occur' has been called
  12476. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12477. will only contain one set of parameters. When the highlights are
  12478. removed (for example with `C-c C-c', or with the next edit (depending
  12479. on `org-remove-highlights-with-change'), this variable is emptied
  12480. as well.")
  12481. (defun org-occur (regexp &optional keep-previous callback)
  12482. "Make a compact tree which shows all matches of REGEXP.
  12483. The tree will show the lines where the regexp matches, and any other context
  12484. defined in `org-show-context-detail', which see.
  12485. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12486. done by a previous call to `org-occur' will be kept, to allow stacking of
  12487. calls to this command.
  12488. Optional argument CALLBACK can be a function of no argument. In this case,
  12489. it is called with point at the end of the match, match data being set
  12490. accordingly. Current match is shown only if the return value is non-nil.
  12491. The function must neither move point nor alter narrowing."
  12492. (interactive "sRegexp: \nP")
  12493. (when (equal regexp "")
  12494. (user-error "Regexp cannot be empty"))
  12495. (unless keep-previous
  12496. (org-remove-occur-highlights nil nil t))
  12497. (push (cons regexp callback) org-occur-parameters)
  12498. (let ((cnt 0))
  12499. (save-excursion
  12500. (goto-char (point-min))
  12501. (when (or (not keep-previous) ; do not want to keep
  12502. (not org-occur-highlights)) ; no previous matches
  12503. ;; hide everything
  12504. (org-overview))
  12505. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12506. (isearch-no-upper-case-p regexp t)
  12507. org-occur-case-fold-search)))
  12508. (while (re-search-forward regexp nil t)
  12509. (when (or (not callback)
  12510. (save-match-data (funcall callback)))
  12511. (setq cnt (1+ cnt))
  12512. (when org-highlight-sparse-tree-matches
  12513. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12514. (org-show-context 'occur-tree)))))
  12515. (when org-remove-highlights-with-change
  12516. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12517. nil 'local))
  12518. (unless org-sparse-tree-open-archived-trees
  12519. (org-hide-archived-subtrees (point-min) (point-max)))
  12520. (run-hooks 'org-occur-hook)
  12521. (when (called-interactively-p 'interactive)
  12522. (message "%d match(es) for regexp %s" cnt regexp))
  12523. cnt))
  12524. (defun org-occur-next-match (&optional n _reset)
  12525. "Function for `next-error-function' to find sparse tree matches.
  12526. N is the number of matches to move, when negative move backwards.
  12527. This function always goes back to the starting point when no
  12528. match is found."
  12529. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12530. (search-func (if (< n 0)
  12531. 'previous-single-char-property-change
  12532. 'next-single-char-property-change))
  12533. (n (abs n))
  12534. (pos (point))
  12535. p1)
  12536. (catch 'exit
  12537. (while (setq p1 (funcall search-func (point) 'org-type))
  12538. (when (equal p1 limit)
  12539. (goto-char pos)
  12540. (user-error "No more matches"))
  12541. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12542. (setq n (1- n))
  12543. (when (= n 0)
  12544. (goto-char p1)
  12545. (throw 'exit (point))))
  12546. (goto-char p1))
  12547. (goto-char p1)
  12548. (user-error "No more matches"))))
  12549. (defun org-show-context (&optional key)
  12550. "Make sure point and context are visible.
  12551. Optional argument KEY, when non-nil, is a symbol. See
  12552. `org-show-context-detail' for allowed values and how much is to
  12553. be shown."
  12554. (org-show-set-visibility
  12555. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12556. ((cdr (assq key org-show-context-detail)))
  12557. (t (cdr (assq 'default org-show-context-detail))))))
  12558. (defun org-show-set-visibility (detail)
  12559. "Set visibility around point according to DETAIL.
  12560. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12561. `tree', `canonical' or t. See `org-show-context-detail' for more
  12562. information."
  12563. ;; Show current heading and possibly its entry, following headline
  12564. ;; or all children.
  12565. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12566. (org-flag-heading nil)
  12567. (org-show-entry)
  12568. ;; If point is hidden within a drawer or a block, make sure to
  12569. ;; expose it.
  12570. (dolist (o (overlays-at (point)))
  12571. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12572. (delete-overlay o)))
  12573. (unless (org-before-first-heading-p)
  12574. (org-with-limited-levels
  12575. (cl-case detail
  12576. ((tree canonical t) (org-show-children))
  12577. ((nil minimal ancestors))
  12578. (t (save-excursion
  12579. (outline-next-heading)
  12580. (org-flag-heading nil)))))))
  12581. ;; Show all siblings.
  12582. (when (eq detail 'lineage) (org-show-siblings))
  12583. ;; Show ancestors, possibly with their children.
  12584. (when (memq detail '(ancestors lineage tree canonical t))
  12585. (save-excursion
  12586. (while (org-up-heading-safe)
  12587. (org-flag-heading nil)
  12588. (when (memq detail '(canonical t)) (org-show-entry))
  12589. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12590. (defvar org-reveal-start-hook nil
  12591. "Hook run before revealing a location.")
  12592. (defun org-reveal (&optional siblings)
  12593. "Show current entry, hierarchy above it, and the following headline.
  12594. This can be used to show a consistent set of context around
  12595. locations exposed with `org-show-context'.
  12596. With optional argument SIBLINGS, on each level of the hierarchy all
  12597. siblings are shown. This repairs the tree structure to what it would
  12598. look like when opened with hierarchical calls to `org-cycle'.
  12599. With a \\[universal-argument] \\[universal-argument] prefix, \
  12600. go to the parent and show the entire tree."
  12601. (interactive "P")
  12602. (run-hooks 'org-reveal-start-hook)
  12603. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12604. ((equal siblings '(16))
  12605. (save-excursion
  12606. (when (org-up-heading-safe)
  12607. (org-show-subtree)
  12608. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12609. (t (org-show-set-visibility 'lineage))))
  12610. (defun org-highlight-new-match (beg end)
  12611. "Highlight from BEG to END and mark the highlight is an occur headline."
  12612. (let ((ov (make-overlay beg end)))
  12613. (overlay-put ov 'face 'secondary-selection)
  12614. (overlay-put ov 'org-type 'org-occur)
  12615. (push ov org-occur-highlights)))
  12616. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12617. "Remove the occur highlights from the buffer.
  12618. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12619. from the `before-change-functions' in the current buffer."
  12620. (interactive)
  12621. (unless org-inhibit-highlight-removal
  12622. (mapc #'delete-overlay org-occur-highlights)
  12623. (setq org-occur-highlights nil)
  12624. (setq org-occur-parameters nil)
  12625. (unless noremove
  12626. (remove-hook 'before-change-functions
  12627. 'org-remove-occur-highlights 'local))))
  12628. ;;;; Priorities
  12629. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12630. "Regular expression matching the priority indicator.")
  12631. (defvar org-remove-priority-next-time nil)
  12632. (defun org-priority-up ()
  12633. "Increase the priority of the current item."
  12634. (interactive)
  12635. (org-priority 'up))
  12636. (defun org-priority-down ()
  12637. "Decrease the priority of the current item."
  12638. (interactive)
  12639. (org-priority 'down))
  12640. (defun org-priority (&optional action _show)
  12641. "Change the priority of an item.
  12642. ACTION can be `set', `up', `down', or a character."
  12643. (interactive "P")
  12644. (if (equal action '(4))
  12645. (org-show-priority)
  12646. (unless org-enable-priority-commands
  12647. (user-error "Priority commands are disabled"))
  12648. (setq action (or action 'set))
  12649. (let (current new news have remove)
  12650. (save-excursion
  12651. (org-back-to-heading t)
  12652. (when (looking-at org-priority-regexp)
  12653. (setq current (string-to-char (match-string 2))
  12654. have t))
  12655. (cond
  12656. ((eq action 'remove)
  12657. (setq remove t new ?\ ))
  12658. ((or (eq action 'set)
  12659. (integerp action))
  12660. (if (not (eq action 'set))
  12661. (setq new action)
  12662. (message "Priority %c-%c, SPC to remove: "
  12663. org-highest-priority org-lowest-priority)
  12664. (save-match-data
  12665. (setq new (read-char-exclusive))))
  12666. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12667. (= (upcase org-lowest-priority) org-lowest-priority))
  12668. (setq new (upcase new)))
  12669. (cond ((equal new ?\ ) (setq remove t))
  12670. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12671. (user-error "Priority must be between `%c' and `%c'"
  12672. org-highest-priority org-lowest-priority))))
  12673. ((eq action 'up)
  12674. (setq new (if have
  12675. (1- current) ; normal cycling
  12676. ;; last priority was empty
  12677. (if (eq last-command this-command)
  12678. org-lowest-priority ; wrap around empty to lowest
  12679. ;; default
  12680. (if org-priority-start-cycle-with-default
  12681. org-default-priority
  12682. (1- org-default-priority))))))
  12683. ((eq action 'down)
  12684. (setq new (if have
  12685. (1+ current) ; normal cycling
  12686. ;; last priority was empty
  12687. (if (eq last-command this-command)
  12688. org-highest-priority ; wrap around empty to highest
  12689. ;; default
  12690. (if org-priority-start-cycle-with-default
  12691. org-default-priority
  12692. (1+ org-default-priority))))))
  12693. (t (user-error "Invalid action")))
  12694. (when (or (< (upcase new) org-highest-priority)
  12695. (> (upcase new) org-lowest-priority))
  12696. (if (and (memq action '(up down))
  12697. (not have) (not (eq last-command this-command)))
  12698. ;; `new' is from default priority
  12699. (error
  12700. "The default can not be set, see `org-default-priority' why")
  12701. ;; normal cycling: `new' is beyond highest/lowest priority
  12702. ;; and is wrapped around to the empty priority
  12703. (setq remove t)))
  12704. (setq news (format "%c" new))
  12705. (if have
  12706. (if remove
  12707. (replace-match "" t t nil 1)
  12708. (replace-match news t t nil 2))
  12709. (if remove
  12710. (user-error "No priority cookie found in line")
  12711. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12712. (if (match-end 2)
  12713. (progn
  12714. (goto-char (match-end 2))
  12715. (insert " [#" news "]"))
  12716. (goto-char (match-beginning 3))
  12717. (insert "[#" news "] "))))
  12718. (org-set-tags nil 'align))
  12719. (if remove
  12720. (message "Priority removed")
  12721. (message "Priority of current item set to %s" news)))))
  12722. (defun org-show-priority ()
  12723. "Show the priority of the current item.
  12724. This priority is composed of the main priority given with the [#A] cookies,
  12725. and by additional input from the age of a schedules or deadline entry."
  12726. (interactive)
  12727. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12728. (org-get-at-bol 'priority)
  12729. (save-excursion
  12730. (save-match-data
  12731. (beginning-of-line)
  12732. (and (looking-at org-heading-regexp)
  12733. (org-get-priority (match-string 0))))))))
  12734. (message "Priority is %d" (if pri pri -1000))))
  12735. (defun org-get-priority (s)
  12736. "Find priority cookie and return priority."
  12737. (save-match-data
  12738. (if (functionp org-get-priority-function)
  12739. (funcall org-get-priority-function)
  12740. (if (not (string-match org-priority-regexp s))
  12741. (* 1000 (- org-lowest-priority org-default-priority))
  12742. (* 1000 (- org-lowest-priority
  12743. (string-to-char (match-string 2 s))))))))
  12744. ;;;; Tags
  12745. (defvar org-agenda-archives-mode)
  12746. (defvar org-map-continue-from nil
  12747. "Position from where mapping should continue.
  12748. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12749. (defvar org-scanner-tags nil
  12750. "The current tag list while the tags scanner is running.")
  12751. (defvar org-trust-scanner-tags nil
  12752. "Should `org-get-tags-at' use the tags for the scanner.
  12753. This is for internal dynamical scoping only.
  12754. When this is non-nil, the function `org-get-tags-at' will return the value
  12755. of `org-scanner-tags' instead of building the list by itself. This
  12756. can lead to large speed-ups when the tags scanner is used in a file with
  12757. many entries, and when the list of tags is retrieved, for example to
  12758. obtain a list of properties. Building the tags list for each entry in such
  12759. a file becomes an N^2 operation - but with this variable set, it scales
  12760. as N.")
  12761. (defvar org--matcher-tags-todo-only nil)
  12762. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12763. "Scan headline tags with inheritance and produce output ACTION.
  12764. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12765. or `agenda' to produce an entry list for an agenda view. It can also be
  12766. a Lisp form or a function that should be called at each matched headline, in
  12767. this case the return value is a list of all return values from these calls.
  12768. MATCHER is a function accepting three arguments, returning
  12769. a non-nil value whenever a given set of tags qualifies a headline
  12770. for inclusion. See `org-make-tags-matcher' for more information.
  12771. As a special case, it can also be set to t (respectively nil) in
  12772. order to match all (respectively none) headline.
  12773. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12774. keyword are included in the output.
  12775. START-LEVEL can be a string with asterisks, reducing the scope to
  12776. headlines matching this string."
  12777. (require 'org-agenda)
  12778. (let* ((re (concat "^"
  12779. (if start-level
  12780. ;; Get the correct level to match
  12781. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12782. org-outline-regexp)
  12783. " *\\(\\<\\("
  12784. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12785. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12786. (props (list 'face 'default
  12787. 'done-face 'org-agenda-done
  12788. 'undone-face 'default
  12789. 'mouse-face 'highlight
  12790. 'org-not-done-regexp org-not-done-regexp
  12791. 'org-todo-regexp org-todo-regexp
  12792. 'org-complex-heading-regexp org-complex-heading-regexp
  12793. 'help-echo
  12794. (format "mouse-2 or RET jump to org file %s"
  12795. (abbreviate-file-name
  12796. (or (buffer-file-name (buffer-base-buffer))
  12797. (buffer-name (buffer-base-buffer)))))))
  12798. (org-map-continue-from nil)
  12799. lspos tags tags-list
  12800. (tags-alist (list (cons 0 org-file-tags)))
  12801. (llast 0) rtn rtn1 level category i txt
  12802. todo marker entry priority
  12803. ts-date ts-date-type ts-date-pair)
  12804. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12805. (setq action (list 'lambda nil action)))
  12806. (save-excursion
  12807. (goto-char (point-min))
  12808. (when (eq action 'sparse-tree)
  12809. (org-overview)
  12810. (org-remove-occur-highlights))
  12811. (while (let (case-fold-search)
  12812. (re-search-forward re nil t))
  12813. (setq org-map-continue-from nil)
  12814. (catch :skip
  12815. (setq todo
  12816. ;; TODO: is the 1-2 difference a bug?
  12817. (when (match-end 1) (match-string-no-properties 2))
  12818. tags (when (match-end 4) (match-string-no-properties 4)))
  12819. (goto-char (setq lspos (match-beginning 0)))
  12820. (setq level (org-reduced-level (org-outline-level))
  12821. category (org-get-category))
  12822. (when (eq action 'agenda)
  12823. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12824. ts-date (car ts-date-pair)
  12825. ts-date-type (cdr ts-date-pair)))
  12826. (setq i llast llast level)
  12827. ;; remove tag lists from same and sublevels
  12828. (while (>= i level)
  12829. (when (setq entry (assoc i tags-alist))
  12830. (setq tags-alist (delete entry tags-alist)))
  12831. (setq i (1- i)))
  12832. ;; add the next tags
  12833. (when tags
  12834. (setq tags (org-split-string tags ":")
  12835. tags-alist
  12836. (cons (cons level tags) tags-alist)))
  12837. ;; compile tags for current headline
  12838. (setq tags-list
  12839. (if org-use-tag-inheritance
  12840. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12841. tags)
  12842. org-scanner-tags tags-list)
  12843. (when org-use-tag-inheritance
  12844. (setcdr (car tags-alist)
  12845. (mapcar (lambda (x)
  12846. (setq x (copy-sequence x))
  12847. (org-add-prop-inherited x))
  12848. (cdar tags-alist))))
  12849. (when (and tags org-use-tag-inheritance
  12850. (or (not (eq t org-use-tag-inheritance))
  12851. org-tags-exclude-from-inheritance))
  12852. ;; Selective inheritance, remove uninherited ones.
  12853. (setcdr (car tags-alist)
  12854. (org-remove-uninherited-tags (cdar tags-alist))))
  12855. (when (and
  12856. ;; eval matcher only when the todo condition is OK
  12857. (and (or (not todo-only) (member todo org-not-done-keywords))
  12858. (if (functionp matcher)
  12859. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12860. (funcall matcher todo tags-list level))
  12861. matcher))
  12862. ;; Call the skipper, but return t if it does not
  12863. ;; skip, so that the `and' form continues evaluating.
  12864. (progn
  12865. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12866. t)
  12867. ;; Check if timestamps are deselecting this entry
  12868. (or (not todo-only)
  12869. (and (member todo org-not-done-keywords)
  12870. (or (not org-agenda-tags-todo-honor-ignore-options)
  12871. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12872. ;; select this headline
  12873. (cond
  12874. ((eq action 'sparse-tree)
  12875. (and org-highlight-sparse-tree-matches
  12876. (org-get-heading) (match-end 0)
  12877. (org-highlight-new-match
  12878. (match-beginning 1) (match-end 1)))
  12879. (org-show-context 'tags-tree))
  12880. ((eq action 'agenda)
  12881. (setq txt (org-agenda-format-item
  12882. ""
  12883. (concat
  12884. (if (eq org-tags-match-list-sublevels 'indented)
  12885. (make-string (1- level) ?.) "")
  12886. (org-get-heading))
  12887. (make-string level ?\s)
  12888. category
  12889. tags-list)
  12890. priority (org-get-priority txt))
  12891. (goto-char lspos)
  12892. (setq marker (org-agenda-new-marker))
  12893. (org-add-props txt props
  12894. 'org-marker marker 'org-hd-marker marker 'org-category category
  12895. 'todo-state todo
  12896. 'ts-date ts-date
  12897. 'priority priority
  12898. 'type (concat "tagsmatch" ts-date-type))
  12899. (push txt rtn))
  12900. ((functionp action)
  12901. (setq org-map-continue-from nil)
  12902. (save-excursion
  12903. (setq rtn1 (funcall action))
  12904. (push rtn1 rtn)))
  12905. (t (user-error "Invalid action")))
  12906. ;; if we are to skip sublevels, jump to end of subtree
  12907. (unless org-tags-match-list-sublevels
  12908. (org-end-of-subtree t)
  12909. (backward-char 1))))
  12910. ;; Get the correct position from where to continue
  12911. (if org-map-continue-from
  12912. (goto-char org-map-continue-from)
  12913. (and (= (point) lspos) (end-of-line 1)))))
  12914. (when (and (eq action 'sparse-tree)
  12915. (not org-sparse-tree-open-archived-trees))
  12916. (org-hide-archived-subtrees (point-min) (point-max)))
  12917. (nreverse rtn)))
  12918. (defun org-remove-uninherited-tags (tags)
  12919. "Remove all tags that are not inherited from the list TAGS."
  12920. (cond
  12921. ((eq org-use-tag-inheritance t)
  12922. (if org-tags-exclude-from-inheritance
  12923. (org-delete-all org-tags-exclude-from-inheritance tags)
  12924. tags))
  12925. ((not org-use-tag-inheritance) nil)
  12926. ((stringp org-use-tag-inheritance)
  12927. (delq nil (mapcar
  12928. (lambda (x)
  12929. (if (and (string-match org-use-tag-inheritance x)
  12930. (not (member x org-tags-exclude-from-inheritance)))
  12931. x nil))
  12932. tags)))
  12933. ((listp org-use-tag-inheritance)
  12934. (delq nil (mapcar
  12935. (lambda (x)
  12936. (if (member x org-use-tag-inheritance) x nil))
  12937. tags)))))
  12938. (defun org-match-sparse-tree (&optional todo-only match)
  12939. "Create a sparse tree according to tags string MATCH.
  12940. MATCH is a string with match syntax. It can contain a selection
  12941. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12942. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12943. those. See the manual for details.
  12944. If optional argument TODO-ONLY is non-nil, only select lines that
  12945. are also TODO tasks."
  12946. (interactive "P")
  12947. (org-agenda-prepare-buffers (list (current-buffer)))
  12948. (let ((org--matcher-tags-todo-only todo-only))
  12949. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12950. org--matcher-tags-todo-only)))
  12951. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12952. (defvar org-cached-props nil)
  12953. (defun org-cached-entry-get (pom property)
  12954. (if (or (eq t org-use-property-inheritance)
  12955. (and (stringp org-use-property-inheritance)
  12956. (let ((case-fold-search t))
  12957. (string-match-p org-use-property-inheritance property)))
  12958. (and (listp org-use-property-inheritance)
  12959. (member-ignore-case property org-use-property-inheritance)))
  12960. ;; Caching is not possible, check it directly.
  12961. (org-entry-get pom property 'inherit)
  12962. ;; Get all properties, so we can do complicated checks easily.
  12963. (cdr (assoc-string property
  12964. (or org-cached-props
  12965. (setq org-cached-props (org-entry-properties pom)))
  12966. t))))
  12967. (defun org-global-tags-completion-table (&optional files)
  12968. "Return the list of all tags in all agenda buffer/files.
  12969. Optional FILES argument is a list of files which can be used
  12970. instead of the agenda files."
  12971. (save-excursion
  12972. (org-uniquify
  12973. (delq nil
  12974. (apply #'append
  12975. (mapcar
  12976. (lambda (file)
  12977. (set-buffer (find-file-noselect file))
  12978. (mapcar (lambda (x)
  12979. (and (stringp (car-safe x))
  12980. (list (car-safe x))))
  12981. (or org-current-tag-alist (org-get-buffer-tags))))
  12982. (if (car-safe files) files
  12983. (org-agenda-files))))))))
  12984. (defun org-make-tags-matcher (match)
  12985. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12986. Returns a cons of the selection string MATCH and a function
  12987. implementing the matcher.
  12988. The matcher is to be called at an Org entry, with point on the
  12989. headline, and returns non-nil if the entry matches the selection
  12990. string MATCH. It must be called with three arguments: the TODO
  12991. keyword at the entry (or nil if none), the list of all tags at
  12992. the entry including inherited ones and the reduced level of the
  12993. headline. Additionally, the category of the entry, if any, must
  12994. be specified as the text property `org-category' on the headline.
  12995. This function sets the variable `org--matcher-tags-todo-only' to
  12996. a non-nil value if the matcher restricts matching to TODO
  12997. entries, otherwise it is not touched.
  12998. See also `org-scan-tags'."
  12999. (unless match
  13000. ;; Get a new match request, with completion against the global
  13001. ;; tags table and the local tags in current buffer.
  13002. (let ((org-last-tags-completion-table
  13003. (org-uniquify
  13004. (delq nil (append (org-get-buffer-tags)
  13005. (org-global-tags-completion-table))))))
  13006. (setq match
  13007. (completing-read
  13008. "Match: "
  13009. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13010. (let ((match0 match)
  13011. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13012. (start 0)
  13013. tagsmatch todomatch tagsmatcher todomatcher)
  13014. ;; Expand group tags.
  13015. (setq match (org-tags-expand match))
  13016. ;; Check if there is a TODO part of this match, which would be the
  13017. ;; part after a "/". To make sure that this slash is not part of
  13018. ;; a property value to be matched against, we also check that
  13019. ;; there is no / after that slash. First, find the last slash.
  13020. (let ((s 0))
  13021. (while (string-match "/+" match s)
  13022. (setq start (match-beginning 0))
  13023. (setq s (match-end 0))))
  13024. (if (and (string-match "/+" match start)
  13025. (not (string-match-p "\"" match start)))
  13026. ;; Match contains also a TODO-matching request.
  13027. (progn
  13028. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13029. (setq todomatch (substring match (match-end 0)))
  13030. (when (string-prefix-p "!" todomatch)
  13031. (setq org--matcher-tags-todo-only t)
  13032. (setq todomatch (substring todomatch 1)))
  13033. (when (string-match "\\`\\s-*\\'" todomatch)
  13034. (setq todomatch nil)))
  13035. ;; Only matching tags.
  13036. (setq tagsmatch match)
  13037. (setq todomatch nil))
  13038. ;; Make the tags matcher.
  13039. (when (org-string-nw-p tagsmatch)
  13040. (let ((orlist nil)
  13041. (orterms (org-split-string tagsmatch "|"))
  13042. term)
  13043. (while (setq term (pop orterms))
  13044. (while (and (equal (substring term -1) "\\") orterms)
  13045. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13046. (while (string-match re term)
  13047. (let* ((rest (substring term (match-end 0)))
  13048. (minus (and (match-end 1)
  13049. (equal (match-string 1 term) "-")))
  13050. (tag (save-match-data
  13051. (replace-regexp-in-string
  13052. "\\\\-" "-" (match-string 2 term))))
  13053. (regexp (eq (string-to-char tag) ?{))
  13054. (levelp (match-end 4))
  13055. (propp (match-end 5))
  13056. (mm
  13057. (cond
  13058. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13059. (levelp
  13060. `(,(org-op-to-function (match-string 3 term))
  13061. level
  13062. ,(string-to-number (match-string 4 term))))
  13063. (propp
  13064. (let* ((gv (pcase (upcase (match-string 5 term))
  13065. ("CATEGORY"
  13066. '(get-text-property (point) 'org-category))
  13067. ("TODO" 'todo)
  13068. (p `(org-cached-entry-get nil ,p))))
  13069. (pv (match-string 7 term))
  13070. (regexp (eq (string-to-char pv) ?{))
  13071. (strp (eq (string-to-char pv) ?\"))
  13072. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13073. (po (org-op-to-function (match-string 6 term)
  13074. (if timep 'time strp))))
  13075. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13076. (when timep (setq pv (org-matcher-time pv)))
  13077. (cond ((and regexp (eq po 'org<>))
  13078. `(not (string-match ,pv (or ,gv ""))))
  13079. (regexp `(string-match ,pv (or ,gv "")))
  13080. (strp `(,po (or ,gv "") ,pv))
  13081. (t
  13082. `(,po
  13083. (string-to-number (or ,gv ""))
  13084. ,(string-to-number pv))))))
  13085. (t `(member ,tag tags-list)))))
  13086. (push (if minus `(not ,mm) mm) tagsmatcher)
  13087. (setq term rest)))
  13088. (push `(and ,@tagsmatcher) orlist)
  13089. (setq tagsmatcher nil))
  13090. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13091. ;; Make the TODO matcher.
  13092. (when (org-string-nw-p todomatch)
  13093. (let ((orlist nil))
  13094. (dolist (term (org-split-string todomatch "|"))
  13095. (while (string-match re term)
  13096. (let* ((minus (and (match-end 1)
  13097. (equal (match-string 1 term) "-")))
  13098. (kwd (match-string 2 term))
  13099. (regexp (eq (string-to-char kwd) ?{))
  13100. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13101. `(equal todo ,kwd))))
  13102. (push (if minus `(not ,mm) mm) todomatcher))
  13103. (setq term (substring term (match-end 0))))
  13104. (push (if (> (length todomatcher) 1)
  13105. (cons 'and todomatcher)
  13106. (car todomatcher))
  13107. orlist)
  13108. (setq todomatcher nil))
  13109. (setq todomatcher (cons 'or orlist))))
  13110. ;; Return the string and function of the matcher. If no
  13111. ;; tags-specific or todo-specific matcher exists, match
  13112. ;; everything.
  13113. (let ((matcher (if (and tagsmatcher todomatcher)
  13114. `(and ,tagsmatcher ,todomatcher)
  13115. (or tagsmatcher todomatcher t))))
  13116. (when org--matcher-tags-todo-only
  13117. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13118. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13119. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13120. "Expand group tags in MATCH.
  13121. This replaces every group tag in MATCH with a regexp tag search.
  13122. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13123. will be replaced like this:
  13124. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13125. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13126. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13127. Replacing by a regexp preserves the structure of the match.
  13128. E.g., this expansion
  13129. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13130. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13131. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13132. A group tag in MATCH can contain regular expressions of its own.
  13133. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13134. will be replaced like this:
  13135. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13136. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13137. assumed to be a single group tag, and the function will return
  13138. the list of tags in this group.
  13139. When DOWNCASE is non-nil, expand downcased TAGS."
  13140. (if org-group-tags
  13141. (let* ((case-fold-search t)
  13142. (stable org-mode-syntax-table)
  13143. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13144. (taggroups (if downcased
  13145. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13146. taggroups)
  13147. taggroups))
  13148. (taggroups-keys (mapcar #'car taggroups))
  13149. (return-match (if downcased (downcase match) match))
  13150. (count 0)
  13151. (work-already-expanded tags-already-expanded)
  13152. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13153. ;; @ and _ are allowed as word-components in tags.
  13154. (modify-syntax-entry ?@ "w" stable)
  13155. (modify-syntax-entry ?_ "w" stable)
  13156. ;; Temporarily replace regexp-expressions in the match-expression.
  13157. (while (string-match "{.+?}" return-match)
  13158. (cl-incf count)
  13159. (push (match-string 0 return-match) regexps-in-match)
  13160. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13161. (while (and taggroups-keys
  13162. (with-syntax-table stable
  13163. (string-match
  13164. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13165. (regexp-opt taggroups-keys) "\\>\\)")
  13166. return-match)))
  13167. (let* ((dir (match-string 1 return-match))
  13168. (tag (match-string 2 return-match))
  13169. (tag (if downcased (downcase tag) tag)))
  13170. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13171. (member tag work-already-expanded))
  13172. (setq tags-in-group (assoc tag taggroups))
  13173. (push tag work-already-expanded)
  13174. ;; Recursively expand each tag in the group, if the tag hasn't
  13175. ;; already been expanded. Restore the match-data after all recursive calls.
  13176. (save-match-data
  13177. (let (tags-expanded)
  13178. (dolist (x (cdr tags-in-group))
  13179. (if (and (member x taggroups-keys)
  13180. (not (member x work-already-expanded)))
  13181. (setq tags-expanded
  13182. (delete-dups
  13183. (append
  13184. (org-tags-expand x t downcased
  13185. work-already-expanded)
  13186. tags-expanded)))
  13187. (setq tags-expanded
  13188. (append (list x) tags-expanded)))
  13189. (setq work-already-expanded
  13190. (delete-dups
  13191. (append tags-expanded
  13192. work-already-expanded))))
  13193. (setq tags-in-group
  13194. (delete-dups (cons (car tags-in-group)
  13195. tags-expanded)))))
  13196. ;; Filter tag-regexps from tags.
  13197. (setq regexp-in-group-escaped
  13198. (delq nil (mapcar (lambda (x)
  13199. (if (stringp x)
  13200. (and (equal "{" (substring x 0 1))
  13201. (equal "}" (substring x -1))
  13202. x)
  13203. x))
  13204. tags-in-group))
  13205. regexp-in-group
  13206. (mapcar (lambda (x)
  13207. (substring x 1 -1))
  13208. regexp-in-group-escaped)
  13209. tags-in-group
  13210. (delq nil (mapcar (lambda (x)
  13211. (if (stringp x)
  13212. (and (not (equal "{" (substring x 0 1)))
  13213. (not (equal "}" (substring x -1)))
  13214. x)
  13215. x))
  13216. tags-in-group)))
  13217. ;; If single-as-list, do no more in the while-loop.
  13218. (if (not single-as-list)
  13219. (progn
  13220. (when regexp-in-group
  13221. (setq regexp-in-group
  13222. (concat "\\|"
  13223. (mapconcat 'identity regexp-in-group
  13224. "\\|"))))
  13225. (setq tags-in-group
  13226. (concat dir
  13227. "{\\<"
  13228. (regexp-opt tags-in-group)
  13229. "\\>"
  13230. regexp-in-group
  13231. "}"))
  13232. (when (stringp tags-in-group)
  13233. (org-add-props tags-in-group '(grouptag t)))
  13234. (setq return-match
  13235. (replace-match tags-in-group t t return-match)))
  13236. (setq tags-in-group
  13237. (append regexp-in-group-escaped tags-in-group))))
  13238. (setq taggroups-keys (delete tag taggroups-keys))))
  13239. ;; Add the regular expressions back into the match-expression again.
  13240. (while regexps-in-match
  13241. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13242. (pop regexps-in-match)
  13243. return-match t t))
  13244. (cl-decf count))
  13245. (if single-as-list
  13246. (if tags-in-group tags-in-group (list return-match))
  13247. return-match))
  13248. (if single-as-list
  13249. (list (if downcased (downcase match) match))
  13250. match)))
  13251. (defun org-op-to-function (op &optional stringp)
  13252. "Turn an operator into the appropriate function."
  13253. (setq op
  13254. (cond
  13255. ((equal op "<" ) '(< string< org-time<))
  13256. ((equal op ">" ) '(> org-string> org-time>))
  13257. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13258. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13259. ((member op '("=" "==")) '(= string= org-time=))
  13260. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13261. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13262. (defun org<> (a b) (not (= a b)))
  13263. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13264. (defun org-string>= (a b) (not (string< a b)))
  13265. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13266. (defun org-string<> (a b) (not (string= a b)))
  13267. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13268. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13269. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13270. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13271. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13272. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13273. (defun org-2ft (s)
  13274. "Convert S to a floating point time.
  13275. If S is already a number, just return it. If it is a string, parse
  13276. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13277. (cond
  13278. ((numberp s) s)
  13279. ((stringp s)
  13280. (condition-case nil
  13281. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13282. (error 0.)))
  13283. (t 0.)))
  13284. (defun org-time-today ()
  13285. "Time in seconds today at 0:00.
  13286. Returns the float number of seconds since the beginning of the
  13287. epoch to the beginning of today (00:00)."
  13288. (float-time (apply 'encode-time
  13289. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13290. (defun org-matcher-time (s)
  13291. "Interpret a time comparison value."
  13292. (save-match-data
  13293. (cond
  13294. ((string= s "<now>") (float-time))
  13295. ((string= s "<today>") (org-time-today))
  13296. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13297. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13298. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13299. (+ (org-time-today)
  13300. (* (string-to-number (match-string 1 s))
  13301. (cdr (assoc (match-string 2 s)
  13302. '(("d" . 86400.0) ("w" . 604800.0)
  13303. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13304. (t (org-2ft s)))))
  13305. (defun org-match-any-p (re list)
  13306. "Does re match any element of list?"
  13307. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13308. (delq nil list))
  13309. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13310. (defvar org-tags-overlay (make-overlay 1 1))
  13311. (delete-overlay org-tags-overlay)
  13312. (defun org-get-local-tags-at (&optional pos)
  13313. "Get a list of tags defined in the current headline."
  13314. (org-get-tags-at pos 'local))
  13315. (defun org-get-local-tags ()
  13316. "Get a list of tags defined in the current headline."
  13317. (org-get-tags-at nil 'local))
  13318. (defun org-get-tags-at (&optional pos local)
  13319. "Get a list of all headline tags applicable at POS.
  13320. POS defaults to point. If tags are inherited, the list contains
  13321. the targets in the same sequence as the headlines appear, i.e.
  13322. the tags of the current headline come last.
  13323. When LOCAL is non-nil, only return tags from the current headline,
  13324. ignore inherited ones."
  13325. (interactive)
  13326. (if (and org-trust-scanner-tags
  13327. (or (not pos) (equal pos (point)))
  13328. (not local))
  13329. org-scanner-tags
  13330. (let (tags ltags lastpos parent)
  13331. (save-excursion
  13332. (save-restriction
  13333. (widen)
  13334. (goto-char (or pos (point)))
  13335. (save-match-data
  13336. (catch 'done
  13337. (condition-case nil
  13338. (progn
  13339. (org-back-to-heading t)
  13340. (while (not (equal lastpos (point)))
  13341. (setq lastpos (point))
  13342. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13343. (setq ltags (org-split-string
  13344. (match-string-no-properties 1) ":"))
  13345. (when parent
  13346. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13347. (setq tags (append
  13348. (if parent
  13349. (org-remove-uninherited-tags ltags)
  13350. ltags)
  13351. tags)))
  13352. (or org-use-tag-inheritance (throw 'done t))
  13353. (when local (throw 'done t))
  13354. (or (org-up-heading-safe) (error nil))
  13355. (setq parent t)))
  13356. (error nil)))))
  13357. (if local
  13358. tags
  13359. (reverse (delete-dups
  13360. (reverse (append
  13361. (org-remove-uninherited-tags
  13362. org-file-tags)
  13363. tags)))))))))
  13364. (defun org-add-prop-inherited (s)
  13365. (add-text-properties 0 (length s) '(inherited t) s)
  13366. s)
  13367. (defun org-toggle-tag (tag &optional onoff)
  13368. "Toggle the tag TAG for the current line.
  13369. If ONOFF is `on' or `off', don't toggle but set to this state."
  13370. (save-excursion
  13371. (org-back-to-heading t)
  13372. (let ((current
  13373. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13374. (line-end-position) t)
  13375. (prog1 (nreverse (org-split-string (match-string 1) ":"))
  13376. (replace-match ""))))
  13377. res)
  13378. (pcase onoff
  13379. (`off (setq current (delete tag current)))
  13380. ((or `on (guard (not (member tag current))))
  13381. (setq res t)
  13382. (cl-pushnew tag current :test #'equal))
  13383. (_ (setq current (delete tag current))))
  13384. (end-of-line)
  13385. (if current
  13386. (progn
  13387. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13388. (org-set-tags nil t))
  13389. (delete-horizontal-space))
  13390. (run-hooks 'org-after-tags-change-hook)
  13391. res)))
  13392. (defun org--align-tags-here (to-col)
  13393. "Align tags on the current headline to TO-COL.
  13394. Assume point is on a headline."
  13395. (let ((pos (point)))
  13396. (beginning-of-line)
  13397. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13398. (>= pos (match-beginning 2)))
  13399. ;; No tags or point within tags: do not align.
  13400. (goto-char pos)
  13401. (goto-char (match-beginning 1))
  13402. (let ((shift (max (- (if (>= to-col 0) to-col
  13403. (- (abs to-col) (string-width (match-string 2))))
  13404. (current-column))
  13405. 1)))
  13406. (replace-match (make-string shift ?\s) nil nil nil 1)
  13407. ;; Preserve initial position, if possible. In any case, stop
  13408. ;; before tags.
  13409. (when (< pos (point)) (goto-char pos))))))
  13410. (defun org-set-tags-command (&optional arg just-align)
  13411. "Call the set-tags command for the current entry."
  13412. (interactive "P")
  13413. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13414. (org-set-tags arg just-align)
  13415. (save-excursion
  13416. (unless (and (org-region-active-p)
  13417. org-loop-over-headlines-in-active-region)
  13418. (org-back-to-heading t))
  13419. (org-set-tags arg just-align))))
  13420. (defun org-set-tags-to (data)
  13421. "Set the tags of the current entry to DATA, replacing the current tags.
  13422. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13423. If DATA is nil or the empty string, any tags will be removed."
  13424. (interactive "sTags: ")
  13425. (setq data
  13426. (cond
  13427. ((eq data nil) "")
  13428. ((equal data "") "")
  13429. ((stringp data)
  13430. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13431. ":"))
  13432. ((listp data)
  13433. (concat ":" (mapconcat 'identity data ":") ":"))))
  13434. (when data
  13435. (save-excursion
  13436. (org-back-to-heading t)
  13437. (when (let ((case-fold-search nil))
  13438. (looking-at org-complex-heading-regexp))
  13439. (if (match-end 5)
  13440. (progn
  13441. (goto-char (match-beginning 5))
  13442. (insert data)
  13443. (delete-region (point) (point-at-eol))
  13444. (org-set-tags nil 'align))
  13445. (goto-char (point-at-eol))
  13446. (insert " " data)
  13447. (org-set-tags nil 'align)))
  13448. (beginning-of-line 1)
  13449. (when (looking-at ".*?\\([ \t]+\\)$")
  13450. (delete-region (match-beginning 1) (match-end 1))))))
  13451. (defun org-align-all-tags ()
  13452. "Align the tags in all headings."
  13453. (interactive)
  13454. (save-excursion
  13455. (or (ignore-errors (org-back-to-heading t))
  13456. (outline-next-heading))
  13457. (if (org-at-heading-p)
  13458. (org-set-tags t)
  13459. (message "No headings"))))
  13460. (defvar org-indent-indentation-per-level)
  13461. (defun org-set-tags (&optional arg just-align)
  13462. "Set the tags for the current headline.
  13463. With prefix ARG, realign all tags in headings in the current buffer.
  13464. When JUST-ALIGN is non-nil, only align tags."
  13465. (interactive "P")
  13466. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13467. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13468. 'region-start-level
  13469. 'region))
  13470. org-loop-over-headlines-in-active-region)
  13471. (org-map-entries
  13472. ;; We don't use ARG and JUST-ALIGN here because these args
  13473. ;; are not useful when looping over headlines.
  13474. #'org-set-tags
  13475. org-loop-over-headlines-in-active-region
  13476. cl
  13477. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13478. (let ((org-setting-tags t))
  13479. (if arg
  13480. (save-excursion
  13481. (goto-char (point-min))
  13482. (while (re-search-forward org-outline-regexp-bol nil t)
  13483. (org-set-tags nil t)
  13484. (end-of-line))
  13485. (message "All tags realigned to column %d" org-tags-column))
  13486. (let* ((current (org-get-tags-string))
  13487. (tags
  13488. (if just-align current
  13489. ;; Get a new set of tags from the user.
  13490. (save-excursion
  13491. (let* ((seen)
  13492. (table
  13493. (setq
  13494. org-last-tags-completion-table
  13495. ;; Uniquify tags in alists, yet preserve
  13496. ;; structure (i.e., keywords).
  13497. (delq nil
  13498. (mapcar
  13499. (lambda (pair)
  13500. (let ((head (car pair)))
  13501. (cond ((symbolp head) pair)
  13502. ((member head seen) nil)
  13503. (t (push head seen)
  13504. pair))))
  13505. (append
  13506. (or org-current-tag-alist
  13507. (org-get-buffer-tags))
  13508. (and
  13509. org-complete-tags-always-offer-all-agenda-tags
  13510. (org-global-tags-completion-table
  13511. (org-agenda-files))))))))
  13512. (current-tags (org-split-string current ":"))
  13513. (inherited-tags
  13514. (nreverse (nthcdr (length current-tags)
  13515. (nreverse (org-get-tags-at))))))
  13516. (replace-regexp-in-string
  13517. "\\([-+&]+\\|,\\)"
  13518. ":"
  13519. (if (or (eq t org-use-fast-tag-selection)
  13520. (and org-use-fast-tag-selection
  13521. (delq nil (mapcar #'cdr table))))
  13522. (org-fast-tag-selection
  13523. current-tags inherited-tags table
  13524. (and org-fast-tag-selection-include-todo
  13525. org-todo-key-alist))
  13526. (let ((org-add-colon-after-tag-completion
  13527. (< 1 (length table))))
  13528. (org-trim
  13529. (completing-read
  13530. "Tags: "
  13531. #'org-tags-completion-function
  13532. nil nil current 'org-tags-history))))))))))
  13533. (when org-tags-sort-function
  13534. (setq tags
  13535. (mapconcat
  13536. #'identity
  13537. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13538. org-tags-sort-function)
  13539. ":")))
  13540. (if (or (string= ":" tags)
  13541. (string= "::" tags))
  13542. (setq tags ""))
  13543. (if (not (org-string-nw-p tags)) (setq tags "")
  13544. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13545. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13546. ;; Insert new tags at the correct column.
  13547. (unless (equal current tags)
  13548. (save-excursion
  13549. (beginning-of-line)
  13550. (let ((case-fold-search nil))
  13551. (looking-at org-complex-heading-regexp))
  13552. ;; Remove current tags, if any.
  13553. (when (match-end 5) (replace-match "" nil nil nil 5))
  13554. ;; Insert new tags, if any. Otherwise, remove trailing
  13555. ;; white spaces.
  13556. (end-of-line)
  13557. (if (not (equal tags ""))
  13558. ;; When text is being inserted on an invisible
  13559. ;; region boundary, it can be inadvertently sucked
  13560. ;; into invisibility.
  13561. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13562. (skip-chars-backward " \t")
  13563. (delete-region (point) (line-end-position)))))
  13564. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13565. ;; is on.
  13566. (unless (equal tags "")
  13567. (let* ((level (save-excursion
  13568. (beginning-of-line)
  13569. (skip-chars-forward "\\*")))
  13570. (offset (if (bound-and-true-p org-indent-mode)
  13571. (* (1- org-indent-indentation-per-level)
  13572. (1- level))
  13573. 0))
  13574. (tags-column
  13575. (+ org-tags-column
  13576. (if (> org-tags-column 0) (- offset) offset))))
  13577. (org--align-tags-here tags-column))))
  13578. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13579. (defun org-change-tag-in-region (beg end tag off)
  13580. "Add or remove TAG for each entry in the region.
  13581. This works in the agenda, and also in an Org buffer."
  13582. (interactive
  13583. (list (region-beginning) (region-end)
  13584. (let ((org-last-tags-completion-table
  13585. (if (derived-mode-p 'org-mode)
  13586. (org-uniquify
  13587. (delq nil (append (org-get-buffer-tags)
  13588. (org-global-tags-completion-table))))
  13589. (org-global-tags-completion-table))))
  13590. (completing-read
  13591. "Tag: " 'org-tags-completion-function nil nil nil
  13592. 'org-tags-history))
  13593. (progn
  13594. (message "[s]et or [r]emove? ")
  13595. (equal (read-char-exclusive) ?r))))
  13596. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13597. (let ((agendap (equal major-mode 'org-agenda-mode))
  13598. l1 l2 m buf pos newhead (cnt 0))
  13599. (goto-char end)
  13600. (setq l2 (1- (org-current-line)))
  13601. (goto-char beg)
  13602. (setq l1 (org-current-line))
  13603. (cl-loop for l from l1 to l2 do
  13604. (org-goto-line l)
  13605. (setq m (get-text-property (point) 'org-hd-marker))
  13606. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13607. (and agendap m))
  13608. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13609. pos (if agendap m (point)))
  13610. (with-current-buffer buf
  13611. (save-excursion
  13612. (save-restriction
  13613. (goto-char pos)
  13614. (setq cnt (1+ cnt))
  13615. (org-toggle-tag tag (if off 'off 'on))
  13616. (setq newhead (org-get-heading)))))
  13617. (and agendap (org-agenda-change-all-lines newhead m))))
  13618. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13619. (defun org-tags-completion-function (string _predicate &optional flag)
  13620. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13621. (confirm (lambda (x) (stringp (car x)))))
  13622. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13623. (setq s1 (match-string 1 string)
  13624. s2 (match-string 2 string))
  13625. (setq s1 "" s2 string))
  13626. (cond
  13627. ((eq flag nil)
  13628. ;; try completion
  13629. (setq rtn (try-completion s2 ctable confirm))
  13630. (when (stringp rtn)
  13631. (setq rtn
  13632. (concat s1 s2 (substring rtn (length s2))
  13633. (if (and org-add-colon-after-tag-completion
  13634. (assoc rtn ctable))
  13635. ":" ""))))
  13636. rtn)
  13637. ((eq flag t)
  13638. ;; all-completions
  13639. (all-completions s2 ctable confirm))
  13640. ((eq flag 'lambda)
  13641. ;; exact match?
  13642. (assoc s2 ctable)))))
  13643. (defun org-fast-tag-insert (kwd tags face &optional end)
  13644. "Insert KDW, and the TAGS, the latter with face FACE.
  13645. Also insert END."
  13646. (insert (format "%-12s" (concat kwd ":"))
  13647. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13648. (or end "")))
  13649. (defun org-fast-tag-show-exit (flag)
  13650. (save-excursion
  13651. (org-goto-line 3)
  13652. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13653. (replace-match ""))
  13654. (when flag
  13655. (end-of-line 1)
  13656. (org-move-to-column (- (window-width) 19) t)
  13657. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13658. (defun org-set-current-tags-overlay (current prefix)
  13659. "Add an overlay to CURRENT tag with PREFIX."
  13660. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13661. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13662. (org-overlay-display org-tags-overlay (concat prefix s))))
  13663. (defvar org-last-tag-selection-key nil)
  13664. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13665. "Fast tag selection with single keys.
  13666. CURRENT is the current list of tags in the headline, INHERITED is the
  13667. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13668. possibly with grouping information. TODO-TABLE is a similar table with
  13669. TODO keywords, should these have keys assigned to them.
  13670. If the keys are nil, a-z are automatically assigned.
  13671. Returns the new tags string, or nil to not change the current settings."
  13672. (let* ((fulltable (append table todo-table))
  13673. (maxlen (apply 'max (mapcar
  13674. (lambda (x)
  13675. (if (stringp (car x)) (string-width (car x)) 0))
  13676. fulltable)))
  13677. (buf (current-buffer))
  13678. (expert (eq org-fast-tag-selection-single-key 'expert))
  13679. (buffer-tags nil)
  13680. (fwidth (+ maxlen 3 1 3))
  13681. (ncol (/ (- (window-width) 4) fwidth))
  13682. (i-face 'org-done)
  13683. (c-face 'org-todo)
  13684. tg cnt e c char c1 c2 ntable tbl rtn
  13685. ov-start ov-end ov-prefix
  13686. (exit-after-next org-fast-tag-selection-single-key)
  13687. (done-keywords org-done-keywords)
  13688. groups ingroup intaggroup)
  13689. (save-excursion
  13690. (beginning-of-line 1)
  13691. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13692. (setq ov-start (match-beginning 1)
  13693. ov-end (match-end 1)
  13694. ov-prefix "")
  13695. (setq ov-start (1- (point-at-eol))
  13696. ov-end (1+ ov-start))
  13697. (skip-chars-forward "^\n\r")
  13698. (setq ov-prefix
  13699. (concat
  13700. (buffer-substring (1- (point)) (point))
  13701. (if (> (current-column) org-tags-column)
  13702. " "
  13703. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13704. (move-overlay org-tags-overlay ov-start ov-end)
  13705. (save-window-excursion
  13706. (if expert
  13707. (set-buffer (get-buffer-create " *Org tags*"))
  13708. (delete-other-windows)
  13709. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13710. (org-switch-to-buffer-other-window " *Org tags*"))
  13711. (erase-buffer)
  13712. (setq-local org-done-keywords done-keywords)
  13713. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13714. (org-fast-tag-insert "Current" current c-face "\n\n")
  13715. (org-fast-tag-show-exit exit-after-next)
  13716. (org-set-current-tags-overlay current ov-prefix)
  13717. (setq tbl fulltable char ?a cnt 0)
  13718. (while (setq e (pop tbl))
  13719. (cond
  13720. ((eq (car e) :startgroup)
  13721. (push '() groups) (setq ingroup t)
  13722. (unless (zerop cnt)
  13723. (setq cnt 0)
  13724. (insert "\n"))
  13725. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13726. ((eq (car e) :endgroup)
  13727. (setq ingroup nil cnt 0)
  13728. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13729. ((eq (car e) :startgrouptag)
  13730. (setq intaggroup t)
  13731. (unless (zerop cnt)
  13732. (setq cnt 0)
  13733. (insert "\n"))
  13734. (insert "[ "))
  13735. ((eq (car e) :endgrouptag)
  13736. (setq intaggroup nil cnt 0)
  13737. (insert "]\n"))
  13738. ((equal e '(:newline))
  13739. (unless (zerop cnt)
  13740. (setq cnt 0)
  13741. (insert "\n")
  13742. (setq e (car tbl))
  13743. (while (equal (car tbl) '(:newline))
  13744. (insert "\n")
  13745. (setq tbl (cdr tbl)))))
  13746. ((equal e '(:grouptags)) (insert " : "))
  13747. (t
  13748. (setq tg (copy-sequence (car e)) c2 nil)
  13749. (if (cdr e)
  13750. (setq c (cdr e))
  13751. ;; automatically assign a character.
  13752. (setq c1 (string-to-char
  13753. (downcase (substring
  13754. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13755. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13756. (while (or (rassoc char ntable) (rassoc char table))
  13757. (setq char (1+ char)))
  13758. (setq c2 c1))
  13759. (setq c (or c2 char)))
  13760. (when ingroup (push tg (car groups)))
  13761. (setq tg (org-add-props tg nil 'face
  13762. (cond
  13763. ((not (assoc tg table))
  13764. (org-get-todo-face tg))
  13765. ((member tg current) c-face)
  13766. ((member tg inherited) i-face))))
  13767. (when (equal (caar tbl) :grouptags)
  13768. (org-add-props tg nil 'face 'org-tag-group))
  13769. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13770. (insert "[" c "] " tg (make-string
  13771. (- fwidth 4 (length tg)) ?\ ))
  13772. (push (cons tg c) ntable)
  13773. (when (= (cl-incf cnt) ncol)
  13774. (insert "\n")
  13775. (when (or ingroup intaggroup) (insert " "))
  13776. (setq cnt 0)))))
  13777. (setq ntable (nreverse ntable))
  13778. (insert "\n")
  13779. (goto-char (point-min))
  13780. (unless expert (org-fit-window-to-buffer))
  13781. (setq rtn
  13782. (catch 'exit
  13783. (while t
  13784. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13785. (if (not groups) "no " "")
  13786. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13787. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13788. (setq org-last-tag-selection-key c)
  13789. (cond
  13790. ((= c ?\r) (throw 'exit t))
  13791. ((= c ?!)
  13792. (setq groups (not groups))
  13793. (goto-char (point-min))
  13794. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13795. ((= c ?\C-c)
  13796. (if (not expert)
  13797. (org-fast-tag-show-exit
  13798. (setq exit-after-next (not exit-after-next)))
  13799. (setq expert nil)
  13800. (delete-other-windows)
  13801. (set-window-buffer (split-window-vertically) " *Org tags*")
  13802. (org-switch-to-buffer-other-window " *Org tags*")
  13803. (org-fit-window-to-buffer)))
  13804. ((or (= c ?\C-g)
  13805. (and (= c ?q) (not (rassoc c ntable))))
  13806. (delete-overlay org-tags-overlay)
  13807. (setq quit-flag t))
  13808. ((= c ?\ )
  13809. (setq current nil)
  13810. (when exit-after-next (setq exit-after-next 'now)))
  13811. ((= c ?\t)
  13812. (condition-case nil
  13813. (setq tg (completing-read
  13814. "Tag: "
  13815. (or buffer-tags
  13816. (with-current-buffer buf
  13817. (setq buffer-tags
  13818. (org-get-buffer-tags))))))
  13819. (quit (setq tg "")))
  13820. (when (string-match "\\S-" tg)
  13821. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13822. (if (member tg current)
  13823. (setq current (delete tg current))
  13824. (push tg current)))
  13825. (when exit-after-next (setq exit-after-next 'now)))
  13826. ((setq e (rassoc c todo-table) tg (car e))
  13827. (with-current-buffer buf
  13828. (save-excursion (org-todo tg)))
  13829. (when exit-after-next (setq exit-after-next 'now)))
  13830. ((setq e (rassoc c ntable) tg (car e))
  13831. (if (member tg current)
  13832. (setq current (delete tg current))
  13833. (cl-loop for g in groups do
  13834. (when (member tg g)
  13835. (dolist (x g) (setq current (delete x current)))))
  13836. (push tg current))
  13837. (when exit-after-next (setq exit-after-next 'now))))
  13838. ;; Create a sorted list
  13839. (setq current
  13840. (sort current
  13841. (lambda (a b)
  13842. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13843. (when (eq exit-after-next 'now) (throw 'exit t))
  13844. (goto-char (point-min))
  13845. (beginning-of-line 2)
  13846. (delete-region (point) (point-at-eol))
  13847. (org-fast-tag-insert "Current" current c-face)
  13848. (org-set-current-tags-overlay current ov-prefix)
  13849. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13850. (setq tg (match-string 1))
  13851. (add-text-properties
  13852. (match-beginning 1) (match-end 1)
  13853. (list 'face
  13854. (cond
  13855. ((member tg current) c-face)
  13856. ((member tg inherited) i-face)
  13857. (t (get-text-property (match-beginning 1) 'face))))))
  13858. (goto-char (point-min)))))
  13859. (delete-overlay org-tags-overlay)
  13860. (if rtn
  13861. (mapconcat 'identity current ":")
  13862. nil))))
  13863. (defun org-get-tags-string ()
  13864. "Get the TAGS string in the current headline."
  13865. (unless (org-at-heading-p t)
  13866. (user-error "Not on a heading"))
  13867. (save-excursion
  13868. (beginning-of-line 1)
  13869. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13870. (match-string-no-properties 1)
  13871. "")))
  13872. (defun org-get-tags ()
  13873. "Get the list of tags specified in the current headline."
  13874. (org-split-string (org-get-tags-string) ":"))
  13875. (defun org-get-buffer-tags ()
  13876. "Get a table of all tags used in the buffer, for completion."
  13877. (org-with-wide-buffer
  13878. (goto-char (point-min))
  13879. (let ((tag-re (concat org-outline-regexp-bol
  13880. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13881. tags)
  13882. (while (re-search-forward tag-re nil t)
  13883. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13884. (push tag tags)))
  13885. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13886. ;;;; The mapping API
  13887. (defvar org-agenda-skip-comment-trees)
  13888. (defvar org-agenda-skip-function)
  13889. (defun org-map-entries (func &optional match scope &rest skip)
  13890. "Call FUNC at each headline selected by MATCH in SCOPE.
  13891. FUNC is a function or a lisp form. The function will be called without
  13892. arguments, with the cursor positioned at the beginning of the headline.
  13893. The return values of all calls to the function will be collected and
  13894. returned as a list.
  13895. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13896. does not need to preserve point. After evaluation, the cursor will be
  13897. moved to the end of the line (presumably of the headline of the
  13898. processed entry) and search continues from there. Under some
  13899. circumstances, this may not produce the wanted results. For example,
  13900. if you have removed (e.g. archived) the current (sub)tree it could
  13901. mean that the next entry will be skipped entirely. In such cases, you
  13902. can specify the position from where search should continue by making
  13903. FUNC set the variable `org-map-continue-from' to the desired buffer
  13904. position.
  13905. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13906. Only headlines that are matched by this query will be considered during
  13907. the iteration. When MATCH is nil or t, all headlines will be
  13908. visited by the iteration.
  13909. SCOPE determines the scope of this command. It can be any of:
  13910. nil The current buffer, respecting the restriction if any
  13911. tree The subtree started with the entry at point
  13912. region The entries within the active region, if any
  13913. region-start-level
  13914. The entries within the active region, but only those at
  13915. the same level than the first one.
  13916. file The current buffer, without restriction
  13917. file-with-archives
  13918. The current buffer, and any archives associated with it
  13919. agenda All agenda files
  13920. agenda-with-archives
  13921. All agenda files with any archive files associated with them
  13922. \(file1 file2 ...)
  13923. If this is a list, all files in the list will be scanned
  13924. The remaining args are treated as settings for the skipping facilities of
  13925. the scanner. The following items can be given here:
  13926. archive skip trees with the archive tag
  13927. comment skip trees with the COMMENT keyword
  13928. function or Emacs Lisp form:
  13929. will be used as value for `org-agenda-skip-function', so
  13930. whenever the function returns a position, FUNC will not be
  13931. called for that entry and search will continue from the
  13932. position returned
  13933. If your function needs to retrieve the tags including inherited tags
  13934. at the *current* entry, you can use the value of the variable
  13935. `org-scanner-tags' which will be much faster than getting the value
  13936. with `org-get-tags-at'. If your function gets properties with
  13937. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13938. to t around the call to `org-entry-properties' to get the same speedup.
  13939. Note that if your function moves around to retrieve tags and properties at
  13940. a *different* entry, you cannot use these techniques."
  13941. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13942. (not (org-region-active-p)))
  13943. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13944. (org-agenda-skip-archived-trees (memq 'archive skip))
  13945. (org-agenda-skip-comment-trees (memq 'comment skip))
  13946. (org-agenda-skip-function
  13947. (car (org-delete-all '(comment archive) skip)))
  13948. (org-tags-match-list-sublevels t)
  13949. (start-level (eq scope 'region-start-level))
  13950. matcher res
  13951. org-todo-keywords-for-agenda
  13952. org-done-keywords-for-agenda
  13953. org-todo-keyword-alist-for-agenda
  13954. org-tag-alist-for-agenda
  13955. org--matcher-tags-todo-only)
  13956. (cond
  13957. ((eq match t) (setq matcher t))
  13958. ((eq match nil) (setq matcher t))
  13959. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13960. (save-excursion
  13961. (save-restriction
  13962. (cond ((eq scope 'tree)
  13963. (org-back-to-heading t)
  13964. (org-narrow-to-subtree)
  13965. (setq scope nil))
  13966. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13967. (org-region-active-p))
  13968. ;; If needed, set start-level to a string like "2"
  13969. (when start-level
  13970. (save-excursion
  13971. (goto-char (region-beginning))
  13972. (unless (org-at-heading-p) (outline-next-heading))
  13973. (setq start-level (org-current-level))))
  13974. (narrow-to-region (region-beginning)
  13975. (save-excursion
  13976. (goto-char (region-end))
  13977. (unless (and (bolp) (org-at-heading-p))
  13978. (outline-next-heading))
  13979. (point)))
  13980. (setq scope nil)))
  13981. (if (not scope)
  13982. (progn
  13983. (org-agenda-prepare-buffers
  13984. (and buffer-file-name (list buffer-file-name)))
  13985. (setq res
  13986. (org-scan-tags
  13987. func matcher org--matcher-tags-todo-only start-level)))
  13988. ;; Get the right scope
  13989. (cond
  13990. ((and scope (listp scope) (symbolp (car scope)))
  13991. (setq scope (eval scope)))
  13992. ((eq scope 'agenda)
  13993. (setq scope (org-agenda-files t)))
  13994. ((eq scope 'agenda-with-archives)
  13995. (setq scope (org-agenda-files t))
  13996. (setq scope (org-add-archive-files scope)))
  13997. ((eq scope 'file)
  13998. (setq scope (and buffer-file-name (list buffer-file-name))))
  13999. ((eq scope 'file-with-archives)
  14000. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14001. (org-agenda-prepare-buffers scope)
  14002. (dolist (file scope)
  14003. (with-current-buffer (org-find-base-buffer-visiting file)
  14004. (org-with-wide-buffer
  14005. (goto-char (point-min))
  14006. (setq res
  14007. (append
  14008. res
  14009. (org-scan-tags
  14010. func matcher org--matcher-tags-todo-only)))))))))
  14011. res)))
  14012. ;;; Properties API
  14013. (defconst org-special-properties
  14014. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14015. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14016. "The special properties valid in Org mode.
  14017. These are properties that are not defined in the property drawer,
  14018. but in some other way.")
  14019. (defconst org-default-properties
  14020. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14021. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14022. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14023. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14024. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14025. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14026. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14027. "Some properties that are used by Org mode for various purposes.
  14028. Being in this list makes sure that they are offered for completion.")
  14029. (defun org--valid-property-p (property)
  14030. "Non nil when string PROPERTY is a valid property name."
  14031. (not
  14032. (or (equal property "")
  14033. (string-match-p "\\s-" property))))
  14034. (defun org--update-property-plist (key val props)
  14035. "Associate KEY to VAL in alist PROPS.
  14036. Modifications are made by side-effect. Return new alist."
  14037. (let* ((appending (string= (substring key -1) "+"))
  14038. (key (if appending (substring key 0 -1) key))
  14039. (old (assoc-string key props t)))
  14040. (if (not old) (cons (cons key val) props)
  14041. (setcdr old (if appending (concat (cdr old) " " val) val))
  14042. props)))
  14043. (defun org-get-property-block (&optional beg force)
  14044. "Return the (beg . end) range of the body of the property drawer.
  14045. BEG is the beginning of the current subtree, or of the part
  14046. before the first headline. If it is not given, it will be found.
  14047. If the drawer does not exist, create it if FORCE is non-nil, or
  14048. return nil."
  14049. (org-with-wide-buffer
  14050. (when beg (goto-char beg))
  14051. (unless (org-before-first-heading-p)
  14052. (let ((beg (cond (beg)
  14053. ((or (not (featurep 'org-inlinetask))
  14054. (org-inlinetask-in-task-p))
  14055. (org-back-to-heading t))
  14056. (t (org-with-limited-levels (org-back-to-heading t))))))
  14057. (forward-line)
  14058. (when (looking-at-p org-planning-line-re) (forward-line))
  14059. (cond ((looking-at org-property-drawer-re)
  14060. (forward-line)
  14061. (cons (point) (progn (goto-char (match-end 0))
  14062. (line-beginning-position))))
  14063. (force
  14064. (goto-char beg)
  14065. (org-insert-property-drawer)
  14066. (let ((pos (save-excursion (search-forward ":END:")
  14067. (line-beginning-position))))
  14068. (cons pos pos))))))))
  14069. (defun org-at-property-p ()
  14070. "Non-nil when point is inside a property drawer.
  14071. See `org-property-re' for match data, if applicable."
  14072. (save-excursion
  14073. (beginning-of-line)
  14074. (and (looking-at org-property-re)
  14075. (let ((property-drawer (save-match-data (org-get-property-block))))
  14076. (and property-drawer
  14077. (>= (point) (car property-drawer))
  14078. (< (point) (cdr property-drawer)))))))
  14079. (defun org-property-action ()
  14080. "Do an action on properties."
  14081. (interactive)
  14082. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14083. (let ((c (read-char-exclusive)))
  14084. (cl-case c
  14085. (?s (call-interactively #'org-set-property))
  14086. (?d (call-interactively #'org-delete-property))
  14087. (?D (call-interactively #'org-delete-property-globally))
  14088. (?c (call-interactively #'org-compute-property-at-point))
  14089. (otherwise (user-error "No such property action %c" c)))))
  14090. (defun org-inc-effort ()
  14091. "Increment the value of the effort property in the current entry."
  14092. (interactive)
  14093. (org-set-effort nil t))
  14094. (defvar org-clock-effort) ; Defined in org-clock.el.
  14095. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14096. (defun org-set-effort (&optional value increment)
  14097. "Set the effort property of the current entry.
  14098. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14099. 10th allowed value.
  14100. When INCREMENT is non-nil, set the property to the next allowed value."
  14101. (interactive "P")
  14102. (when (equal value 0) (setq value 10))
  14103. (let* ((completion-ignore-case t)
  14104. (prop org-effort-property)
  14105. (cur (org-entry-get nil prop))
  14106. (allowed (org-property-get-allowed-values nil prop 'table))
  14107. (existing (mapcar 'list (org-property-values prop)))
  14108. (heading (nth 4 (org-heading-components)))
  14109. rpl
  14110. (val (cond
  14111. ((stringp value) value)
  14112. ((and allowed (integerp value))
  14113. (or (car (nth (1- value) allowed))
  14114. (car (org-last allowed))))
  14115. ((and allowed increment)
  14116. (or (cl-caadr (member (list cur) allowed))
  14117. (user-error "Allowed effort values are not set")))
  14118. (allowed
  14119. (message "Select 1-9,0, [RET%s]: %s"
  14120. (if cur (concat "=" cur) "")
  14121. (mapconcat 'car allowed " "))
  14122. (setq rpl (read-char-exclusive))
  14123. (if (equal rpl ?\r)
  14124. cur
  14125. (setq rpl (- rpl ?0))
  14126. (when (equal rpl 0) (setq rpl 10))
  14127. (if (and (> rpl 0) (<= rpl (length allowed)))
  14128. (car (nth (1- rpl) allowed))
  14129. (org-completing-read "Effort: " allowed nil))))
  14130. (t
  14131. (org-completing-read
  14132. (concat "Effort" (and cur (string-match "\\S-" cur)
  14133. (concat " [" cur "]"))
  14134. ": ")
  14135. existing nil nil "" nil cur)))))
  14136. (unless (equal (org-entry-get nil prop) val)
  14137. (org-entry-put nil prop val))
  14138. (org-refresh-property
  14139. '((effort . identity)
  14140. (effort-minutes . org-duration-to-minutes))
  14141. val)
  14142. (when (equal heading (bound-and-true-p org-clock-current-task))
  14143. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14144. (org-clock-update-mode-line))
  14145. (message "%s is now %s" prop val)))
  14146. (defun org-entry-properties (&optional pom which)
  14147. "Get all properties of the current entry.
  14148. When POM is a buffer position, get all properties from the entry
  14149. there instead.
  14150. This includes the TODO keyword, the tags, time strings for
  14151. deadline, scheduled, and clocking, and any additional properties
  14152. defined in the entry.
  14153. If WHICH is nil or `all', get all properties. If WHICH is
  14154. `special' or `standard', only get that subclass. If WHICH is
  14155. a string, only get that property.
  14156. Return value is an alist. Keys are properties, as upcased
  14157. strings."
  14158. (org-with-point-at pom
  14159. (when (and (derived-mode-p 'org-mode)
  14160. (ignore-errors (org-back-to-heading t)))
  14161. (catch 'exit
  14162. (let* ((beg (point))
  14163. (specific (and (stringp which) (upcase which)))
  14164. (which (cond ((not specific) which)
  14165. ((member specific org-special-properties) 'special)
  14166. (t 'standard)))
  14167. props)
  14168. ;; Get the special properties, like TODO and TAGS.
  14169. (when (memq which '(nil all special))
  14170. (when (or (not specific) (string= specific "CLOCKSUM"))
  14171. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14172. (when clocksum
  14173. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14174. props)))
  14175. (when specific (throw 'exit props)))
  14176. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14177. (let ((clocksumt (get-text-property (point)
  14178. :org-clock-minutes-today)))
  14179. (when clocksumt
  14180. (push (cons "CLOCKSUM_T"
  14181. (org-duration-from-minutes clocksumt))
  14182. props)))
  14183. (when specific (throw 'exit props)))
  14184. (when (or (not specific) (string= specific "ITEM"))
  14185. (let ((case-fold-search nil))
  14186. (when (looking-at org-complex-heading-regexp)
  14187. (push (cons "ITEM"
  14188. (let ((title (match-string-no-properties 4)))
  14189. (if (org-string-nw-p title)
  14190. (org-remove-tabs title)
  14191. "")))
  14192. props)))
  14193. (when specific (throw 'exit props)))
  14194. (when (or (not specific) (string= specific "TODO"))
  14195. (let ((case-fold-search nil))
  14196. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14197. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14198. (when specific (throw 'exit props)))
  14199. (when (or (not specific) (string= specific "PRIORITY"))
  14200. (push (cons "PRIORITY"
  14201. (if (looking-at org-priority-regexp)
  14202. (match-string-no-properties 2)
  14203. (char-to-string org-default-priority)))
  14204. props)
  14205. (when specific (throw 'exit props)))
  14206. (when (or (not specific) (string= specific "FILE"))
  14207. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14208. props)
  14209. (when specific (throw 'exit props)))
  14210. (when (or (not specific) (string= specific "TAGS"))
  14211. (let ((value (org-string-nw-p (org-get-tags-string))))
  14212. (when value (push (cons "TAGS" value) props)))
  14213. (when specific (throw 'exit props)))
  14214. (when (or (not specific) (string= specific "ALLTAGS"))
  14215. (let ((value (org-get-tags-at)))
  14216. (when value
  14217. (push (cons "ALLTAGS"
  14218. (format ":%s:" (mapconcat #'identity value ":")))
  14219. props)))
  14220. (when specific (throw 'exit props)))
  14221. (when (or (not specific) (string= specific "BLOCKED"))
  14222. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14223. (when specific (throw 'exit props)))
  14224. (when (or (not specific)
  14225. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14226. (forward-line)
  14227. (when (looking-at-p org-planning-line-re)
  14228. (end-of-line)
  14229. (let ((bol (line-beginning-position))
  14230. ;; Backward compatibility: time keywords used to
  14231. ;; be configurable (before 8.3). Make sure we
  14232. ;; get the correct keyword.
  14233. (key-assoc `(("CLOSED" . ,org-closed-string)
  14234. ("DEADLINE" . ,org-deadline-string)
  14235. ("SCHEDULED" . ,org-scheduled-string))))
  14236. (dolist (pair (if specific (list (assoc specific key-assoc))
  14237. key-assoc))
  14238. (save-excursion
  14239. (when (search-backward (cdr pair) bol t)
  14240. (goto-char (match-end 0))
  14241. (skip-chars-forward " \t")
  14242. (and (looking-at org-ts-regexp-both)
  14243. (push (cons (car pair)
  14244. (match-string-no-properties 0))
  14245. props)))))))
  14246. (when specific (throw 'exit props)))
  14247. (when (or (not specific)
  14248. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14249. (let ((find-ts
  14250. (lambda (end ts)
  14251. ;; Fix next time-stamp before END. TS is the
  14252. ;; list of time-stamps found so far.
  14253. (let ((ts ts)
  14254. (regexp (cond
  14255. ((string= specific "TIMESTAMP")
  14256. org-ts-regexp)
  14257. ((string= specific "TIMESTAMP_IA")
  14258. org-ts-regexp-inactive)
  14259. ((assoc "TIMESTAMP_IA" ts)
  14260. org-ts-regexp)
  14261. ((assoc "TIMESTAMP" ts)
  14262. org-ts-regexp-inactive)
  14263. (t org-ts-regexp-both))))
  14264. (catch 'next
  14265. (while (re-search-forward regexp end t)
  14266. (backward-char)
  14267. (let ((object (org-element-context)))
  14268. ;; Accept to match timestamps in node
  14269. ;; properties, too.
  14270. (when (memq (org-element-type object)
  14271. '(node-property timestamp))
  14272. (let ((type
  14273. (org-element-property :type object)))
  14274. (cond
  14275. ((and (memq type '(active active-range))
  14276. (not (equal specific "TIMESTAMP_IA")))
  14277. (unless (assoc "TIMESTAMP" ts)
  14278. (push (cons "TIMESTAMP"
  14279. (org-element-property
  14280. :raw-value object))
  14281. ts)
  14282. (when specific (throw 'exit ts))))
  14283. ((and (memq type '(inactive inactive-range))
  14284. (not (string= specific "TIMESTAMP")))
  14285. (unless (assoc "TIMESTAMP_IA" ts)
  14286. (push (cons "TIMESTAMP_IA"
  14287. (org-element-property
  14288. :raw-value object))
  14289. ts)
  14290. (when specific (throw 'exit ts))))))
  14291. ;; Both timestamp types are found,
  14292. ;; move to next part.
  14293. (when (= (length ts) 2) (throw 'next ts)))))
  14294. ts)))))
  14295. (goto-char beg)
  14296. ;; First look for timestamps within headline.
  14297. (let ((ts (funcall find-ts (line-end-position) nil)))
  14298. (if (= (length ts) 2) (setq props (nconc ts props))
  14299. ;; Then find timestamps in the section, skipping
  14300. ;; planning line.
  14301. (let ((end (save-excursion (outline-next-heading))))
  14302. (forward-line)
  14303. (when (looking-at-p org-planning-line-re) (forward-line))
  14304. (setq props (nconc (funcall find-ts end ts) props))))))))
  14305. ;; Get the standard properties, like :PROP:.
  14306. (when (memq which '(nil all standard))
  14307. ;; If we are looking after a specific property, delegate
  14308. ;; to `org-entry-get', which is faster. However, make an
  14309. ;; exception for "CATEGORY", since it can be also set
  14310. ;; through keywords (i.e. #+CATEGORY).
  14311. (if (and specific (not (equal specific "CATEGORY")))
  14312. (let ((value (org-entry-get beg specific nil t)))
  14313. (throw 'exit (and value (list (cons specific value)))))
  14314. (let ((range (org-get-property-block beg)))
  14315. (when range
  14316. (let ((end (cdr range)) seen-base)
  14317. (goto-char (car range))
  14318. ;; Unlike to `org--update-property-plist', we
  14319. ;; handle the case where base values is found
  14320. ;; after its extension. We also forbid standard
  14321. ;; properties to be named as special properties.
  14322. (while (re-search-forward org-property-re end t)
  14323. (let* ((key (upcase (match-string-no-properties 2)))
  14324. (extendp (string-match-p "\\+\\'" key))
  14325. (key-base (if extendp (substring key 0 -1) key))
  14326. (value (match-string-no-properties 3)))
  14327. (cond
  14328. ((member-ignore-case key-base org-special-properties))
  14329. (extendp
  14330. (setq props
  14331. (org--update-property-plist key value props)))
  14332. ((member key seen-base))
  14333. (t (push key seen-base)
  14334. (let ((p (assoc-string key props t)))
  14335. (if p (setcdr p (concat value " " (cdr p)))
  14336. (push (cons key value) props))))))))))))
  14337. (unless (assoc "CATEGORY" props)
  14338. (push (cons "CATEGORY" (org-get-category beg)) props)
  14339. (when (string= specific "CATEGORY") (throw 'exit props)))
  14340. ;; Return value.
  14341. props)))))
  14342. (defun org--property-local-values (property literal-nil)
  14343. "Return value for PROPERTY in current entry.
  14344. Value is a list whose car is the base value for PROPERTY and cdr
  14345. a list of accumulated values. Return nil if neither is found in
  14346. the entry. Also return nil when PROPERTY is set to \"nil\",
  14347. unless LITERAL-NIL is non-nil."
  14348. (let ((range (org-get-property-block)))
  14349. (when range
  14350. (goto-char (car range))
  14351. (let* ((case-fold-search t)
  14352. (end (cdr range))
  14353. (value
  14354. ;; Base value.
  14355. (save-excursion
  14356. (let ((v (and (re-search-forward
  14357. (org-re-property property nil t) end t)
  14358. (match-string-no-properties 3))))
  14359. (list (if literal-nil v (org-not-nil v)))))))
  14360. ;; Find additional values.
  14361. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14362. (while (re-search-forward property+ end t)
  14363. (push (match-string-no-properties 3) value)))
  14364. ;; Return final values.
  14365. (and (not (equal value '(nil))) (nreverse value))))))
  14366. (defun org--property-global-value (property literal-nil)
  14367. "Return value for PROPERTY in current buffer.
  14368. Return value is a string. Return nil if property is not set
  14369. globally. Also return nil when PROPERTY is set to \"nil\",
  14370. unless LITERAL-NIL is non-nil."
  14371. (let ((global
  14372. (cdr (or (assoc-string property org-file-properties t)
  14373. (assoc-string property org-global-properties t)
  14374. (assoc-string property org-global-properties-fixed t)))))
  14375. (if literal-nil global (org-not-nil global))))
  14376. (defun org-entry-get (pom property &optional inherit literal-nil)
  14377. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14378. If INHERIT is non-nil and the entry does not have the property,
  14379. then also check higher levels of the hierarchy. If INHERIT is
  14380. the symbol `selective', use inheritance only if the setting in
  14381. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14382. If the property is present but empty, the return value is the
  14383. empty string. If the property is not present at all, nil is
  14384. returned. In any other case, return the value as a string.
  14385. Search is case-insensitive.
  14386. If LITERAL-NIL is set, return the string value \"nil\" as
  14387. a string, do not interpret it as the list atom nil. This is used
  14388. for inheritance when a \"nil\" value can supersede a non-nil
  14389. value higher up the hierarchy."
  14390. (org-with-point-at pom
  14391. (cond
  14392. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14393. ;; We need a special property. Use `org-entry-properties' to
  14394. ;; retrieve it, but specify the wanted property.
  14395. (cdr (assoc-string property (org-entry-properties nil property))))
  14396. ((and inherit
  14397. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14398. (org-entry-get-with-inheritance property literal-nil))
  14399. (t
  14400. (let* ((local (org--property-local-values property literal-nil))
  14401. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14402. (if literal-nil value (org-not-nil value)))))))
  14403. (defun org-property-or-variable-value (var &optional inherit)
  14404. "Check if there is a property fixing the value of VAR.
  14405. If yes, return this value. If not, return the current value of the variable."
  14406. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14407. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14408. (read prop)
  14409. (symbol-value var))))
  14410. (defun org-entry-delete (pom property)
  14411. "Delete PROPERTY from entry at point-or-marker POM.
  14412. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14413. non-nil when a property was removed."
  14414. (org-with-point-at pom
  14415. (pcase (org-get-property-block)
  14416. (`(,begin . ,origin)
  14417. (let* ((end (copy-marker origin))
  14418. (re (org-re-property
  14419. (concat (regexp-quote property) "\\+?") t t)))
  14420. (goto-char begin)
  14421. (while (re-search-forward re end t)
  14422. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14423. ;; If drawer is empty, remove it altogether.
  14424. (when (= begin end)
  14425. (delete-region (line-beginning-position 0)
  14426. (line-beginning-position 2)))
  14427. ;; Return non-nil if some property was removed.
  14428. (prog1 (/= end origin) (set-marker end nil))))
  14429. (_ nil))))
  14430. ;; Multi-values properties are properties that contain multiple values
  14431. ;; These values are assumed to be single words, separated by whitespace.
  14432. (defun org-entry-add-to-multivalued-property (pom property value)
  14433. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14434. (let* ((old (org-entry-get pom property))
  14435. (values (and old (org-split-string old "[ \t]"))))
  14436. (setq value (org-entry-protect-space value))
  14437. (unless (member value values)
  14438. (setq values (append values (list value)))
  14439. (org-entry-put pom property
  14440. (mapconcat 'identity values " ")))))
  14441. (defun org-entry-remove-from-multivalued-property (pom property value)
  14442. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14443. (let* ((old (org-entry-get pom property))
  14444. (values (and old (org-split-string old "[ \t]"))))
  14445. (setq value (org-entry-protect-space value))
  14446. (when (member value values)
  14447. (setq values (delete value values))
  14448. (org-entry-put pom property
  14449. (mapconcat 'identity values " ")))))
  14450. (defun org-entry-member-in-multivalued-property (pom property value)
  14451. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14452. (let* ((old (org-entry-get pom property))
  14453. (values (and old (org-split-string old "[ \t]"))))
  14454. (setq value (org-entry-protect-space value))
  14455. (member value values)))
  14456. (defun org-entry-get-multivalued-property (pom property)
  14457. "Return a list of values in a multivalued property."
  14458. (let* ((value (org-entry-get pom property))
  14459. (values (and value (org-split-string value "[ \t]"))))
  14460. (mapcar 'org-entry-restore-space values)))
  14461. (defun org-entry-put-multivalued-property (pom property &rest values)
  14462. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14463. VALUES should be a list of strings. Spaces will be protected."
  14464. (org-entry-put pom property
  14465. (mapconcat 'org-entry-protect-space values " "))
  14466. (let* ((value (org-entry-get pom property))
  14467. (values (and value (org-split-string value "[ \t]"))))
  14468. (mapcar 'org-entry-restore-space values)))
  14469. (defun org-entry-protect-space (s)
  14470. "Protect spaces and newline in string S."
  14471. (while (string-match " " s)
  14472. (setq s (replace-match "%20" t t s)))
  14473. (while (string-match "\n" s)
  14474. (setq s (replace-match "%0A" t t s)))
  14475. s)
  14476. (defun org-entry-restore-space (s)
  14477. "Restore spaces and newline in string S."
  14478. (while (string-match "%20" s)
  14479. (setq s (replace-match " " t t s)))
  14480. (while (string-match "%0A" s)
  14481. (setq s (replace-match "\n" t t s)))
  14482. s)
  14483. (defvar org-entry-property-inherited-from (make-marker)
  14484. "Marker pointing to the entry from where a property was inherited.
  14485. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14486. location of the entry where the inheritance search matched. If there was
  14487. no match, the marker will point nowhere.
  14488. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14489. is set.")
  14490. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14491. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14492. The search will stop at the first ancestor which has the property defined.
  14493. If the value found is \"nil\", return nil to show that the property
  14494. should be considered as undefined (this is the meaning of nil here).
  14495. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14496. (move-marker org-entry-property-inherited-from nil)
  14497. (org-with-wide-buffer
  14498. (let (value)
  14499. (catch 'exit
  14500. (while t
  14501. (let ((v (org--property-local-values property literal-nil)))
  14502. (when v
  14503. (setq value
  14504. (concat (mapconcat #'identity (delq nil v) " ")
  14505. (and value " ")
  14506. value)))
  14507. (cond
  14508. ((car v)
  14509. (org-back-to-heading t)
  14510. (move-marker org-entry-property-inherited-from (point))
  14511. (throw 'exit nil))
  14512. ((org-up-heading-safe))
  14513. (t
  14514. (let ((global (org--property-global-value property literal-nil)))
  14515. (cond ((not global))
  14516. (value (setq value (concat global " " value)))
  14517. (t (setq value global))))
  14518. (throw 'exit nil))))))
  14519. (if literal-nil value (org-not-nil value)))))
  14520. (defvar org-property-changed-functions nil
  14521. "Hook called when the value of a property has changed.
  14522. Each hook function should accept two arguments, the name of the property
  14523. and the new value.")
  14524. (defun org-entry-put (pom property value)
  14525. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14526. If the value is nil, it is converted to the empty string. If it
  14527. is not a string, an error is raised. Also raise an error on
  14528. invalid property names.
  14529. PROPERTY can be any regular property (see
  14530. `org-special-properties'). It can also be \"TODO\",
  14531. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14532. For the last two properties, VALUE may have any of the special
  14533. values \"earlier\" and \"later\". The function then increases or
  14534. decreases scheduled or deadline date by one day."
  14535. (cond ((null value) (setq value ""))
  14536. ((not (stringp value)) (error "Properties values should be strings"))
  14537. ((not (org--valid-property-p property))
  14538. (user-error "Invalid property name: \"%s\"" property)))
  14539. (org-with-point-at pom
  14540. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14541. (org-back-to-heading t)
  14542. (org-with-limited-levels (org-back-to-heading t)))
  14543. (let ((beg (point)))
  14544. (cond
  14545. ((equal property "TODO")
  14546. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14547. ((not (member value org-todo-keywords-1))
  14548. (user-error "\"%s\" is not a valid TODO state" value)))
  14549. (org-todo value)
  14550. (org-set-tags nil 'align))
  14551. ((equal property "PRIORITY")
  14552. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14553. (org-set-tags nil 'align))
  14554. ((equal property "SCHEDULED")
  14555. (forward-line)
  14556. (if (and (looking-at-p org-planning-line-re)
  14557. (re-search-forward
  14558. org-scheduled-time-regexp (line-end-position) t))
  14559. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14560. ((string= value "later") (org-timestamp-change 1 'day))
  14561. ((string= value "") (org-schedule '(4)))
  14562. (t (org-schedule nil value)))
  14563. (if (member value '("earlier" "later" ""))
  14564. (call-interactively #'org-schedule)
  14565. (org-schedule nil value))))
  14566. ((equal property "DEADLINE")
  14567. (forward-line)
  14568. (if (and (looking-at-p org-planning-line-re)
  14569. (re-search-forward
  14570. org-deadline-time-regexp (line-end-position) t))
  14571. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14572. ((string= value "later") (org-timestamp-change 1 'day))
  14573. ((string= value "") (org-deadline '(4)))
  14574. (t (org-deadline nil value)))
  14575. (if (member value '("earlier" "later" ""))
  14576. (call-interactively #'org-deadline)
  14577. (org-deadline nil value))))
  14578. ((member property org-special-properties)
  14579. (error "The %s property cannot be set with `org-entry-put'" property))
  14580. (t
  14581. (let* ((range (org-get-property-block beg 'force))
  14582. (end (cdr range))
  14583. (case-fold-search t))
  14584. (goto-char (car range))
  14585. (if (re-search-forward (org-re-property property nil t) end t)
  14586. (progn (delete-region (match-beginning 0) (match-end 0))
  14587. (goto-char (match-beginning 0)))
  14588. (goto-char end)
  14589. (insert "\n")
  14590. (backward-char))
  14591. (insert ":" property ":")
  14592. (when value (insert " " value))
  14593. (org-indent-line)))))
  14594. (run-hook-with-args 'org-property-changed-functions property value)))
  14595. (defun org-buffer-property-keys
  14596. (&optional specials defaults columns ignore-malformed)
  14597. "Get all property keys in the current buffer.
  14598. When SPECIALS is non-nil, also list the special properties that
  14599. reflect things like tags and TODO state.
  14600. When DEFAULTS is non-nil, also include properties that has
  14601. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14602. DESCRIPTION, LOCATION, and LOGGING and others.
  14603. When COLUMNS in non-nil, also include property names given in
  14604. COLUMN formats in the current buffer.
  14605. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14606. automatically performed, such drawers will be silently ignored."
  14607. (let ((case-fold-search t)
  14608. (props (append
  14609. (and specials org-special-properties)
  14610. (and defaults (cons org-effort-property org-default-properties))
  14611. nil)))
  14612. (org-with-wide-buffer
  14613. (goto-char (point-min))
  14614. (while (re-search-forward org-property-start-re nil t)
  14615. (let ((range (org-get-property-block)))
  14616. (catch 'skip
  14617. (unless range
  14618. (when (and (not ignore-malformed)
  14619. (not (org-before-first-heading-p))
  14620. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14621. (line-beginning-position))))
  14622. (org-get-property-block nil t))
  14623. (throw 'skip nil))
  14624. (goto-char (car range))
  14625. (let ((begin (car range))
  14626. (end (cdr range)))
  14627. ;; Make sure that found property block is not located
  14628. ;; before current point, as it would generate an infloop.
  14629. ;; It can happen, for example, in the following
  14630. ;; situation:
  14631. ;;
  14632. ;; * Headline
  14633. ;; :PROPERTIES:
  14634. ;; ...
  14635. ;; :END:
  14636. ;; *************** Inlinetask
  14637. ;; #+BEGIN_EXAMPLE
  14638. ;; :PROPERTIES:
  14639. ;; #+END_EXAMPLE
  14640. ;;
  14641. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14642. (while (< (point) end)
  14643. (let ((p (progn (looking-at org-property-re)
  14644. (match-string-no-properties 2))))
  14645. ;; Only add true property name, not extension symbol.
  14646. (push (if (not (string-match-p "\\+\\'" p)) p
  14647. (substring p 0 -1))
  14648. props))
  14649. (forward-line))))
  14650. (outline-next-heading)))
  14651. (when columns
  14652. (goto-char (point-min))
  14653. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14654. (let ((element (org-element-at-point)))
  14655. (when (memq (org-element-type element) '(keyword node-property))
  14656. (let ((value (org-element-property :value element))
  14657. (start 0))
  14658. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14659. (setq start (match-end 0))
  14660. (let ((p (match-string-no-properties 1 value)))
  14661. (unless (member-ignore-case p org-special-properties)
  14662. (push p props))))))))))
  14663. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14664. (defun org-property-values (key)
  14665. "List all non-nil values of property KEY in current buffer."
  14666. (org-with-wide-buffer
  14667. (goto-char (point-min))
  14668. (let ((case-fold-search t)
  14669. (re (org-re-property key))
  14670. values)
  14671. (while (re-search-forward re nil t)
  14672. (push (org-entry-get (point) key) values))
  14673. (delete-dups values))))
  14674. (defun org-insert-property-drawer ()
  14675. "Insert a property drawer into the current entry."
  14676. (org-with-wide-buffer
  14677. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14678. (org-back-to-heading t)
  14679. (org-with-limited-levels (org-back-to-heading t)))
  14680. (forward-line)
  14681. (when (looking-at-p org-planning-line-re) (forward-line))
  14682. (unless (looking-at-p org-property-drawer-re)
  14683. ;; Make sure we start editing a line from current entry, not from
  14684. ;; next one. It prevents extending text properties or overlays
  14685. ;; belonging to the latter.
  14686. (when (bolp) (backward-char))
  14687. (let ((begin (1+ (point)))
  14688. (inhibit-read-only t))
  14689. (insert "\n:PROPERTIES:\n:END:")
  14690. (when (eobp) (insert "\n"))
  14691. (org-indent-region begin (point))))))
  14692. (defun org-insert-drawer (&optional arg drawer)
  14693. "Insert a drawer at point.
  14694. When optional argument ARG is non-nil, insert a property drawer.
  14695. Optional argument DRAWER, when non-nil, is a string representing
  14696. drawer's name. Otherwise, the user is prompted for a name.
  14697. If a region is active, insert the drawer around that region
  14698. instead.
  14699. Point is left between drawer's boundaries."
  14700. (interactive "P")
  14701. (let* ((drawer (if arg "PROPERTIES"
  14702. (or drawer (read-from-minibuffer "Drawer: ")))))
  14703. (cond
  14704. ;; With C-u, fall back on `org-insert-property-drawer'
  14705. (arg (org-insert-property-drawer))
  14706. ;; Check validity of suggested drawer's name.
  14707. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14708. (user-error "Invalid drawer name"))
  14709. ;; With an active region, insert a drawer at point.
  14710. ((not (org-region-active-p))
  14711. (progn
  14712. (unless (bolp) (insert "\n"))
  14713. (insert (format ":%s:\n\n:END:\n" drawer))
  14714. (forward-line -2)))
  14715. ;; Otherwise, insert the drawer at point
  14716. (t
  14717. (let ((rbeg (region-beginning))
  14718. (rend (copy-marker (region-end))))
  14719. (unwind-protect
  14720. (progn
  14721. (goto-char rbeg)
  14722. (beginning-of-line)
  14723. (when (save-excursion
  14724. (re-search-forward org-outline-regexp-bol rend t))
  14725. (user-error "Drawers cannot contain headlines"))
  14726. ;; Position point at the beginning of the first
  14727. ;; non-blank line in region. Insert drawer's opening
  14728. ;; there, then indent it.
  14729. (org-skip-whitespace)
  14730. (beginning-of-line)
  14731. (insert ":" drawer ":\n")
  14732. (forward-line -1)
  14733. (indent-for-tab-command)
  14734. ;; Move point to the beginning of the first blank line
  14735. ;; after the last non-blank line in region. Insert
  14736. ;; drawer's closing, then indent it.
  14737. (goto-char rend)
  14738. (skip-chars-backward " \r\t\n")
  14739. (insert "\n:END:")
  14740. (deactivate-mark t)
  14741. (indent-for-tab-command)
  14742. (unless (eolp) (insert "\n")))
  14743. ;; Clear marker, whatever the outcome of insertion is.
  14744. (set-marker rend nil)))))))
  14745. (defvar org-property-set-functions-alist nil
  14746. "Property set function alist.
  14747. Each entry should have the following format:
  14748. (PROPERTY . READ-FUNCTION)
  14749. The read function will be called with the same argument as
  14750. `org-completing-read'.")
  14751. (defun org-set-property-function (property)
  14752. "Get the function that should be used to set PROPERTY.
  14753. This is computed according to `org-property-set-functions-alist'."
  14754. (or (cdr (assoc property org-property-set-functions-alist))
  14755. 'org-completing-read))
  14756. (defun org-read-property-value (property)
  14757. "Read PROPERTY value from user."
  14758. (let* ((completion-ignore-case t)
  14759. (allowed (org-property-get-allowed-values nil property 'table))
  14760. (cur (org-entry-get nil property))
  14761. (prompt (concat property " value"
  14762. (if (and cur (string-match "\\S-" cur))
  14763. (concat " [" cur "]") "") ": "))
  14764. (set-function (org-set-property-function property))
  14765. (val (if allowed
  14766. (funcall set-function prompt allowed nil
  14767. (not (get-text-property 0 'org-unrestricted
  14768. (caar allowed))))
  14769. (funcall set-function prompt
  14770. (mapcar 'list (org-property-values property))
  14771. nil nil "" nil cur))))
  14772. (org-trim val)))
  14773. (defvar org-last-set-property nil)
  14774. (defvar org-last-set-property-value nil)
  14775. (defun org-read-property-name ()
  14776. "Read a property name."
  14777. (let ((completion-ignore-case t)
  14778. (default-prop (or (and (org-at-property-p)
  14779. (match-string-no-properties 2))
  14780. org-last-set-property)))
  14781. (org-completing-read
  14782. (concat "Property"
  14783. (if default-prop (concat " [" default-prop "]") "")
  14784. ": ")
  14785. (mapcar #'list (org-buffer-property-keys nil t t))
  14786. nil nil nil nil default-prop)))
  14787. (defun org-set-property-and-value (use-last)
  14788. "Allow to set [PROPERTY]: [value] direction from prompt.
  14789. When use-default, don't even ask, just use the last
  14790. \"[PROPERTY]: [value]\" string from the history."
  14791. (interactive "P")
  14792. (let* ((completion-ignore-case t)
  14793. (pv (or (and use-last org-last-set-property-value)
  14794. (org-completing-read
  14795. "Enter a \"[Property]: [value]\" pair: "
  14796. nil nil nil nil nil
  14797. org-last-set-property-value)))
  14798. prop val)
  14799. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14800. (setq prop (match-string 1 pv)
  14801. val (match-string 2 pv))
  14802. (org-set-property prop val))))
  14803. (defun org-set-property (property value)
  14804. "In the current entry, set PROPERTY to VALUE.
  14805. When called interactively, this will prompt for a property name, offering
  14806. completion on existing and default properties. And then it will prompt
  14807. for a value, offering completion either on allowed values (via an inherited
  14808. xxx_ALL property) or on existing values in other instances of this property
  14809. in the current file.
  14810. Throw an error when trying to set a property with an invalid name."
  14811. (interactive (list nil nil))
  14812. (let ((property (or property (org-read-property-name))))
  14813. ;; `org-entry-put' also makes the following check, but this one
  14814. ;; avoids polluting `org-last-set-property' and
  14815. ;; `org-last-set-property-value' needlessly.
  14816. (unless (org--valid-property-p property)
  14817. (user-error "Invalid property name: \"%s\"" property))
  14818. (let ((value (or value (org-read-property-value property)))
  14819. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14820. (setq org-last-set-property property)
  14821. (setq org-last-set-property-value (concat property ": " value))
  14822. ;; Possibly postprocess the inserted value:
  14823. (when fn (setq value (funcall fn value)))
  14824. (unless (equal (org-entry-get nil property) value)
  14825. (org-entry-put nil property value)))))
  14826. (defun org-find-property (property &optional value)
  14827. "Find first entry in buffer that sets PROPERTY.
  14828. When optional argument VALUE is non-nil, only consider an entry
  14829. if it contains PROPERTY set to this value. If PROPERTY should be
  14830. explicitly set to nil, use string \"nil\" for VALUE.
  14831. Return position where the entry begins, or nil if there is no
  14832. such entry. If narrowing is in effect, only search the visible
  14833. part of the buffer."
  14834. (save-excursion
  14835. (goto-char (point-min))
  14836. (let ((case-fold-search t)
  14837. (re (org-re-property property nil (not value) value)))
  14838. (catch 'exit
  14839. (while (re-search-forward re nil t)
  14840. (when (if value (org-at-property-p)
  14841. (org-entry-get (point) property nil t))
  14842. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14843. (defun org-delete-property (property)
  14844. "In the current entry, delete PROPERTY."
  14845. (interactive
  14846. (let* ((completion-ignore-case t)
  14847. (cat (org-entry-get (point) "CATEGORY"))
  14848. (props0 (org-entry-properties nil 'standard))
  14849. (props (if cat props0
  14850. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14851. (prop (if (< 1 (length props))
  14852. (completing-read "Property: " props nil t)
  14853. (caar props))))
  14854. (list prop)))
  14855. (if (not property)
  14856. (message "No property to delete in this entry")
  14857. (org-entry-delete nil property)
  14858. (message "Property \"%s\" deleted" property)))
  14859. (defun org-delete-property-globally (property)
  14860. "Remove PROPERTY globally, from all entries.
  14861. This function ignores narrowing, if any."
  14862. (interactive
  14863. (let* ((completion-ignore-case t)
  14864. (prop (completing-read
  14865. "Globally remove property: "
  14866. (mapcar #'list (org-buffer-property-keys)))))
  14867. (list prop)))
  14868. (org-with-wide-buffer
  14869. (goto-char (point-min))
  14870. (let ((count 0)
  14871. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14872. (while (re-search-forward re nil t)
  14873. (when (org-entry-delete (point) property) (cl-incf count)))
  14874. (message "Property \"%s\" removed from %d entries" property count))))
  14875. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14876. (defun org-compute-property-at-point ()
  14877. "Compute the property at point.
  14878. This looks for an enclosing column format, extracts the operator and
  14879. then applies it to the property in the column format's scope."
  14880. (interactive)
  14881. (unless (org-at-property-p)
  14882. (user-error "Not at a property"))
  14883. (let ((prop (match-string-no-properties 2)))
  14884. (org-columns-get-format-and-top-level)
  14885. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14886. (user-error "No operator defined for property %s" prop))
  14887. (org-columns-compute prop)))
  14888. (defvar org-property-allowed-value-functions nil
  14889. "Hook for functions supplying allowed values for a specific property.
  14890. The functions must take a single argument, the name of the property, and
  14891. return a flat list of allowed values. If \":ETC\" is one of
  14892. the values, this means that these values are intended as defaults for
  14893. completion, but that other values should be allowed too.
  14894. The functions must return nil if they are not responsible for this
  14895. property.")
  14896. (defun org-property-get-allowed-values (pom property &optional table)
  14897. "Get allowed values for the property PROPERTY.
  14898. When TABLE is non-nil, return an alist that can directly be used for
  14899. completion."
  14900. (let (vals)
  14901. (cond
  14902. ((equal property "TODO")
  14903. (setq vals (org-with-point-at pom
  14904. (append org-todo-keywords-1 '("")))))
  14905. ((equal property "PRIORITY")
  14906. (let ((n org-lowest-priority))
  14907. (while (>= n org-highest-priority)
  14908. (push (char-to-string n) vals)
  14909. (setq n (1- n)))))
  14910. ((equal property "CATEGORY"))
  14911. ((member property org-special-properties))
  14912. ((setq vals (run-hook-with-args-until-success
  14913. 'org-property-allowed-value-functions property)))
  14914. (t
  14915. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14916. (when (and vals (string-match "\\S-" vals))
  14917. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14918. (setq vals (mapcar (lambda (x)
  14919. (cond ((stringp x) x)
  14920. ((numberp x) (number-to-string x))
  14921. ((symbolp x) (symbol-name x))
  14922. (t "???")))
  14923. vals)))))
  14924. (when (member ":ETC" vals)
  14925. (setq vals (remove ":ETC" vals))
  14926. (org-add-props (car vals) '(org-unrestricted t)))
  14927. (if table (mapcar 'list vals) vals)))
  14928. (defun org-property-previous-allowed-value (&optional _previous)
  14929. "Switch to the next allowed value for this property."
  14930. (interactive)
  14931. (org-property-next-allowed-value t))
  14932. (defun org-property-next-allowed-value (&optional previous)
  14933. "Switch to the next allowed value for this property."
  14934. (interactive)
  14935. (unless (org-at-property-p)
  14936. (user-error "Not at a property"))
  14937. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14938. (key (match-string 2))
  14939. (value (match-string 3))
  14940. (allowed (or (org-property-get-allowed-values (point) key)
  14941. (and (member value '("[ ]" "[-]" "[X]"))
  14942. '("[ ]" "[X]"))))
  14943. (heading (save-match-data (nth 4 (org-heading-components))))
  14944. nval)
  14945. (unless allowed
  14946. (user-error "Allowed values for this property have not been defined"))
  14947. (when previous (setq allowed (reverse allowed)))
  14948. (when (member value allowed)
  14949. (setq nval (car (cdr (member value allowed)))))
  14950. (setq nval (or nval (car allowed)))
  14951. (when (equal nval value)
  14952. (user-error "Only one allowed value for this property"))
  14953. (org-at-property-p)
  14954. (replace-match (concat " :" key ": " nval) t t)
  14955. (org-indent-line)
  14956. (beginning-of-line 1)
  14957. (skip-chars-forward " \t")
  14958. (when (equal prop org-effort-property)
  14959. (org-refresh-property
  14960. '((effort . identity)
  14961. (effort-minutes . org-duration-to-minutes))
  14962. nval)
  14963. (when (string= org-clock-current-task heading)
  14964. (setq org-clock-effort nval)
  14965. (org-clock-update-mode-line)))
  14966. (run-hook-with-args 'org-property-changed-functions key nval)))
  14967. (defun org-find-olp (path &optional this-buffer)
  14968. "Return a marker pointing to the entry at outline path OLP.
  14969. If anything goes wrong, throw an error.
  14970. You can wrap this call to catch the error like this:
  14971. (condition-case msg
  14972. (org-mobile-locate-entry (match-string 4))
  14973. (error (nth 1 msg)))
  14974. The return value will then be either a string with the error message,
  14975. or a marker if everything is OK.
  14976. If THIS-BUFFER is set, the outline path does not contain a file,
  14977. only headings."
  14978. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14979. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14980. (level 1)
  14981. (lmin 1)
  14982. (lmax 1)
  14983. end found flevel)
  14984. (unless buffer (error "File not found :%s" file))
  14985. (with-current-buffer buffer
  14986. (unless (derived-mode-p 'org-mode)
  14987. (error "Buffer %s needs to be in Org mode" buffer))
  14988. (org-with-wide-buffer
  14989. (goto-char (point-min))
  14990. (dolist (heading path)
  14991. (let ((re (format org-complex-heading-regexp-format
  14992. (regexp-quote heading)))
  14993. (cnt 0))
  14994. (while (re-search-forward re end t)
  14995. (setq level (- (match-end 1) (match-beginning 1)))
  14996. (when (and (>= level lmin) (<= level lmax))
  14997. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14998. (when (= cnt 0)
  14999. (error "Heading not found on level %d: %s" lmax heading))
  15000. (when (> cnt 1)
  15001. (error "Heading not unique on level %d: %s" lmax heading))
  15002. (goto-char found)
  15003. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15004. (setq end (save-excursion (org-end-of-subtree t t)))))
  15005. (when (org-at-heading-p)
  15006. (point-marker))))))
  15007. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15008. "Find node HEADING in BUFFER.
  15009. Return a marker to the heading if it was found, or nil if not.
  15010. If POS-ONLY is set, return just the position instead of a marker.
  15011. The heading text must match exact, but it may have a TODO keyword,
  15012. a priority cookie and tags in the standard locations."
  15013. (with-current-buffer (or buffer (current-buffer))
  15014. (org-with-wide-buffer
  15015. (goto-char (point-min))
  15016. (let (case-fold-search)
  15017. (when (re-search-forward
  15018. (format org-complex-heading-regexp-format
  15019. (regexp-quote heading)) nil t)
  15020. (if pos-only
  15021. (match-beginning 0)
  15022. (move-marker (make-marker) (match-beginning 0))))))))
  15023. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15024. "Find Org node headline HEADING in all .org files in directory DIR.
  15025. When the target headline is found, return a marker to this location."
  15026. (let ((files (directory-files (or dir default-directory)
  15027. t "\\`[^.#].*\\.org\\'"))
  15028. visiting m buffer)
  15029. (catch 'found
  15030. (dolist (file files)
  15031. (message "trying %s" file)
  15032. (setq visiting (org-find-base-buffer-visiting file))
  15033. (setq buffer (or visiting (find-file-noselect file)))
  15034. (setq m (org-find-exact-headline-in-buffer
  15035. heading buffer))
  15036. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15037. (and m (throw 'found m))))))
  15038. (defun org-find-entry-with-id (ident)
  15039. "Locate the entry that contains the ID property with exact value IDENT.
  15040. IDENT can be a string, a symbol or a number, this function will search for
  15041. the string representation of it.
  15042. Return the position where this entry starts, or nil if there is no such entry."
  15043. (interactive "sID: ")
  15044. (let ((id (cond
  15045. ((stringp ident) ident)
  15046. ((symbolp ident) (symbol-name ident))
  15047. ((numberp ident) (number-to-string ident))
  15048. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15049. (org-with-wide-buffer (org-find-property "ID" id))))
  15050. ;;;; Timestamps
  15051. (defvar org-last-changed-timestamp nil)
  15052. (defvar org-last-inserted-timestamp nil
  15053. "The last time stamp inserted with `org-insert-time-stamp'.")
  15054. (defun org-time-stamp (arg &optional inactive)
  15055. "Prompt for a date/time and insert a time stamp.
  15056. If the user specifies a time like HH:MM or if this command is
  15057. called with at least one prefix argument, the time stamp contains
  15058. the date and the time. Otherwise, only the date is included.
  15059. All parts of a date not specified by the user are filled in from
  15060. the timestamp at point, if any, or the current date/time
  15061. otherwise.
  15062. If there is already a timestamp at the cursor, it is replaced.
  15063. With two universal prefix arguments, insert an active timestamp
  15064. with the current time without prompting the user.
  15065. When called from lisp, the timestamp is inactive if INACTIVE is
  15066. non-nil."
  15067. (interactive "P")
  15068. (let* ((ts (cond
  15069. ((org-at-date-range-p t)
  15070. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15071. ((org-at-timestamp-p 'lax) (match-string 0))))
  15072. ;; Default time is either the timestamp at point or today.
  15073. ;; When entering a range, only the range start is considered.
  15074. (default-time (if (not ts) (current-time)
  15075. (apply #'encode-time (org-parse-time-string ts))))
  15076. (default-input (and ts (org-get-compact-tod ts)))
  15077. (repeater (and ts
  15078. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15079. (match-string 0 ts)))
  15080. org-time-was-given
  15081. org-end-time-was-given
  15082. (time
  15083. (and (if (equal arg '(16)) (current-time)
  15084. ;; Preserve `this-command' and `last-command'.
  15085. (let ((this-command this-command)
  15086. (last-command last-command))
  15087. (org-read-date
  15088. arg 'totime nil nil default-time default-input
  15089. inactive))))))
  15090. (cond
  15091. ((and ts
  15092. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15093. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15094. (insert "--")
  15095. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15096. (ts
  15097. ;; Make sure we're on a timestamp. When in the middle of a date
  15098. ;; range, move arbitrarily to range end.
  15099. (unless (org-at-timestamp-p 'lax)
  15100. (skip-chars-forward "-")
  15101. (org-at-timestamp-p 'lax))
  15102. (replace-match "")
  15103. (setq org-last-changed-timestamp
  15104. (org-insert-time-stamp
  15105. time (or org-time-was-given arg)
  15106. inactive nil nil (list org-end-time-was-given)))
  15107. (when repeater
  15108. (backward-char)
  15109. (insert " " repeater)
  15110. (setq org-last-changed-timestamp
  15111. (concat (substring org-last-inserted-timestamp 0 -1)
  15112. " " repeater ">")))
  15113. (message "Timestamp updated"))
  15114. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15115. (t (org-insert-time-stamp
  15116. time (or org-time-was-given arg) inactive nil nil
  15117. (list org-end-time-was-given))))))
  15118. ;; FIXME: can we use this for something else, like computing time differences?
  15119. (defun org-get-compact-tod (s)
  15120. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15121. (let* ((t1 (match-string 1 s))
  15122. (h1 (string-to-number (match-string 2 s)))
  15123. (m1 (string-to-number (match-string 3 s)))
  15124. (t2 (and (match-end 4) (match-string 5 s)))
  15125. (h2 (and t2 (string-to-number (match-string 6 s))))
  15126. (m2 (and t2 (string-to-number (match-string 7 s))))
  15127. dh dm)
  15128. (if (not t2)
  15129. t1
  15130. (setq dh (- h2 h1) dm (- m2 m1))
  15131. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15132. (concat t1 "+" (number-to-string dh)
  15133. (and (/= 0 dm) (format ":%02d" dm)))))))
  15134. (defun org-time-stamp-inactive (&optional arg)
  15135. "Insert an inactive time stamp.
  15136. An inactive time stamp is enclosed in square brackets instead of angle
  15137. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15138. does not link to the calendar and cannot be changed with the S-cursor keys.
  15139. So these are more for recording a certain time/date."
  15140. (interactive "P")
  15141. (org-time-stamp arg 'inactive))
  15142. (defvar org-date-ovl (make-overlay 1 1))
  15143. (overlay-put org-date-ovl 'face 'org-date-selected)
  15144. (delete-overlay org-date-ovl)
  15145. (defvar org-ans1) ; dynamically scoped parameter
  15146. (defvar org-ans2) ; dynamically scoped parameter
  15147. (defvar org-plain-time-of-day-regexp) ; defined below
  15148. (defvar org-overriding-default-time nil) ; dynamically scoped
  15149. (defvar org-read-date-overlay nil)
  15150. (defvar org-dcst nil) ; dynamically scoped
  15151. (defvar org-read-date-history nil)
  15152. (defvar org-read-date-final-answer nil)
  15153. (defvar org-read-date-analyze-futurep nil)
  15154. (defvar org-read-date-analyze-forced-year nil)
  15155. (defvar org-read-date-inactive)
  15156. (defvar org-read-date-minibuffer-local-map
  15157. (let* ((map (make-sparse-keymap)))
  15158. (set-keymap-parent map minibuffer-local-map)
  15159. (org-defkey map (kbd ".")
  15160. (lambda () (interactive)
  15161. ;; Are we at the beginning of the prompt?
  15162. (if (looking-back "^[^:]+: "
  15163. (let ((inhibit-field-text-motion t))
  15164. (line-beginning-position)))
  15165. (org-eval-in-calendar '(calendar-goto-today))
  15166. (insert "."))))
  15167. (org-defkey map (kbd "C-.")
  15168. (lambda () (interactive)
  15169. (org-eval-in-calendar '(calendar-goto-today))))
  15170. (org-defkey map [(meta shift left)]
  15171. (lambda () (interactive)
  15172. (org-eval-in-calendar '(calendar-backward-month 1))))
  15173. (org-defkey map [(meta shift right)]
  15174. (lambda () (interactive)
  15175. (org-eval-in-calendar '(calendar-forward-month 1))))
  15176. (org-defkey map [(meta shift up)]
  15177. (lambda () (interactive)
  15178. (org-eval-in-calendar '(calendar-backward-year 1))))
  15179. (org-defkey map [(meta shift down)]
  15180. (lambda () (interactive)
  15181. (org-eval-in-calendar '(calendar-forward-year 1))))
  15182. (org-defkey map [?\e (shift left)]
  15183. (lambda () (interactive)
  15184. (org-eval-in-calendar '(calendar-backward-month 1))))
  15185. (org-defkey map [?\e (shift right)]
  15186. (lambda () (interactive)
  15187. (org-eval-in-calendar '(calendar-forward-month 1))))
  15188. (org-defkey map [?\e (shift up)]
  15189. (lambda () (interactive)
  15190. (org-eval-in-calendar '(calendar-backward-year 1))))
  15191. (org-defkey map [?\e (shift down)]
  15192. (lambda () (interactive)
  15193. (org-eval-in-calendar '(calendar-forward-year 1))))
  15194. (org-defkey map [(shift up)]
  15195. (lambda () (interactive)
  15196. (org-eval-in-calendar '(calendar-backward-week 1))))
  15197. (org-defkey map [(shift down)]
  15198. (lambda () (interactive)
  15199. (org-eval-in-calendar '(calendar-forward-week 1))))
  15200. (org-defkey map [(shift left)]
  15201. (lambda () (interactive)
  15202. (org-eval-in-calendar '(calendar-backward-day 1))))
  15203. (org-defkey map [(shift right)]
  15204. (lambda () (interactive)
  15205. (org-eval-in-calendar '(calendar-forward-day 1))))
  15206. (org-defkey map "!"
  15207. (lambda () (interactive)
  15208. (org-eval-in-calendar '(diary-view-entries))
  15209. (message "")))
  15210. (org-defkey map ">"
  15211. (lambda () (interactive)
  15212. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15213. (org-defkey map "<"
  15214. (lambda () (interactive)
  15215. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15216. (org-defkey map "\C-v"
  15217. (lambda () (interactive)
  15218. (org-eval-in-calendar
  15219. '(calendar-scroll-left-three-months 1))))
  15220. (org-defkey map "\M-v"
  15221. (lambda () (interactive)
  15222. (org-eval-in-calendar
  15223. '(calendar-scroll-right-three-months 1))))
  15224. map)
  15225. "Keymap for minibuffer commands when using `org-read-date'.")
  15226. (defvar org-def)
  15227. (defvar org-defdecode)
  15228. (defvar org-with-time)
  15229. (defvar calendar-setup) ; Dynamically scoped.
  15230. (defun org-read-date (&optional with-time to-time from-string prompt
  15231. default-time default-input inactive)
  15232. "Read a date, possibly a time, and make things smooth for the user.
  15233. The prompt will suggest to enter an ISO date, but you can also enter anything
  15234. which will at least partially be understood by `parse-time-string'.
  15235. Unrecognized parts of the date will default to the current day, month, year,
  15236. hour and minute. If this command is called to replace a timestamp at point,
  15237. or to enter the second timestamp of a range, the default time is taken
  15238. from the existing stamp. Furthermore, the command prefers the future,
  15239. so if you are giving a date where the year is not given, and the day-month
  15240. combination is already past in the current year, it will assume you
  15241. mean next year. For details, see the manual. A few examples:
  15242. 3-2-5 --> 2003-02-05
  15243. feb 15 --> currentyear-02-15
  15244. 2/15 --> currentyear-02-15
  15245. sep 12 9 --> 2009-09-12
  15246. 12:45 --> today 12:45
  15247. 22 sept 0:34 --> currentyear-09-22 0:34
  15248. 12 --> currentyear-currentmonth-12
  15249. Fri --> nearest Friday after today
  15250. -Tue --> last Tuesday
  15251. etc.
  15252. Furthermore you can specify a relative date by giving, as the *first* thing
  15253. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15254. change in days weeks, months, years.
  15255. With a single plus or minus, the date is relative to today. With a double
  15256. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15257. +4d --> four days from today
  15258. +4 --> same as above
  15259. +2w --> two weeks from today
  15260. ++5 --> five days from default date
  15261. The function understands only English month and weekday abbreviations.
  15262. While prompting, a calendar is popped up - you can also select the
  15263. date with the mouse (button 1). The calendar shows a period of three
  15264. months. To scroll it to other months, use the keys `>' and `<'.
  15265. If you don't like the calendar, turn it off with
  15266. (setq org-read-date-popup-calendar nil)
  15267. With optional argument TO-TIME, the date will immediately be converted
  15268. to an internal time.
  15269. With an optional argument WITH-TIME, the prompt will suggest to
  15270. also insert a time. Note that when WITH-TIME is not set, you can
  15271. still enter a time, and this function will inform the calling routine
  15272. about this change. The calling routine may then choose to change the
  15273. format used to insert the time stamp into the buffer to include the time.
  15274. With optional argument FROM-STRING, read from this string instead from
  15275. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15276. the time/date that is used for everything that is not specified by the
  15277. user."
  15278. (require 'parse-time)
  15279. (let* ((org-with-time with-time)
  15280. (org-time-stamp-rounding-minutes
  15281. (if (equal org-with-time '(16))
  15282. '(0 0)
  15283. org-time-stamp-rounding-minutes))
  15284. (org-dcst org-display-custom-times)
  15285. (ct (org-current-time))
  15286. (org-def (or org-overriding-default-time default-time ct))
  15287. (org-defdecode (decode-time org-def))
  15288. (cur-frame (selected-frame))
  15289. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15290. (calendar-setup
  15291. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15292. (calendar-move-hook nil)
  15293. (calendar-view-diary-initially-flag nil)
  15294. (calendar-view-holidays-initially-flag nil)
  15295. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15296. ;; Rationalize `org-def' and `org-defdecode', if required.
  15297. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15298. (setf (nth 2 org-defdecode) -1)
  15299. (setf (nth 1 org-defdecode) 59)
  15300. (setq org-def (apply #'encode-time org-defdecode))
  15301. (setq org-defdecode (decode-time org-def)))
  15302. (let* ((timestr (format-time-string
  15303. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15304. org-def))
  15305. (prompt (concat (if prompt (concat prompt " ") "")
  15306. (format "Date+time [%s]: " timestr))))
  15307. (cond
  15308. (from-string (setq ans from-string))
  15309. (org-read-date-popup-calendar
  15310. (save-excursion
  15311. (save-window-excursion
  15312. (calendar)
  15313. (when (eq calendar-setup 'calendar-only)
  15314. (setq cal-frame
  15315. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15316. (select-frame cal-frame))
  15317. (org-eval-in-calendar '(setq cursor-type nil) t)
  15318. (unwind-protect
  15319. (progn
  15320. (calendar-forward-day (- (time-to-days org-def)
  15321. (calendar-absolute-from-gregorian
  15322. (calendar-current-date))))
  15323. (org-eval-in-calendar nil t)
  15324. (let* ((old-map (current-local-map))
  15325. (map (copy-keymap calendar-mode-map))
  15326. (minibuffer-local-map
  15327. (copy-keymap org-read-date-minibuffer-local-map)))
  15328. (org-defkey map (kbd "RET") 'org-calendar-select)
  15329. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15330. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15331. (unwind-protect
  15332. (progn
  15333. (use-local-map map)
  15334. (setq org-read-date-inactive inactive)
  15335. (add-hook 'post-command-hook 'org-read-date-display)
  15336. (setq org-ans0
  15337. (read-string prompt
  15338. default-input
  15339. 'org-read-date-history
  15340. nil))
  15341. ;; org-ans0: from prompt
  15342. ;; org-ans1: from mouse click
  15343. ;; org-ans2: from calendar motion
  15344. (setq ans
  15345. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15346. (remove-hook 'post-command-hook 'org-read-date-display)
  15347. (use-local-map old-map)
  15348. (when org-read-date-overlay
  15349. (delete-overlay org-read-date-overlay)
  15350. (setq org-read-date-overlay nil)))))
  15351. (bury-buffer "*Calendar*")
  15352. (when cal-frame
  15353. (delete-frame cal-frame)
  15354. (select-frame-set-input-focus cur-frame))))))
  15355. (t ; Naked prompt only
  15356. (unwind-protect
  15357. (setq ans (read-string prompt default-input
  15358. 'org-read-date-history timestr))
  15359. (when org-read-date-overlay
  15360. (delete-overlay org-read-date-overlay)
  15361. (setq org-read-date-overlay nil))))))
  15362. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15363. (when org-read-date-analyze-forced-year
  15364. (message "Year was forced into %s"
  15365. (if org-read-date-force-compatible-dates
  15366. "compatible range (1970-2037)"
  15367. "range representable on this machine"))
  15368. (ding))
  15369. ;; One round trip to get rid of 34th of August and stuff like that....
  15370. (setq final (decode-time (apply 'encode-time final)))
  15371. (setq org-read-date-final-answer ans)
  15372. (if to-time
  15373. (apply 'encode-time final)
  15374. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15375. (format "%04d-%02d-%02d %02d:%02d"
  15376. (nth 5 final) (nth 4 final) (nth 3 final)
  15377. (nth 2 final) (nth 1 final))
  15378. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15379. (defun org-read-date-display ()
  15380. "Display the current date prompt interpretation in the minibuffer."
  15381. (when org-read-date-display-live
  15382. (when org-read-date-overlay
  15383. (delete-overlay org-read-date-overlay))
  15384. (when (minibufferp (current-buffer))
  15385. (save-excursion
  15386. (end-of-line 1)
  15387. (while (not (equal (buffer-substring
  15388. (max (point-min) (- (point) 4)) (point))
  15389. " "))
  15390. (insert " ")))
  15391. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15392. " " (or org-ans1 org-ans2)))
  15393. (org-end-time-was-given nil)
  15394. (f (org-read-date-analyze ans org-def org-defdecode))
  15395. (fmts (if org-dcst
  15396. org-time-stamp-custom-formats
  15397. org-time-stamp-formats))
  15398. (fmt (if (or org-with-time
  15399. (and (boundp 'org-time-was-given) org-time-was-given))
  15400. (cdr fmts)
  15401. (car fmts)))
  15402. (txt (format-time-string fmt (apply 'encode-time f)))
  15403. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15404. (txt (concat "=> " txt)))
  15405. (when (and org-end-time-was-given
  15406. (string-match org-plain-time-of-day-regexp txt))
  15407. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15408. org-end-time-was-given
  15409. (substring txt (match-end 0)))))
  15410. (when org-read-date-analyze-futurep
  15411. (setq txt (concat txt " (=>F)")))
  15412. (setq org-read-date-overlay
  15413. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15414. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15415. (defun org-read-date-analyze (ans def defdecode)
  15416. "Analyze the combined answer of the date prompt."
  15417. ;; FIXME: cleanup and comment
  15418. ;; Pass `current-time' result to `decode-time' (instead of calling
  15419. ;; without arguments) so that only `current-time' has to be
  15420. ;; overridden in tests.
  15421. (let ((org-def def)
  15422. (org-defdecode defdecode)
  15423. (nowdecode (decode-time (current-time)))
  15424. delta deltan deltaw deltadef year month day
  15425. hour minute second wday pm h2 m2 tl wday1
  15426. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15427. (setq org-read-date-analyze-futurep nil
  15428. org-read-date-analyze-forced-year nil)
  15429. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15430. (setq ans "+0"))
  15431. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15432. (setq ans (replace-match "" t t ans)
  15433. deltan (car delta)
  15434. deltaw (nth 1 delta)
  15435. deltadef (nth 2 delta)))
  15436. ;; Check if there is an iso week date in there. If yes, store the
  15437. ;; info and postpone interpreting it until the rest of the parsing
  15438. ;; is done.
  15439. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15440. (setq iso-year (when (match-end 1)
  15441. (org-small-year-to-year
  15442. (string-to-number (match-string 1 ans))))
  15443. iso-weekday (when (match-end 3)
  15444. (string-to-number (match-string 3 ans)))
  15445. iso-week (string-to-number (match-string 2 ans)))
  15446. (setq ans (replace-match "" t t ans)))
  15447. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15448. (when (string-match
  15449. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15450. (setq year (if (match-end 2)
  15451. (string-to-number (match-string 2 ans))
  15452. (progn (setq kill-year t)
  15453. (string-to-number (format-time-string "%Y"))))
  15454. month (string-to-number (match-string 3 ans))
  15455. day (string-to-number (match-string 4 ans)))
  15456. (setq year (org-small-year-to-year year))
  15457. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15458. t nil ans)))
  15459. ;; Help matching dotted european dates
  15460. (when (string-match
  15461. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15462. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15463. (setq kill-year t)
  15464. (string-to-number (format-time-string "%Y")))
  15465. day (string-to-number (match-string 1 ans))
  15466. month (string-to-number (match-string 2 ans))
  15467. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15468. t nil ans)))
  15469. ;; Help matching american dates, like 5/30 or 5/30/7
  15470. (when (string-match
  15471. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15472. (setq year (if (match-end 4)
  15473. (string-to-number (match-string 4 ans))
  15474. (progn (setq kill-year t)
  15475. (string-to-number (format-time-string "%Y"))))
  15476. month (string-to-number (match-string 1 ans))
  15477. day (string-to-number (match-string 2 ans)))
  15478. (setq year (org-small-year-to-year year))
  15479. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15480. t nil ans)))
  15481. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15482. ;; If there is a time with am/pm, and *no* time without it, we convert
  15483. ;; so that matching will be successful.
  15484. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15485. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15486. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15487. (setq hour (string-to-number (match-string 1 ans))
  15488. minute (if (match-end 3)
  15489. (string-to-number (match-string 3 ans))
  15490. 0)
  15491. pm (equal ?p
  15492. (string-to-char (downcase (match-string 4 ans)))))
  15493. (if (and (= hour 12) (not pm))
  15494. (setq hour 0)
  15495. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15496. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15497. t t ans))))
  15498. ;; Check if a time range is given as a duration
  15499. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15500. (setq hour (string-to-number (match-string 1 ans))
  15501. h2 (+ hour (string-to-number (match-string 3 ans)))
  15502. minute (string-to-number (match-string 2 ans))
  15503. m2 (+ minute (if (match-end 5) (string-to-number
  15504. (match-string 5 ans))0)))
  15505. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15506. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15507. t t ans)))
  15508. ;; Check if there is a time range
  15509. (when (boundp 'org-end-time-was-given)
  15510. (setq org-time-was-given nil)
  15511. (when (and (string-match org-plain-time-of-day-regexp ans)
  15512. (match-end 8))
  15513. (setq org-end-time-was-given (match-string 8 ans))
  15514. (setq ans (concat (substring ans 0 (match-beginning 7))
  15515. (substring ans (match-end 7))))))
  15516. (setq tl (parse-time-string ans)
  15517. day (or (nth 3 tl) (nth 3 org-defdecode))
  15518. month
  15519. (cond ((nth 4 tl))
  15520. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15521. ;; Day was specified. Make sure DAY+MONTH
  15522. ;; combination happens in the future.
  15523. ((nth 3 tl)
  15524. (setq futurep t)
  15525. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15526. (nth 4 nowdecode)))
  15527. (t (nth 4 org-defdecode)))
  15528. year
  15529. (cond ((and (not kill-year) (nth 5 tl)))
  15530. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15531. ;; Month was guessed in the future and is at least
  15532. ;; equal to NOWDECODE's. Fix year accordingly.
  15533. (futurep
  15534. (if (or (> month (nth 4 nowdecode))
  15535. (>= day (nth 3 nowdecode)))
  15536. (nth 5 nowdecode)
  15537. (1+ (nth 5 nowdecode))))
  15538. ;; Month was specified. Make sure MONTH+YEAR
  15539. ;; combination happens in the future.
  15540. ((nth 4 tl)
  15541. (setq futurep t)
  15542. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15543. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15544. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15545. (t (nth 5 nowdecode))))
  15546. (t (nth 5 org-defdecode)))
  15547. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15548. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15549. second (or (nth 0 tl) 0)
  15550. wday (nth 6 tl))
  15551. (when (and (eq org-read-date-prefer-future 'time)
  15552. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15553. (equal day (nth 3 nowdecode))
  15554. (equal month (nth 4 nowdecode))
  15555. (equal year (nth 5 nowdecode))
  15556. (nth 2 tl)
  15557. (or (< (nth 2 tl) (nth 2 nowdecode))
  15558. (and (= (nth 2 tl) (nth 2 nowdecode))
  15559. (nth 1 tl)
  15560. (< (nth 1 tl) (nth 1 nowdecode)))))
  15561. (setq day (1+ day)
  15562. futurep t))
  15563. ;; Special date definitions below
  15564. (cond
  15565. (iso-week
  15566. ;; There was an iso week
  15567. (require 'cal-iso)
  15568. (setq futurep nil)
  15569. (setq year (or iso-year year)
  15570. day (or iso-weekday wday 1)
  15571. wday nil ; to make sure that the trigger below does not match
  15572. iso-date (calendar-gregorian-from-absolute
  15573. (calendar-iso-to-absolute
  15574. (list iso-week day year))))
  15575. ; FIXME: Should we also push ISO weeks into the future?
  15576. ; (when (and org-read-date-prefer-future
  15577. ; (not iso-year)
  15578. ; (< (calendar-absolute-from-gregorian iso-date)
  15579. ; (time-to-days (current-time))))
  15580. ; (setq year (1+ year)
  15581. ; iso-date (calendar-gregorian-from-absolute
  15582. ; (calendar-iso-to-absolute
  15583. ; (list iso-week day year)))))
  15584. (setq month (car iso-date)
  15585. year (nth 2 iso-date)
  15586. day (nth 1 iso-date)))
  15587. (deltan
  15588. (setq futurep nil)
  15589. (unless deltadef
  15590. ;; Pass `current-time' result to `decode-time' (instead of
  15591. ;; calling without arguments) so that only `current-time' has
  15592. ;; to be overridden in tests.
  15593. (let ((now (decode-time (current-time))))
  15594. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15595. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15596. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15597. ((equal deltaw "m") (setq month (+ month deltan)))
  15598. ((equal deltaw "y") (setq year (+ year deltan)))))
  15599. ((and wday (not (nth 3 tl)))
  15600. ;; Weekday was given, but no day, so pick that day in the week
  15601. ;; on or after the derived date.
  15602. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15603. (unless (equal wday wday1)
  15604. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15605. (when (and (boundp 'org-time-was-given)
  15606. (nth 2 tl))
  15607. (setq org-time-was-given t))
  15608. (when (< year 100) (setq year (+ 2000 year)))
  15609. ;; Check of the date is representable
  15610. (if org-read-date-force-compatible-dates
  15611. (progn
  15612. (when (< year 1970)
  15613. (setq year 1970 org-read-date-analyze-forced-year t))
  15614. (when (> year 2037)
  15615. (setq year 2037 org-read-date-analyze-forced-year t)))
  15616. (condition-case nil
  15617. (ignore (encode-time second minute hour day month year))
  15618. (error
  15619. (setq year (nth 5 org-defdecode))
  15620. (setq org-read-date-analyze-forced-year t))))
  15621. (setq org-read-date-analyze-futurep futurep)
  15622. (list second minute hour day month year)))
  15623. (defvar parse-time-weekdays)
  15624. (defun org-read-date-get-relative (s today default)
  15625. "Check string S for special relative date string.
  15626. TODAY and DEFAULT are internal times, for today and for a default.
  15627. Return shift list (N what def-flag)
  15628. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15629. N is the number of WHATs to shift.
  15630. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15631. the DEFAULT date rather than TODAY."
  15632. (require 'parse-time)
  15633. (when (and
  15634. (string-match
  15635. (concat
  15636. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15637. "\\([0-9]+\\)?"
  15638. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15639. "\\([ \t]\\|$\\)") s)
  15640. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15641. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15642. (string-to-char (substring (match-string 1 s) -1))
  15643. ?+))
  15644. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15645. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15646. (what (if (match-end 3) (match-string 3 s) "d"))
  15647. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15648. (date (if rel default today))
  15649. (wday (nth 6 (decode-time date)))
  15650. delta)
  15651. (if wday1
  15652. (progn
  15653. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15654. (when (= delta 0) (setq delta 7))
  15655. (when (= dir ?-)
  15656. (setq delta (- delta 7))
  15657. (when (= delta 0) (setq delta -7)))
  15658. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15659. (list delta "d" rel))
  15660. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15661. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15662. "Turn a user-specified date into the internal representation.
  15663. The internal representation needed by the calendar is (month day year).
  15664. This is a wrapper to handle the brain-dead convention in calendar that
  15665. user function argument order change dependent on argument order."
  15666. (pcase calendar-date-style
  15667. (`american (list arg1 arg2 arg3))
  15668. (`european (list arg2 arg1 arg3))
  15669. (`iso (list arg2 arg3 arg1))))
  15670. (defun org-eval-in-calendar (form &optional keepdate)
  15671. "Eval FORM in the calendar window and return to current window.
  15672. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15673. (let ((sf (selected-frame))
  15674. (sw (selected-window)))
  15675. (select-window (get-buffer-window "*Calendar*" t))
  15676. (eval form)
  15677. (when (and (not keepdate) (calendar-cursor-to-date))
  15678. (let* ((date (calendar-cursor-to-date))
  15679. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15680. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15681. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15682. (select-window sw)
  15683. (select-frame-set-input-focus sf)))
  15684. (defun org-calendar-select ()
  15685. "Return to `org-read-date' with the date currently selected.
  15686. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15687. (interactive)
  15688. (when (calendar-cursor-to-date)
  15689. (let* ((date (calendar-cursor-to-date))
  15690. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15691. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15692. (when (active-minibuffer-window) (exit-minibuffer))))
  15693. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15694. "Insert a date stamp for the date given by the internal TIME.
  15695. See `format-time-string' for the format of TIME.
  15696. WITH-HM means use the stamp format that includes the time of the day.
  15697. INACTIVE means use square brackets instead of angular ones, so that the
  15698. stamp will not contribute to the agenda.
  15699. PRE and POST are optional strings to be inserted before and after the
  15700. stamp.
  15701. The command returns the inserted time stamp."
  15702. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15703. stamp)
  15704. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15705. (insert-before-markers (or pre ""))
  15706. (when (listp extra)
  15707. (setq extra (car extra))
  15708. (if (and (stringp extra)
  15709. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15710. (setq extra (format "-%02d:%02d"
  15711. (string-to-number (match-string 1 extra))
  15712. (string-to-number (match-string 2 extra))))
  15713. (setq extra nil)))
  15714. (when extra
  15715. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15716. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15717. (insert-before-markers (or post ""))
  15718. (setq org-last-inserted-timestamp stamp)))
  15719. (defun org-toggle-time-stamp-overlays ()
  15720. "Toggle the use of custom time stamp formats."
  15721. (interactive)
  15722. (setq org-display-custom-times (not org-display-custom-times))
  15723. (unless org-display-custom-times
  15724. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15725. (while (setq p (next-single-property-change p 'display))
  15726. (when (and (get-text-property p 'display)
  15727. (eq (get-text-property p 'face) 'org-date))
  15728. (remove-text-properties
  15729. p (setq p (next-single-property-change p 'display))
  15730. '(display t))))
  15731. (set-buffer-modified-p bmp)))
  15732. (org-restart-font-lock)
  15733. (setq org-table-may-need-update t)
  15734. (if org-display-custom-times
  15735. (message "Time stamps are overlaid with custom format")
  15736. (message "Time stamp overlays removed")))
  15737. (defun org-display-custom-time (beg end)
  15738. "Overlay modified time stamp format over timestamp between BEG and END."
  15739. (let* ((ts (buffer-substring beg end))
  15740. t1 with-hm tf time str (off 0))
  15741. (save-match-data
  15742. (setq t1 (org-parse-time-string ts t))
  15743. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15744. (setq off (- (match-end 0) (match-beginning 0)))))
  15745. (setq end (- end off))
  15746. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15747. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15748. time (org-fix-decoded-time t1)
  15749. str (org-add-props
  15750. (format-time-string
  15751. (substring tf 1 -1) (apply 'encode-time time))
  15752. nil 'mouse-face 'highlight))
  15753. (put-text-property beg end 'display str)))
  15754. (defun org-fix-decoded-time (time)
  15755. "Set 0 instead of nil for the first 6 elements of time.
  15756. Don't touch the rest."
  15757. (let ((n 0))
  15758. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15759. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15760. "Difference between TIMESTAMP-STRING and now in days.
  15761. If SECONDS is non-nil, return the difference in seconds."
  15762. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15763. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15764. (funcall fdiff (current-time)))))
  15765. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15766. "Is the time in TIMESTAMP-STRING close to the current date?"
  15767. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15768. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15769. (not (org-entry-is-done-p))))
  15770. (defun org-get-wdays (ts &optional delay zero-delay)
  15771. "Get the deadline lead time appropriate for timestring TS.
  15772. When DELAY is non-nil, get the delay time for scheduled items
  15773. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15774. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15775. don't try to find the delay cookie in the scheduled timestamp."
  15776. (let ((tv (if delay org-scheduled-delay-days
  15777. org-deadline-warning-days)))
  15778. (cond
  15779. ((or (and delay (< tv 0))
  15780. (and delay zero-delay (<= tv 0))
  15781. (and (not delay) (<= tv 0)))
  15782. ;; Enforce this value no matter what
  15783. (- tv))
  15784. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15785. ;; lead time is specified.
  15786. (floor (* (string-to-number (match-string 1 ts))
  15787. (cdr (assoc (match-string 2 ts)
  15788. '(("d" . 1) ("w" . 7)
  15789. ("m" . 30.4) ("y" . 365.25)
  15790. ("h" . 0.041667)))))))
  15791. ;; go for the default.
  15792. (t tv))))
  15793. (defun org-calendar-select-mouse (ev)
  15794. "Return to `org-read-date' with the date currently selected.
  15795. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15796. (interactive "e")
  15797. (mouse-set-point ev)
  15798. (when (calendar-cursor-to-date)
  15799. (let* ((date (calendar-cursor-to-date))
  15800. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15801. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15802. (when (active-minibuffer-window) (exit-minibuffer))))
  15803. (defun org-check-deadlines (ndays)
  15804. "Check if there are any deadlines due or past due.
  15805. A deadline is considered due if it happens within `org-deadline-warning-days'
  15806. days from today's date. If the deadline appears in an entry marked DONE,
  15807. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15808. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15809. are shown."
  15810. (interactive "P")
  15811. (let* ((org-warn-days
  15812. (cond
  15813. ((equal ndays '(4)) 100000)
  15814. (ndays (prefix-numeric-value ndays))
  15815. (t (abs org-deadline-warning-days))))
  15816. (case-fold-search nil)
  15817. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15818. (callback
  15819. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15820. (message "%d deadlines past-due or due within %d days"
  15821. (org-occur regexp nil callback)
  15822. org-warn-days)))
  15823. (defsubst org-re-timestamp (type)
  15824. "Return a regexp for timestamp TYPE.
  15825. Allowed values for TYPE are:
  15826. all: all timestamps
  15827. active: only active timestamps (<...>)
  15828. inactive: only inactive timestamps ([...])
  15829. scheduled: only scheduled timestamps
  15830. deadline: only deadline timestamps
  15831. closed: only closed time-stamps
  15832. When TYPE is nil, fall back on returning a regexp that matches
  15833. both scheduled and deadline timestamps."
  15834. (cl-case type
  15835. (all org-ts-regexp-both)
  15836. (active org-ts-regexp)
  15837. (inactive org-ts-regexp-inactive)
  15838. (scheduled org-scheduled-time-regexp)
  15839. (deadline org-deadline-time-regexp)
  15840. (closed org-closed-time-regexp)
  15841. (otherwise
  15842. (concat "\\<"
  15843. (regexp-opt (list org-deadline-string org-scheduled-string))
  15844. " *<\\([^>]+\\)>"))))
  15845. (defun org-check-before-date (d)
  15846. "Check if there are deadlines or scheduled entries before date D."
  15847. (interactive (list (org-read-date)))
  15848. (let* ((case-fold-search nil)
  15849. (regexp (org-re-timestamp org-ts-type))
  15850. (ts-type org-ts-type)
  15851. (callback
  15852. (lambda ()
  15853. (let ((match (match-string 1)))
  15854. (and (if (memq ts-type '(active inactive all))
  15855. (eq (org-element-type (save-excursion
  15856. (backward-char)
  15857. (org-element-context)))
  15858. 'timestamp)
  15859. (org-at-planning-p))
  15860. (time-less-p
  15861. (org-time-string-to-time match t)
  15862. (org-time-string-to-time d t)))))))
  15863. (message "%d entries before %s"
  15864. (org-occur regexp nil callback)
  15865. d)))
  15866. (defun org-check-after-date (d)
  15867. "Check if there are deadlines or scheduled entries after date D."
  15868. (interactive (list (org-read-date)))
  15869. (let* ((case-fold-search nil)
  15870. (regexp (org-re-timestamp org-ts-type))
  15871. (ts-type org-ts-type)
  15872. (callback
  15873. (lambda ()
  15874. (let ((match (match-string 1)))
  15875. (and (if (memq ts-type '(active inactive all))
  15876. (eq (org-element-type (save-excursion
  15877. (backward-char)
  15878. (org-element-context)))
  15879. 'timestamp)
  15880. (org-at-planning-p))
  15881. (not (time-less-p
  15882. (org-time-string-to-time match t)
  15883. (org-time-string-to-time d t))))))))
  15884. (message "%d entries after %s"
  15885. (org-occur regexp nil callback)
  15886. d)))
  15887. (defun org-check-dates-range (start-date end-date)
  15888. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15889. (interactive (list (org-read-date nil nil nil "Range starts")
  15890. (org-read-date nil nil nil "Range end")))
  15891. (let ((case-fold-search nil)
  15892. (regexp (org-re-timestamp org-ts-type))
  15893. (callback
  15894. (let ((type org-ts-type))
  15895. (lambda ()
  15896. (let ((match (match-string 1)))
  15897. (and
  15898. (if (memq type '(active inactive all))
  15899. (eq (org-element-type (save-excursion
  15900. (backward-char)
  15901. (org-element-context)))
  15902. 'timestamp)
  15903. (org-at-planning-p))
  15904. (not (time-less-p
  15905. (org-time-string-to-time match t)
  15906. (org-time-string-to-time start-date t)))
  15907. (time-less-p
  15908. (org-time-string-to-time match t)
  15909. (org-time-string-to-time end-date t))))))))
  15910. (message "%d entries between %s and %s"
  15911. (org-occur regexp nil callback) start-date end-date)))
  15912. (defun org-evaluate-time-range (&optional to-buffer)
  15913. "Evaluate a time range by computing the difference between start and end.
  15914. Normally the result is just printed in the echo area, but with prefix arg
  15915. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15916. If the time range is actually in a table, the result is inserted into the
  15917. next column.
  15918. For time difference computation, a year is assumed to be exactly 365
  15919. days in order to avoid rounding problems."
  15920. (interactive "P")
  15921. (or
  15922. (org-clock-update-time-maybe)
  15923. (save-excursion
  15924. (unless (org-at-date-range-p t)
  15925. (goto-char (point-at-bol))
  15926. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15927. (unless (org-at-date-range-p t)
  15928. (user-error "Not at a time-stamp range, and none found in current line")))
  15929. (let* ((ts1 (match-string 1))
  15930. (ts2 (match-string 2))
  15931. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15932. (match-end (match-end 0))
  15933. (time1 (org-time-string-to-time ts1))
  15934. (time2 (org-time-string-to-time ts2))
  15935. (t1 (float-time time1))
  15936. (t2 (float-time time2))
  15937. (diff (abs (- t2 t1)))
  15938. (negative (< (- t2 t1) 0))
  15939. ;; (ys (floor (* 365 24 60 60)))
  15940. (ds (* 24 60 60))
  15941. (hs (* 60 60))
  15942. (fy "%dy %dd %02d:%02d")
  15943. (fy1 "%dy %dd")
  15944. (fd "%dd %02d:%02d")
  15945. (fd1 "%dd")
  15946. (fh "%02d:%02d")
  15947. y d h m align)
  15948. (if havetime
  15949. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15950. y 0
  15951. d (floor (/ diff ds)) diff (mod diff ds)
  15952. h (floor (/ diff hs)) diff (mod diff hs)
  15953. m (floor (/ diff 60)))
  15954. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15955. y 0
  15956. d (floor (+ (/ diff ds) 0.5))
  15957. h 0 m 0))
  15958. (if (not to-buffer)
  15959. (message "%s" (org-make-tdiff-string y d h m))
  15960. (if (org-at-table-p)
  15961. (progn
  15962. (goto-char match-end)
  15963. (setq align t)
  15964. (and (looking-at " *|") (goto-char (match-end 0))))
  15965. (goto-char match-end))
  15966. (when (looking-at
  15967. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15968. (replace-match ""))
  15969. (when negative (insert " -"))
  15970. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15971. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15972. (insert " " (format fh h m))))
  15973. (when align (org-table-align))
  15974. (message "Time difference inserted")))))
  15975. (defun org-make-tdiff-string (y d h m)
  15976. (let ((fmt "")
  15977. (l nil))
  15978. (when (> y 0)
  15979. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15980. (push y l))
  15981. (when (> d 0)
  15982. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15983. (push d l))
  15984. (when (> h 0)
  15985. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15986. (push h l))
  15987. (when (> m 0)
  15988. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15989. (push m l))
  15990. (apply 'format fmt (nreverse l))))
  15991. (defun org-time-string-to-time (s &optional zone)
  15992. "Convert timestamp string S into internal time.
  15993. The optional ZONE is omitted or nil for Emacs local time, t for
  15994. Universal Time, ‘wall’ for system wall clock time, or a string as
  15995. in the TZ environment variable."
  15996. (apply #'encode-time (org-parse-time-string s nil zone)))
  15997. (defun org-time-string-to-seconds (s &optional zone)
  15998. "Convert a timestamp string S into a number of seconds.
  15999. The optional ZONE is omitted or nil for Emacs local time, t for
  16000. Universal Time, ‘wall’ for system wall clock time, or a string as
  16001. in the TZ environment variable."
  16002. (float-time (org-time-string-to-time s zone)))
  16003. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16004. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16005. "Convert time stamp S to an absolute day number.
  16006. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16007. stamp, get the closest date to DAYNR. If PREFER is
  16008. `past' (respectively `future') return a date past (respectively
  16009. after) or equal to DAYNR.
  16010. POS is the location of time stamp S, as a buffer position in
  16011. BUFFER.
  16012. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16013. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16014. signaled."
  16015. (cond
  16016. ((string-match "\\`%%\\((.*)\\)" s)
  16017. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16018. ;; only able to match individual dates. If it fails, raise an
  16019. ;; error.
  16020. (if (and daynr
  16021. (org-diary-sexp-entry
  16022. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16023. daynr
  16024. (signal 'org-diary-sexp-no-match (list s))))
  16025. (daynr (org-closest-date s daynr prefer))
  16026. (t (time-to-days
  16027. (condition-case errdata
  16028. (apply #'encode-time (org-parse-time-string s))
  16029. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16030. s
  16031. (if (not (and buffer pos)) ""
  16032. (format-message " at %d in buffer `%s'" pos buffer))
  16033. (cdr errdata))))))))
  16034. (defun org-days-to-iso-week (days)
  16035. "Return the iso week number."
  16036. (require 'cal-iso)
  16037. (car (calendar-iso-from-absolute days)))
  16038. (defun org-small-year-to-year (year)
  16039. "Convert 2-digit years into 4-digit years.
  16040. YEAR is expanded into one of the 30 next years, if possible, or
  16041. into a past one. Any year larger than 99 is returned unchanged."
  16042. (if (>= year 100) year
  16043. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16044. (century (/ current 100))
  16045. (offset (- year (% current 100))))
  16046. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16047. ((> offset -70) (+ (* century 100) year))
  16048. (t (+ (* (1+ century) 100) year))))))
  16049. (defun org-time-from-absolute (d)
  16050. "Return the time corresponding to date D.
  16051. D may be an absolute day number, or a calendar-type list (month day year)."
  16052. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16053. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16054. (defvar org-agenda-current-date)
  16055. (defun org-calendar-holiday ()
  16056. "List of holidays, for Diary display in Org mode."
  16057. (require 'holidays)
  16058. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16059. (and hl (mapconcat #'identity hl "; "))))
  16060. (defun org-diary-sexp-entry (sexp entry d)
  16061. "Process a SEXP diary ENTRY for date D."
  16062. (require 'diary-lib)
  16063. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16064. ;; dynamically.
  16065. (let* ((sexp `(let ((entry ,entry)
  16066. (date ',d))
  16067. ,(car (read-from-string sexp))))
  16068. (result (if calendar-debug-sexp (eval sexp)
  16069. (condition-case nil
  16070. (eval sexp)
  16071. (error
  16072. (beep)
  16073. (message "Bad sexp at line %d in %s: %s"
  16074. (org-current-line)
  16075. (buffer-file-name) sexp)
  16076. (sleep-for 2))))))
  16077. (cond ((stringp result) (split-string result "; "))
  16078. ((and (consp result)
  16079. (not (consp (cdr result)))
  16080. (stringp (cdr result))) (cdr result))
  16081. ((and (consp result)
  16082. (stringp (car result))) result)
  16083. (result entry))))
  16084. (defun org-diary-to-ical-string (frombuf)
  16085. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16086. This uses the icalendar.el library."
  16087. (let* ((tmpdir temporary-file-directory)
  16088. (tmpfile (make-temp-name
  16089. (expand-file-name "orgics" tmpdir)))
  16090. buf rtn b e)
  16091. (with-current-buffer frombuf
  16092. (icalendar-export-region (point-min) (point-max) tmpfile)
  16093. (setq buf (find-buffer-visiting tmpfile))
  16094. (set-buffer buf)
  16095. (goto-char (point-min))
  16096. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16097. (setq b (match-beginning 0)))
  16098. (goto-char (point-max))
  16099. (when (re-search-backward "^END:VEVENT" nil t)
  16100. (setq e (match-end 0)))
  16101. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16102. (kill-buffer buf)
  16103. (delete-file tmpfile)
  16104. rtn))
  16105. (defun org-closest-date (start current prefer)
  16106. "Return closest date to CURRENT starting from START.
  16107. CURRENT and START are both time stamps.
  16108. When PREFER is `past', return a date that is either CURRENT or
  16109. past. When PREFER is `future', return a date that is either
  16110. CURRENT or future.
  16111. Only time stamps with a repeater are modified. Any other time
  16112. stamp stay unchanged. In any case, return value is an absolute
  16113. day number."
  16114. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16115. ;; No repeater. Do not shift time stamp.
  16116. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16117. (let ((value (string-to-number (match-string 1 start)))
  16118. (type (match-string 2 start)))
  16119. (if (= 0 value)
  16120. ;; Repeater with a 0-value is considered as void.
  16121. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16122. (let* ((base (org-date-to-gregorian start))
  16123. (target (org-date-to-gregorian current))
  16124. (sday (calendar-absolute-from-gregorian base))
  16125. (cday (calendar-absolute-from-gregorian target))
  16126. n1 n2)
  16127. ;; If START is already past CURRENT, just return START.
  16128. (if (<= cday sday) sday
  16129. ;; Compute closest date before (N1) and closest date past
  16130. ;; (N2) CURRENT.
  16131. (pcase type
  16132. ("h"
  16133. (let ((missing-hours
  16134. (mod (+ (- (* 24 (- cday sday))
  16135. (nth 2 (org-parse-time-string start)))
  16136. org-extend-today-until)
  16137. value)))
  16138. (setf n1 (if (= missing-hours 0) cday
  16139. (- cday (1+ (/ missing-hours 24)))))
  16140. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16141. ((or "d" "w")
  16142. (let ((value (if (equal type "w") (* 7 value) value)))
  16143. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16144. (setf n2 (+ n1 value))))
  16145. ("m"
  16146. (let* ((add-months
  16147. (lambda (d n)
  16148. ;; Add N months to gregorian date D, i.e.,
  16149. ;; a list (MONTH DAY YEAR). Return a valid
  16150. ;; gregorian date.
  16151. (let ((m (+ (nth 0 d) n)))
  16152. (list (mod m 12)
  16153. (nth 1 d)
  16154. (+ (/ m 12) (nth 2 d))))))
  16155. (months ; Complete months to TARGET.
  16156. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16157. (- (nth 0 target) (nth 0 base))
  16158. ;; If START's day is greater than
  16159. ;; TARGET's, remove incomplete month.
  16160. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16161. value)
  16162. value))
  16163. (before (funcall add-months base months)))
  16164. (setf n1 (calendar-absolute-from-gregorian before))
  16165. (setf n2
  16166. (calendar-absolute-from-gregorian
  16167. (funcall add-months before value)))))
  16168. (_
  16169. (let* ((d (nth 1 base))
  16170. (m (nth 0 base))
  16171. (y (nth 2 base))
  16172. (years ; Complete years to TARGET.
  16173. (* (/ (- (nth 2 target)
  16174. y
  16175. ;; If START's month and day are
  16176. ;; greater than TARGET's, remove
  16177. ;; incomplete year.
  16178. (if (or (> (nth 0 target) m)
  16179. (and (= (nth 0 target) m)
  16180. (> (nth 1 target) d)))
  16181. 0
  16182. 1))
  16183. value)
  16184. value))
  16185. (before (list m d (+ y years))))
  16186. (setf n1 (calendar-absolute-from-gregorian before))
  16187. (setf n2 (calendar-absolute-from-gregorian
  16188. (list m d (+ (nth 2 before) value)))))))
  16189. ;; Handle PREFER parameter, if any.
  16190. (cond
  16191. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16192. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16193. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16194. (defun org-date-to-gregorian (d)
  16195. "Turn any specification of date D into a Gregorian date for the calendar."
  16196. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16197. ((and (listp d) (= (length d) 3)) d)
  16198. ((stringp d)
  16199. (let ((d (org-parse-time-string d)))
  16200. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16201. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16202. (defun org-parse-time-string (s &optional nodefault zone)
  16203. "Parse the standard Org time string.
  16204. This should be a lot faster than the normal `parse-time-string'.
  16205. If time is not given, defaults to 0:00. However, with optional
  16206. NODEFAULT, hour and minute fields will be nil if not given.
  16207. The optional ZONE is omitted or nil for Emacs local time, t for
  16208. Universal Time, ‘wall’ for system wall clock time, or a string as
  16209. in the TZ environment variable."
  16210. (cond ((string-match org-ts-regexp0 s)
  16211. (list 0
  16212. (when (or (match-beginning 8) (not nodefault))
  16213. (string-to-number (or (match-string 8 s) "0")))
  16214. (when (or (match-beginning 7) (not nodefault))
  16215. (string-to-number (or (match-string 7 s) "0")))
  16216. (string-to-number (match-string 4 s))
  16217. (string-to-number (match-string 3 s))
  16218. (string-to-number (match-string 2 s))
  16219. nil nil zone))
  16220. ((string-match "^<[^>]+>$" s)
  16221. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16222. ;; second argument. However, this requires at least Emacs
  16223. ;; 25.1. We can do it when we switch to this version as our
  16224. ;; minimal requirement.
  16225. (decode-time (seconds-to-time (org-matcher-time s))))
  16226. (t (error "Not a standard Org time string: %s" s))))
  16227. (defun org-timestamp-up (&optional arg)
  16228. "Increase the date item at the cursor by one.
  16229. If the cursor is on the year, change the year. If it is on the month,
  16230. the day or the time, change that.
  16231. With prefix ARG, change by that many units."
  16232. (interactive "p")
  16233. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16234. (defun org-timestamp-down (&optional arg)
  16235. "Decrease the date item at the cursor by one.
  16236. If the cursor is on the year, change the year. If it is on the month,
  16237. the day or the time, change that.
  16238. With prefix ARG, change by that many units."
  16239. (interactive "p")
  16240. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16241. (defun org-timestamp-up-day (&optional arg)
  16242. "Increase the date in the time stamp by one day.
  16243. With prefix ARG, change that many days."
  16244. (interactive "p")
  16245. (if (and (not (org-at-timestamp-p 'lax))
  16246. (org-at-heading-p))
  16247. (org-todo 'up)
  16248. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16249. (defun org-timestamp-down-day (&optional arg)
  16250. "Decrease the date in the time stamp by one day.
  16251. With prefix ARG, change that many days."
  16252. (interactive "p")
  16253. (if (and (not (org-at-timestamp-p 'lax))
  16254. (org-at-heading-p))
  16255. (org-todo 'down)
  16256. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16257. (defun org-at-timestamp-p (&optional extended)
  16258. "Non-nil if point is inside a timestamp.
  16259. By default, the function only consider syntactically valid active
  16260. timestamps. However, the caller may have a broader definition
  16261. for timestamps. As a consequence, optional argument EXTENDED can
  16262. be set to the following values
  16263. `inactive'
  16264. Include also syntactically valid inactive timestamps.
  16265. `agenda'
  16266. Include timestamps allowed in Agenda, i.e., those in
  16267. properties drawers, planning lines and clock lines.
  16268. `lax'
  16269. Ignore context. The function matches any part of the
  16270. document looking like a timestamp. This includes comments,
  16271. example blocks...
  16272. For backward-compatibility with Org 9.0, every other non-nil
  16273. value is equivalent to `inactive'.
  16274. When at a timestamp, return the position of the point as a symbol
  16275. among `bracket', `after', `year', `month', `hour', `minute',
  16276. `day' or a number of character from the last know part of the
  16277. time stamp.
  16278. When matching, the match groups are the following:
  16279. group 1: year
  16280. group 2: month
  16281. group 3: day number
  16282. group 4: day name
  16283. group 5: hours, if any
  16284. group 6: minutes, if any"
  16285. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16286. (pos (point))
  16287. (match?
  16288. (let ((boundaries (org-in-regexp regexp)))
  16289. (save-match-data
  16290. (cond ((null boundaries) nil)
  16291. ((eq extended 'lax) t)
  16292. (t
  16293. (or (and (eq extended 'agenda)
  16294. (or (org-at-planning-p)
  16295. (org-at-property-p)
  16296. (and (bound-and-true-p
  16297. org-agenda-include-inactive-timestamps)
  16298. (org-at-clock-log-p))))
  16299. (eq 'timestamp
  16300. (save-excursion
  16301. (when (= pos (cdr boundaries)) (forward-char -1))
  16302. (org-element-type (org-element-context)))))))))))
  16303. (cond
  16304. ((not match?) nil)
  16305. ((= pos (match-beginning 0)) 'bracket)
  16306. ;; Distinguish location right before the closing bracket from
  16307. ;; right after it.
  16308. ((= pos (1- (match-end 0))) 'bracket)
  16309. ((= pos (match-end 0)) 'after)
  16310. ((org-pos-in-match-range pos 2) 'year)
  16311. ((org-pos-in-match-range pos 3) 'month)
  16312. ((org-pos-in-match-range pos 7) 'hour)
  16313. ((org-pos-in-match-range pos 8) 'minute)
  16314. ((or (org-pos-in-match-range pos 4)
  16315. (org-pos-in-match-range pos 5)) 'day)
  16316. ((and (> pos (or (match-end 8) (match-end 5)))
  16317. (< pos (match-end 0)))
  16318. (- pos (or (match-end 8) (match-end 5))))
  16319. (t 'day))))
  16320. (defun org-toggle-timestamp-type ()
  16321. "Toggle the type (<active> or [inactive]) of a time stamp."
  16322. (interactive)
  16323. (when (org-at-timestamp-p 'lax)
  16324. (let ((beg (match-beginning 0)) (end (match-end 0))
  16325. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16326. (save-excursion
  16327. (goto-char beg)
  16328. (while (re-search-forward "[][<>]" end t)
  16329. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16330. t t)))
  16331. (message "Timestamp is now %sactive"
  16332. (if (equal (char-after beg) ?<) "" "in")))))
  16333. (defun org-at-clock-log-p ()
  16334. "Non-nil if point is on a clock log line."
  16335. (and (org-match-line org-clock-line-re)
  16336. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16337. (defvar org-clock-history) ; defined in org-clock.el
  16338. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16339. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16340. "Change the date in the time stamp at point.
  16341. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16342. `year', `minute', `second'. If WHAT is not given, the cursor position
  16343. in the timestamp determines what will be changed.
  16344. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16345. (let ((origin (point))
  16346. (timestamp? (org-at-timestamp-p 'lax))
  16347. origin-cat
  16348. with-hm inactive
  16349. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16350. extra rem
  16351. ts time time0 fixnext clrgx)
  16352. (unless timestamp? (user-error "Not at a timestamp"))
  16353. (if (and (not what) (eq timestamp? 'bracket))
  16354. (org-toggle-timestamp-type)
  16355. ;; Point isn't on brackets. Remember the part of the time-stamp
  16356. ;; the point was in. Indeed, size of time-stamps may change,
  16357. ;; but point must be kept in the same category nonetheless.
  16358. (setq origin-cat timestamp?)
  16359. (when (and (not what) (not (eq timestamp? 'day))
  16360. org-display-custom-times
  16361. (get-text-property (point) 'display)
  16362. (not (get-text-property (1- (point)) 'display)))
  16363. (setq timestamp? 'day))
  16364. (setq timestamp? (or what timestamp?)
  16365. inactive (= (char-after (match-beginning 0)) ?\[)
  16366. ts (match-string 0))
  16367. (replace-match "")
  16368. (when (string-match
  16369. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16370. ts)
  16371. (setq extra (match-string 1 ts))
  16372. (when suppress-tmp-delay
  16373. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16374. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16375. (setq with-hm t))
  16376. (setq time0 (org-parse-time-string ts))
  16377. (when (and updown
  16378. (eq timestamp? 'minute)
  16379. (not current-prefix-arg))
  16380. ;; This looks like s-up and s-down. Change by one rounding step.
  16381. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16382. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16383. (setcar (cdr time0) (+ (nth 1 time0)
  16384. (if (> n 0) (- rem) (- dm rem))))))
  16385. (setq time
  16386. (apply #'encode-time
  16387. (or (car time0) 0)
  16388. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16389. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16390. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16391. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16392. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16393. (nthcdr 6 time0)))
  16394. (when (and (memq timestamp? '(hour minute))
  16395. extra
  16396. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16397. (setq extra (org-modify-ts-extra
  16398. extra
  16399. (if (eq timestamp? 'hour) 2 5)
  16400. n dm)))
  16401. (when (integerp timestamp?)
  16402. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16403. (when (eq what 'calendar)
  16404. (let ((cal-date (org-get-date-from-calendar)))
  16405. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16406. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16407. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16408. (setcar time0 (or (car time0) 0))
  16409. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16410. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16411. (setq time (apply 'encode-time time0))))
  16412. ;; Insert the new time-stamp, and ensure point stays in the same
  16413. ;; category as before (i.e. not after the last position in that
  16414. ;; category).
  16415. (let ((pos (point)))
  16416. ;; Stay before inserted string. `save-excursion' is of no use.
  16417. (setq org-last-changed-timestamp
  16418. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16419. (goto-char pos))
  16420. (save-match-data
  16421. (looking-at org-ts-regexp3)
  16422. (goto-char
  16423. (pcase origin-cat
  16424. ;; `day' category ends before `hour' if any, or at the end
  16425. ;; of the day name.
  16426. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16427. (`hour (min (match-end 7) origin))
  16428. (`minute (min (1- (match-end 8)) origin))
  16429. ((pred integerp) (min (1- (match-end 0)) origin))
  16430. ;; Point was right after the time-stamp. However, the
  16431. ;; time-stamp length might have changed, so refer to
  16432. ;; (match-end 0) instead.
  16433. (`after (match-end 0))
  16434. ;; `year' and `month' have both fixed size: point couldn't
  16435. ;; have moved into another part.
  16436. (_ origin))))
  16437. ;; Update clock if on a CLOCK line.
  16438. (org-clock-update-time-maybe)
  16439. ;; Maybe adjust the closest clock in `org-clock-history'
  16440. (when org-clock-adjust-closest
  16441. (if (not (and (org-at-clock-log-p)
  16442. (< 1 (length (delq nil (mapcar 'marker-position
  16443. org-clock-history))))))
  16444. (message "No clock to adjust")
  16445. (cond ((save-excursion ; fix previous clock?
  16446. (re-search-backward org-ts-regexp0 nil t)
  16447. (looking-back (concat org-clock-string " \\[")
  16448. (line-beginning-position)))
  16449. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16450. ((save-excursion ; fix next clock?
  16451. (re-search-backward org-ts-regexp0 nil t)
  16452. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16453. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16454. (save-window-excursion
  16455. ;; Find closest clock to point, adjust the previous/next one in history
  16456. (let* ((p (save-excursion (org-back-to-heading t)))
  16457. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16458. (clfixnth
  16459. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16460. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16461. (if (not clfixpos)
  16462. (message "No clock to adjust")
  16463. (save-excursion
  16464. (org-goto-marker-or-bmk clfixpos)
  16465. (org-show-subtree)
  16466. (when (re-search-forward clrgx nil t)
  16467. (goto-char (match-beginning 1))
  16468. (let (org-clock-adjust-closest)
  16469. (org-timestamp-change n timestamp? updown))
  16470. (message "Clock adjusted in %s for heading: %s"
  16471. (file-name-nondirectory (buffer-file-name))
  16472. (org-get-heading t t)))))))))
  16473. ;; Try to recenter the calendar window, if any.
  16474. (when (and org-calendar-follow-timestamp-change
  16475. (get-buffer-window "*Calendar*" t)
  16476. (memq timestamp? '(day month year)))
  16477. (org-recenter-calendar (time-to-days time))))))
  16478. (defun org-modify-ts-extra (s pos n dm)
  16479. "Change the different parts of the lead-time and repeat fields in timestamp."
  16480. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16481. ng h m new rem)
  16482. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16483. (cond
  16484. ((or (org-pos-in-match-range pos 2)
  16485. (org-pos-in-match-range pos 3))
  16486. (setq m (string-to-number (match-string 3 s))
  16487. h (string-to-number (match-string 2 s)))
  16488. (if (org-pos-in-match-range pos 2)
  16489. (setq h (+ h n))
  16490. (setq n (* dm (with-no-warnings (signum n))))
  16491. (unless (= 0 (setq rem (% m dm)))
  16492. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16493. (setq m (+ m n)))
  16494. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16495. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16496. (setq h (mod h 24))
  16497. (setq ng 1 new (format "-%02d:%02d" h m)))
  16498. ((org-pos-in-match-range pos 6)
  16499. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16500. ((org-pos-in-match-range pos 5)
  16501. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16502. ((org-pos-in-match-range pos 9)
  16503. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16504. ((org-pos-in-match-range pos 8)
  16505. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16506. (when ng
  16507. (setq s (concat
  16508. (substring s 0 (match-beginning ng))
  16509. new
  16510. (substring s (match-end ng))))))
  16511. s))
  16512. (defun org-recenter-calendar (d)
  16513. "If the calendar is visible, recenter it to date D."
  16514. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16515. (when cwin
  16516. (let ((calendar-move-hook nil))
  16517. (with-selected-window cwin
  16518. (calendar-goto-date
  16519. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16520. (defun org-goto-calendar (&optional arg)
  16521. "Go to the Emacs calendar at the current date.
  16522. If there is a time stamp in the current line, go to that date.
  16523. A prefix ARG can be used to force the current date."
  16524. (interactive "P")
  16525. (let ((calendar-move-hook nil)
  16526. (calendar-view-holidays-initially-flag nil)
  16527. (calendar-view-diary-initially-flag nil)
  16528. diff)
  16529. (when (or (org-at-timestamp-p 'lax)
  16530. (org-match-line (concat ".*" org-ts-regexp)))
  16531. (let ((d1 (time-to-days (current-time)))
  16532. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16533. (setq diff (- d2 d1))))
  16534. (calendar)
  16535. (calendar-goto-today)
  16536. (when (and diff (not arg)) (calendar-forward-day diff))))
  16537. (defun org-get-date-from-calendar ()
  16538. "Return a list (month day year) of date at point in calendar."
  16539. (with-current-buffer "*Calendar*"
  16540. (save-match-data
  16541. (calendar-cursor-to-date))))
  16542. (defun org-date-from-calendar ()
  16543. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16544. If there is already a time stamp at the cursor position, update it."
  16545. (interactive)
  16546. (if (org-at-timestamp-p 'lax)
  16547. (org-timestamp-change 0 'calendar)
  16548. (let ((cal-date (org-get-date-from-calendar)))
  16549. (org-insert-time-stamp
  16550. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16551. (defcustom org-effort-durations
  16552. `(("min" . 1)
  16553. ("h" . 60)
  16554. ("d" . ,(* 60 8))
  16555. ("w" . ,(* 60 8 5))
  16556. ("m" . ,(* 60 8 5 4))
  16557. ("y" . ,(* 60 8 5 40)))
  16558. "Conversion factor to minutes for an effort modifier.
  16559. Each entry has the form (MODIFIER . MINUTES).
  16560. In an effort string, a number followed by MODIFIER is multiplied
  16561. by the specified number of MINUTES to obtain an effort in
  16562. minutes.
  16563. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16564. effort string \"2hours\" is equivalent to 120 minutes."
  16565. :group 'org-agenda
  16566. :version "26.1"
  16567. :package-version '(Org . "8.3")
  16568. :type '(alist :key-type (string :tag "Modifier")
  16569. :value-type (number :tag "Minutes")))
  16570. (defcustom org-image-actual-width t
  16571. "Should we use the actual width of images when inlining them?
  16572. When set to t, always use the image width.
  16573. When set to a number, use imagemagick (when available) to set
  16574. the image's width to this value.
  16575. When set to a number in a list, try to get the width from any
  16576. #+ATTR.* keyword if it matches a width specification like
  16577. #+ATTR_HTML: :width 300px
  16578. and fall back on that number if none is found.
  16579. When set to nil, try to get the width from an #+ATTR.* keyword
  16580. and fall back on the original width if none is found.
  16581. This requires Emacs >= 24.1, build with imagemagick support."
  16582. :group 'org-appearance
  16583. :version "24.4"
  16584. :package-version '(Org . "8.0")
  16585. :type '(choice
  16586. (const :tag "Use the image width" t)
  16587. (integer :tag "Use a number of pixels")
  16588. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16589. (const :tag "Use #+ATTR* or don't resize" nil)))
  16590. (defcustom org-agenda-inhibit-startup nil
  16591. "Inhibit startup when preparing agenda buffers.
  16592. When this variable is t, the initialization of the Org agenda
  16593. buffers is inhibited: e.g. the visibility state is not set, the
  16594. tables are not re-aligned, etc."
  16595. :type 'boolean
  16596. :version "24.3"
  16597. :group 'org-agenda)
  16598. (defcustom org-agenda-ignore-properties nil
  16599. "Avoid updating text properties when building the agenda.
  16600. Properties are used to prepare buffers for effort estimates,
  16601. appointments, statistics and subtree-local categories.
  16602. If you don't use these in the agenda, you can add them to this
  16603. list and agenda building will be a bit faster.
  16604. The value is a list, with zero or more of the symbols `effort', `appt',
  16605. `stats' or `category'."
  16606. :type '(set :greedy t
  16607. (const effort)
  16608. (const appt)
  16609. (const stats)
  16610. (const category))
  16611. :version "26.1"
  16612. :package-version '(Org . "8.3")
  16613. :group 'org-agenda)
  16614. ;;;; Files
  16615. (defun org-save-all-org-buffers ()
  16616. "Save all Org buffers without user confirmation."
  16617. (interactive)
  16618. (message "Saving all Org buffers...")
  16619. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16620. (when (featurep 'org-id) (org-id-locations-save))
  16621. (message "Saving all Org buffers... done"))
  16622. (defun org-revert-all-org-buffers ()
  16623. "Revert all Org buffers.
  16624. Prompt for confirmation when there are unsaved changes.
  16625. Be sure you know what you are doing before letting this function
  16626. overwrite your changes.
  16627. This function is useful in a setup where one tracks org files
  16628. with a version control system, to revert on one machine after pulling
  16629. changes from another. I believe the procedure must be like this:
  16630. 1. M-x org-save-all-org-buffers
  16631. 2. Pull changes from the other machine, resolve conflicts
  16632. 3. M-x org-revert-all-org-buffers"
  16633. (interactive)
  16634. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16635. (user-error "Abort"))
  16636. (save-excursion
  16637. (save-window-excursion
  16638. (dolist (b (buffer-list))
  16639. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16640. (with-current-buffer b buffer-file-name))
  16641. (pop-to-buffer-same-window b)
  16642. (revert-buffer t 'no-confirm)))
  16643. (when (and (featurep 'org-id) org-id-track-globally)
  16644. (org-id-locations-load)))))
  16645. ;;;; Agenda files
  16646. ;;;###autoload
  16647. (defun org-switchb (&optional arg)
  16648. "Switch between Org buffers.
  16649. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16650. With `\\[universal-argument] \\[universal-argument]' \
  16651. prefix, restrict available buffers to agenda files."
  16652. (interactive "P")
  16653. (let ((blist (org-buffer-list
  16654. (cond ((equal arg '(4)) 'files)
  16655. ((equal arg '(16)) 'agenda)))))
  16656. (pop-to-buffer-same-window
  16657. (completing-read "Org buffer: "
  16658. (mapcar #'list (mapcar #'buffer-name blist))
  16659. nil t))))
  16660. (defun org-buffer-list (&optional predicate exclude-tmp)
  16661. "Return a list of Org buffers.
  16662. PREDICATE can be `export', `files' or `agenda'.
  16663. export restrict the list to Export buffers.
  16664. files restrict the list to buffers visiting Org files.
  16665. agenda restrict the list to buffers visiting agenda files.
  16666. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16667. (let* ((bfn nil)
  16668. (agenda-files (and (eq predicate 'agenda)
  16669. (mapcar 'file-truename (org-agenda-files t))))
  16670. (filter
  16671. (cond
  16672. ((eq predicate 'files)
  16673. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16674. ((eq predicate 'export)
  16675. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16676. ((eq predicate 'agenda)
  16677. (lambda (b)
  16678. (with-current-buffer b
  16679. (and (derived-mode-p 'org-mode)
  16680. (setq bfn (buffer-file-name b))
  16681. (member (file-truename bfn) agenda-files)))))
  16682. (t (lambda (b) (with-current-buffer b
  16683. (or (derived-mode-p 'org-mode)
  16684. (string-match "\\*Org .*Export"
  16685. (buffer-name b)))))))))
  16686. (delq nil
  16687. (mapcar
  16688. (lambda(b)
  16689. (if (and (funcall filter b)
  16690. (or (not exclude-tmp)
  16691. (not (string-match "tmp" (buffer-name b)))))
  16692. b
  16693. nil))
  16694. (buffer-list)))))
  16695. (defun org-agenda-files (&optional unrestricted archives)
  16696. "Get the list of agenda files.
  16697. Optional UNRESTRICTED means return the full list even if a restriction
  16698. is currently in place.
  16699. When ARCHIVES is t, include all archive files that are really being
  16700. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16701. `org-agenda-archives-mode' is t."
  16702. (let ((files
  16703. (cond
  16704. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16705. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16706. ((listp org-agenda-files) org-agenda-files)
  16707. (t (error "Invalid value of `org-agenda-files'")))))
  16708. (setq files (apply 'append
  16709. (mapcar (lambda (f)
  16710. (if (file-directory-p f)
  16711. (directory-files
  16712. f t org-agenda-file-regexp)
  16713. (list f)))
  16714. files)))
  16715. (when org-agenda-skip-unavailable-files
  16716. (setq files (delq nil
  16717. (mapcar (function
  16718. (lambda (file)
  16719. (and (file-readable-p file) file)))
  16720. files))))
  16721. (when (or (eq archives t)
  16722. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16723. (setq files (org-add-archive-files files)))
  16724. files))
  16725. (defun org-agenda-file-p (&optional file)
  16726. "Return non-nil, if FILE is an agenda file.
  16727. If FILE is omitted, use the file associated with the current
  16728. buffer."
  16729. (let ((fname (or file (buffer-file-name))))
  16730. (and fname
  16731. (member (file-truename fname)
  16732. (mapcar #'file-truename (org-agenda-files t))))))
  16733. (defun org-edit-agenda-file-list ()
  16734. "Edit the list of agenda files.
  16735. Depending on setup, this either uses customize to edit the variable
  16736. `org-agenda-files', or it visits the file that is holding the list. In the
  16737. latter case, the buffer is set up in a way that saving it automatically kills
  16738. the buffer and restores the previous window configuration."
  16739. (interactive)
  16740. (if (stringp org-agenda-files)
  16741. (let ((cw (current-window-configuration)))
  16742. (find-file org-agenda-files)
  16743. (setq-local org-window-configuration cw)
  16744. (add-hook 'after-save-hook
  16745. (lambda ()
  16746. (set-window-configuration
  16747. (prog1 org-window-configuration
  16748. (kill-buffer (current-buffer))))
  16749. (org-install-agenda-files-menu)
  16750. (message "New agenda file list installed"))
  16751. nil 'local)
  16752. (message "%s" (substitute-command-keys
  16753. "Edit list and finish with \\[save-buffer]")))
  16754. (customize-variable 'org-agenda-files)))
  16755. (defun org-store-new-agenda-file-list (list)
  16756. "Set new value for the agenda file list and save it correctly."
  16757. (if (stringp org-agenda-files)
  16758. (let ((fe (org-read-agenda-file-list t)) b u)
  16759. (while (setq b (find-buffer-visiting org-agenda-files))
  16760. (kill-buffer b))
  16761. (with-temp-file org-agenda-files
  16762. (insert
  16763. (mapconcat
  16764. (lambda (f) ;; Keep un-expanded entries.
  16765. (if (setq u (assoc f fe))
  16766. (cdr u)
  16767. f))
  16768. list "\n")
  16769. "\n")))
  16770. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16771. (org-insert-mode-line-in-empty-file nil))
  16772. (setq org-agenda-files list)
  16773. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16774. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16775. "Read the list of agenda files from a file.
  16776. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16777. filenames, used by `org-store-new-agenda-file-list' to write back
  16778. un-expanded file names."
  16779. (when (file-directory-p org-agenda-files)
  16780. (error "`org-agenda-files' cannot be a single directory"))
  16781. (when (stringp org-agenda-files)
  16782. (with-temp-buffer
  16783. (insert-file-contents org-agenda-files)
  16784. (mapcar
  16785. (lambda (f)
  16786. (let ((e (expand-file-name (substitute-in-file-name f)
  16787. org-directory)))
  16788. (if pair-with-expansion
  16789. (cons e f)
  16790. e)))
  16791. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16792. ;;;###autoload
  16793. (defun org-cycle-agenda-files ()
  16794. "Cycle through the files in `org-agenda-files'.
  16795. If the current buffer visits an agenda file, find the next one in the list.
  16796. If the current buffer does not, find the first agenda file."
  16797. (interactive)
  16798. (let* ((fs (or (org-agenda-files t)
  16799. (user-error "No agenda files")))
  16800. (files (copy-sequence fs))
  16801. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16802. file)
  16803. (when tcf
  16804. (while (and (setq file (pop files))
  16805. (not (equal (file-truename file) tcf)))))
  16806. (find-file (car (or files fs)))
  16807. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16808. (defun org-agenda-file-to-front (&optional to-end)
  16809. "Move/add the current file to the top of the agenda file list.
  16810. If the file is not present in the list, it is added to the front. If it is
  16811. present, it is moved there. With optional argument TO-END, add/move to the
  16812. end of the list."
  16813. (interactive "P")
  16814. (let ((org-agenda-skip-unavailable-files nil)
  16815. (file-alist (mapcar (lambda (x)
  16816. (cons (file-truename x) x))
  16817. (org-agenda-files t)))
  16818. (ctf (file-truename
  16819. (or buffer-file-name
  16820. (user-error "Please save the current buffer to a file"))))
  16821. x had)
  16822. (setq x (assoc ctf file-alist) had x)
  16823. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16824. (if to-end
  16825. (setq file-alist (append (delq x file-alist) (list x)))
  16826. (setq file-alist (cons x (delq x file-alist))))
  16827. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16828. (org-install-agenda-files-menu)
  16829. (message "File %s to %s of agenda file list"
  16830. (if had "moved" "added") (if to-end "end" "front"))))
  16831. (defun org-remove-file (&optional file)
  16832. "Remove current file from the list of files in variable `org-agenda-files'.
  16833. These are the files which are being checked for agenda entries.
  16834. Optional argument FILE means use this file instead of the current."
  16835. (interactive)
  16836. (let* ((org-agenda-skip-unavailable-files nil)
  16837. (file (or file buffer-file-name
  16838. (user-error "Current buffer does not visit a file")))
  16839. (true-file (file-truename file))
  16840. (afile (abbreviate-file-name file))
  16841. (files (delq nil (mapcar
  16842. (lambda (x)
  16843. (unless (equal true-file
  16844. (file-truename x))
  16845. x))
  16846. (org-agenda-files t)))))
  16847. (if (not (= (length files) (length (org-agenda-files t))))
  16848. (progn
  16849. (org-store-new-agenda-file-list files)
  16850. (org-install-agenda-files-menu)
  16851. (message "Removed from Org Agenda list: %s" afile))
  16852. (message "File was not in list: %s (not removed)" afile))))
  16853. (defun org-file-menu-entry (file)
  16854. (vector file (list 'find-file file) t))
  16855. (defun org-check-agenda-file (file)
  16856. "Make sure FILE exists. If not, ask user what to do."
  16857. (unless (file-exists-p file)
  16858. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16859. (abbreviate-file-name file))
  16860. (let ((r (downcase (read-char-exclusive))))
  16861. (cond
  16862. ((equal r ?r)
  16863. (org-remove-file file)
  16864. (throw 'nextfile t))
  16865. (t (user-error "Abort"))))))
  16866. (defun org-get-agenda-file-buffer (file)
  16867. "Get an agenda buffer visiting FILE.
  16868. If the buffer needs to be created, add it to the list of buffers
  16869. which might be released later."
  16870. (let ((buf (org-find-base-buffer-visiting file)))
  16871. (if buf
  16872. buf ; just return it
  16873. ;; Make a new buffer and remember it
  16874. (setq buf (find-file-noselect file))
  16875. (when buf (push buf org-agenda-new-buffers))
  16876. buf)))
  16877. (defun org-release-buffers (blist)
  16878. "Release all buffers in list, asking the user for confirmation when needed.
  16879. When a buffer is unmodified, it is just killed. When modified, it is saved
  16880. \(if the user agrees) and then killed."
  16881. (let (file)
  16882. (dolist (buf blist)
  16883. (setq file (buffer-file-name buf))
  16884. (when (and (buffer-modified-p buf)
  16885. file
  16886. (y-or-n-p (format "Save file %s? " file)))
  16887. (with-current-buffer buf (save-buffer)))
  16888. (kill-buffer buf))))
  16889. (defun org-agenda-prepare-buffers (files)
  16890. "Create buffers for all agenda files, protect archived trees and comments."
  16891. (interactive)
  16892. (let ((pa '(:org-archived t))
  16893. (pc '(:org-comment t))
  16894. (pall '(:org-archived t :org-comment t))
  16895. (inhibit-read-only t)
  16896. (org-inhibit-startup org-agenda-inhibit-startup)
  16897. (rea (concat ":" org-archive-tag ":"))
  16898. re pos)
  16899. (setq org-tag-alist-for-agenda nil
  16900. org-tag-groups-alist-for-agenda nil)
  16901. (save-excursion
  16902. (save-restriction
  16903. (dolist (file files)
  16904. (catch 'nextfile
  16905. (if (bufferp file)
  16906. (set-buffer file)
  16907. (org-check-agenda-file file)
  16908. (set-buffer (org-get-agenda-file-buffer file)))
  16909. (widen)
  16910. (org-set-regexps-and-options 'tags-only)
  16911. (setq pos (point))
  16912. (or (memq 'category org-agenda-ignore-properties)
  16913. (org-refresh-category-properties))
  16914. (or (memq 'stats org-agenda-ignore-properties)
  16915. (org-refresh-stats-properties))
  16916. (or (memq 'effort org-agenda-ignore-properties)
  16917. (org-refresh-effort-properties))
  16918. (or (memq 'appt org-agenda-ignore-properties)
  16919. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16920. (setq org-todo-keywords-for-agenda
  16921. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16922. (setq org-done-keywords-for-agenda
  16923. (append org-done-keywords-for-agenda org-done-keywords))
  16924. (setq org-todo-keyword-alist-for-agenda
  16925. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16926. (setq org-tag-alist-for-agenda
  16927. (org-uniquify
  16928. (append org-tag-alist-for-agenda
  16929. org-current-tag-alist)))
  16930. ;; Merge current file's tag groups into global
  16931. ;; `org-tag-groups-alist-for-agenda'.
  16932. (when org-group-tags
  16933. (dolist (alist org-tag-groups-alist)
  16934. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16935. (if old
  16936. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16937. (push alist org-tag-groups-alist-for-agenda)))))
  16938. (org-with-silent-modifications
  16939. (save-excursion
  16940. (remove-text-properties (point-min) (point-max) pall)
  16941. (when org-agenda-skip-archived-trees
  16942. (goto-char (point-min))
  16943. (while (re-search-forward rea nil t)
  16944. (when (org-at-heading-p t)
  16945. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16946. (goto-char (point-min))
  16947. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16948. (while (re-search-forward re nil t)
  16949. (when (save-match-data (org-in-commented-heading-p t))
  16950. (add-text-properties
  16951. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16952. (goto-char pos)))))
  16953. (setq org-todo-keywords-for-agenda
  16954. (org-uniquify org-todo-keywords-for-agenda))
  16955. (setq org-todo-keyword-alist-for-agenda
  16956. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16957. ;;;; CDLaTeX minor mode
  16958. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16959. "Keymap for the minor `org-cdlatex-mode'.")
  16960. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16961. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16962. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16963. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16964. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16965. (defvar org-cdlatex-texmathp-advice-is-done nil
  16966. "Flag remembering if we have applied the advice to texmathp already.")
  16967. (define-minor-mode org-cdlatex-mode
  16968. "Toggle the minor `org-cdlatex-mode'.
  16969. This mode supports entering LaTeX environment and math in LaTeX fragments
  16970. in Org mode.
  16971. \\{org-cdlatex-mode-map}"
  16972. nil " OCDL" nil
  16973. (when org-cdlatex-mode
  16974. (require 'cdlatex)
  16975. (run-hooks 'cdlatex-mode-hook)
  16976. (cdlatex-compute-tables))
  16977. (unless org-cdlatex-texmathp-advice-is-done
  16978. (setq org-cdlatex-texmathp-advice-is-done t)
  16979. (defadvice texmathp (around org-math-always-on activate)
  16980. "Always return t in Org buffers.
  16981. This is because we want to insert math symbols without dollars even outside
  16982. the LaTeX math segments. If Org mode thinks that point is actually inside
  16983. an embedded LaTeX fragment, let `texmathp' do its job.
  16984. `\\[org-cdlatex-mode-map]'"
  16985. (interactive)
  16986. (let (p)
  16987. (cond
  16988. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16989. ((eq this-command 'cdlatex-math-symbol)
  16990. (setq ad-return-value t
  16991. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16992. (t
  16993. (let ((p (org-inside-LaTeX-fragment-p)))
  16994. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16995. (setq ad-return-value t
  16996. texmathp-why '("Org mode embedded math" . 0))
  16997. (when p ad-do-it)))))))))
  16998. (defun turn-on-org-cdlatex ()
  16999. "Unconditionally turn on `org-cdlatex-mode'."
  17000. (org-cdlatex-mode 1))
  17001. (defun org-try-cdlatex-tab ()
  17002. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17003. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17004. - inside a LaTeX fragment, or
  17005. - after the first word in a line, where an abbreviation expansion could
  17006. insert a LaTeX environment."
  17007. (when org-cdlatex-mode
  17008. (cond
  17009. ;; Before any word on the line: No expansion possible.
  17010. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17011. ;; Just after first word on the line: Expand it. Make sure it
  17012. ;; cannot happen on headlines, though.
  17013. ((save-excursion
  17014. (skip-chars-backward "a-zA-Z0-9*")
  17015. (skip-chars-backward " \t")
  17016. (and (bolp) (not (org-at-heading-p))))
  17017. (cdlatex-tab) t)
  17018. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17019. (defun org-cdlatex-underscore-caret (&optional _arg)
  17020. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17021. Revert to the normal definition outside of these fragments."
  17022. (interactive "P")
  17023. (if (org-inside-LaTeX-fragment-p)
  17024. (call-interactively 'cdlatex-sub-superscript)
  17025. (let (org-cdlatex-mode)
  17026. (call-interactively (key-binding (vector last-input-event))))))
  17027. (defun org-cdlatex-math-modify (&optional _arg)
  17028. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17029. Revert to the normal definition outside of these fragments."
  17030. (interactive "P")
  17031. (if (org-inside-LaTeX-fragment-p)
  17032. (call-interactively 'cdlatex-math-modify)
  17033. (let (org-cdlatex-mode)
  17034. (call-interactively (key-binding (vector last-input-event))))))
  17035. (defun org-cdlatex-environment-indent (&optional environment item)
  17036. "Execute `cdlatex-environment' and indent the inserted environment.
  17037. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17038. The inserted environment is indented to current indentation
  17039. unless point is at the beginning of the line, in which the
  17040. environment remains unintended."
  17041. (interactive)
  17042. ;; cdlatex-environment always return nil. Therefore, capture output
  17043. ;; first and determine if an environment was selected.
  17044. (let* ((beg (point-marker))
  17045. (end (copy-marker (point) t))
  17046. (inserted (progn
  17047. (ignore-errors (cdlatex-environment environment item))
  17048. (< beg end)))
  17049. ;; Figure out how many lines to move forward after the
  17050. ;; environment has been inserted.
  17051. (lines (when inserted
  17052. (save-excursion
  17053. (- (cl-loop while (< beg (point))
  17054. with x = 0
  17055. do (forward-line -1)
  17056. (cl-incf x)
  17057. finally return x)
  17058. (if (progn (goto-char beg)
  17059. (and (progn (skip-chars-forward " \t") (eolp))
  17060. (progn (skip-chars-backward " \t") (bolp))))
  17061. 1 0)))))
  17062. (env (org-trim (delete-and-extract-region beg end))))
  17063. (when inserted
  17064. ;; Get indentation of next line unless at column 0.
  17065. (let ((ind (if (bolp) 0
  17066. (save-excursion
  17067. (org-return-indent)
  17068. (prog1 (org-get-indentation)
  17069. (when (progn (skip-chars-forward " \t") (eolp))
  17070. (delete-region beg (point)))))))
  17071. (bol (progn (skip-chars-backward " \t") (bolp))))
  17072. ;; Insert a newline before environment unless at column zero
  17073. ;; to "escape" the current line. Insert a newline if
  17074. ;; something is one the same line as \end{ENVIRONMENT}.
  17075. (insert
  17076. (concat (unless bol "\n") env
  17077. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17078. (unless (zerop ind)
  17079. (save-excursion
  17080. (goto-char beg)
  17081. (while (< (point) end)
  17082. (unless (eolp) (indent-line-to ind))
  17083. (forward-line))))
  17084. (goto-char beg)
  17085. (forward-line lines)
  17086. (indent-line-to ind)))
  17087. (set-marker beg nil)
  17088. (set-marker end nil)))
  17089. ;;;; LaTeX fragments
  17090. (defun org-inside-LaTeX-fragment-p ()
  17091. "Test if point is inside a LaTeX fragment.
  17092. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17093. sequence appearing also before point.
  17094. Even though the matchers for math are configurable, this function assumes
  17095. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17096. delimiters are skipped when they have been removed by customization.
  17097. The return value is nil, or a cons cell with the delimiter and the
  17098. position of this delimiter.
  17099. This function does a reasonably good job, but can locally be fooled by
  17100. for example currency specifications. For example it will assume being in
  17101. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17102. fragments that are properly closed, but during editing, we have to live
  17103. with the uncertainty caused by missing closing delimiters. This function
  17104. looks only before point, not after."
  17105. (catch 'exit
  17106. (let ((pos (point))
  17107. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17108. (lim (save-excursion (org-backward-paragraph) (point)))
  17109. dd-on str (start 0) m re)
  17110. (goto-char pos)
  17111. (when dodollar
  17112. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17113. re (nth 1 (assoc "$" org-latex-regexps)))
  17114. (while (string-match re str start)
  17115. (cond
  17116. ((= (match-end 0) (length str))
  17117. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17118. ((= (match-end 0) (- (length str) 5))
  17119. (throw 'exit nil))
  17120. (t (setq start (match-end 0))))))
  17121. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17122. (goto-char pos)
  17123. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17124. (and (match-beginning 2) (throw 'exit nil))
  17125. ;; count $$
  17126. (while (re-search-backward "\\$\\$" lim t)
  17127. (setq dd-on (not dd-on)))
  17128. (goto-char pos)
  17129. (when dd-on (cons "$$" m))))))
  17130. (defun org-inside-latex-macro-p ()
  17131. "Is point inside a LaTeX macro or its arguments?"
  17132. (save-match-data
  17133. (org-in-regexp
  17134. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17135. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17136. "Build an overlay between BEG and END using IMAGE file.
  17137. Argument IMAGETYPE is the extension of the displayed image,
  17138. as a string. It defaults to \"png\"."
  17139. (let ((ov (make-overlay beg end))
  17140. (imagetype (or (intern imagetype) 'png)))
  17141. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17142. (overlay-put ov 'evaporate t)
  17143. (overlay-put ov
  17144. 'modification-hooks
  17145. (list (lambda (o _flag _beg _end &optional _l)
  17146. (delete-overlay o))))
  17147. (overlay-put ov
  17148. 'display
  17149. (list 'image :type imagetype :file image :ascent 'center))))
  17150. (defun org--list-latex-overlays (&optional beg end)
  17151. "List all Org LaTeX overlays in current buffer.
  17152. Limit to overlays between BEG and END when those are provided."
  17153. (cl-remove-if-not
  17154. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17155. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17156. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17157. "Remove all overlays with LaTeX fragment images in current buffer.
  17158. When optional arguments BEG and END are non-nil, remove all
  17159. overlays between them instead. Return a non-nil value when some
  17160. overlays were removed, nil otherwise."
  17161. (let ((overlays (org--list-latex-overlays beg end)))
  17162. (mapc #'delete-overlay overlays)
  17163. overlays))
  17164. (defun org-toggle-latex-fragment (&optional arg)
  17165. "Preview the LaTeX fragment at point, or all locally or globally.
  17166. If the cursor is on a LaTeX fragment, create the image and overlay
  17167. it over the source code, if there is none. Remove it otherwise.
  17168. If there is no fragment at point, display all fragments in the
  17169. current section.
  17170. With prefix ARG, preview or clear image for all fragments in the
  17171. current subtree or in the whole buffer when used before the first
  17172. headline. With a prefix ARG `\\[universal-argument] \
  17173. \\[universal-argument]' preview or clear images
  17174. for all fragments in the buffer."
  17175. (interactive "P")
  17176. (when (display-graphic-p)
  17177. (catch 'exit
  17178. (save-excursion
  17179. (let (beg end msg)
  17180. (cond
  17181. ((or (equal arg '(16))
  17182. (and (equal arg '(4))
  17183. (org-with-limited-levels (org-before-first-heading-p))))
  17184. (if (org-remove-latex-fragment-image-overlays)
  17185. (progn (message "LaTeX fragments images removed from buffer")
  17186. (throw 'exit nil))
  17187. (setq msg "Creating images for buffer...")))
  17188. ((equal arg '(4))
  17189. (org-with-limited-levels (org-back-to-heading t))
  17190. (setq beg (point))
  17191. (setq end (progn (org-end-of-subtree t) (point)))
  17192. (if (org-remove-latex-fragment-image-overlays beg end)
  17193. (progn
  17194. (message "LaTeX fragment images removed from subtree")
  17195. (throw 'exit nil))
  17196. (setq msg "Creating images for subtree...")))
  17197. ((let ((datum (org-element-context)))
  17198. (when (memq (org-element-type datum)
  17199. '(latex-environment latex-fragment))
  17200. (setq beg (org-element-property :begin datum))
  17201. (setq end (org-element-property :end datum))
  17202. (if (org-remove-latex-fragment-image-overlays beg end)
  17203. (progn (message "LaTeX fragment image removed")
  17204. (throw 'exit nil))
  17205. (setq msg "Creating image...")))))
  17206. (t
  17207. (org-with-limited-levels
  17208. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17209. (outline-previous-heading)
  17210. (point)))
  17211. (setq end (progn (outline-next-heading) (point)))
  17212. (if (org-remove-latex-fragment-image-overlays beg end)
  17213. (progn
  17214. (message "LaTeX fragment images removed from section")
  17215. (throw 'exit nil))
  17216. (setq msg "Creating images for section...")))))
  17217. (let ((file (buffer-file-name (buffer-base-buffer))))
  17218. (org-format-latex
  17219. (concat org-preview-latex-image-directory "org-ltximg")
  17220. beg end
  17221. ;; Emacs cannot overlay images from remote hosts. Create
  17222. ;; it in `temporary-file-directory' instead.
  17223. (if (or (not file) (file-remote-p file))
  17224. temporary-file-directory
  17225. default-directory)
  17226. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17227. (message (concat msg "done")))))))
  17228. (defun org-format-latex
  17229. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17230. "Replace LaTeX fragments with links to an image.
  17231. The function takes care of creating the replacement image.
  17232. Only consider fragments between BEG and END when those are
  17233. provided.
  17234. When optional argument OVERLAYS is non-nil, display the image on
  17235. top of the fragment instead of replacing it.
  17236. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17237. Some of the options can be changed using the variable
  17238. `org-format-latex-options', which see."
  17239. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17240. (unless (eq processing-type 'verbatim)
  17241. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17242. (cnt 0)
  17243. checkdir-flag)
  17244. (goto-char (or beg (point-min)))
  17245. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17246. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17247. (overlay-recenter (or end (point-max))))
  17248. (while (re-search-forward math-regexp end t)
  17249. (unless (and overlays
  17250. (eq (get-char-property (point) 'org-overlay-type)
  17251. 'org-latex-overlay))
  17252. (let* ((context (org-element-context))
  17253. (type (org-element-type context)))
  17254. (when (memq type '(latex-environment latex-fragment))
  17255. (let ((block-type (eq type 'latex-environment))
  17256. (value (org-element-property :value context))
  17257. (beg (org-element-property :begin context))
  17258. (end (save-excursion
  17259. (goto-char (org-element-property :end context))
  17260. (skip-chars-backward " \r\t\n")
  17261. (point))))
  17262. (cond
  17263. ((eq processing-type 'mathjax)
  17264. ;; Prepare for MathJax processing.
  17265. (if (not (string-match "\\`\\$\\$?" value))
  17266. (goto-char end)
  17267. (delete-region beg end)
  17268. (if (string= (match-string 0 value) "$$")
  17269. (insert "\\[" (substring value 2 -2) "\\]")
  17270. (insert "\\(" (substring value 1 -1) "\\)"))))
  17271. ((assq processing-type org-preview-latex-process-alist)
  17272. ;; Process to an image.
  17273. (cl-incf cnt)
  17274. (goto-char beg)
  17275. (let* ((processing-info
  17276. (cdr (assq processing-type org-preview-latex-process-alist)))
  17277. (face (face-at-point))
  17278. ;; Get the colors from the face at point.
  17279. (fg
  17280. (let ((color (plist-get org-format-latex-options
  17281. :foreground)))
  17282. (if (and forbuffer (eq color 'auto))
  17283. (face-attribute face :foreground nil 'default)
  17284. color)))
  17285. (bg
  17286. (let ((color (plist-get org-format-latex-options
  17287. :background)))
  17288. (if (and forbuffer (eq color 'auto))
  17289. (face-attribute face :background nil 'default)
  17290. color)))
  17291. (hash (sha1 (prin1-to-string
  17292. (list org-format-latex-header
  17293. org-latex-default-packages-alist
  17294. org-latex-packages-alist
  17295. org-format-latex-options
  17296. forbuffer value fg bg))))
  17297. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17298. (absprefix (expand-file-name prefix dir))
  17299. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17300. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17301. (sep (and block-type "\n\n"))
  17302. (link (concat sep "[[file:" linkfile "]]" sep))
  17303. (options
  17304. (org-combine-plists
  17305. org-format-latex-options
  17306. `(:foreground ,fg :background ,bg))))
  17307. (when msg (message msg cnt))
  17308. (unless checkdir-flag ; Ensure the directory exists.
  17309. (setq checkdir-flag t)
  17310. (let ((todir (file-name-directory absprefix)))
  17311. (unless (file-directory-p todir)
  17312. (make-directory todir t))))
  17313. (unless (file-exists-p movefile)
  17314. (org-create-formula-image
  17315. value movefile options forbuffer processing-type))
  17316. (if overlays
  17317. (progn
  17318. (dolist (o (overlays-in beg end))
  17319. (when (eq (overlay-get o 'org-overlay-type)
  17320. 'org-latex-overlay)
  17321. (delete-overlay o)))
  17322. (org--format-latex-make-overlay beg end movefile imagetype)
  17323. (goto-char end))
  17324. (delete-region beg end)
  17325. (insert
  17326. (org-add-props link
  17327. (list 'org-latex-src
  17328. (replace-regexp-in-string "\"" "" value)
  17329. 'org-latex-src-embed-type
  17330. (if block-type 'paragraph 'character)))))))
  17331. ((eq processing-type 'mathml)
  17332. ;; Process to MathML.
  17333. (unless (org-format-latex-mathml-available-p)
  17334. (user-error "LaTeX to MathML converter not configured"))
  17335. (cl-incf cnt)
  17336. (when msg (message msg cnt))
  17337. (goto-char beg)
  17338. (delete-region beg end)
  17339. (insert (org-format-latex-as-mathml
  17340. value block-type prefix dir)))
  17341. (t
  17342. (error "Unknown conversion process %s for LaTeX fragments"
  17343. processing-type)))))))))))
  17344. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17345. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17346. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17347. sucessful, return the portion between \"<math...> </math>\"
  17348. elements otherwise return nil. When MATHML-FILE is specified,
  17349. write the results in to that file. When invoked as an
  17350. interactive command, prompt for LATEX-FRAG, with initial value
  17351. set to the current active region and echo the results for user
  17352. inspection."
  17353. (interactive (list (let ((frag (when (org-region-active-p)
  17354. (buffer-substring-no-properties
  17355. (region-beginning) (region-end)))))
  17356. (read-string "LaTeX Fragment: " frag nil frag))))
  17357. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17358. (let* ((tmp-in-file
  17359. (let ((file (file-relative-name
  17360. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17361. (write-region latex-frag nil file)
  17362. file))
  17363. (tmp-out-file (file-relative-name
  17364. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17365. (cmd (format-spec
  17366. org-latex-to-mathml-convert-command
  17367. `((?j . ,(and org-latex-to-mathml-jar-file
  17368. (shell-quote-argument
  17369. (expand-file-name
  17370. org-latex-to-mathml-jar-file))))
  17371. (?I . ,(shell-quote-argument tmp-in-file))
  17372. (?i . ,latex-frag)
  17373. (?o . ,(shell-quote-argument tmp-out-file)))))
  17374. mathml shell-command-output)
  17375. (when (called-interactively-p 'any)
  17376. (unless (org-format-latex-mathml-available-p)
  17377. (user-error "LaTeX to MathML converter not configured")))
  17378. (message "Running %s" cmd)
  17379. (setq shell-command-output (shell-command-to-string cmd))
  17380. (setq mathml
  17381. (when (file-readable-p tmp-out-file)
  17382. (with-current-buffer (find-file-noselect tmp-out-file t)
  17383. (goto-char (point-min))
  17384. (when (re-search-forward
  17385. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17386. (regexp-quote
  17387. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17388. nil t)
  17389. (prog1 (match-string 0) (kill-buffer))))))
  17390. (cond
  17391. (mathml
  17392. (setq mathml
  17393. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17394. (when mathml-file
  17395. (write-region mathml nil mathml-file))
  17396. (when (called-interactively-p 'any)
  17397. (message mathml)))
  17398. ((message "LaTeX to MathML conversion failed")
  17399. (message shell-command-output)))
  17400. (delete-file tmp-in-file)
  17401. (when (file-exists-p tmp-out-file)
  17402. (delete-file tmp-out-file))
  17403. mathml))
  17404. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17405. prefix &optional dir)
  17406. "Use `org-create-math-formula' but check local cache first."
  17407. (let* ((absprefix (expand-file-name prefix dir))
  17408. (print-length nil) (print-level nil)
  17409. (formula-id (concat
  17410. "formula-"
  17411. (sha1
  17412. (prin1-to-string
  17413. (list latex-frag
  17414. org-latex-to-mathml-convert-command)))))
  17415. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17416. (formula-cache-dir (file-name-directory formula-cache)))
  17417. (unless (file-directory-p formula-cache-dir)
  17418. (make-directory formula-cache-dir t))
  17419. (unless (file-exists-p formula-cache)
  17420. (org-create-math-formula latex-frag formula-cache))
  17421. (if (file-exists-p formula-cache)
  17422. ;; Successful conversion. Return the link to MathML file.
  17423. (org-add-props
  17424. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17425. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17426. 'org-latex-src-embed-type (if latex-frag-type
  17427. 'paragraph 'character)))
  17428. ;; Failed conversion. Return the LaTeX fragment verbatim
  17429. latex-frag)))
  17430. (defun org--get-display-dpi ()
  17431. "Get the DPI of the display.
  17432. The function assumes that the display has the same pixel width in
  17433. the horizontal and vertical directions."
  17434. (if (display-graphic-p)
  17435. (round (/ (display-pixel-height)
  17436. (/ (display-mm-height) 25.4)))
  17437. (error "Attempt to calculate the dpi of a non-graphic display")))
  17438. (defun org-create-formula-image
  17439. (string tofile options buffer &optional processing-type)
  17440. "Create an image from LaTeX source using external processes.
  17441. The LaTeX STRING is saved to a temporary LaTeX file, then
  17442. converted to an image file by process PROCESSING-TYPE defined in
  17443. `org-preview-latex-process-alist'. A nil value defaults to
  17444. `org-preview-latex-default-process'.
  17445. The generated image file is eventually moved to TOFILE.
  17446. The OPTIONS argument controls the size, foreground color and
  17447. background color of the generated image.
  17448. When BUFFER non-nil, this function is used for LaTeX previewing.
  17449. Otherwise, it is used to deal with LaTeX snippets showed in
  17450. a HTML file."
  17451. (let* ((processing-type (or processing-type
  17452. org-preview-latex-default-process))
  17453. (processing-info
  17454. (cdr (assq processing-type org-preview-latex-process-alist)))
  17455. (programs (plist-get processing-info :programs))
  17456. (error-message (or (plist-get processing-info :message) ""))
  17457. (use-xcolor (plist-get processing-info :use-xcolor))
  17458. (image-input-type (plist-get processing-info :image-input-type))
  17459. (image-output-type (plist-get processing-info :image-output-type))
  17460. (post-clean (or (plist-get processing-info :post-clean)
  17461. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17462. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17463. (latex-header
  17464. (or (plist-get processing-info :latex-header)
  17465. (org-latex-make-preamble
  17466. (org-export-get-environment (org-export-get-backend 'latex))
  17467. org-format-latex-header
  17468. 'snippet)))
  17469. (latex-compiler (plist-get processing-info :latex-compiler))
  17470. (image-converter (plist-get processing-info :image-converter))
  17471. (tmpdir temporary-file-directory)
  17472. (texfilebase (make-temp-name
  17473. (expand-file-name "orgtex" tmpdir)))
  17474. (texfile (concat texfilebase ".tex"))
  17475. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17476. '(1.0 . 1.0)))
  17477. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17478. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17479. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17480. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17481. "Black"))
  17482. (bg (or (plist-get options (if buffer :background :html-background))
  17483. "Transparent"))
  17484. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17485. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17486. (dolist (program programs)
  17487. (org-check-external-command program error-message))
  17488. (if use-xcolor
  17489. (progn (if (eq fg 'default)
  17490. (setq fg (org-latex-color :foreground))
  17491. (setq fg (org-latex-color-format fg)))
  17492. (if (eq bg 'default)
  17493. (setq bg (org-latex-color :background))
  17494. (setq bg (org-latex-color-format
  17495. (if (string= bg "Transparent") "white" bg))))
  17496. (with-temp-file texfile
  17497. (insert latex-header)
  17498. (insert "\n\\begin{document}\n"
  17499. "\\definecolor{fg}{rgb}{" fg "}\n"
  17500. "\\definecolor{bg}{rgb}{" bg "}\n"
  17501. "\n\\pagecolor{bg}\n"
  17502. "\n{\\color{fg}\n"
  17503. string
  17504. "\n}\n"
  17505. "\n\\end{document}\n")))
  17506. (if (eq fg 'default)
  17507. (setq fg (org-dvipng-color :foreground))
  17508. (unless (string= fg "Transparent")
  17509. (setq fg (org-dvipng-color-format fg))))
  17510. (if (eq bg 'default)
  17511. (setq bg (org-dvipng-color :background))
  17512. (unless (string= bg "Transparent")
  17513. (setq bg (org-dvipng-color-format bg))))
  17514. (with-temp-file texfile
  17515. (insert latex-header)
  17516. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17517. (let* ((err-msg (format "Please adjust `%s' part of \
  17518. `org-preview-latex-process-alist'."
  17519. processing-type))
  17520. (image-input-file
  17521. (org-compile-file
  17522. texfile latex-compiler image-input-type err-msg log-buf))
  17523. (image-output-file
  17524. (org-compile-file
  17525. image-input-file image-converter image-output-type err-msg log-buf
  17526. `((?F . ,(shell-quote-argument fg))
  17527. (?B . ,(shell-quote-argument bg))
  17528. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17529. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17530. (copy-file image-output-file tofile 'replace)
  17531. (dolist (e post-clean)
  17532. (when (file-exists-p (concat texfilebase e))
  17533. (delete-file (concat texfilebase e))))
  17534. image-output-file)))
  17535. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17536. "Fill a LaTeX header template TPL.
  17537. In the template, the following place holders will be recognized:
  17538. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17539. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17540. [PACKAGES] \\usepackage statements for PKG
  17541. [NO-PACKAGES] do not include PKG
  17542. [EXTRA] the string EXTRA
  17543. [NO-EXTRA] do not include EXTRA
  17544. For backward compatibility, if both the positive and the negative place
  17545. holder is missing, the positive one (without the \"NO-\") will be
  17546. assumed to be present at the end of the template.
  17547. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17548. EXTRA is a string.
  17549. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17550. (let (rpl (end ""))
  17551. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17552. (setq rpl (if (or (match-end 1) (not def-pkg))
  17553. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17554. tpl (replace-match rpl t t tpl))
  17555. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17556. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17557. (setq rpl (if (or (match-end 1) (not pkg))
  17558. "" (org-latex-packages-to-string pkg snippets-p t))
  17559. tpl (replace-match rpl t t tpl))
  17560. (when pkg (setq end
  17561. (concat end "\n"
  17562. (org-latex-packages-to-string pkg snippets-p)))))
  17563. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17564. (setq rpl (if (or (match-end 1) (not extra))
  17565. "" (concat extra "\n"))
  17566. tpl (replace-match rpl t t tpl))
  17567. (when (and extra (string-match "\\S-" extra))
  17568. (setq end (concat end "\n" extra))))
  17569. (if (string-match "\\S-" end)
  17570. (concat tpl "\n" end)
  17571. tpl)))
  17572. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17573. "Turn an alist of packages into a string with the \\usepackage macros."
  17574. (setq pkg (mapconcat (lambda(p)
  17575. (cond
  17576. ((stringp p) p)
  17577. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17578. (format "%% Package %s omitted" (cadr p)))
  17579. ((equal "" (car p))
  17580. (format "\\usepackage{%s}" (cadr p)))
  17581. (t
  17582. (format "\\usepackage[%s]{%s}"
  17583. (car p) (cadr p)))))
  17584. pkg
  17585. "\n"))
  17586. (if newline (concat pkg "\n") pkg))
  17587. (defun org-dvipng-color (attr)
  17588. "Return a RGB color specification for dvipng."
  17589. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17590. (defun org-dvipng-color-format (color-name)
  17591. "Convert COLOR-NAME to a RGB color value for dvipng."
  17592. (apply #'format "rgb %s %s %s"
  17593. (mapcar 'org-normalize-color
  17594. (color-values color-name))))
  17595. (defun org-latex-color (attr)
  17596. "Return a RGB color for the LaTeX color package."
  17597. (org-latex-color-format (face-attribute 'default attr nil)))
  17598. (defun org-latex-color-format (color-name)
  17599. "Convert COLOR-NAME to a RGB color value."
  17600. (apply #'format "%s,%s,%s"
  17601. (mapcar 'org-normalize-color
  17602. (color-values color-name))))
  17603. (defun org-normalize-color (value)
  17604. "Return string to be used as color value for an RGB component."
  17605. (format "%g" (/ value 65535.0)))
  17606. ;; Image display
  17607. (defvar-local org-inline-image-overlays nil)
  17608. (defun org-toggle-inline-images (&optional include-linked)
  17609. "Toggle the display of inline images.
  17610. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17611. (interactive "P")
  17612. (if org-inline-image-overlays
  17613. (progn
  17614. (org-remove-inline-images)
  17615. (when (called-interactively-p 'interactive)
  17616. (message "Inline image display turned off")))
  17617. (org-display-inline-images include-linked)
  17618. (when (called-interactively-p 'interactive)
  17619. (message (if org-inline-image-overlays
  17620. (format "%d images displayed inline"
  17621. (length org-inline-image-overlays))
  17622. "No images to display inline")))))
  17623. (defun org-redisplay-inline-images ()
  17624. "Refresh the display of inline images."
  17625. (interactive)
  17626. (if (not org-inline-image-overlays)
  17627. (org-toggle-inline-images)
  17628. (org-toggle-inline-images)
  17629. (org-toggle-inline-images)))
  17630. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17631. "Display inline images.
  17632. An inline image is a link which follows either of these
  17633. conventions:
  17634. 1. Its path is a file with an extension matching return value
  17635. from `image-file-name-regexp' and it has no contents.
  17636. 2. Its description consists in a single link of the previous
  17637. type.
  17638. When optional argument INCLUDE-LINKED is non-nil, also links with
  17639. a text description part will be inlined. This can be nice for
  17640. a quick look at those images, but it does not reflect what
  17641. exported files will look like.
  17642. When optional argument REFRESH is non-nil, refresh existing
  17643. images between BEG and END. This will create new image displays
  17644. only if necessary. BEG and END default to the buffer
  17645. boundaries."
  17646. (interactive "P")
  17647. (when (display-graphic-p)
  17648. (unless refresh
  17649. (org-remove-inline-images)
  17650. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17651. (org-with-wide-buffer
  17652. (goto-char (or beg (point-min)))
  17653. (let ((case-fold-search t)
  17654. (file-extension-re (image-file-name-regexp)))
  17655. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17656. (let ((link (save-match-data (org-element-context))))
  17657. ;; Check if we're at an inline image.
  17658. (when (and (equal (org-element-property :type link) "file")
  17659. (or include-linked
  17660. (not (org-element-property :contents-begin link)))
  17661. (let ((parent (org-element-property :parent link)))
  17662. (or (not (eq (org-element-type parent) 'link))
  17663. (not (cdr (org-element-contents parent)))))
  17664. (string-match-p file-extension-re
  17665. (org-element-property :path link)))
  17666. (let ((file (expand-file-name
  17667. (org-link-unescape
  17668. (org-element-property :path link)))))
  17669. (when (file-exists-p file)
  17670. (let ((width
  17671. ;; Apply `org-image-actual-width' specifications.
  17672. (cond
  17673. ((not (image-type-available-p 'imagemagick)) nil)
  17674. ((eq org-image-actual-width t) nil)
  17675. ((listp org-image-actual-width)
  17676. (or
  17677. ;; First try to find a width among
  17678. ;; attributes associated to the paragraph
  17679. ;; containing link.
  17680. (let ((paragraph
  17681. (let ((e link))
  17682. (while (and (setq e (org-element-property
  17683. :parent e))
  17684. (not (eq (org-element-type e)
  17685. 'paragraph))))
  17686. e)))
  17687. (when paragraph
  17688. (save-excursion
  17689. (goto-char (org-element-property :begin paragraph))
  17690. (when
  17691. (re-search-forward
  17692. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17693. (org-element-property
  17694. :post-affiliated paragraph)
  17695. t)
  17696. (string-to-number (match-string 1))))))
  17697. ;; Otherwise, fall-back to provided number.
  17698. (car org-image-actual-width)))
  17699. ((numberp org-image-actual-width)
  17700. org-image-actual-width)))
  17701. (old (get-char-property-and-overlay
  17702. (org-element-property :begin link)
  17703. 'org-image-overlay)))
  17704. (if (and (car-safe old) refresh)
  17705. (image-refresh (overlay-get (cdr old) 'display))
  17706. (let ((image (create-image file
  17707. (and width 'imagemagick)
  17708. nil
  17709. :width width)))
  17710. (when image
  17711. (let* ((link
  17712. ;; If inline image is the description
  17713. ;; of another link, be sure to
  17714. ;; consider the latter as the one to
  17715. ;; apply the overlay on.
  17716. (let ((parent
  17717. (org-element-property :parent link)))
  17718. (if (eq (org-element-type parent) 'link)
  17719. parent
  17720. link)))
  17721. (ov (make-overlay
  17722. (org-element-property :begin link)
  17723. (progn
  17724. (goto-char
  17725. (org-element-property :end link))
  17726. (skip-chars-backward " \t")
  17727. (point)))))
  17728. (overlay-put ov 'display image)
  17729. (overlay-put ov 'face 'default)
  17730. (overlay-put ov 'org-image-overlay t)
  17731. (overlay-put
  17732. ov 'modification-hooks
  17733. (list 'org-display-inline-remove-overlay))
  17734. (push ov org-inline-image-overlays)))))))))))))))
  17735. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17736. "Remove inline-display overlay if a corresponding region is modified."
  17737. (let ((inhibit-modification-hooks t))
  17738. (when (and ov after)
  17739. (delete ov org-inline-image-overlays)
  17740. (delete-overlay ov))))
  17741. (defun org-remove-inline-images ()
  17742. "Remove inline display of images."
  17743. (interactive)
  17744. (mapc #'delete-overlay org-inline-image-overlays)
  17745. (setq org-inline-image-overlays nil))
  17746. ;;;; Key bindings
  17747. ;; Outline functions from `outline-mode-prefix-map'
  17748. ;; that can be remapped in Org:
  17749. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17750. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17751. (define-key org-mode-map [remap outline-forward-same-level]
  17752. 'org-forward-heading-same-level)
  17753. (define-key org-mode-map [remap outline-backward-same-level]
  17754. 'org-backward-heading-same-level)
  17755. (define-key org-mode-map [remap outline-show-branches]
  17756. 'org-kill-note-or-show-branches)
  17757. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17758. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17759. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17760. (define-key org-mode-map [remap outline-next-visible-heading]
  17761. 'org-next-visible-heading)
  17762. (define-key org-mode-map [remap outline-previous-visible-heading]
  17763. 'org-previous-visible-heading)
  17764. (define-key org-mode-map [remap show-children] 'org-show-children)
  17765. ;; Outline functions from `outline-mode-prefix-map' that can not
  17766. ;; be remapped in Org:
  17767. ;; - the column "key binding" shows whether the Outline function is still
  17768. ;; available in Org mode on the same key that it has been bound to in
  17769. ;; Outline mode:
  17770. ;; - "overridden": key used for a different functionality in Org mode
  17771. ;; - else: key still bound to the same Outline function in Org mode
  17772. ;; | Outline function | key binding | Org replacement |
  17773. ;; |------------------------------------+-------------+--------------------------|
  17774. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17775. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17776. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17777. ;; | `show-entry' | overridden | no replacement |
  17778. ;; | `show-branches' | `C-c C-k' | still same function |
  17779. ;; | `show-subtree' | overridden | visibility cycling |
  17780. ;; | `show-all' | overridden | no replacement |
  17781. ;; | `hide-subtree' | overridden | visibility cycling |
  17782. ;; | `hide-body' | overridden | no replacement |
  17783. ;; | `hide-entry' | overridden | visibility cycling |
  17784. ;; | `hide-leaves' | overridden | no replacement |
  17785. ;; | `hide-sublevels' | overridden | no replacement |
  17786. ;; | `hide-other' | overridden | no replacement |
  17787. ;; Make `C-c C-x' a prefix key
  17788. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17789. ;; TAB key with modifiers
  17790. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17791. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17792. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17793. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17794. ;; The following line is necessary under Suse GNU/Linux
  17795. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17796. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17797. (define-key org-mode-map [backtab] 'org-shifttab)
  17798. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17799. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17800. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  17801. ;; Cursor keys with modifiers
  17802. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17803. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17804. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17805. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17806. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17807. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17808. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17809. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17810. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17811. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17812. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17813. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17814. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17815. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17816. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17817. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17818. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17819. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17820. ;; Babel keys
  17821. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17822. (dolist (pair org-babel-key-bindings)
  17823. (define-key org-babel-map (car pair) (cdr pair)))
  17824. ;;; Extra keys for tty access.
  17825. ;; We only set them when really needed because otherwise the
  17826. ;; menus don't show the simple keys
  17827. (when (or org-use-extra-keys (not window-system))
  17828. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17829. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17830. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17831. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17832. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17833. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17834. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17835. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17836. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17837. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17838. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17839. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17840. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17841. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17842. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17843. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17844. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17845. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17846. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17847. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17848. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17849. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17850. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17851. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17852. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17853. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17854. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17855. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17856. ;; All the other keys
  17857. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17858. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17859. (if (boundp 'narrow-map)
  17860. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17861. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17862. (if (boundp 'narrow-map)
  17863. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17864. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17865. (if (boundp 'narrow-map)
  17866. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17867. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17868. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17869. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17870. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17871. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17872. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17873. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17874. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17875. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17876. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17877. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17878. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17879. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17880. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17881. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17882. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17883. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17884. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17885. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17886. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17887. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17888. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17889. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17890. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17891. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17892. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17893. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17894. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17895. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17896. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17897. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17898. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17899. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17900. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17901. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17902. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17903. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17904. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17905. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17906. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17907. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17908. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17909. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17910. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17911. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17912. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17913. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17914. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17915. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17916. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17917. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17918. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17919. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17920. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17921. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17922. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17923. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17924. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17925. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17926. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17927. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17928. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17929. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17930. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17931. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17932. (org-defkey org-mode-map "\C-m" 'org-return)
  17933. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17934. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17935. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17936. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17937. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17938. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17939. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17940. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17941. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17942. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17943. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17944. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17945. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17946. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17947. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17948. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17949. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17950. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17951. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17952. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17953. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17954. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17955. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17956. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17957. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17958. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17959. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17960. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17961. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17962. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17963. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17964. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17965. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17966. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17967. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17968. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17969. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17970. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17971. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17972. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17973. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17974. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17975. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17976. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17977. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17978. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17979. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17980. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17981. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17982. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17983. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17984. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17985. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17986. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17987. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17988. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17989. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17990. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17991. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17992. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17993. (defconst org-speed-commands-default
  17994. '(
  17995. ("Outline Navigation")
  17996. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17997. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17998. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17999. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18000. ("F" . org-next-block)
  18001. ("B" . org-previous-block)
  18002. ("u" . (org-speed-move-safe 'outline-up-heading))
  18003. ("j" . org-goto)
  18004. ("g" . (org-refile t))
  18005. ("Outline Visibility")
  18006. ("c" . org-cycle)
  18007. ("C" . org-shifttab)
  18008. (" " . org-display-outline-path)
  18009. ("s" . org-narrow-to-subtree)
  18010. ("=" . org-columns)
  18011. ("Outline Structure Editing")
  18012. ("U" . org-metaup)
  18013. ("D" . org-metadown)
  18014. ("r" . org-metaright)
  18015. ("l" . org-metaleft)
  18016. ("R" . org-shiftmetaright)
  18017. ("L" . org-shiftmetaleft)
  18018. ("i" . (progn (forward-char 1) (call-interactively
  18019. 'org-insert-heading-respect-content)))
  18020. ("^" . org-sort)
  18021. ("w" . org-refile)
  18022. ("a" . org-archive-subtree-default-with-confirmation)
  18023. ("@" . org-mark-subtree)
  18024. ("#" . org-toggle-comment)
  18025. ("Clock Commands")
  18026. ("I" . org-clock-in)
  18027. ("O" . org-clock-out)
  18028. ("Meta Data Editing")
  18029. ("t" . org-todo)
  18030. ("," . (org-priority))
  18031. ("0" . (org-priority ?\ ))
  18032. ("1" . (org-priority ?A))
  18033. ("2" . (org-priority ?B))
  18034. ("3" . (org-priority ?C))
  18035. (":" . org-set-tags-command)
  18036. ("e" . org-set-effort)
  18037. ("E" . org-inc-effort)
  18038. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18039. (org-entry-put (point) "APPT_WARNTIME" m)))
  18040. ("Agenda Views etc")
  18041. ("v" . org-agenda)
  18042. ("/" . org-sparse-tree)
  18043. ("Misc")
  18044. ("o" . org-open-at-point)
  18045. ("?" . org-speed-command-help)
  18046. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18047. (">" . (org-agenda-remove-restriction-lock))
  18048. )
  18049. "The default speed commands.")
  18050. (defun org-print-speed-command (e)
  18051. (if (> (length (car e)) 1)
  18052. (progn
  18053. (princ "\n")
  18054. (princ (car e))
  18055. (princ "\n")
  18056. (princ (make-string (length (car e)) ?-))
  18057. (princ "\n"))
  18058. (princ (car e))
  18059. (princ " ")
  18060. (if (symbolp (cdr e))
  18061. (princ (symbol-name (cdr e)))
  18062. (prin1 (cdr e)))
  18063. (princ "\n")))
  18064. (defun org-speed-command-help ()
  18065. "Show the available speed commands."
  18066. (interactive)
  18067. (if (not org-use-speed-commands)
  18068. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18069. (with-output-to-temp-buffer "*Help*"
  18070. (princ "User-defined Speed commands\n===========================\n")
  18071. (mapc #'org-print-speed-command org-speed-commands-user)
  18072. (princ "\n")
  18073. (princ "Built-in Speed commands\n=======================\n")
  18074. (mapc #'org-print-speed-command org-speed-commands-default))
  18075. (with-current-buffer "*Help*"
  18076. (setq truncate-lines t))))
  18077. (defun org-speed-move-safe (cmd)
  18078. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18079. If not, return to the original position and throw an error."
  18080. (interactive)
  18081. (let ((pos (point)))
  18082. (call-interactively cmd)
  18083. (unless (and (bolp) (org-at-heading-p))
  18084. (goto-char pos)
  18085. (error "Boundary reached while executing %s" cmd))))
  18086. (defvar org-self-insert-command-undo-counter 0)
  18087. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18088. (defvar org-speed-command nil)
  18089. (defun org-speed-command-activate (keys)
  18090. "Hook for activating single-letter speed commands.
  18091. `org-speed-commands-default' specifies a minimal command set.
  18092. Use `org-speed-commands-user' for further customization."
  18093. (when (or (and (bolp) (looking-at org-outline-regexp))
  18094. (and (functionp org-use-speed-commands)
  18095. (funcall org-use-speed-commands)))
  18096. (cdr (assoc keys (append org-speed-commands-user
  18097. org-speed-commands-default)))))
  18098. (defun org-babel-speed-command-activate (keys)
  18099. "Hook for activating single-letter code block commands."
  18100. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18101. (cdr (assoc keys org-babel-key-bindings))))
  18102. (defcustom org-speed-command-hook
  18103. '(org-speed-command-activate org-babel-speed-command-activate)
  18104. "Hook for activating speed commands at strategic locations.
  18105. Hook functions are called in sequence until a valid handler is
  18106. found.
  18107. Each hook takes a single argument, a user-pressed command key
  18108. which is also a `self-insert-command' from the global map.
  18109. Within the hook, examine the cursor position and the command key
  18110. and return nil or a valid handler as appropriate. Handler could
  18111. be one of an interactive command, a function, or a form.
  18112. Set `org-use-speed-commands' to non-nil value to enable this
  18113. hook. The default setting is `org-speed-command-activate'."
  18114. :group 'org-structure
  18115. :version "24.1"
  18116. :type 'hook)
  18117. (defun org-self-insert-command (N)
  18118. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18119. If the cursor is in a table looking at whitespace, the whitespace is
  18120. overwritten, and the table is not marked as requiring realignment."
  18121. (interactive "p")
  18122. (org-check-before-invisible-edit 'insert)
  18123. (cond
  18124. ((and org-use-speed-commands
  18125. (let ((kv (this-command-keys-vector)))
  18126. (setq org-speed-command
  18127. (run-hook-with-args-until-success
  18128. 'org-speed-command-hook
  18129. (make-string 1 (aref kv (1- (length kv))))))))
  18130. (cond
  18131. ((commandp org-speed-command)
  18132. (setq this-command org-speed-command)
  18133. (call-interactively org-speed-command))
  18134. ((functionp org-speed-command)
  18135. (funcall org-speed-command))
  18136. ((and org-speed-command (listp org-speed-command))
  18137. (eval org-speed-command))
  18138. (t (let (org-use-speed-commands)
  18139. (call-interactively 'org-self-insert-command)))))
  18140. ((and
  18141. (org-at-table-p)
  18142. (progn
  18143. ;; Check if we blank the field, and if that triggers align.
  18144. (and (featurep 'org-table) org-table-auto-blank-field
  18145. (memq last-command
  18146. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18147. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18148. ;; Got extra space, this field does not determine
  18149. ;; column width.
  18150. (let (org-table-may-need-update) (org-table-blank-field))
  18151. ;; No extra space, this field may determine column
  18152. ;; width.
  18153. (org-table-blank-field)))
  18154. t)
  18155. (eq N 1)
  18156. (looking-at "[^|\n]* \\( \\)|"))
  18157. ;; There is room for insertion without re-aligning the table.
  18158. (delete-region (match-beginning 1) (match-end 1))
  18159. (self-insert-command N))
  18160. (t
  18161. (setq org-table-may-need-update t)
  18162. (self-insert-command N)
  18163. (org-fix-tags-on-the-fly)
  18164. (when org-self-insert-cluster-for-undo
  18165. (if (not (eq last-command 'org-self-insert-command))
  18166. (setq org-self-insert-command-undo-counter 1)
  18167. (if (>= org-self-insert-command-undo-counter 20)
  18168. (setq org-self-insert-command-undo-counter 1)
  18169. (and (> org-self-insert-command-undo-counter 0)
  18170. buffer-undo-list (listp buffer-undo-list)
  18171. (not (cadr buffer-undo-list)) ; remove nil entry
  18172. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18173. (setq org-self-insert-command-undo-counter
  18174. (1+ org-self-insert-command-undo-counter))))))))
  18175. (defun org-check-before-invisible-edit (kind)
  18176. "Check is editing if kind KIND would be dangerous with invisible text around.
  18177. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18178. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18179. (when (and org-catch-invisible-edits
  18180. (or (not (boundp 'visible-mode)) (not visible-mode))
  18181. (or (get-char-property (point) 'invisible)
  18182. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18183. ;; OK, we need to take a closer look. Do not consider
  18184. ;; invisibility obtained through text properties (e.g., link
  18185. ;; fontification), as it cannot be toggled.
  18186. (let* ((invisible-at-point
  18187. (pcase (get-char-property-and-overlay (point) 'invisible)
  18188. (`(,_ . ,(and (pred overlayp) o)) o)))
  18189. ;; Assume that point cannot land in the middle of an
  18190. ;; overlay, or between two overlays.
  18191. (invisible-before-point
  18192. (and (not invisible-at-point)
  18193. (not (bobp))
  18194. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18195. (`(,_ . ,(and (pred overlayp) o)) o))))
  18196. (border-and-ok-direction
  18197. (or
  18198. ;; Check if we are acting predictably before invisible
  18199. ;; text.
  18200. (and invisible-at-point
  18201. (memq kind '(insert delete-backward)))
  18202. ;; Check if we are acting predictably after invisible text
  18203. ;; This works not well, and I have turned it off. It seems
  18204. ;; better to always show and stop after invisible text.
  18205. ;; (and (not invisible-at-point) invisible-before-point
  18206. ;; (memq kind '(insert delete)))
  18207. )))
  18208. (when (or invisible-at-point invisible-before-point)
  18209. (when (eq org-catch-invisible-edits 'error)
  18210. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18211. (if (and org-custom-properties-overlays
  18212. (y-or-n-p "Display invisible properties in this buffer? "))
  18213. (org-toggle-custom-properties-visibility)
  18214. ;; Make the area visible
  18215. (save-excursion
  18216. (when invisible-before-point
  18217. (goto-char
  18218. (previous-single-char-property-change (point) 'invisible)))
  18219. ;; Remove whatever overlay is currently making yet-to-be
  18220. ;; edited text invisible. Also remove nested invisibility
  18221. ;; related overlays.
  18222. (delete-overlay (or invisible-at-point invisible-before-point))
  18223. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18224. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18225. (`(,_ . ,(and (pred overlayp) o))
  18226. (delete-overlay o)
  18227. t)))))
  18228. (cond
  18229. ((eq org-catch-invisible-edits 'show)
  18230. ;; That's it, we do the edit after showing
  18231. (message
  18232. "Unfolding invisible region around point before editing")
  18233. (sit-for 1))
  18234. ((and (eq org-catch-invisible-edits 'smart)
  18235. border-and-ok-direction)
  18236. (message "Unfolding invisible region around point before editing"))
  18237. (t
  18238. ;; Don't do the edit, make the user repeat it in full visibility
  18239. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18240. (defun org-fix-tags-on-the-fly ()
  18241. "Align tags in headline at point.
  18242. Unlike to `org-set-tags', it ignores region and sorting."
  18243. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18244. (org-at-heading-p))
  18245. (let ((org-ignore-region t)
  18246. (org-tags-sort-function nil))
  18247. (org-set-tags nil t))))
  18248. (defun org-delete-backward-char (N)
  18249. "Like `delete-backward-char', insert whitespace at field end in tables.
  18250. When deleting backwards, in tables this function will insert whitespace in
  18251. front of the next \"|\" separator, to keep the table aligned. The table will
  18252. still be marked for re-alignment if the field did fill the entire column,
  18253. because, in this case the deletion might narrow the column."
  18254. (interactive "p")
  18255. (save-match-data
  18256. (org-check-before-invisible-edit 'delete-backward)
  18257. (if (and (org-at-table-p)
  18258. (eq N 1)
  18259. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18260. (looking-at ".*?|"))
  18261. (let ((pos (point))
  18262. (noalign (looking-at "[^|\n\r]* |"))
  18263. (c org-table-may-need-update))
  18264. (backward-delete-char N)
  18265. (unless overwrite-mode
  18266. (skip-chars-forward "^|")
  18267. (insert " ")
  18268. (goto-char (1- pos)))
  18269. ;; noalign: if there were two spaces at the end, this field
  18270. ;; does not determine the width of the column.
  18271. (when noalign (setq org-table-may-need-update c)))
  18272. (backward-delete-char N)
  18273. (org-fix-tags-on-the-fly))))
  18274. (defun org-delete-char (N)
  18275. "Like `delete-char', but insert whitespace at field end in tables.
  18276. When deleting characters, in tables this function will insert whitespace in
  18277. front of the next \"|\" separator, to keep the table aligned. The table will
  18278. still be marked for re-alignment if the field did fill the entire column,
  18279. because, in this case the deletion might narrow the column."
  18280. (interactive "p")
  18281. (save-match-data
  18282. (org-check-before-invisible-edit 'delete)
  18283. (if (and (org-at-table-p)
  18284. (not (bolp))
  18285. (not (= (char-after) ?|))
  18286. (eq N 1))
  18287. (if (looking-at ".*?|")
  18288. (let ((pos (point))
  18289. (noalign (looking-at "[^|\n\r]* |"))
  18290. (c org-table-may-need-update))
  18291. (replace-match
  18292. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18293. (goto-char pos)
  18294. ;; noalign: if there were two spaces at the end, this field
  18295. ;; does not determine the width of the column.
  18296. (when noalign (setq org-table-may-need-update c)))
  18297. (delete-char N))
  18298. (delete-char N)
  18299. (org-fix-tags-on-the-fly))))
  18300. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18301. (put 'org-self-insert-command 'delete-selection
  18302. (lambda ()
  18303. (not (run-hook-with-args-until-success
  18304. 'self-insert-uses-region-functions))))
  18305. (put 'orgtbl-self-insert-command 'delete-selection
  18306. (lambda ()
  18307. (not (run-hook-with-args-until-success
  18308. 'self-insert-uses-region-functions))))
  18309. (put 'org-delete-char 'delete-selection 'supersede)
  18310. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18311. (put 'org-yank 'delete-selection 'yank)
  18312. ;; Make `flyspell-mode' delay after some commands
  18313. (put 'org-self-insert-command 'flyspell-delayed t)
  18314. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18315. (put 'org-delete-char 'flyspell-delayed t)
  18316. (put 'org-delete-backward-char 'flyspell-delayed t)
  18317. ;; Make pabbrev-mode expand after Org mode commands
  18318. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18319. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18320. (defun org-remap (map &rest commands)
  18321. "In MAP, remap the functions given in COMMANDS.
  18322. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18323. (let (new old)
  18324. (while commands
  18325. (setq old (pop commands) new (pop commands))
  18326. (org-defkey map (vector 'remap old) new))))
  18327. (defun org-transpose-words ()
  18328. "Transpose words for Org.
  18329. This uses the `org-mode-transpose-word-syntax-table' syntax
  18330. table, which interprets characters in `org-emphasis-alist' as
  18331. word constituents."
  18332. (interactive)
  18333. (with-syntax-table org-mode-transpose-word-syntax-table
  18334. (call-interactively 'transpose-words)))
  18335. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18336. (when (eq org-enable-table-editor 'optimized)
  18337. ;; If the user wants maximum table support, we need to hijack
  18338. ;; some standard editing functions
  18339. (org-remap org-mode-map
  18340. 'self-insert-command 'org-self-insert-command
  18341. 'delete-char 'org-delete-char
  18342. 'delete-backward-char 'org-delete-backward-char)
  18343. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18344. (defvar org-ctrl-c-ctrl-c-hook nil
  18345. "Hook for functions attaching themselves to `C-c C-c'.
  18346. This can be used to add additional functionality to the C-c C-c
  18347. key which executes context-dependent commands. This hook is run
  18348. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18349. run after the last test.
  18350. Each function will be called with no arguments. The function
  18351. must check if the context is appropriate for it to act. If yes,
  18352. it should do its thing and then return a non-nil value. If the
  18353. context is wrong, just do nothing and return nil.")
  18354. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18355. "Hook for functions attaching themselves to `C-c C-c'.
  18356. This can be used to add additional functionality to the C-c C-c
  18357. key which executes context-dependent commands. This hook is run
  18358. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18359. before the first test.
  18360. Each function will be called with no arguments. The function
  18361. must check if the context is appropriate for it to act. If yes,
  18362. it should do its thing and then return a non-nil value. If the
  18363. context is wrong, just do nothing and return nil.")
  18364. (defvar org-tab-first-hook nil
  18365. "Hook for functions to attach themselves to TAB.
  18366. See `org-ctrl-c-ctrl-c-hook' for more information.
  18367. This hook runs as the first action when TAB is pressed, even before
  18368. `org-cycle' messes around with the `outline-regexp' to cater for
  18369. inline tasks and plain list item folding.
  18370. If any function in this hook returns t, any other actions that
  18371. would have been caused by TAB (such as table field motion or visibility
  18372. cycling) will not occur.")
  18373. (defvar org-tab-after-check-for-table-hook nil
  18374. "Hook for functions to attach themselves to TAB.
  18375. See `org-ctrl-c-ctrl-c-hook' for more information.
  18376. This hook runs after it has been established that the cursor is not in a
  18377. table, but before checking if the cursor is in a headline or if global cycling
  18378. should be done.
  18379. If any function in this hook returns t, not other actions like visibility
  18380. cycling will be done.")
  18381. (defvar org-tab-after-check-for-cycling-hook nil
  18382. "Hook for functions to attach themselves to TAB.
  18383. See `org-ctrl-c-ctrl-c-hook' for more information.
  18384. This hook runs after it has been established that not table field motion and
  18385. not visibility should be done because of current context. This is probably
  18386. the place where a package like yasnippets can hook in.")
  18387. (defvar org-tab-before-tab-emulation-hook nil
  18388. "Hook for functions to attach themselves to TAB.
  18389. See `org-ctrl-c-ctrl-c-hook' for more information.
  18390. This hook runs after every other options for TAB have been exhausted, but
  18391. before indentation and \t insertion takes place.")
  18392. (defvar org-metaleft-hook nil
  18393. "Hook for functions attaching themselves to `M-left'.
  18394. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18395. (defvar org-metaright-hook nil
  18396. "Hook for functions attaching themselves to `M-right'.
  18397. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18398. (defvar org-metaup-hook nil
  18399. "Hook for functions attaching themselves to `M-up'.
  18400. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18401. (defvar org-metadown-hook nil
  18402. "Hook for functions attaching themselves to `M-down'.
  18403. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18404. (defvar org-shiftmetaleft-hook nil
  18405. "Hook for functions attaching themselves to `M-S-left'.
  18406. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18407. (defvar org-shiftmetaright-hook nil
  18408. "Hook for functions attaching themselves to `M-S-right'.
  18409. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18410. (defvar org-shiftmetaup-hook nil
  18411. "Hook for functions attaching themselves to `M-S-up'.
  18412. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18413. (defvar org-shiftmetadown-hook nil
  18414. "Hook for functions attaching themselves to `M-S-down'.
  18415. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18416. (defvar org-metareturn-hook nil
  18417. "Hook for functions attaching themselves to `M-RET'.
  18418. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18419. (defvar org-shiftup-hook nil
  18420. "Hook for functions attaching themselves to `S-up'.
  18421. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18422. (defvar org-shiftup-final-hook nil
  18423. "Hook for functions attaching themselves to `S-up'.
  18424. This one runs after all other options except shift-select have been excluded.
  18425. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18426. (defvar org-shiftdown-hook nil
  18427. "Hook for functions attaching themselves to `S-down'.
  18428. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18429. (defvar org-shiftdown-final-hook nil
  18430. "Hook for functions attaching themselves to `S-down'.
  18431. This one runs after all other options except shift-select have been excluded.
  18432. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18433. (defvar org-shiftleft-hook nil
  18434. "Hook for functions attaching themselves to `S-left'.
  18435. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18436. (defvar org-shiftleft-final-hook nil
  18437. "Hook for functions attaching themselves to `S-left'.
  18438. This one runs after all other options except shift-select have been excluded.
  18439. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18440. (defvar org-shiftright-hook nil
  18441. "Hook for functions attaching themselves to `S-right'.
  18442. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18443. (defvar org-shiftright-final-hook nil
  18444. "Hook for functions attaching themselves to `S-right'.
  18445. This one runs after all other options except shift-select have been excluded.
  18446. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18447. (defun org-modifier-cursor-error ()
  18448. "Throw an error, a modified cursor command was applied in wrong context."
  18449. (user-error "This command is active in special context like tables, headlines or items"))
  18450. (defun org-shiftselect-error ()
  18451. "Throw an error because Shift-Cursor command was applied in wrong context."
  18452. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18453. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18454. (user-error "This command works only in special context like headlines or timestamps")))
  18455. (defun org-call-for-shift-select (cmd)
  18456. (let ((this-command-keys-shift-translated t))
  18457. (call-interactively cmd)))
  18458. (defun org-shifttab (&optional arg)
  18459. "Global visibility cycling or move to previous table field.
  18460. Call `org-table-previous-field' within a table.
  18461. When ARG is nil, cycle globally through visibility states.
  18462. When ARG is a numeric prefix, show contents of this level."
  18463. (interactive "P")
  18464. (cond
  18465. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18466. ((integerp arg)
  18467. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18468. (message "Content view to level: %d" arg)
  18469. (org-content (prefix-numeric-value arg2))
  18470. (org-cycle-show-empty-lines t)
  18471. (setq org-cycle-global-status 'overview)))
  18472. (t (call-interactively 'org-global-cycle))))
  18473. (defun org-shiftmetaleft ()
  18474. "Promote subtree or delete table column.
  18475. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18476. `org-table-delete-column', depending on context. See the
  18477. individual commands for more information."
  18478. (interactive)
  18479. (cond
  18480. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18481. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18482. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18483. ((if (not (org-region-active-p)) (org-at-item-p)
  18484. (save-excursion (goto-char (region-beginning))
  18485. (org-at-item-p)))
  18486. (call-interactively 'org-outdent-item-tree))
  18487. (t (org-modifier-cursor-error))))
  18488. (defun org-shiftmetaright ()
  18489. "Demote subtree or insert table column.
  18490. Calls `org-demote-subtree', `org-indent-item-tree', or
  18491. `org-table-insert-column', depending on context. See the
  18492. individual commands for more information."
  18493. (interactive)
  18494. (cond
  18495. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18496. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18497. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18498. ((if (not (org-region-active-p)) (org-at-item-p)
  18499. (save-excursion (goto-char (region-beginning))
  18500. (org-at-item-p)))
  18501. (call-interactively 'org-indent-item-tree))
  18502. (t (org-modifier-cursor-error))))
  18503. (defun org-shiftmetaup (&optional _arg)
  18504. "Drag the line at point up.
  18505. In a table, kill the current row.
  18506. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18507. but also adjust the previous clocked item in the clock history.
  18508. Everywhere else, drag the line at point up."
  18509. (interactive "P")
  18510. (cond
  18511. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18512. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18513. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18514. (call-interactively 'org-timestamp-up)))
  18515. (t (call-interactively 'org-drag-line-backward))))
  18516. (defun org-shiftmetadown (&optional _arg)
  18517. "Drag the line at point down.
  18518. In a table, insert an empty row at the current line.
  18519. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18520. but also adjust the previous clocked item in the clock history.
  18521. Everywhere else, drag the line at point down."
  18522. (interactive "P")
  18523. (cond
  18524. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18525. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18526. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18527. (call-interactively 'org-timestamp-down)))
  18528. (t (call-interactively 'org-drag-line-forward))))
  18529. (defsubst org-hidden-tree-error ()
  18530. (user-error
  18531. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18532. (defun org-metaleft (&optional _arg)
  18533. "Promote heading, list item at point or move table column left.
  18534. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18535. depending on context. With no specific context, calls the Emacs
  18536. default `backward-word'. See the individual commands for more
  18537. information.
  18538. This function runs the hook `org-metaleft-hook' as a first step,
  18539. and returns at first non-nil value."
  18540. (interactive "P")
  18541. (cond
  18542. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18543. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18544. ((org-with-limited-levels
  18545. (or (org-at-heading-p)
  18546. (and (org-region-active-p)
  18547. (save-excursion
  18548. (goto-char (region-beginning))
  18549. (org-at-heading-p)))))
  18550. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18551. (call-interactively 'org-do-promote))
  18552. ;; At an inline task.
  18553. ((org-at-heading-p)
  18554. (call-interactively 'org-inlinetask-promote))
  18555. ((or (org-at-item-p)
  18556. (and (org-region-active-p)
  18557. (save-excursion
  18558. (goto-char (region-beginning))
  18559. (org-at-item-p))))
  18560. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18561. (call-interactively 'org-outdent-item))
  18562. (t (call-interactively 'backward-word))))
  18563. (defun org-metaright (&optional _arg)
  18564. "Demote heading, list item at point or move table column right.
  18565. In front of a drawer or a block keyword, indent it correctly.
  18566. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18567. `org-indent-drawer' or `org-indent-block' depending on context.
  18568. With no specific context, calls the Emacs default `forward-word'.
  18569. See the individual commands for more information.
  18570. This function runs the hook `org-metaright-hook' as a first step,
  18571. and returns at first non-nil value."
  18572. (interactive "P")
  18573. (cond
  18574. ((run-hook-with-args-until-success 'org-metaright-hook))
  18575. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18576. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18577. ((org-at-block-p) (call-interactively 'org-indent-block))
  18578. ((org-with-limited-levels
  18579. (or (org-at-heading-p)
  18580. (and (org-region-active-p)
  18581. (save-excursion
  18582. (goto-char (region-beginning))
  18583. (org-at-heading-p)))))
  18584. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18585. (call-interactively 'org-do-demote))
  18586. ;; At an inline task.
  18587. ((org-at-heading-p)
  18588. (call-interactively 'org-inlinetask-demote))
  18589. ((or (org-at-item-p)
  18590. (and (org-region-active-p)
  18591. (save-excursion
  18592. (goto-char (region-beginning))
  18593. (org-at-item-p))))
  18594. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18595. (call-interactively 'org-indent-item))
  18596. (t (call-interactively 'forward-word))))
  18597. (defun org-check-for-hidden (what)
  18598. "Check if there are hidden headlines/items in the current visual line.
  18599. WHAT can be either `headlines' or `items'. If the current line is
  18600. an outline or item heading and it has a folded subtree below it,
  18601. this function returns t, nil otherwise."
  18602. (let ((re (cond
  18603. ((eq what 'headlines) org-outline-regexp-bol)
  18604. ((eq what 'items) (org-item-beginning-re))
  18605. (t (error "This should not happen"))))
  18606. beg end)
  18607. (save-excursion
  18608. (catch 'exit
  18609. (unless (org-region-active-p)
  18610. (setq beg (point-at-bol))
  18611. (beginning-of-line 2)
  18612. (while (and (not (eobp)) ;; this is like `next-line'
  18613. (get-char-property (1- (point)) 'invisible))
  18614. (beginning-of-line 2))
  18615. (setq end (point))
  18616. (goto-char beg)
  18617. (goto-char (point-at-eol))
  18618. (setq end (max end (point)))
  18619. (while (re-search-forward re end t)
  18620. (when (get-char-property (match-beginning 0) 'invisible)
  18621. (throw 'exit t))))
  18622. nil))))
  18623. (defun org-metaup (&optional _arg)
  18624. "Move subtree up or move table row up.
  18625. Calls `org-move-subtree-up' or `org-table-move-row' or
  18626. `org-move-item-up', depending on context. See the individual commands
  18627. for more information."
  18628. (interactive "P")
  18629. (cond
  18630. ((run-hook-with-args-until-success 'org-metaup-hook))
  18631. ((org-region-active-p)
  18632. (let* ((a (min (region-beginning) (region-end)))
  18633. (b (1- (max (region-beginning) (region-end))))
  18634. (c (save-excursion (goto-char a)
  18635. (move-beginning-of-line 0)))
  18636. (d (save-excursion (goto-char a)
  18637. (move-end-of-line 0) (point))))
  18638. (transpose-regions a b c d)
  18639. (goto-char c)))
  18640. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18641. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18642. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18643. (t (org-drag-element-backward))))
  18644. (defun org-metadown (&optional _arg)
  18645. "Move subtree down or move table row down.
  18646. Calls `org-move-subtree-down' or `org-table-move-row' or
  18647. `org-move-item-down', depending on context. See the individual
  18648. commands for more information."
  18649. (interactive "P")
  18650. (cond
  18651. ((run-hook-with-args-until-success 'org-metadown-hook))
  18652. ((org-region-active-p)
  18653. (let* ((a (min (region-beginning) (region-end)))
  18654. (b (max (region-beginning) (region-end)))
  18655. (c (save-excursion (goto-char b)
  18656. (move-beginning-of-line 1)))
  18657. (d (save-excursion (goto-char b)
  18658. (move-end-of-line 1) (1+ (point)))))
  18659. (transpose-regions a b c d)
  18660. (goto-char d)))
  18661. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18662. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18663. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18664. (t (org-drag-element-forward))))
  18665. (defun org-shiftup (&optional arg)
  18666. "Increase item in timestamp or increase priority of current headline.
  18667. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18668. depending on context. See the individual commands for more information."
  18669. (interactive "P")
  18670. (cond
  18671. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18672. ((and org-support-shift-select (org-region-active-p))
  18673. (org-call-for-shift-select 'previous-line))
  18674. ((org-at-timestamp-p 'lax)
  18675. (call-interactively (if org-edit-timestamp-down-means-later
  18676. 'org-timestamp-down 'org-timestamp-up)))
  18677. ((and (not (eq org-support-shift-select 'always))
  18678. org-enable-priority-commands
  18679. (org-at-heading-p))
  18680. (call-interactively 'org-priority-up))
  18681. ((and (not org-support-shift-select) (org-at-item-p))
  18682. (call-interactively 'org-previous-item))
  18683. ((org-clocktable-try-shift 'up arg))
  18684. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18685. (org-support-shift-select
  18686. (org-call-for-shift-select 'previous-line))
  18687. (t (org-shiftselect-error))))
  18688. (defun org-shiftdown (&optional arg)
  18689. "Decrease item in timestamp or decrease priority of current headline.
  18690. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18691. depending on context. See the individual commands for more information."
  18692. (interactive "P")
  18693. (cond
  18694. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18695. ((and org-support-shift-select (org-region-active-p))
  18696. (org-call-for-shift-select 'next-line))
  18697. ((org-at-timestamp-p 'lax)
  18698. (call-interactively (if org-edit-timestamp-down-means-later
  18699. 'org-timestamp-up 'org-timestamp-down)))
  18700. ((and (not (eq org-support-shift-select 'always))
  18701. org-enable-priority-commands
  18702. (org-at-heading-p))
  18703. (call-interactively 'org-priority-down))
  18704. ((and (not org-support-shift-select) (org-at-item-p))
  18705. (call-interactively 'org-next-item))
  18706. ((org-clocktable-try-shift 'down arg))
  18707. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18708. (org-support-shift-select
  18709. (org-call-for-shift-select 'next-line))
  18710. (t (org-shiftselect-error))))
  18711. (defun org-shiftright (&optional arg)
  18712. "Cycle the thing at point or in the current line, depending on context.
  18713. Depending on context, this does one of the following:
  18714. - switch a timestamp at point one day into the future
  18715. - on a headline, switch to the next TODO keyword.
  18716. - on an item, switch entire list to the next bullet type
  18717. - on a property line, switch to the next allowed value
  18718. - on a clocktable definition line, move time block into the future"
  18719. (interactive "P")
  18720. (cond
  18721. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18722. ((and org-support-shift-select (org-region-active-p))
  18723. (org-call-for-shift-select 'forward-char))
  18724. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18725. ((and (not (eq org-support-shift-select 'always))
  18726. (org-at-heading-p))
  18727. (let ((org-inhibit-logging
  18728. (not org-treat-S-cursor-todo-selection-as-state-change))
  18729. (org-inhibit-blocking
  18730. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18731. (org-call-with-arg 'org-todo 'right)))
  18732. ((or (and org-support-shift-select
  18733. (not (eq org-support-shift-select 'always))
  18734. (org-at-item-bullet-p))
  18735. (and (not org-support-shift-select) (org-at-item-p)))
  18736. (org-call-with-arg 'org-cycle-list-bullet nil))
  18737. ((and (not (eq org-support-shift-select 'always))
  18738. (org-at-property-p))
  18739. (call-interactively 'org-property-next-allowed-value))
  18740. ((org-clocktable-try-shift 'right arg))
  18741. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18742. (org-support-shift-select
  18743. (org-call-for-shift-select 'forward-char))
  18744. (t (org-shiftselect-error))))
  18745. (defun org-shiftleft (&optional arg)
  18746. "Cycle the thing at point or in the current line, depending on context.
  18747. Depending on context, this does one of the following:
  18748. - switch a timestamp at point one day into the past
  18749. - on a headline, switch to the previous TODO keyword.
  18750. - on an item, switch entire list to the previous bullet type
  18751. - on a property line, switch to the previous allowed value
  18752. - on a clocktable definition line, move time block into the past"
  18753. (interactive "P")
  18754. (cond
  18755. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18756. ((and org-support-shift-select (org-region-active-p))
  18757. (org-call-for-shift-select 'backward-char))
  18758. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18759. ((and (not (eq org-support-shift-select 'always))
  18760. (org-at-heading-p))
  18761. (let ((org-inhibit-logging
  18762. (not org-treat-S-cursor-todo-selection-as-state-change))
  18763. (org-inhibit-blocking
  18764. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18765. (org-call-with-arg 'org-todo 'left)))
  18766. ((or (and org-support-shift-select
  18767. (not (eq org-support-shift-select 'always))
  18768. (org-at-item-bullet-p))
  18769. (and (not org-support-shift-select) (org-at-item-p)))
  18770. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18771. ((and (not (eq org-support-shift-select 'always))
  18772. (org-at-property-p))
  18773. (call-interactively 'org-property-previous-allowed-value))
  18774. ((org-clocktable-try-shift 'left arg))
  18775. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18776. (org-support-shift-select
  18777. (org-call-for-shift-select 'backward-char))
  18778. (t (org-shiftselect-error))))
  18779. (defun org-shiftcontrolright ()
  18780. "Switch to next TODO set."
  18781. (interactive)
  18782. (cond
  18783. ((and org-support-shift-select (org-region-active-p))
  18784. (org-call-for-shift-select 'forward-word))
  18785. ((and (not (eq org-support-shift-select 'always))
  18786. (org-at-heading-p))
  18787. (org-call-with-arg 'org-todo 'nextset))
  18788. (org-support-shift-select
  18789. (org-call-for-shift-select 'forward-word))
  18790. (t (org-shiftselect-error))))
  18791. (defun org-shiftcontrolleft ()
  18792. "Switch to previous TODO set."
  18793. (interactive)
  18794. (cond
  18795. ((and org-support-shift-select (org-region-active-p))
  18796. (org-call-for-shift-select 'backward-word))
  18797. ((and (not (eq org-support-shift-select 'always))
  18798. (org-at-heading-p))
  18799. (org-call-with-arg 'org-todo 'previousset))
  18800. (org-support-shift-select
  18801. (org-call-for-shift-select 'backward-word))
  18802. (t (org-shiftselect-error))))
  18803. (defun org-shiftcontrolup (&optional n)
  18804. "Change timestamps synchronously up in CLOCK log lines.
  18805. Optional argument N tells to change by that many units."
  18806. (interactive "P")
  18807. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18808. (let (org-support-shift-select)
  18809. (org-clock-timestamps-up n))
  18810. (user-error "Not at a clock log")))
  18811. (defun org-shiftcontroldown (&optional n)
  18812. "Change timestamps synchronously down in CLOCK log lines.
  18813. Optional argument N tells to change by that many units."
  18814. (interactive "P")
  18815. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18816. (let (org-support-shift-select)
  18817. (org-clock-timestamps-down n))
  18818. (user-error "Not at a clock log")))
  18819. (defun org-increase-number-at-point (&optional inc)
  18820. "Increment the number at point.
  18821. With an optional prefix numeric argument INC, increment using
  18822. this numeric value."
  18823. (interactive "p")
  18824. (if (not (number-at-point))
  18825. (user-error "Not on a number")
  18826. (unless inc (setq inc 1))
  18827. (let ((pos (point))
  18828. (beg (skip-chars-backward "-+^/*0-9eE."))
  18829. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18830. (setq nap (buffer-substring-no-properties
  18831. (+ pos beg) (+ pos beg end)))
  18832. (delete-region (+ pos beg) (+ pos beg end))
  18833. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18834. (when (org-at-table-p)
  18835. (org-table-align)
  18836. (org-table-end-of-field 1))))
  18837. (defun org-decrease-number-at-point (&optional inc)
  18838. "Decrement the number at point.
  18839. With an optional prefix numeric argument INC, decrement using
  18840. this numeric value."
  18841. (interactive "p")
  18842. (org-increase-number-at-point (- (or inc 1))))
  18843. (defun org-ctrl-c-ret ()
  18844. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18845. (interactive)
  18846. (cond
  18847. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18848. (t (call-interactively 'org-insert-heading))))
  18849. (defun org-find-visible ()
  18850. (let ((s (point)))
  18851. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18852. (get-char-property s 'invisible)))
  18853. s))
  18854. (defun org-find-invisible ()
  18855. (let ((s (point)))
  18856. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18857. (not (get-char-property s 'invisible))))
  18858. s))
  18859. (defun org-copy-visible (beg end)
  18860. "Copy the visible parts of the region."
  18861. (interactive "r")
  18862. (let (snippets s)
  18863. (save-excursion
  18864. (save-restriction
  18865. (narrow-to-region beg end)
  18866. (setq s (goto-char (point-min)))
  18867. (while (not (= (point) (point-max)))
  18868. (goto-char (org-find-invisible))
  18869. (push (buffer-substring s (point)) snippets)
  18870. (setq s (goto-char (org-find-visible))))))
  18871. (kill-new (apply 'concat (nreverse snippets)))))
  18872. (defun org-copy-special ()
  18873. "Copy region in table or copy current subtree.
  18874. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18875. context. See the individual commands for more information."
  18876. (interactive)
  18877. (call-interactively
  18878. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18879. (defun org-cut-special ()
  18880. "Cut region in table or cut current subtree.
  18881. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18882. context. See the individual commands for more information."
  18883. (interactive)
  18884. (call-interactively
  18885. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18886. (defun org-paste-special (arg)
  18887. "Paste rectangular region into table, or past subtree relative to level.
  18888. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18889. See the individual commands for more information."
  18890. (interactive "P")
  18891. (if (org-at-table-p)
  18892. (org-table-paste-rectangle)
  18893. (org-paste-subtree arg)))
  18894. (defun org-edit-special (&optional arg)
  18895. "Call a special editor for the element at point.
  18896. When at a table, call the formula editor with `org-table-edit-formulas'.
  18897. When in a source code block, call `org-edit-src-code'.
  18898. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18899. When in an export block, call `org-edit-export-block'.
  18900. When in a LaTeX environment, call `org-edit-latex-environment'.
  18901. When at an #+INCLUDE keyword, visit the included file.
  18902. When at a footnote reference, call `org-edit-footnote-reference'
  18903. On a link, call `ffap' to visit the link at point.
  18904. Otherwise, return a user error."
  18905. (interactive "P")
  18906. (let ((element (org-element-at-point)))
  18907. (barf-if-buffer-read-only)
  18908. (pcase (org-element-type element)
  18909. (`src-block
  18910. (if (not arg) (org-edit-src-code)
  18911. (let* ((info (org-babel-get-src-block-info))
  18912. (lang (nth 0 info))
  18913. (params (nth 2 info))
  18914. (session (cdr (assq :session params))))
  18915. (if (not session) (org-edit-src-code)
  18916. ;; At a src-block with a session and function called with
  18917. ;; an ARG: switch to the buffer related to the inferior
  18918. ;; process.
  18919. (switch-to-buffer
  18920. (funcall (intern (concat "org-babel-prep-session:" lang))
  18921. session params))))))
  18922. (`keyword
  18923. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18924. (org-open-link-from-string
  18925. (format "[[%s]]"
  18926. (expand-file-name
  18927. (let ((value (org-element-property :value element)))
  18928. (cond ((org-file-url-p value)
  18929. (user-error "The file is specified as a URL, cannot be edited"))
  18930. ((not (org-string-nw-p value))
  18931. (user-error "No file to edit"))
  18932. ((string-match "\\`\"\\(.*?\\)\"" value)
  18933. (match-string 1 value))
  18934. ((string-match "\\`[^ \t\"]\\S-*" value)
  18935. (match-string 0 value))
  18936. (t (user-error "No valid file specified")))))))
  18937. (user-error "No special environment to edit here")))
  18938. (`table
  18939. (if (eq (org-element-property :type element) 'table.el)
  18940. (org-edit-table.el)
  18941. (call-interactively 'org-table-edit-formulas)))
  18942. ;; Only Org tables contain `table-row' type elements.
  18943. (`table-row (call-interactively 'org-table-edit-formulas))
  18944. (`example-block (org-edit-src-code))
  18945. (`export-block (org-edit-export-block))
  18946. (`fixed-width (org-edit-fixed-width-region))
  18947. (`latex-environment (org-edit-latex-environment))
  18948. (_
  18949. ;; No notable element at point. Though, we may be at a link or
  18950. ;; a footnote reference, which are objects. Thus, scan deeper.
  18951. (let ((context (org-element-context element)))
  18952. (pcase (org-element-type context)
  18953. (`footnote-reference (org-edit-footnote-reference))
  18954. (`inline-src-block (org-edit-inline-src-code))
  18955. (`link (call-interactively #'ffap))
  18956. (_ (user-error "No special environment to edit here"))))))))
  18957. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18958. (defun org-ctrl-c-ctrl-c (&optional arg)
  18959. "Set tags in headline, or update according to changed information at point.
  18960. This command does many different things, depending on context:
  18961. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18962. this is what we do.
  18963. - If the cursor is on a statistics cookie, update it.
  18964. - If the cursor is in a headline, prompt for tags and insert them
  18965. into the current line, aligned to `org-tags-column'. When called
  18966. with prefix arg, realign all tags in the current buffer.
  18967. - If the cursor is in one of the special #+KEYWORD lines, this
  18968. triggers scanning the buffer for these lines and updating the
  18969. information.
  18970. - If the cursor is inside a table, realign the table. This command
  18971. works even if the automatic table editor has been turned off.
  18972. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18973. the entire table.
  18974. - If the cursor is at a footnote reference or definition, jump to
  18975. the corresponding definition or references, respectively.
  18976. - If the cursor is a the beginning of a dynamic block, update it.
  18977. - If the current buffer is a capture buffer, close note and file it.
  18978. - If the cursor is on a <<<target>>>, update radio targets and
  18979. corresponding links in this buffer.
  18980. - If the cursor is on a numbered item in a plain list, renumber the
  18981. ordered list.
  18982. - If the cursor is on a checkbox, toggle it.
  18983. - If the cursor is on a code block, evaluate it. The variable
  18984. `org-confirm-babel-evaluate' can be used to control prompting
  18985. before code block evaluation, by default every code block
  18986. evaluation requires confirmation. Code block evaluation can be
  18987. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18988. (interactive "P")
  18989. (cond
  18990. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18991. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18992. (org-remove-occur-highlights)
  18993. (message "Temporary highlights/overlays removed from current buffer"))
  18994. ((and (local-variable-p 'org-finish-function)
  18995. (fboundp org-finish-function))
  18996. (funcall org-finish-function))
  18997. ((org-babel-hash-at-point))
  18998. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18999. (t
  19000. (let* ((context
  19001. (org-element-lineage
  19002. (org-element-context)
  19003. ;; Limit to supported contexts.
  19004. '(babel-call clock dynamic-block footnote-definition
  19005. footnote-reference inline-babel-call inline-src-block
  19006. inlinetask item keyword node-property paragraph
  19007. plain-list property-drawer radio-target src-block
  19008. statistics-cookie table table-cell table-row
  19009. timestamp)
  19010. t))
  19011. (type (org-element-type context)))
  19012. ;; For convenience: at the first line of a paragraph on the same
  19013. ;; line as an item, apply function on that item instead.
  19014. (when (eq type 'paragraph)
  19015. (let ((parent (org-element-property :parent context)))
  19016. (when (and (eq (org-element-type parent) 'item)
  19017. (= (line-beginning-position)
  19018. (org-element-property :begin parent)))
  19019. (setq context parent)
  19020. (setq type 'item))))
  19021. ;; Act according to type of element or object at point.
  19022. ;;
  19023. ;; Do nothing on a blank line, except if it is contained in
  19024. ;; a src block. Hence, we first check if point is in such
  19025. ;; a block and then if it is at a blank line.
  19026. (pcase type
  19027. ((or `inline-src-block `src-block)
  19028. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19029. (org-babel-eval-wipe-error-buffer)
  19030. (org-babel-execute-src-block
  19031. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19032. ((guard (org-match-line "[ \t]*$"))
  19033. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19034. (user-error
  19035. (substitute-command-keys
  19036. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19037. ((or `babel-call `inline-babel-call)
  19038. (let ((info (org-babel-lob-get-info context)))
  19039. (when info (org-babel-execute-src-block nil info))))
  19040. (`clock (org-clock-update-time-maybe))
  19041. (`dynamic-block
  19042. (save-excursion
  19043. (goto-char (org-element-property :post-affiliated context))
  19044. (org-update-dblock)))
  19045. (`footnote-definition
  19046. (goto-char (org-element-property :post-affiliated context))
  19047. (call-interactively 'org-footnote-action))
  19048. (`footnote-reference (call-interactively #'org-footnote-action))
  19049. ((or `headline `inlinetask)
  19050. (save-excursion (goto-char (org-element-property :begin context))
  19051. (call-interactively #'org-set-tags)))
  19052. (`item
  19053. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19054. ;; unconditionally, whereas `C-u' will toggle its presence.
  19055. ;; Without a universal argument, if the item has a checkbox,
  19056. ;; toggle it. Otherwise repair the list.
  19057. (let* ((box (org-element-property :checkbox context))
  19058. (struct (org-element-property :structure context))
  19059. (old-struct (copy-tree struct))
  19060. (parents (org-list-parents-alist struct))
  19061. (prevs (org-list-prevs-alist struct))
  19062. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19063. (org-list-set-checkbox
  19064. (org-element-property :begin context) struct
  19065. (cond ((equal arg '(16)) "[-]")
  19066. ((and (not box) (equal arg '(4))) "[ ]")
  19067. ((or (not box) (equal arg '(4))) nil)
  19068. ((eq box 'on) "[ ]")
  19069. (t "[X]")))
  19070. ;; Mimic `org-list-write-struct' but with grabbing a return
  19071. ;; value from `org-list-struct-fix-box'.
  19072. (org-list-struct-fix-ind struct parents 2)
  19073. (org-list-struct-fix-item-end struct)
  19074. (org-list-struct-fix-bul struct prevs)
  19075. (org-list-struct-fix-ind struct parents)
  19076. (let ((block-item
  19077. (org-list-struct-fix-box struct parents prevs orderedp)))
  19078. (if (and box (equal struct old-struct))
  19079. (if (equal arg '(16))
  19080. (message "Checkboxes already reset")
  19081. (user-error "Cannot toggle this checkbox: %s"
  19082. (if (eq box 'on)
  19083. "all subitems checked"
  19084. "unchecked subitems")))
  19085. (org-list-struct-apply-struct struct old-struct)
  19086. (org-update-checkbox-count-maybe))
  19087. (when block-item
  19088. (message "Checkboxes were removed due to empty box at line %d"
  19089. (org-current-line block-item))))))
  19090. (`keyword
  19091. (let ((org-inhibit-startup-visibility-stuff t)
  19092. (org-startup-align-all-tables nil))
  19093. (when (boundp 'org-table-coordinate-overlays)
  19094. (mapc #'delete-overlay org-table-coordinate-overlays)
  19095. (setq org-table-coordinate-overlays nil))
  19096. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19097. (message "Local setup has been refreshed"))
  19098. (`plain-list
  19099. ;; At a plain list, with a double C-u argument, set
  19100. ;; checkboxes of each item to "[-]", whereas a single one
  19101. ;; will toggle their presence according to the state of the
  19102. ;; first item in the list. Without an argument, repair the
  19103. ;; list.
  19104. (let* ((begin (org-element-property :contents-begin context))
  19105. (beginm (move-marker (make-marker) begin))
  19106. (struct (org-element-property :structure context))
  19107. (old-struct (copy-tree struct))
  19108. (first-box (save-excursion
  19109. (goto-char begin)
  19110. (looking-at org-list-full-item-re)
  19111. (match-string-no-properties 3)))
  19112. (new-box (cond ((equal arg '(16)) "[-]")
  19113. ((equal arg '(4)) (unless first-box "[ ]"))
  19114. ((equal first-box "[X]") "[ ]")
  19115. (t "[X]"))))
  19116. (cond
  19117. (arg
  19118. (dolist (pos
  19119. (org-list-get-all-items
  19120. begin struct (org-list-prevs-alist struct)))
  19121. (org-list-set-checkbox pos struct new-box)))
  19122. ((and first-box (eq (point) begin))
  19123. ;; For convenience, when point is at bol on the first
  19124. ;; item of the list and no argument is provided, simply
  19125. ;; toggle checkbox of that item, if any.
  19126. (org-list-set-checkbox begin struct new-box)))
  19127. (org-list-write-struct
  19128. struct (org-list-parents-alist struct) old-struct)
  19129. (org-update-checkbox-count-maybe)
  19130. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19131. ((or `property-drawer `node-property)
  19132. (call-interactively #'org-property-action))
  19133. (`radio-target
  19134. (call-interactively #'org-update-radio-target-regexp))
  19135. (`statistics-cookie
  19136. (call-interactively #'org-update-statistics-cookies))
  19137. ((or `table `table-cell `table-row)
  19138. ;; At a table, recalculate every field and align it. Also
  19139. ;; send the table if necessary. If the table has
  19140. ;; a `table.el' type, just give up. At a table row or cell,
  19141. ;; maybe recalculate line but always align table.
  19142. (if (eq (org-element-property :type context) 'table.el)
  19143. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19144. Use `\\[org-edit-special]' to edit table.el tables"))
  19145. (let ((org-enable-table-editor t))
  19146. (if (or (eq type 'table)
  19147. ;; Check if point is at a TBLFM line.
  19148. (and (eq type 'table-row)
  19149. (= (point) (org-element-property :end context))))
  19150. (save-excursion
  19151. (if (org-at-TBLFM-p)
  19152. (progn (require 'org-table)
  19153. (org-table-calc-current-TBLFM))
  19154. (goto-char (org-element-property :contents-begin context))
  19155. (org-call-with-arg 'org-table-recalculate (or arg t))
  19156. (orgtbl-send-table 'maybe)))
  19157. (org-table-maybe-eval-formula)
  19158. (cond (arg (call-interactively #'org-table-recalculate))
  19159. ((org-table-maybe-recalculate-line))
  19160. (t (org-table-align)))))))
  19161. (`timestamp (org-timestamp-change 0 'day))
  19162. ((and `nil (guard (org-at-heading-p)))
  19163. ;; When point is on an unsupported object type, we can miss
  19164. ;; the fact that it also is at a heading. Handle it here.
  19165. (call-interactively #'org-set-tags))
  19166. ((guard
  19167. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19168. (_
  19169. (user-error
  19170. (substitute-command-keys
  19171. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19172. (defun org-mode-restart ()
  19173. (interactive)
  19174. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19175. (funcall major-mode)
  19176. (hack-local-variables)
  19177. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19178. (org-indent-mode -1))
  19179. (org-reset-file-cache))
  19180. (message "%s restarted" major-mode))
  19181. (defun org-kill-note-or-show-branches ()
  19182. "Abort storing current note, or call `outline-show-branches'."
  19183. (interactive)
  19184. (if (not org-finish-function)
  19185. (progn
  19186. (outline-hide-subtree)
  19187. (call-interactively 'outline-show-branches))
  19188. (let ((org-note-abort t))
  19189. (funcall org-finish-function))))
  19190. (defun org-delete-indentation (&optional arg)
  19191. "Join current line to previous and fix whitespace at join.
  19192. If previous line is a headline add to headline title. Otherwise
  19193. the function calls `delete-indentation'.
  19194. With a non-nil optional argument, join it to the following one."
  19195. (interactive "*P")
  19196. (if (save-excursion
  19197. (beginning-of-line (if arg 1 0))
  19198. (let ((case-fold-search nil))
  19199. (looking-at org-complex-heading-regexp)))
  19200. ;; At headline.
  19201. (let ((tags-column (when (match-beginning 5)
  19202. (save-excursion (goto-char (match-beginning 5))
  19203. (current-column))))
  19204. (string (concat " " (progn (when arg (forward-line 1))
  19205. (org-trim (delete-and-extract-region
  19206. (line-beginning-position)
  19207. (line-end-position)))))))
  19208. (unless (bobp) (delete-region (point) (1- (point))))
  19209. (goto-char (or (match-end 4)
  19210. (match-beginning 5)
  19211. (match-end 0)))
  19212. (skip-chars-backward " \t")
  19213. (save-excursion (insert string))
  19214. ;; Adjust alignment of tags.
  19215. (cond
  19216. ((not tags-column)) ;no tags
  19217. (org-auto-align-tags (org-set-tags nil t))
  19218. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19219. (delete-indentation arg)))
  19220. (defun org-open-line (n)
  19221. "Insert a new row in tables, call `open-line' elsewhere.
  19222. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19223. As a special case, when a document starts with a table, allow to
  19224. call `open-line' on the very first character."
  19225. (interactive "*p")
  19226. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19227. (org-table-insert-row)
  19228. (open-line n)))
  19229. (defun org-return (&optional indent)
  19230. "Goto next table row or insert a newline.
  19231. Calls `org-table-next-row' or `newline', depending on context.
  19232. When optional INDENT argument is non-nil, call
  19233. `newline-and-indent' instead of `newline'.
  19234. When `org-return-follows-link' is non-nil and point is on
  19235. a timestamp or a link, call `org-open-at-point'. However, it
  19236. will not happen if point is in a table or on a \"dead\"
  19237. object (e.g., within a comment). In these case, you need to use
  19238. `org-open-at-point' directly."
  19239. (interactive)
  19240. (let ((context (if org-return-follows-link (org-element-context)
  19241. (org-element-at-point))))
  19242. (cond
  19243. ;; In a table, call `org-table-next-row'.
  19244. ((or (and (eq (org-element-type context) 'table)
  19245. (>= (point) (org-element-property :contents-begin context))
  19246. (< (point) (org-element-property :contents-end context)))
  19247. (org-element-lineage context '(table-row table-cell) t))
  19248. (org-table-justify-field-maybe)
  19249. (call-interactively #'org-table-next-row))
  19250. ;; On a link or a timestamp, call `org-open-at-point' if
  19251. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19252. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19253. ((and org-return-follows-link
  19254. (or (org-in-regexp org-ts-regexp-both nil t)
  19255. (org-in-regexp org-tsr-regexp-both nil t)
  19256. (org-in-regexp org-any-link-re nil t)))
  19257. (call-interactively #'org-open-at-point))
  19258. ;; Insert newline in heading, but preserve tags.
  19259. ((and (not (bolp))
  19260. (save-excursion (beginning-of-line)
  19261. (let ((case-fold-search nil))
  19262. (looking-at org-complex-heading-regexp))))
  19263. ;; At headline. Split line. However, if point is on keyword,
  19264. ;; priority cookie or tags, do not break any of them: add
  19265. ;; a newline after the headline instead.
  19266. (let ((tags-column (and (match-beginning 5)
  19267. (save-excursion (goto-char (match-beginning 5))
  19268. (current-column))))
  19269. (string
  19270. (when (and (match-end 4) (org-point-in-group (point) 4))
  19271. (delete-and-extract-region (point) (match-end 4)))))
  19272. ;; Adjust tag alignment.
  19273. (cond
  19274. ((not (and tags-column string)))
  19275. (org-auto-align-tags (org-set-tags nil t))
  19276. (t (org--align-tags-here tags-column))) ;preserve tags column
  19277. (end-of-line)
  19278. (org-show-entry)
  19279. (if indent (newline-and-indent) (newline))
  19280. (when string (save-excursion (insert (org-trim string))))))
  19281. ;; In a list, make sure indenting keeps trailing text within.
  19282. ((and indent
  19283. (not (eolp))
  19284. (org-element-lineage context '(item)))
  19285. (let ((trailing-data
  19286. (delete-and-extract-region (point) (line-end-position))))
  19287. (newline-and-indent)
  19288. (save-excursion (insert trailing-data))))
  19289. (t (if indent (newline-and-indent) (newline))))))
  19290. (defun org-return-indent ()
  19291. "Goto next table row or insert a newline and indent.
  19292. Calls `org-table-next-row' or `newline-and-indent', depending on
  19293. context. See the individual commands for more information."
  19294. (interactive)
  19295. (org-return t))
  19296. (defun org-ctrl-c-star ()
  19297. "Compute table, or change heading status of lines.
  19298. Calls `org-table-recalculate' or `org-toggle-heading',
  19299. depending on context."
  19300. (interactive)
  19301. (cond
  19302. ((org-at-table-p)
  19303. (call-interactively 'org-table-recalculate))
  19304. (t
  19305. ;; Convert all lines in region to list items
  19306. (call-interactively 'org-toggle-heading))))
  19307. (defun org-ctrl-c-minus ()
  19308. "Insert separator line in table or modify bullet status of line.
  19309. Also turns a plain line or a region of lines into list items.
  19310. Calls `org-table-insert-hline', `org-toggle-item', or
  19311. `org-cycle-list-bullet', depending on context."
  19312. (interactive)
  19313. (cond
  19314. ((org-at-table-p)
  19315. (call-interactively 'org-table-insert-hline))
  19316. ((org-region-active-p)
  19317. (call-interactively 'org-toggle-item))
  19318. ((org-in-item-p)
  19319. (call-interactively 'org-cycle-list-bullet))
  19320. (t
  19321. (call-interactively 'org-toggle-item))))
  19322. (defun org-toggle-heading (&optional nstars)
  19323. "Convert headings to normal text, or items or text to headings.
  19324. If there is no active region, only convert the current line.
  19325. With a `\\[universal-argument]' prefix, convert the whole list at
  19326. point into heading.
  19327. In a region:
  19328. - If the first non blank line is a headline, remove the stars
  19329. from all headlines in the region.
  19330. - If it is a normal line, turn each and every normal line (i.e.,
  19331. not an heading or an item) in the region into headings. If you
  19332. want to convert only the first line of this region, use one
  19333. universal prefix argument.
  19334. - If it is a plain list item, turn all plain list items into headings.
  19335. When converting a line into a heading, the number of stars is chosen
  19336. such that the lines become children of the current entry. However,
  19337. when a numeric prefix argument is given, its value determines the
  19338. number of stars to add."
  19339. (interactive "P")
  19340. (let ((skip-blanks
  19341. (function
  19342. ;; Return beginning of first non-blank line, starting from
  19343. ;; line at POS.
  19344. (lambda (pos)
  19345. (save-excursion
  19346. (goto-char pos)
  19347. (while (org-at-comment-p) (forward-line))
  19348. (skip-chars-forward " \r\t\n")
  19349. (point-at-bol)))))
  19350. beg end toggled)
  19351. ;; Determine boundaries of changes. If a universal prefix has
  19352. ;; been given, put the list in a region. If region ends at a bol,
  19353. ;; do not consider the last line to be in the region.
  19354. (when (and current-prefix-arg (org-at-item-p))
  19355. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19356. (org-mark-element))
  19357. (if (org-region-active-p)
  19358. (setq beg (funcall skip-blanks (region-beginning))
  19359. end (copy-marker (save-excursion
  19360. (goto-char (region-end))
  19361. (if (bolp) (point) (point-at-eol)))))
  19362. (setq beg (funcall skip-blanks (point-at-bol))
  19363. end (copy-marker (point-at-eol))))
  19364. ;; Ensure inline tasks don't count as headings.
  19365. (org-with-limited-levels
  19366. (save-excursion
  19367. (goto-char beg)
  19368. (cond
  19369. ;; Case 1. Started at an heading: de-star headings.
  19370. ((org-at-heading-p)
  19371. (while (< (point) end)
  19372. (when (org-at-heading-p t)
  19373. (looking-at org-outline-regexp) (replace-match "")
  19374. (setq toggled t))
  19375. (forward-line)))
  19376. ;; Case 2. Started at an item: change items into headlines.
  19377. ;; One star will be added by `org-list-to-subtree'.
  19378. ((org-at-item-p)
  19379. (while (< (point) end)
  19380. (when (org-at-item-p)
  19381. ;; Pay attention to cases when region ends before list.
  19382. (let* ((struct (org-list-struct))
  19383. (list-end
  19384. (min (org-list-get-bottom-point struct) (1+ end))))
  19385. (save-restriction
  19386. (narrow-to-region (point) list-end)
  19387. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19388. (setq toggled t))
  19389. (forward-line)))
  19390. ;; Case 3. Started at normal text: make every line an heading,
  19391. ;; skipping headlines and items.
  19392. (t (let* ((stars
  19393. (make-string
  19394. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19395. (add-stars
  19396. (cond (nstars "") ; stars from prefix only
  19397. ((equal stars "") "*") ; before first heading
  19398. (org-odd-levels-only "**") ; inside heading, odd
  19399. (t "*"))) ; inside heading, oddeven
  19400. (rpl (concat stars add-stars " "))
  19401. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19402. (while (< (point) (if (equal nstars '(4)) lend end))
  19403. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19404. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19405. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19406. (forward-line)))))))
  19407. (unless toggled (message "Cannot toggle heading from here"))))
  19408. (defun org-meta-return (&optional arg)
  19409. "Insert a new heading or wrap a region in a table.
  19410. Calls `org-insert-heading', `org-insert-item' or
  19411. `org-table-wrap-region', depending on context. When called with
  19412. an argument, unconditionally call `org-insert-heading'."
  19413. (interactive "P")
  19414. (org-check-before-invisible-edit 'insert)
  19415. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19416. (call-interactively (cond (arg #'org-insert-heading)
  19417. ((org-at-table-p) #'org-table-wrap-region)
  19418. ((org-in-item-p) #'org-insert-item)
  19419. (t #'org-insert-heading)))))
  19420. ;;; Menu entries
  19421. (defsubst org-in-subtree-not-table-p ()
  19422. "Are we in a subtree and not in a table?"
  19423. (and (not (org-before-first-heading-p))
  19424. (not (org-at-table-p))))
  19425. ;; Define the Org mode menus
  19426. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19427. '("Tbl"
  19428. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19429. ["Next Field" org-cycle (org-at-table-p)]
  19430. ["Previous Field" org-shifttab (org-at-table-p)]
  19431. ["Next Row" org-return (org-at-table-p)]
  19432. "--"
  19433. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19434. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19435. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19436. "--"
  19437. ("Column"
  19438. ["Move Column Left" org-metaleft (org-at-table-p)]
  19439. ["Move Column Right" org-metaright (org-at-table-p)]
  19440. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19441. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19442. ("Row"
  19443. ["Move Row Up" org-metaup (org-at-table-p)]
  19444. ["Move Row Down" org-metadown (org-at-table-p)]
  19445. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19446. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19447. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19448. "--"
  19449. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19450. ("Rectangle"
  19451. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19452. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19453. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19454. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19455. "--"
  19456. ("Calculate"
  19457. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19458. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19459. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19460. "--"
  19461. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19462. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19463. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19464. "--"
  19465. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19466. "--"
  19467. ["Sum Column/Rectangle" org-table-sum
  19468. (or (org-at-table-p) (org-region-active-p))]
  19469. ["Which Column?" org-table-current-column (org-at-table-p)])
  19470. ["Debug Formulas"
  19471. org-table-toggle-formula-debugger
  19472. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19473. ["Show Col/Row Numbers"
  19474. org-table-toggle-coordinate-overlays
  19475. :style toggle
  19476. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19477. "--"
  19478. ["Create" org-table-create (and (not (org-at-table-p))
  19479. org-enable-table-editor)]
  19480. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19481. ["Import from File" org-table-import (not (org-at-table-p))]
  19482. ["Export to File" org-table-export (org-at-table-p)]
  19483. "--"
  19484. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19485. "--"
  19486. ("Plot"
  19487. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19488. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19489. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19490. '("Org"
  19491. ("Show/Hide"
  19492. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19493. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19494. ["Sparse Tree..." org-sparse-tree t]
  19495. ["Reveal Context" org-reveal t]
  19496. ["Show All" outline-show-all t]
  19497. "--"
  19498. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19499. "--"
  19500. ["New Heading" org-insert-heading t]
  19501. ("Navigate Headings"
  19502. ["Up" outline-up-heading t]
  19503. ["Next" outline-next-visible-heading t]
  19504. ["Previous" outline-previous-visible-heading t]
  19505. ["Next Same Level" outline-forward-same-level t]
  19506. ["Previous Same Level" outline-backward-same-level t]
  19507. "--"
  19508. ["Jump" org-goto t])
  19509. ("Edit Structure"
  19510. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19511. "--"
  19512. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19513. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19514. "--"
  19515. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19516. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19517. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19518. "--"
  19519. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19520. "--"
  19521. ["Copy visible text" org-copy-visible t]
  19522. "--"
  19523. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19524. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19525. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19526. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19527. "--"
  19528. ["Sort Region/Children" org-sort t]
  19529. "--"
  19530. ["Convert to odd levels" org-convert-to-odd-levels t]
  19531. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19532. ("Editing"
  19533. ["Emphasis..." org-emphasize t]
  19534. ["Edit Source Example" org-edit-special t]
  19535. "--"
  19536. ["Footnote new/jump" org-footnote-action t]
  19537. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19538. ("Archive"
  19539. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19540. "--"
  19541. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19542. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19543. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19544. )
  19545. "--"
  19546. ("Hyperlinks"
  19547. ["Store Link (Global)" org-store-link t]
  19548. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19549. ["Insert Link" org-insert-link t]
  19550. ["Follow Link" org-open-at-point t]
  19551. "--"
  19552. ["Next link" org-next-link t]
  19553. ["Previous link" org-previous-link t]
  19554. "--"
  19555. ["Descriptive Links"
  19556. org-toggle-link-display
  19557. :style radio
  19558. :selected org-descriptive-links
  19559. ]
  19560. ["Literal Links"
  19561. org-toggle-link-display
  19562. :style radio
  19563. :selected (not org-descriptive-links)])
  19564. "--"
  19565. ("TODO Lists"
  19566. ["TODO/DONE/-" org-todo t]
  19567. ("Select keyword"
  19568. ["Next keyword" org-shiftright (org-at-heading-p)]
  19569. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19570. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19571. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19572. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19573. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19574. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19575. "--"
  19576. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19577. :selected org-enforce-todo-dependencies :style toggle :active t]
  19578. "Settings for tree at point"
  19579. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19580. :selected (org-entry-get nil "ORDERED")
  19581. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19582. ["Do Children parallel" org-toggle-ordered-property :style radio
  19583. :selected (not (org-entry-get nil "ORDERED"))
  19584. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19585. "--"
  19586. ["Set Priority" org-priority t]
  19587. ["Priority Up" org-shiftup t]
  19588. ["Priority Down" org-shiftdown t]
  19589. "--"
  19590. ["Get news from all feeds" org-feed-update-all t]
  19591. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19592. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19593. ("TAGS and Properties"
  19594. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19595. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19596. "--"
  19597. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19598. ["Column view of properties" org-columns t]
  19599. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19600. ("Dates and Scheduling"
  19601. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19602. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19603. ("Change Date"
  19604. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19605. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19606. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19607. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19608. ["Compute Time Range" org-evaluate-time-range t]
  19609. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19610. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19611. "--"
  19612. ["Custom time format" org-toggle-time-stamp-overlays
  19613. :style radio :selected org-display-custom-times]
  19614. "--"
  19615. ["Goto Calendar" org-goto-calendar t]
  19616. ["Date from Calendar" org-date-from-calendar t]
  19617. "--"
  19618. ["Start/Restart Timer" org-timer-start t]
  19619. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19620. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19621. ["Insert Timer String" org-timer t]
  19622. ["Insert Timer Item" org-timer-item t])
  19623. ("Logging work"
  19624. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19625. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19626. ["Clock out" org-clock-out t]
  19627. ["Clock cancel" org-clock-cancel t]
  19628. "--"
  19629. ["Mark as default task" org-clock-mark-default-task t]
  19630. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19631. ["Goto running clock" org-clock-goto t]
  19632. "--"
  19633. ["Display times" org-clock-display t]
  19634. ["Create clock table" org-clock-report t]
  19635. "--"
  19636. ["Record DONE time"
  19637. (progn (setq org-log-done (not org-log-done))
  19638. (message "Switching to %s will %s record a timestamp"
  19639. (car org-done-keywords)
  19640. (if org-log-done "automatically" "not")))
  19641. :style toggle :selected org-log-done])
  19642. "--"
  19643. ["Agenda Command..." org-agenda t]
  19644. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19645. ("File List for Agenda")
  19646. ("Special views current file"
  19647. ["TODO Tree" org-show-todo-tree t]
  19648. ["Check Deadlines" org-check-deadlines t]
  19649. ["Tags/Property tree" org-match-sparse-tree t])
  19650. "--"
  19651. ["Export/Publish..." org-export-dispatch t]
  19652. ("LaTeX"
  19653. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19654. :selected org-cdlatex-mode]
  19655. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19656. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19657. ["Modify math symbol" org-cdlatex-math-modify
  19658. (org-inside-LaTeX-fragment-p)]
  19659. ["Insert citation" org-reftex-citation t])
  19660. "--"
  19661. ("MobileOrg"
  19662. ["Push Files and Views" org-mobile-push t]
  19663. ["Get Captured and Flagged" org-mobile-pull t]
  19664. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19665. "--"
  19666. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19667. "--"
  19668. ("Documentation"
  19669. ["Show Version" org-version t]
  19670. ["Info Documentation" org-info t])
  19671. ("Customize"
  19672. ["Browse Org Group" org-customize t]
  19673. "--"
  19674. ["Expand This Menu" org-create-customize-menu
  19675. (fboundp 'customize-menu-create)])
  19676. ["Send bug report" org-submit-bug-report t]
  19677. "--"
  19678. ("Refresh/Reload"
  19679. ["Refresh setup current buffer" org-mode-restart t]
  19680. ["Reload Org (after update)" org-reload t]
  19681. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19682. ))
  19683. (defun org-info (&optional node)
  19684. "Read documentation for Org in the info system.
  19685. With optional NODE, go directly to that node."
  19686. (interactive)
  19687. (info (format "(org)%s" (or node ""))))
  19688. ;;;###autoload
  19689. (defun org-submit-bug-report ()
  19690. "Submit a bug report on Org via mail.
  19691. Don't hesitate to report any problems or inaccurate documentation.
  19692. If you don't have setup sending mail from (X)Emacs, please copy the
  19693. output buffer into your mail program, as it gives us important
  19694. information about your Org version and configuration."
  19695. (interactive)
  19696. (require 'reporter)
  19697. (defvar reporter-prompt-for-summary-p)
  19698. (org-load-modules-maybe)
  19699. (org-require-autoloaded-modules)
  19700. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19701. (reporter-submit-bug-report
  19702. "emacs-orgmode@gnu.org"
  19703. (org-version nil 'full)
  19704. (let (list)
  19705. (save-window-excursion
  19706. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19707. (delete-other-windows)
  19708. (erase-buffer)
  19709. (insert "You are about to submit a bug report to the Org mailing list.
  19710. We would like to add your full Org and Outline configuration to the
  19711. bug report. This greatly simplifies the work of the maintainer and
  19712. other experts on the mailing list.
  19713. HOWEVER, some variables you have customized may contain private
  19714. information. The names of customers, colleagues, or friends, might
  19715. appear in the form of file names, tags, todo states, or search strings.
  19716. If you answer yes to the prompt, you might want to check and remove
  19717. such private information before sending the email.")
  19718. (add-text-properties (point-min) (point-max) '(face org-warning))
  19719. (when (yes-or-no-p "Include your Org configuration ")
  19720. (mapatoms
  19721. (lambda (v)
  19722. (and (boundp v)
  19723. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19724. (or (and (symbol-value v)
  19725. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19726. (and
  19727. (get v 'custom-type) (get v 'standard-value)
  19728. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19729. (push v list)))))
  19730. (kill-buffer (get-buffer "*Warn about privacy*"))
  19731. list))
  19732. nil nil
  19733. "Remember to cover the basics, that is, what you expected to happen and
  19734. what in fact did happen. You don't know how to make a good report? See
  19735. http://orgmode.org/manual/Feedback.html#Feedback
  19736. Your bug report will be posted to the Org mailing list.
  19737. ------------------------------------------------------------------------")
  19738. (save-excursion
  19739. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19740. (replace-match "\\1Bug: \\3 [\\2]")))))
  19741. (defun org-install-agenda-files-menu ()
  19742. (let ((bl (buffer-list)))
  19743. (save-excursion
  19744. (while bl
  19745. (set-buffer (pop bl))
  19746. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19747. (when (derived-mode-p 'org-mode)
  19748. (easy-menu-change
  19749. '("Org") "File List for Agenda"
  19750. (append
  19751. (list
  19752. ["Edit File List" (org-edit-agenda-file-list) t]
  19753. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19754. ["Remove Current File from List" org-remove-file t]
  19755. ["Cycle through agenda files" org-cycle-agenda-files t]
  19756. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19757. "--")
  19758. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19759. ;;;; Documentation
  19760. (defun org-require-autoloaded-modules ()
  19761. (interactive)
  19762. (mapc #'require
  19763. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19764. org-table org-timer)))
  19765. ;;;###autoload
  19766. (defun org-reload (&optional uncompiled)
  19767. "Reload all org lisp files.
  19768. With prefix arg UNCOMPILED, load the uncompiled versions."
  19769. (interactive "P")
  19770. (require 'loadhist)
  19771. (let* ((org-dir (org-find-library-dir "org"))
  19772. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19773. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19774. (remove-re (format "\\`%s\\'"
  19775. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19776. (feats (delete-dups
  19777. (mapcar 'file-name-sans-extension
  19778. (mapcar 'file-name-nondirectory
  19779. (delq nil
  19780. (mapcar 'feature-file
  19781. features))))))
  19782. (lfeat (append
  19783. (sort
  19784. (setq feats
  19785. (delq nil (mapcar
  19786. (lambda (f)
  19787. (if (and (string-match feature-re f)
  19788. (not (string-match remove-re f)))
  19789. f nil))
  19790. feats)))
  19791. 'string-lessp)
  19792. (list "org-version" "org")))
  19793. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19794. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19795. load-uncore load-misses)
  19796. (setq load-misses
  19797. (delq 't
  19798. (mapcar (lambda (f)
  19799. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19800. (and (string= org-dir contrib-dir)
  19801. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19802. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19803. (add-to-list 'load-uncore f 'append)
  19804. 't)
  19805. f))
  19806. lfeat)))
  19807. (when load-uncore
  19808. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19809. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19810. (if load-misses
  19811. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19812. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19813. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19814. ;;;###autoload
  19815. (defun org-customize ()
  19816. "Call the customize function with org as argument."
  19817. (interactive)
  19818. (org-load-modules-maybe)
  19819. (org-require-autoloaded-modules)
  19820. (customize-browse 'org))
  19821. (defun org-create-customize-menu ()
  19822. "Create a full customization menu for Org mode, insert it into the menu."
  19823. (interactive)
  19824. (org-load-modules-maybe)
  19825. (org-require-autoloaded-modules)
  19826. (if (fboundp 'customize-menu-create)
  19827. (progn
  19828. (easy-menu-change
  19829. '("Org") "Customize"
  19830. `(["Browse Org group" org-customize t]
  19831. "--"
  19832. ,(customize-menu-create 'org)
  19833. ["Set" Custom-set t]
  19834. ["Save" Custom-save t]
  19835. ["Reset to Current" Custom-reset-current t]
  19836. ["Reset to Saved" Custom-reset-saved t]
  19837. ["Reset to Standard Settings" Custom-reset-standard t]))
  19838. (message "\"Org\"-menu now contains full customization menu"))
  19839. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19840. ;;;; Miscellaneous stuff
  19841. ;;; Generally useful functions
  19842. (defun org-get-at-eol (property n)
  19843. "Get text property PROPERTY at the end of line less N characters."
  19844. (get-text-property (- (point-at-eol) n) property))
  19845. (defun org-find-text-property-in-string (prop s)
  19846. "Return the first non-nil value of property PROP in string S."
  19847. (or (get-text-property 0 prop s)
  19848. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19849. prop s)))
  19850. (defun org-display-warning (message)
  19851. "Display the given MESSAGE as a warning."
  19852. (display-warning 'org message :warning))
  19853. (defun org-eval (form)
  19854. "Eval FORM and return result."
  19855. (condition-case error
  19856. (eval form)
  19857. (error (format "%%![Error: %s]" error))))
  19858. (defun org-in-clocktable-p ()
  19859. "Check if the cursor is in a clocktable."
  19860. (let ((pos (point)) start)
  19861. (save-excursion
  19862. (end-of-line 1)
  19863. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19864. (setq start (match-beginning 0))
  19865. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19866. (>= (match-end 0) pos)
  19867. start))))
  19868. (defun org-in-verbatim-emphasis ()
  19869. (save-match-data
  19870. (and (org-in-regexp org-verbatim-re 2)
  19871. (>= (point) (match-beginning 3))
  19872. (<= (point) (match-end 4)))))
  19873. (defun org-overlay-display (ovl text &optional face evap)
  19874. "Make overlay OVL display TEXT with face FACE."
  19875. (overlay-put ovl 'display text)
  19876. (if face (overlay-put ovl 'face face))
  19877. (if evap (overlay-put ovl 'evaporate t)))
  19878. (defun org-overlay-before-string (ovl text &optional face evap)
  19879. "Make overlay OVL display TEXT with face FACE."
  19880. (if face (org-add-props text nil 'face face))
  19881. (overlay-put ovl 'before-string text)
  19882. (if evap (overlay-put ovl 'evaporate t)))
  19883. (defun org-find-overlays (prop &optional pos delete)
  19884. "Find all overlays specifying PROP at POS or point.
  19885. If DELETE is non-nil, delete all those overlays."
  19886. (let (found)
  19887. (dolist (ov (overlays-at (or pos (point))) found)
  19888. (cond ((not (overlay-get ov prop)))
  19889. (delete (delete-overlay ov))
  19890. (t (push ov found))))))
  19891. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19892. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19893. (if (and marker (marker-buffer marker)
  19894. (buffer-live-p (marker-buffer marker)))
  19895. (progn
  19896. (pop-to-buffer-same-window (marker-buffer marker))
  19897. (when (or (> marker (point-max)) (< marker (point-min)))
  19898. (widen))
  19899. (goto-char marker)
  19900. (org-show-context 'org-goto))
  19901. (if bookmark
  19902. (bookmark-jump bookmark)
  19903. (error "Cannot find location"))))
  19904. (defun org-quote-csv-field (s)
  19905. "Quote field for inclusion in CSV material."
  19906. (if (string-match "[\",]" s)
  19907. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19908. s))
  19909. (defun org-force-self-insert (N)
  19910. "Needed to enforce self-insert under remapping."
  19911. (interactive "p")
  19912. (self-insert-command N))
  19913. (defun org-shorten-string (s maxlength)
  19914. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19915. If the string is shorter or has length MAXLENGTH, just return the
  19916. original string. If it is longer, the functions finds a space in the
  19917. string, breaks this string off at that locations and adds three dots
  19918. as ellipsis. Including the ellipsis, the string will not be longer
  19919. than MAXLENGTH. If finding a good breaking point in the string does
  19920. not work, the string is just chopped off in the middle of a word
  19921. if necessary."
  19922. (if (<= (length s) maxlength)
  19923. s
  19924. (let* ((n (max (- maxlength 4) 1))
  19925. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19926. (if (string-match re s)
  19927. (concat (match-string 1 s) "...")
  19928. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19929. (defun org-get-indentation (&optional line)
  19930. "Get the indentation of the current line, interpreting tabs.
  19931. When LINE is given, assume it represents a line and compute its indentation."
  19932. (if line
  19933. (when (string-match "^ *" (org-remove-tabs line))
  19934. (match-end 0))
  19935. (save-excursion
  19936. (beginning-of-line 1)
  19937. (skip-chars-forward " \t")
  19938. (current-column))))
  19939. (defun org-get-string-indentation (s)
  19940. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19941. (let ((n -1) (i 0) (w tab-width) c)
  19942. (catch 'exit
  19943. (while (< (setq n (1+ n)) (length s))
  19944. (setq c (aref s n))
  19945. (cond ((= c ?\ ) (setq i (1+ i)))
  19946. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19947. (t (throw 'exit t)))))
  19948. i))
  19949. (defun org-remove-tabs (s &optional width)
  19950. "Replace tabulators in S with spaces.
  19951. Assumes that s is a single line, starting in column 0."
  19952. (setq width (or width tab-width))
  19953. (while (string-match "\t" s)
  19954. (setq s (replace-match
  19955. (make-string
  19956. (- (* width (/ (+ (match-beginning 0) width) width))
  19957. (match-beginning 0)) ?\ )
  19958. t t s)))
  19959. s)
  19960. (defun org-fix-indentation (line ind)
  19961. "Fix indentation in LINE.
  19962. IND is a cons cell with target and minimum indentation.
  19963. If the current indentation in LINE is smaller than the minimum,
  19964. leave it alone. If it is larger than ind, set it to the target."
  19965. (let* ((l (org-remove-tabs line))
  19966. (i (org-get-indentation l))
  19967. (i1 (car ind)) (i2 (cdr ind)))
  19968. (when (>= i i2) (setq l (substring line i2)))
  19969. (if (> i1 0)
  19970. (concat (make-string i1 ?\ ) l)
  19971. l)))
  19972. (defun org-remove-indentation (code &optional n)
  19973. "Remove maximum common indentation in string CODE and return it.
  19974. N may optionally be the number of columns to remove. Return CODE
  19975. as-is if removal failed."
  19976. (with-temp-buffer
  19977. (insert code)
  19978. (if (org-do-remove-indentation n) (buffer-string) code)))
  19979. (defun org-do-remove-indentation (&optional n)
  19980. "Remove the maximum common indentation from the buffer.
  19981. When optional argument N is a positive integer, remove exactly
  19982. that much characters from indentation, if possible. Return nil
  19983. if it fails."
  19984. (catch :exit
  19985. (goto-char (point-min))
  19986. ;; Find maximum common indentation, if not specified.
  19987. (let ((n (or n
  19988. (let ((min-ind (point-max)))
  19989. (save-excursion
  19990. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19991. (let ((ind (1- (current-column))))
  19992. (if (zerop ind) (throw :exit nil)
  19993. (setq min-ind (min min-ind ind))))))
  19994. min-ind))))
  19995. (if (zerop n) (throw :exit nil)
  19996. ;; Remove exactly N indentation, but give up if not possible.
  19997. (while (not (eobp))
  19998. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  19999. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20000. ((< ind n) (throw :exit nil))
  20001. (t (indent-line-to (- ind n))))
  20002. (forward-line)))
  20003. ;; Signal success.
  20004. t))))
  20005. (defun org-fill-template (template alist)
  20006. "Find each %key of ALIST in TEMPLATE and replace it."
  20007. (let ((case-fold-search nil))
  20008. (dolist (entry (sort (copy-sequence alist)
  20009. (lambda (a b) (< (length (car a)) (length (car b))))))
  20010. (setq template
  20011. (replace-regexp-in-string
  20012. (concat "%" (regexp-quote (car entry)))
  20013. (or (cdr entry) "") template t t)))
  20014. template))
  20015. (defun org-base-buffer (buffer)
  20016. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20017. (if (not buffer)
  20018. buffer
  20019. (or (buffer-base-buffer buffer)
  20020. buffer)))
  20021. (defun org-wrap (string &optional width lines)
  20022. "Wrap string to either a number of lines, or a width in characters.
  20023. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20024. that costs. If there is a word longer than WIDTH, the text is actually
  20025. wrapped to the length of that word.
  20026. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20027. many lines, whatever width that takes.
  20028. The return value is a list of lines, without newlines at the end."
  20029. (let* ((words (org-split-string string "[ \t\n]+"))
  20030. (maxword (apply 'max (mapcar 'org-string-width words)))
  20031. w ll)
  20032. (cond (width
  20033. (org-do-wrap words (max maxword width)))
  20034. (lines
  20035. (setq w maxword)
  20036. (setq ll (org-do-wrap words maxword))
  20037. (if (<= (length ll) lines)
  20038. ll
  20039. (setq ll words)
  20040. (while (> (length ll) lines)
  20041. (setq w (1+ w))
  20042. (setq ll (org-do-wrap words w)))
  20043. ll))
  20044. (t (error "Cannot wrap this")))))
  20045. (defun org-do-wrap (words width)
  20046. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20047. (let (lines line)
  20048. (while words
  20049. (setq line (pop words))
  20050. (while (and words (< (+ (length line) (length (car words))) width))
  20051. (setq line (concat line " " (pop words))))
  20052. (setq lines (push line lines)))
  20053. (nreverse lines)))
  20054. (defun org-quote-vert (s)
  20055. "Replace \"|\" with \"\\vert\"."
  20056. (while (string-match "|" s)
  20057. (setq s (replace-match "\\vert" t t s)))
  20058. s)
  20059. (defun org-uuidgen-p (s)
  20060. "Is S an ID created by UUIDGEN?"
  20061. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20062. (defun org-in-src-block-p (&optional inside)
  20063. "Whether point is in a code source block.
  20064. When INSIDE is non-nil, don't consider we are within a src block
  20065. when point is at #+BEGIN_SRC or #+END_SRC."
  20066. (let ((case-fold-search t))
  20067. (or (and (eq (get-char-property (point) 'src-block) t))
  20068. (and (not inside)
  20069. (save-match-data
  20070. (save-excursion
  20071. (beginning-of-line)
  20072. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20073. (defun org-context ()
  20074. "Return a list of contexts of the current cursor position.
  20075. If several contexts apply, all are returned.
  20076. Each context entry is a list with a symbol naming the context, and
  20077. two positions indicating start and end of the context. Possible
  20078. contexts are:
  20079. :headline anywhere in a headline
  20080. :headline-stars on the leading stars in a headline
  20081. :todo-keyword on a TODO keyword (including DONE) in a headline
  20082. :tags on the TAGS in a headline
  20083. :priority on the priority cookie in a headline
  20084. :item on the first line of a plain list item
  20085. :item-bullet on the bullet/number of a plain list item
  20086. :checkbox on the checkbox in a plain list item
  20087. :table in an Org table
  20088. :table-special on a special filed in a table
  20089. :table-table in a table.el table
  20090. :clocktable in a clocktable
  20091. :src-block in a source block
  20092. :link on a hyperlink
  20093. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20094. :target on a <<target>>
  20095. :radio-target on a <<<radio-target>>>
  20096. :latex-fragment on a LaTeX fragment
  20097. :latex-preview on a LaTeX fragment with overlaid preview image
  20098. This function expects the position to be visible because it uses font-lock
  20099. faces as a help to recognize the following contexts: :table-special, :link,
  20100. and :keyword."
  20101. (let* ((f (get-text-property (point) 'face))
  20102. (faces (if (listp f) f (list f)))
  20103. (case-fold-search t)
  20104. (p (point)) clist o)
  20105. ;; First the large context
  20106. (cond
  20107. ((org-at-heading-p t)
  20108. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20109. (when (progn
  20110. (beginning-of-line 1)
  20111. (looking-at org-todo-line-tags-regexp))
  20112. (push (org-point-in-group p 1 :headline-stars) clist)
  20113. (push (org-point-in-group p 2 :todo-keyword) clist)
  20114. (push (org-point-in-group p 4 :tags) clist))
  20115. (goto-char p)
  20116. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20117. (when (looking-at "\\[#[A-Z0-9]\\]")
  20118. (push (org-point-in-group p 0 :priority) clist)))
  20119. ((org-at-item-p)
  20120. (push (org-point-in-group p 2 :item-bullet) clist)
  20121. (push (list :item (point-at-bol)
  20122. (save-excursion (org-end-of-item) (point)))
  20123. clist)
  20124. (and (org-at-item-checkbox-p)
  20125. (push (org-point-in-group p 0 :checkbox) clist)))
  20126. ((org-at-table-p)
  20127. (push (list :table (org-table-begin) (org-table-end)) clist)
  20128. (when (memq 'org-formula faces)
  20129. (push (list :table-special
  20130. (previous-single-property-change p 'face)
  20131. (next-single-property-change p 'face)) clist)))
  20132. ((org-at-table-p 'any)
  20133. (push (list :table-table) clist)))
  20134. (goto-char p)
  20135. (let ((case-fold-search t))
  20136. ;; New the "medium" contexts: clocktables, source blocks
  20137. (cond ((org-in-clocktable-p)
  20138. (push (list :clocktable
  20139. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20140. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20141. (match-beginning 1))
  20142. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20143. (match-end 0))) clist))
  20144. ((org-in-src-block-p)
  20145. (push (list :src-block
  20146. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20147. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20148. (match-beginning 1))
  20149. (and (search-forward "#+END_SRC" nil t)
  20150. (match-beginning 0))) clist))))
  20151. (goto-char p)
  20152. ;; Now the small context
  20153. (cond
  20154. ((org-at-timestamp-p)
  20155. (push (org-point-in-group p 0 :timestamp) clist))
  20156. ((memq 'org-link faces)
  20157. (push (list :link
  20158. (previous-single-property-change p 'face)
  20159. (next-single-property-change p 'face)) clist))
  20160. ((memq 'org-special-keyword faces)
  20161. (push (list :keyword
  20162. (previous-single-property-change p 'face)
  20163. (next-single-property-change p 'face)) clist))
  20164. ((org-at-target-p)
  20165. (push (org-point-in-group p 0 :target) clist)
  20166. (goto-char (1- (match-beginning 0)))
  20167. (when (looking-at org-radio-target-regexp)
  20168. (push (org-point-in-group p 0 :radio-target) clist))
  20169. (goto-char p))
  20170. ((setq o (cl-some
  20171. (lambda (o)
  20172. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20173. o))
  20174. (overlays-at (point))))
  20175. (push (list :latex-fragment
  20176. (overlay-start o) (overlay-end o)) clist)
  20177. (push (list :latex-preview
  20178. (overlay-start o) (overlay-end o)) clist))
  20179. ((org-inside-LaTeX-fragment-p)
  20180. ;; FIXME: positions wrong.
  20181. (push (list :latex-fragment (point) (point)) clist)))
  20182. (setq clist (nreverse (delq nil clist)))
  20183. clist))
  20184. (defun org-in-regexp (regexp &optional nlines visually)
  20185. "Check if point is inside a match of REGEXP.
  20186. Normally only the current line is checked, but you can include
  20187. NLINES extra lines around point into the search. If VISUALLY is
  20188. set, require that the cursor is not after the match but really
  20189. on, so that the block visually is on the match.
  20190. Return nil or a cons cell (BEG . END) where BEG and END are,
  20191. respectively, the positions at the beginning and the end of the
  20192. match."
  20193. (catch :exit
  20194. (let ((pos (point))
  20195. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20196. (save-excursion
  20197. (beginning-of-line (- 1 (or nlines 0)))
  20198. (while (and (re-search-forward regexp eol t)
  20199. (<= (match-beginning 0) pos))
  20200. (let ((end (match-end 0)))
  20201. (when (or (> end pos) (and (= end pos) (not visually)))
  20202. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20203. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20204. "Non-nil when point is between matches of START-RE and END-RE.
  20205. Also return a non-nil value when point is on one of the matches.
  20206. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20207. buffer positions. Default values are the positions of headlines
  20208. surrounding the point.
  20209. The functions returns a cons cell whose car (resp. cdr) is the
  20210. position before START-RE (resp. after END-RE)."
  20211. (save-match-data
  20212. (let ((pos (point))
  20213. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20214. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20215. beg end)
  20216. (save-excursion
  20217. ;; Point is on a block when on START-RE or if START-RE can be
  20218. ;; found before it...
  20219. (and (or (org-in-regexp start-re)
  20220. (re-search-backward start-re limit-up t))
  20221. (setq beg (match-beginning 0))
  20222. ;; ... and END-RE after it...
  20223. (goto-char (match-end 0))
  20224. (re-search-forward end-re limit-down t)
  20225. (> (setq end (match-end 0)) pos)
  20226. ;; ... without another START-RE in-between.
  20227. (goto-char (match-beginning 0))
  20228. (not (re-search-backward start-re (1+ beg) t))
  20229. ;; Return value.
  20230. (cons beg end))))))
  20231. (defun org-in-block-p (names)
  20232. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20233. NAMES is a list of strings containing names of blocks.
  20234. Return first block name matched, or nil. Beware that in case of
  20235. nested blocks, the returned name may not belong to the closest
  20236. block from point."
  20237. (save-match-data
  20238. (catch 'exit
  20239. (let ((case-fold-search t)
  20240. (lim-up (save-excursion (outline-previous-heading)))
  20241. (lim-down (save-excursion (outline-next-heading))))
  20242. (dolist (name names)
  20243. (let ((n (regexp-quote name)))
  20244. (when (org-between-regexps-p
  20245. (concat "^[ \t]*#\\+begin_" n)
  20246. (concat "^[ \t]*#\\+end_" n)
  20247. lim-up lim-down)
  20248. (throw 'exit n)))))
  20249. nil)))
  20250. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20251. "Call `multi-occur' with buffers for all agenda files."
  20252. (interactive "sOrg-files matching: ")
  20253. (let* ((files (org-agenda-files))
  20254. (tnames (mapcar #'file-truename files))
  20255. (extra org-agenda-text-search-extra-files))
  20256. (when (eq (car extra) 'agenda-archives)
  20257. (setq extra (cdr extra))
  20258. (setq files (org-add-archive-files files)))
  20259. (dolist (f extra)
  20260. (unless (member (file-truename f) tnames)
  20261. (unless (member f files) (setq files (append files (list f))))
  20262. (setq tnames (append tnames (list (file-truename f))))))
  20263. (multi-occur
  20264. (mapcar (lambda (x)
  20265. (with-current-buffer
  20266. ;; FIXME: Why not just (find-file-noselect x)?
  20267. ;; Is it to avoid the "revert buffer" prompt?
  20268. (or (get-file-buffer x) (find-file-noselect x))
  20269. (widen)
  20270. (current-buffer)))
  20271. files)
  20272. regexp)))
  20273. (add-hook 'occur-mode-find-occurrence-hook
  20274. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20275. (defun org-occur-link-in-agenda-files ()
  20276. "Create a link and search for it in the agendas.
  20277. The link is not stored in `org-stored-links', it is just created
  20278. for the search purpose."
  20279. (interactive)
  20280. (let ((link (condition-case nil
  20281. (org-store-link nil)
  20282. (error "Unable to create a link to here"))))
  20283. (org-occur-in-agenda-files (regexp-quote link))))
  20284. (defun org-reverse-string (string)
  20285. "Return the reverse of STRING."
  20286. (apply 'string (reverse (string-to-list string))))
  20287. ;; defsubst org-uniquify must be defined before first use
  20288. (defun org-uniquify-alist (alist)
  20289. "Merge elements of ALIST with the same key.
  20290. For example, in this alist:
  20291. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20292. => \\='((a 1 3) (b 2))
  20293. merge (a 1) and (a 3) into (a 1 3).
  20294. The function returns the new ALIST."
  20295. (let (rtn)
  20296. (dolist (e alist rtn)
  20297. (let (n)
  20298. (if (not (assoc (car e) rtn))
  20299. (push e rtn)
  20300. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20301. (setq rtn (assq-delete-all (car e) rtn))
  20302. (push n rtn))))))
  20303. (defun org-delete-all (elts list)
  20304. "Remove all elements in ELTS from LIST.
  20305. Comparison is done with `equal'. It is a destructive operation
  20306. that may remove elements by altering the list structure."
  20307. (while elts
  20308. (setq list (delete (pop elts) list)))
  20309. list)
  20310. (defun org-back-over-empty-lines ()
  20311. "Move backwards over whitespace, to the beginning of the first empty line.
  20312. Returns the number of empty lines passed."
  20313. (let ((pos (point)))
  20314. (if (cdr (assq 'heading org-blank-before-new-entry))
  20315. (skip-chars-backward " \t\n\r")
  20316. (unless (eobp)
  20317. (forward-line -1)))
  20318. (beginning-of-line 2)
  20319. (goto-char (min (point) pos))
  20320. (count-lines (point) pos)))
  20321. (defun org-skip-whitespace ()
  20322. (skip-chars-forward " \t\n\r"))
  20323. (defun org-point-in-group (point group &optional context)
  20324. "Check if POINT is in match-group GROUP.
  20325. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20326. match. If the match group does not exist or point is not inside it,
  20327. return nil."
  20328. (and (match-beginning group)
  20329. (>= point (match-beginning group))
  20330. (<= point (match-end group))
  20331. (if context
  20332. (list context (match-beginning group) (match-end group))
  20333. t)))
  20334. (defun org-switch-to-buffer-other-window (&rest args)
  20335. "Switch to buffer in a second window on the current frame.
  20336. In particular, do not allow pop-up frames.
  20337. Returns the newly created buffer."
  20338. (org-no-popups
  20339. (apply 'switch-to-buffer-other-window args)))
  20340. (defun org-combine-plists (&rest plists)
  20341. "Create a single property list from all plists in PLISTS.
  20342. The process starts by copying the first list, and then setting properties
  20343. from the other lists. Settings in the last list are the most significant
  20344. ones and overrule settings in the other lists."
  20345. (let ((rtn (copy-sequence (pop plists)))
  20346. p v ls)
  20347. (while plists
  20348. (setq ls (pop plists))
  20349. (while ls
  20350. (setq p (pop ls) v (pop ls))
  20351. (setq rtn (plist-put rtn p v))))
  20352. rtn))
  20353. (defun org-replace-escapes (string table)
  20354. "Replace %-escapes in STRING with values in TABLE.
  20355. TABLE is an association list with keys like \"%a\" and string values.
  20356. The sequences in STRING may contain normal field width and padding information,
  20357. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20358. so values can contain further %-escapes if they are define later in TABLE."
  20359. (let ((tbl (copy-alist table))
  20360. (case-fold-search nil)
  20361. (pchg 0)
  20362. re rpl)
  20363. (dolist (e tbl)
  20364. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20365. (when (and (cdr e) (string-match re (cdr e)))
  20366. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20367. (safe "SREF"))
  20368. (add-text-properties 0 3 (list 'sref sref) safe)
  20369. (setcdr e (replace-match safe t t (cdr e)))))
  20370. (while (string-match re string)
  20371. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20372. (cdr e)))
  20373. (setq string (replace-match rpl t t string))))
  20374. (while (setq pchg (next-property-change pchg string))
  20375. (let ((sref (get-text-property pchg 'sref string)))
  20376. (when (and sref (string-match "SREF" string pchg))
  20377. (setq string (replace-match sref t t string)))))
  20378. string))
  20379. (defun org-find-base-buffer-visiting (file)
  20380. "Like `find-buffer-visiting' but always return the base buffer and
  20381. not an indirect buffer."
  20382. (let ((buf (or (get-file-buffer file)
  20383. (find-buffer-visiting file))))
  20384. (if buf
  20385. (or (buffer-base-buffer buf) buf)
  20386. nil)))
  20387. ;;; TODO: Only called once, from ox-odt which should probably use
  20388. ;;; org-export-inline-image-p or something.
  20389. (defun org-file-image-p (file)
  20390. "Return non-nil if FILE is an image."
  20391. (save-match-data
  20392. (string-match (image-file-name-regexp) file)))
  20393. (defun org-get-cursor-date (&optional with-time)
  20394. "Return the date at cursor in as a time.
  20395. This works in the calendar and in the agenda, anywhere else it just
  20396. returns the current time.
  20397. If WITH-TIME is non-nil, returns the time of the event at point (in
  20398. the agenda) or the current time of the day."
  20399. (let (date day defd tp hod mod)
  20400. (when with-time
  20401. (setq tp (get-text-property (point) 'time))
  20402. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20403. (setq hod (string-to-number (match-string 1 tp))
  20404. mod (string-to-number (match-string 2 tp))))
  20405. (or tp (let ((now (decode-time)))
  20406. (setq hod (nth 2 now)
  20407. mod (nth 1 now)))))
  20408. (cond
  20409. ((eq major-mode 'calendar-mode)
  20410. (setq date (calendar-cursor-to-date)
  20411. defd (encode-time 0 (or mod 0) (or hod 0)
  20412. (nth 1 date) (nth 0 date) (nth 2 date))))
  20413. ((eq major-mode 'org-agenda-mode)
  20414. (setq day (get-text-property (point) 'day))
  20415. (when day
  20416. (setq date (calendar-gregorian-from-absolute day)
  20417. defd (encode-time 0 (or mod 0) (or hod 0)
  20418. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20419. (or defd (current-time))))
  20420. (defun org-mark-subtree (&optional up)
  20421. "Mark the current subtree.
  20422. This puts point at the start of the current subtree, and mark at
  20423. the end. If a numeric prefix UP is given, move up into the
  20424. hierarchy of headlines by UP levels before marking the subtree."
  20425. (interactive "P")
  20426. (org-with-limited-levels
  20427. (cond ((org-at-heading-p) (beginning-of-line))
  20428. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20429. (t (outline-previous-visible-heading 1))))
  20430. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20431. (if (called-interactively-p 'any)
  20432. (call-interactively 'org-mark-element)
  20433. (org-mark-element)))
  20434. (defun org-file-newer-than-p (file time)
  20435. "Non-nil if FILE is newer than TIME.
  20436. FILE is a filename, as a string, TIME is a list of integers, as
  20437. returned by, e.g., `current-time'."
  20438. (and (file-exists-p file)
  20439. ;; Only compare times up to whole seconds as some file-systems
  20440. ;; (e.g. HFS+) do not retain any finer granularity. As
  20441. ;; a consequence, make sure we return non-nil when the two
  20442. ;; times are equal.
  20443. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20444. (cl-subseq time 0 2)))))
  20445. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20446. "Compile a SOURCE file using PROCESS.
  20447. PROCESS is either a function or a list of shell commands, as
  20448. strings. EXT is a file extension, without the leading dot, as
  20449. a string. It is used to check if the process actually succeeded.
  20450. PROCESS must create a file with the same base name and directory
  20451. as SOURCE, but ending with EXT. The function then returns its
  20452. filename. Otherwise, it raises an error. The error message can
  20453. then be refined by providing string ERR-MSG, which is appended to
  20454. the standard message.
  20455. If PROCESS is a function, it is called with a single argument:
  20456. the SOURCE file.
  20457. If it is a list of commands, each of them is called using
  20458. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20459. %O are replaced with, respectively, SOURCE base name, name, full
  20460. name, directory and absolute output file name. It is possible,
  20461. however, to use more place-holders by specifying them in optional
  20462. argument SPEC, as an alist following the pattern
  20463. (CHARACTER . REPLACEMENT-STRING).
  20464. When PROCESS is a list of commands, optional argument LOG-BUF can
  20465. be set to a buffer or a buffer name. `shell-command' then uses
  20466. it for output."
  20467. (let* ((base-name (file-name-base source))
  20468. (full-name (file-truename source))
  20469. (out-dir (or (file-name-directory source) "./"))
  20470. (output (expand-file-name (concat base-name "." ext) out-dir))
  20471. (time (current-time))
  20472. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20473. (save-window-excursion
  20474. (pcase process
  20475. ((pred functionp) (funcall process (shell-quote-argument source)))
  20476. ((pred consp)
  20477. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20478. (spec (append spec
  20479. `((?b . ,(shell-quote-argument base-name))
  20480. (?f . ,(shell-quote-argument source))
  20481. (?F . ,(shell-quote-argument full-name))
  20482. (?o . ,(shell-quote-argument out-dir))
  20483. (?O . ,(shell-quote-argument output))))))
  20484. (dolist (command process)
  20485. (shell-command (format-spec command spec) log-buf))
  20486. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20487. (_ (error "No valid command to process %S%s" source err-msg))))
  20488. ;; Check for process failure. Output file is expected to be
  20489. ;; located in the same directory as SOURCE.
  20490. (unless (org-file-newer-than-p output time)
  20491. (error (format "File %S wasn't produced%s" output err-msg)))
  20492. output))
  20493. ;;; Indentation
  20494. (defvar org-element-greater-elements)
  20495. (defun org--get-expected-indentation (element contentsp)
  20496. "Expected indentation column for current line, according to ELEMENT.
  20497. ELEMENT is an element containing point. CONTENTSP is non-nil
  20498. when indentation is to be computed according to contents of
  20499. ELEMENT."
  20500. (let ((type (org-element-type element))
  20501. (start (org-element-property :begin element))
  20502. (post-affiliated (org-element-property :post-affiliated element)))
  20503. (org-with-wide-buffer
  20504. (cond
  20505. (contentsp
  20506. (cl-case type
  20507. ((diary-sexp footnote-definition) 0)
  20508. ((headline inlinetask nil)
  20509. (if (not org-adapt-indentation) 0
  20510. (let ((level (org-current-level)))
  20511. (if level (1+ level) 0))))
  20512. ((item plain-list) (org-list-item-body-column post-affiliated))
  20513. (t
  20514. (goto-char start)
  20515. (org-get-indentation))))
  20516. ((memq type '(headline inlinetask nil))
  20517. (if (org-match-line "[ \t]*$")
  20518. (org--get-expected-indentation element t)
  20519. 0))
  20520. ((memq type '(diary-sexp footnote-definition)) 0)
  20521. ;; First paragraph of a footnote definition or an item.
  20522. ;; Indent like parent.
  20523. ((< (line-beginning-position) start)
  20524. (org--get-expected-indentation
  20525. (org-element-property :parent element) t))
  20526. ;; At first line: indent according to previous sibling, if any,
  20527. ;; ignoring footnote definitions and inline tasks, or parent's
  20528. ;; contents.
  20529. ((= (line-beginning-position) start)
  20530. (catch 'exit
  20531. (while t
  20532. (if (= (point-min) start) (throw 'exit 0)
  20533. (goto-char (1- start))
  20534. (let* ((previous (org-element-at-point))
  20535. (parent previous))
  20536. (while (and parent (<= (org-element-property :end parent) start))
  20537. (setq previous parent
  20538. parent (org-element-property :parent parent)))
  20539. (cond
  20540. ((not previous) (throw 'exit 0))
  20541. ((> (org-element-property :end previous) start)
  20542. (throw 'exit (org--get-expected-indentation previous t)))
  20543. ((memq (org-element-type previous)
  20544. '(footnote-definition inlinetask))
  20545. (setq start (org-element-property :begin previous)))
  20546. (t (goto-char (org-element-property :begin previous))
  20547. (throw 'exit
  20548. (if (bolp) (org-get-indentation)
  20549. ;; At first paragraph in an item or
  20550. ;; a footnote definition.
  20551. (org--get-expected-indentation
  20552. (org-element-property :parent previous) t))))))))))
  20553. ;; Otherwise, move to the first non-blank line above.
  20554. (t
  20555. (beginning-of-line)
  20556. (let ((pos (point)))
  20557. (skip-chars-backward " \r\t\n")
  20558. (cond
  20559. ;; Two blank lines end a footnote definition or a plain
  20560. ;; list. When we indent an empty line after them, the
  20561. ;; containing list or footnote definition is over, so it
  20562. ;; qualifies as a previous sibling. Therefore, we indent
  20563. ;; like its first line.
  20564. ((and (memq type '(footnote-definition plain-list))
  20565. (> (count-lines (point) pos) 2))
  20566. (goto-char start)
  20567. (org-get-indentation))
  20568. ;; Line above is the first one of a paragraph at the
  20569. ;; beginning of an item or a footnote definition. Indent
  20570. ;; like parent.
  20571. ((< (line-beginning-position) start)
  20572. (org--get-expected-indentation
  20573. (org-element-property :parent element) t))
  20574. ;; Line above is the beginning of an element, i.e., point
  20575. ;; was originally on the blank lines between element's start
  20576. ;; and contents.
  20577. ((= (line-beginning-position) post-affiliated)
  20578. (org--get-expected-indentation element t))
  20579. ;; POS is after contents in a greater element. Indent like
  20580. ;; the beginning of the element.
  20581. ((and (memq type org-element-greater-elements)
  20582. (let ((cend (org-element-property :contents-end element)))
  20583. (and cend (<= cend pos))))
  20584. ;; As a special case, if point is at the end of a footnote
  20585. ;; definition or an item, indent like the very last element
  20586. ;; within. If that last element is an item, indent like
  20587. ;; its contents.
  20588. (if (memq type '(footnote-definition item plain-list))
  20589. (let ((last (org-element-at-point)))
  20590. (goto-char pos)
  20591. (org--get-expected-indentation
  20592. last (eq (org-element-type last) 'item)))
  20593. (goto-char start)
  20594. (org-get-indentation)))
  20595. ;; In any other case, indent like the current line.
  20596. (t (org-get-indentation)))))))))
  20597. (defun org--align-node-property ()
  20598. "Align node property at point.
  20599. Alignment is done according to `org-property-format', which see."
  20600. (when (save-excursion
  20601. (beginning-of-line)
  20602. (looking-at org-property-re))
  20603. (replace-match
  20604. (concat (match-string 4)
  20605. (org-trim
  20606. (format org-property-format (match-string 1) (match-string 3))))
  20607. t t)))
  20608. (defun org-indent-line ()
  20609. "Indent line depending on context.
  20610. Indentation is done according to the following rules:
  20611. - Footnote definitions, diary sexps, headlines and inline tasks
  20612. have to start at column 0.
  20613. - On the very first line of an element, consider, in order, the
  20614. next rules until one matches:
  20615. 1. If there's a sibling element before, ignoring footnote
  20616. definitions and inline tasks, indent like its first line.
  20617. 2. If element has a parent, indent like its contents. More
  20618. precisely, if parent is an item, indent after the
  20619. description part, if any, or the bullet (see
  20620. `org-list-description-max-indent'). Else, indent like
  20621. parent's first line.
  20622. 3. Otherwise, indent relatively to current level, if
  20623. `org-adapt-indentation' is non-nil, or to left margin.
  20624. - On a blank line at the end of an element, indent according to
  20625. the type of the element. More precisely
  20626. 1. If element is a plain list, an item, or a footnote
  20627. definition, indent like the very last element within.
  20628. 2. If element is a paragraph, indent like its last non blank
  20629. line.
  20630. 3. Otherwise, indent like its very first line.
  20631. - In the code part of a source block, use language major mode
  20632. to indent current line if `org-src-tab-acts-natively' is
  20633. non-nil. If it is nil, do nothing.
  20634. - Otherwise, indent like the first non-blank line above.
  20635. The function doesn't indent an item as it could break the whole
  20636. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20637. `\\[org-shiftmetaright]'.
  20638. Also align node properties according to `org-property-format'."
  20639. (interactive)
  20640. (cond
  20641. (orgstruct-is-++
  20642. (let ((indent-line-function
  20643. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20644. (indent-according-to-mode)))
  20645. ((org-at-heading-p) 'noindent)
  20646. (t
  20647. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20648. (type (org-element-type element)))
  20649. (cond ((and (memq type '(plain-list item))
  20650. (= (line-beginning-position)
  20651. (org-element-property :post-affiliated element)))
  20652. 'noindent)
  20653. ((and (eq type 'latex-environment)
  20654. (>= (point) (org-element-property :post-affiliated element))
  20655. (< (point) (org-with-wide-buffer
  20656. (goto-char (org-element-property :end element))
  20657. (skip-chars-backward " \r\t\n")
  20658. (line-beginning-position 2))))
  20659. 'noindent)
  20660. ((and (eq type 'src-block)
  20661. org-src-tab-acts-natively
  20662. (> (line-beginning-position)
  20663. (org-element-property :post-affiliated element))
  20664. (< (line-beginning-position)
  20665. (org-with-wide-buffer
  20666. (goto-char (org-element-property :end element))
  20667. (skip-chars-backward " \r\t\n")
  20668. (line-beginning-position))))
  20669. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20670. (t
  20671. (let ((column (org--get-expected-indentation element nil)))
  20672. ;; Preserve current column.
  20673. (if (<= (current-column) (current-indentation))
  20674. (indent-line-to column)
  20675. (save-excursion (indent-line-to column))))
  20676. ;; Align node property. Also preserve current column.
  20677. (when (eq type 'node-property)
  20678. (let ((column (current-column)))
  20679. (org--align-node-property)
  20680. (org-move-to-column column)))))))))
  20681. (defun org-indent-region (start end)
  20682. "Indent each non-blank line in the region.
  20683. Called from a program, START and END specify the region to
  20684. indent. The function will not indent contents of example blocks,
  20685. verse blocks and export blocks as leading white spaces are
  20686. assumed to be significant there."
  20687. (interactive "r")
  20688. (save-excursion
  20689. (goto-char start)
  20690. (skip-chars-forward " \r\t\n")
  20691. (unless (eobp) (beginning-of-line))
  20692. (let ((indent-to
  20693. (lambda (ind pos)
  20694. ;; Set IND as indentation for all lines between point and
  20695. ;; POS. Blank lines are ignored. Leave point after POS
  20696. ;; once done.
  20697. (let ((limit (copy-marker pos)))
  20698. (while (< (point) limit)
  20699. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20700. (forward-line))
  20701. (set-marker limit nil))))
  20702. (end (copy-marker end)))
  20703. (while (< (point) end)
  20704. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20705. (let* ((element (org-element-at-point))
  20706. (type (org-element-type element))
  20707. (element-end (copy-marker (org-element-property :end element)))
  20708. (ind (org--get-expected-indentation element nil)))
  20709. (cond
  20710. ;; Element indented as a single block. Example blocks
  20711. ;; preserving indentation are a special case since the
  20712. ;; "contents" must not be indented whereas the block
  20713. ;; boundaries can.
  20714. ((or (memq type '(export-block latex-environment))
  20715. (and (eq type 'example-block)
  20716. (not
  20717. (or org-src-preserve-indentation
  20718. (org-element-property :preserve-indent element)))))
  20719. (let ((offset (- ind (org-get-indentation))))
  20720. (unless (zerop offset)
  20721. (indent-rigidly (org-element-property :begin element)
  20722. (org-element-property :end element)
  20723. offset)))
  20724. (goto-char element-end))
  20725. ;; Elements indented line wise. Be sure to exclude
  20726. ;; example blocks (preserving indentation) and source
  20727. ;; blocks from this category as they are treated
  20728. ;; specially later.
  20729. ((or (memq type '(paragraph table table-row))
  20730. (not (or (org-element-property :contents-begin element)
  20731. (memq type '(example-block src-block)))))
  20732. (when (eq type 'node-property)
  20733. (org--align-node-property)
  20734. (beginning-of-line))
  20735. (funcall indent-to ind (min element-end end)))
  20736. ;; Elements consisting of three parts: before the
  20737. ;; contents, the contents, and after the contents. The
  20738. ;; contents are treated specially, according to the
  20739. ;; element type, or not indented at all. Other parts are
  20740. ;; indented as a single block.
  20741. (t
  20742. (let* ((post (copy-marker
  20743. (org-element-property :post-affiliated element)))
  20744. (cbeg
  20745. (copy-marker
  20746. (cond
  20747. ((not (org-element-property :contents-begin element))
  20748. ;; Fake contents for source blocks.
  20749. (org-with-wide-buffer
  20750. (goto-char post)
  20751. (line-beginning-position 2)))
  20752. ((memq type '(footnote-definition item plain-list))
  20753. ;; Contents in these elements could start on
  20754. ;; the same line as the beginning of the
  20755. ;; element. Make sure we start indenting
  20756. ;; from the second line.
  20757. (org-with-wide-buffer
  20758. (goto-char post)
  20759. (end-of-line)
  20760. (skip-chars-forward " \r\t\n")
  20761. (if (eobp) (point) (line-beginning-position))))
  20762. (t (org-element-property :contents-begin element)))))
  20763. (cend (copy-marker
  20764. (or (org-element-property :contents-end element)
  20765. ;; Fake contents for source blocks.
  20766. (org-with-wide-buffer
  20767. (goto-char element-end)
  20768. (skip-chars-backward " \r\t\n")
  20769. (line-beginning-position)))
  20770. t)))
  20771. ;; Do not change items indentation individually as it
  20772. ;; might break the list as a whole. On the other
  20773. ;; hand, when at a plain list, indent it as a whole.
  20774. (cond ((eq type 'plain-list)
  20775. (let ((offset (- ind (org-get-indentation))))
  20776. (unless (zerop offset)
  20777. (indent-rigidly (org-element-property :begin element)
  20778. (org-element-property :end element)
  20779. offset))
  20780. (goto-char cbeg)))
  20781. ((eq type 'item) (goto-char cbeg))
  20782. (t (funcall indent-to ind (min cbeg end))))
  20783. (when (< (point) end)
  20784. (cl-case type
  20785. ((example-block verse-block))
  20786. (src-block
  20787. ;; In a source block, indent source code
  20788. ;; according to language major mode, but only if
  20789. ;; `org-src-tab-acts-natively' is non-nil.
  20790. (when (and (< (point) end) org-src-tab-acts-natively)
  20791. (ignore-errors
  20792. (org-babel-do-in-edit-buffer
  20793. (indent-region (point-min) (point-max))))))
  20794. (t (org-indent-region (point) (min cend end))))
  20795. (goto-char (min cend end))
  20796. (when (< (point) end)
  20797. (funcall indent-to ind (min element-end end))))
  20798. (set-marker post nil)
  20799. (set-marker cbeg nil)
  20800. (set-marker cend nil))))
  20801. (set-marker element-end nil))))
  20802. (set-marker end nil))))
  20803. (defun org-indent-drawer ()
  20804. "Indent the drawer at point."
  20805. (interactive)
  20806. (unless (save-excursion
  20807. (beginning-of-line)
  20808. (looking-at-p org-drawer-regexp))
  20809. (user-error "Not at a drawer"))
  20810. (let ((element (org-element-at-point)))
  20811. (unless (memq (org-element-type element) '(drawer property-drawer))
  20812. (user-error "Not at a drawer"))
  20813. (org-with-wide-buffer
  20814. (org-indent-region (org-element-property :begin element)
  20815. (org-element-property :end element))))
  20816. (message "Drawer at point indented"))
  20817. (defun org-indent-block ()
  20818. "Indent the block at point."
  20819. (interactive)
  20820. (unless (save-excursion
  20821. (beginning-of-line)
  20822. (let ((case-fold-search t))
  20823. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20824. (user-error "Not at a block"))
  20825. (let ((element (org-element-at-point)))
  20826. (unless (memq (org-element-type element)
  20827. '(comment-block center-block dynamic-block example-block
  20828. export-block quote-block special-block
  20829. src-block verse-block))
  20830. (user-error "Not at a block"))
  20831. (org-with-wide-buffer
  20832. (org-indent-region (org-element-property :begin element)
  20833. (org-element-property :end element))))
  20834. (message "Block at point indented"))
  20835. ;;; Filling
  20836. ;; We use our own fill-paragraph and auto-fill functions.
  20837. ;; `org-fill-paragraph' relies on adaptive filling and context
  20838. ;; checking. Appropriate `fill-prefix' is computed with
  20839. ;; `org-adaptive-fill-function'.
  20840. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20841. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20842. ;; `org-adaptive-fill-function' value. Internally,
  20843. ;; `org-comment-line-break-function' breaks the line.
  20844. ;; `org-setup-filling' installs filling and auto-filling related
  20845. ;; variables during `org-mode' initialization.
  20846. (defvar org-element-paragraph-separate) ; org-element.el
  20847. (defun org-setup-filling ()
  20848. (require 'org-element)
  20849. ;; Prevent auto-fill from inserting unwanted new items.
  20850. (when (boundp 'fill-nobreak-predicate)
  20851. (setq-local
  20852. fill-nobreak-predicate
  20853. (org-uniquify
  20854. (append fill-nobreak-predicate
  20855. '(org-fill-line-break-nobreak-p
  20856. org-fill-n-macro-as-item-nobreak-p
  20857. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20858. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20859. (setq-local paragraph-start paragraph-ending)
  20860. (setq-local paragraph-separate paragraph-ending))
  20861. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20862. (setq-local auto-fill-inhibit-regexp nil)
  20863. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20864. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20865. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20866. (defun org-fill-line-break-nobreak-p ()
  20867. "Non-nil when a new line at point would create an Org line break."
  20868. (save-excursion
  20869. (skip-chars-backward "[ \t]")
  20870. (skip-chars-backward "\\\\")
  20871. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20872. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20873. "Non-nil when a new line at point would split a timestamp."
  20874. (and (org-at-timestamp-p 'lax)
  20875. (not (looking-at org-ts-regexp-both))))
  20876. (defun org-fill-n-macro-as-item-nobreak-p ()
  20877. "Non-nil when a new line at point would create a new list."
  20878. ;; During export, a "n" macro followed by a dot or a closing
  20879. ;; parenthesis can end up being parsed as a new list item.
  20880. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20881. (declare-function message-in-body-p "message" ())
  20882. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20883. (defun org-adaptive-fill-function ()
  20884. "Compute a fill prefix for the current line.
  20885. Return fill prefix, as a string, or nil if current line isn't
  20886. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20887. matches in paragraphs or comments, use it."
  20888. (catch 'exit
  20889. (when (derived-mode-p 'message-mode)
  20890. (save-excursion
  20891. (beginning-of-line)
  20892. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20893. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20894. ((looking-at message-cite-prefix-regexp)
  20895. (throw 'exit (match-string-no-properties 0)))
  20896. ((looking-at org-outline-regexp)
  20897. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20898. (org-with-wide-buffer
  20899. (unless (org-at-heading-p)
  20900. (let* ((p (line-beginning-position))
  20901. (element (save-excursion
  20902. (beginning-of-line)
  20903. (org-element-at-point)))
  20904. (type (org-element-type element))
  20905. (post-affiliated (org-element-property :post-affiliated element)))
  20906. (unless (< p post-affiliated)
  20907. (cl-case type
  20908. (comment
  20909. (save-excursion
  20910. (beginning-of-line)
  20911. (looking-at "[ \t]*")
  20912. (concat (match-string 0) "# ")))
  20913. (footnote-definition "")
  20914. ((item plain-list)
  20915. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20916. (paragraph
  20917. ;; Fill prefix is usually the same as the current line,
  20918. ;; unless the paragraph is at the beginning of an item.
  20919. (let ((parent (org-element-property :parent element)))
  20920. (save-excursion
  20921. (beginning-of-line)
  20922. (cond ((eq (org-element-type parent) 'item)
  20923. (make-string (org-list-item-body-column
  20924. (org-element-property :begin parent))
  20925. ?\s))
  20926. ((and adaptive-fill-regexp
  20927. ;; Locally disable
  20928. ;; `adaptive-fill-function' to let
  20929. ;; `fill-context-prefix' handle
  20930. ;; `adaptive-fill-regexp' variable.
  20931. (let (adaptive-fill-function)
  20932. (fill-context-prefix
  20933. post-affiliated
  20934. (org-element-property :end element)))))
  20935. ((looking-at "[ \t]+") (match-string 0))
  20936. (t "")))))
  20937. (comment-block
  20938. ;; Only fill contents if P is within block boundaries.
  20939. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20940. (forward-line)
  20941. (point)))
  20942. (cend (save-excursion
  20943. (goto-char (org-element-property :end element))
  20944. (skip-chars-backward " \r\t\n")
  20945. (line-beginning-position))))
  20946. (when (and (>= p cbeg) (< p cend))
  20947. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20948. (match-string 0)
  20949. "")))))))))))
  20950. (declare-function message-goto-body "message" ())
  20951. (defvar message-cite-prefix-regexp) ; From message.el
  20952. (defun org-fill-element (&optional justify)
  20953. "Fill element at point, when applicable.
  20954. This function only applies to comment blocks, comments, example
  20955. blocks and paragraphs. Also, as a special case, re-align table
  20956. when point is at one.
  20957. If JUSTIFY is non-nil (interactively, with prefix argument),
  20958. justify as well. If `sentence-end-double-space' is non-nil, then
  20959. period followed by one space does not end a sentence, so don't
  20960. break a line there. The variable `fill-column' controls the
  20961. width for filling.
  20962. For convenience, when point is at a plain list, an item or
  20963. a footnote definition, try to fill the first paragraph within."
  20964. (with-syntax-table org-mode-transpose-word-syntax-table
  20965. ;; Move to end of line in order to get the first paragraph within
  20966. ;; a plain list or a footnote definition.
  20967. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20968. ;; First check if point is in a blank line at the beginning of
  20969. ;; the buffer. In that case, ignore filling.
  20970. (cl-case (org-element-type element)
  20971. ;; Use major mode filling function is src blocks.
  20972. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20973. ;; Align Org tables, leave table.el tables as-is.
  20974. (table-row (org-table-align) t)
  20975. (table
  20976. (when (eq (org-element-property :type element) 'org)
  20977. (save-excursion
  20978. (goto-char (org-element-property :post-affiliated element))
  20979. (org-table-align)))
  20980. t)
  20981. (paragraph
  20982. ;; Paragraphs may contain `line-break' type objects.
  20983. (let ((beg (max (point-min)
  20984. (org-element-property :contents-begin element)))
  20985. (end (min (point-max)
  20986. (org-element-property :contents-end element))))
  20987. ;; Do nothing if point is at an affiliated keyword.
  20988. (if (< (line-end-position) beg) t
  20989. (when (derived-mode-p 'message-mode)
  20990. ;; In `message-mode', do not fill following citation
  20991. ;; in current paragraph nor text before message body.
  20992. (let ((body-start (save-excursion (message-goto-body))))
  20993. (when body-start (setq beg (max body-start beg))))
  20994. (when (save-excursion
  20995. (re-search-forward
  20996. (concat "^" message-cite-prefix-regexp) end t))
  20997. (setq end (match-beginning 0))))
  20998. ;; Fill paragraph, taking line breaks into account.
  20999. (save-excursion
  21000. (goto-char beg)
  21001. (let ((cuts (list beg)))
  21002. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21003. (when (eq 'line-break
  21004. (org-element-type
  21005. (save-excursion (backward-char)
  21006. (org-element-context))))
  21007. (push (point) cuts)))
  21008. (dolist (c (delq end cuts))
  21009. (fill-region-as-paragraph c end justify)
  21010. (setq end c))))
  21011. t)))
  21012. ;; Contents of `comment-block' type elements should be
  21013. ;; filled as plain text, but only if point is within block
  21014. ;; markers.
  21015. (comment-block
  21016. (let* ((case-fold-search t)
  21017. (beg (save-excursion
  21018. (goto-char (org-element-property :begin element))
  21019. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21020. (forward-line)
  21021. (point)))
  21022. (end (save-excursion
  21023. (goto-char (org-element-property :end element))
  21024. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21025. (line-beginning-position))))
  21026. (if (or (< (point) beg) (> (point) end)) t
  21027. (fill-region-as-paragraph
  21028. (save-excursion (end-of-line)
  21029. (re-search-backward "^[ \t]*$" beg 'move)
  21030. (line-beginning-position))
  21031. (save-excursion (beginning-of-line)
  21032. (re-search-forward "^[ \t]*$" end 'move)
  21033. (line-beginning-position))
  21034. justify))))
  21035. ;; Fill comments.
  21036. (comment
  21037. (let ((begin (org-element-property :post-affiliated element))
  21038. (end (org-element-property :end element)))
  21039. (when (and (>= (point) begin) (<= (point) end))
  21040. (let ((begin (save-excursion
  21041. (end-of-line)
  21042. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21043. (progn (forward-line) (point))
  21044. begin)))
  21045. (end (save-excursion
  21046. (end-of-line)
  21047. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21048. (1- (line-beginning-position))
  21049. (skip-chars-backward " \r\t\n")
  21050. (line-end-position)))))
  21051. ;; Do not fill comments when at a blank line.
  21052. (when (> end begin)
  21053. (let ((fill-prefix
  21054. (save-excursion
  21055. (beginning-of-line)
  21056. (looking-at "[ \t]*#")
  21057. (let ((comment-prefix (match-string 0)))
  21058. (goto-char (match-end 0))
  21059. (if (looking-at adaptive-fill-regexp)
  21060. (concat comment-prefix (match-string 0))
  21061. (concat comment-prefix " "))))))
  21062. (save-excursion
  21063. (fill-region-as-paragraph begin end justify))))))
  21064. t))
  21065. ;; Ignore every other element.
  21066. (otherwise t)))))
  21067. (defun org-fill-paragraph (&optional justify region)
  21068. "Fill element at point, when applicable.
  21069. This function only applies to comment blocks, comments, example
  21070. blocks and paragraphs. Also, as a special case, re-align table
  21071. when point is at one.
  21072. For convenience, when point is at a plain list, an item or
  21073. a footnote definition, try to fill the first paragraph within.
  21074. If JUSTIFY is non-nil (interactively, with prefix argument),
  21075. justify as well. If `sentence-end-double-space' is non-nil, then
  21076. period followed by one space does not end a sentence, so don't
  21077. break a line there. The variable `fill-column' controls the
  21078. width for filling.
  21079. The REGION argument is non-nil if called interactively; in that
  21080. case, if Transient Mark mode is enabled and the mark is active,
  21081. fill each of the elements in the active region, instead of just
  21082. filling the current element."
  21083. (interactive (progn
  21084. (barf-if-buffer-read-only)
  21085. (list (if current-prefix-arg 'full) t)))
  21086. (cond
  21087. ((and (derived-mode-p 'message-mode)
  21088. (or (not (message-in-body-p))
  21089. (save-excursion (move-beginning-of-line 1)
  21090. (looking-at message-cite-prefix-regexp))))
  21091. ;; First ensure filling is correct in message-mode.
  21092. (let ((fill-paragraph-function
  21093. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21094. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21095. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21096. (paragraph-separate
  21097. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21098. (fill-paragraph nil)))
  21099. ((and region transient-mark-mode mark-active
  21100. (not (eq (region-beginning) (region-end))))
  21101. (let ((origin (point-marker))
  21102. (start (region-beginning)))
  21103. (unwind-protect
  21104. (progn
  21105. (goto-char (region-end))
  21106. (while (> (point) start)
  21107. (org-backward-paragraph)
  21108. (org-fill-element justify)))
  21109. (goto-char origin)
  21110. (set-marker origin nil))))
  21111. (t (org-fill-element justify))))
  21112. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21113. (defun org-auto-fill-function ()
  21114. "Auto-fill function."
  21115. ;; Check if auto-filling is meaningful.
  21116. (let ((fc (current-fill-column)))
  21117. (when (and fc (> (current-column) fc))
  21118. (let* ((fill-prefix (org-adaptive-fill-function))
  21119. ;; Enforce empty fill prefix, if required. Otherwise, it
  21120. ;; will be computed again.
  21121. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21122. (when fill-prefix (do-auto-fill))))))
  21123. (defun org-comment-line-break-function (&optional soft)
  21124. "Break line at point and indent, continuing comment if within one.
  21125. The inserted newline is marked hard if variable
  21126. `use-hard-newlines' is true, unless optional argument SOFT is
  21127. non-nil."
  21128. (if soft (insert-and-inherit ?\n) (newline 1))
  21129. (save-excursion (forward-char -1) (delete-horizontal-space))
  21130. (delete-horizontal-space)
  21131. (indent-to-left-margin)
  21132. (insert-before-markers-and-inherit fill-prefix))
  21133. ;;; Fixed Width Areas
  21134. (defun org-toggle-fixed-width ()
  21135. "Toggle fixed-width markup.
  21136. Add or remove fixed-width markup on current line, whenever it
  21137. makes sense. Return an error otherwise.
  21138. If a region is active and if it contains only fixed-width areas
  21139. or blank lines, remove all fixed-width markup in it. If the
  21140. region contains anything else, convert all non-fixed-width lines
  21141. to fixed-width ones.
  21142. Blank lines at the end of the region are ignored unless the
  21143. region only contains such lines."
  21144. (interactive)
  21145. (if (not (org-region-active-p))
  21146. ;; No region:
  21147. ;;
  21148. ;; Remove fixed width marker only in a fixed-with element.
  21149. ;;
  21150. ;; Add fixed width maker in paragraphs, in blank lines after
  21151. ;; elements or at the beginning of a headline or an inlinetask,
  21152. ;; and before any one-line elements (e.g., a clock).
  21153. (progn
  21154. (beginning-of-line)
  21155. (let* ((element (org-element-at-point))
  21156. (type (org-element-type element)))
  21157. (cond
  21158. ((and (eq type 'fixed-width)
  21159. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21160. (replace-match
  21161. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21162. ((and (memq type '(babel-call clock comment diary-sexp headline
  21163. horizontal-rule keyword paragraph
  21164. planning))
  21165. (<= (org-element-property :post-affiliated element) (point)))
  21166. (skip-chars-forward " \t")
  21167. (insert ": "))
  21168. ((and (looking-at-p "[ \t]*$")
  21169. (or (eq type 'inlinetask)
  21170. (save-excursion
  21171. (skip-chars-forward " \r\t\n")
  21172. (<= (org-element-property :end element) (point)))))
  21173. (delete-region (point) (line-end-position))
  21174. (org-indent-line)
  21175. (insert ": "))
  21176. (t (user-error "Cannot insert a fixed-width line here")))))
  21177. ;; Region active.
  21178. (let* ((begin (save-excursion
  21179. (goto-char (region-beginning))
  21180. (line-beginning-position)))
  21181. (end (copy-marker
  21182. (save-excursion
  21183. (goto-char (region-end))
  21184. (unless (eolp) (beginning-of-line))
  21185. (if (save-excursion (re-search-backward "\\S-" begin t))
  21186. (progn (skip-chars-backward " \r\t\n") (point))
  21187. (point)))))
  21188. (all-fixed-width-p
  21189. (catch 'not-all-p
  21190. (save-excursion
  21191. (goto-char begin)
  21192. (skip-chars-forward " \r\t\n")
  21193. (when (eobp) (throw 'not-all-p nil))
  21194. (while (< (point) end)
  21195. (let ((element (org-element-at-point)))
  21196. (if (eq (org-element-type element) 'fixed-width)
  21197. (goto-char (org-element-property :end element))
  21198. (throw 'not-all-p nil))))
  21199. t))))
  21200. (if all-fixed-width-p
  21201. (save-excursion
  21202. (goto-char begin)
  21203. (while (< (point) end)
  21204. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21205. (replace-match
  21206. "" nil nil nil
  21207. (if (= (line-end-position) (match-end 0)) 0 1)))
  21208. (forward-line)))
  21209. (let ((min-ind (point-max)))
  21210. ;; Find minimum indentation across all lines.
  21211. (save-excursion
  21212. (goto-char begin)
  21213. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21214. (setq min-ind 0)
  21215. (catch 'zerop
  21216. (while (< (point) end)
  21217. (unless (looking-at-p "[ \t]*$")
  21218. (let ((ind (org-get-indentation)))
  21219. (setq min-ind (min min-ind ind))
  21220. (when (zerop ind) (throw 'zerop t))))
  21221. (forward-line)))))
  21222. ;; Loop over all lines and add fixed-width markup everywhere
  21223. ;; but in fixed-width lines.
  21224. (save-excursion
  21225. (goto-char begin)
  21226. (while (< (point) end)
  21227. (cond
  21228. ((org-at-heading-p)
  21229. (insert ": ")
  21230. (forward-line)
  21231. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21232. (insert ":")
  21233. (forward-line)))
  21234. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21235. (let* ((element (org-element-at-point))
  21236. (element-end (org-element-property :end element)))
  21237. (if (eq (org-element-type element) 'fixed-width)
  21238. (progn (goto-char element-end)
  21239. (skip-chars-backward " \r\t\n")
  21240. (forward-line))
  21241. (let ((limit (min end element-end)))
  21242. (while (< (point) limit)
  21243. (org-move-to-column min-ind t)
  21244. (insert ": ")
  21245. (forward-line))))))
  21246. (t
  21247. (org-move-to-column min-ind t)
  21248. (insert ": ")
  21249. (forward-line)))))))
  21250. (set-marker end nil))))
  21251. ;;; Comments
  21252. ;; Org comments syntax is quite complex. It requires the entire line
  21253. ;; to be just a comment. Also, even with the right syntax at the
  21254. ;; beginning of line, some elements (e.g., verse-block or
  21255. ;; example-block) don't accept comments. Usual Emacs comment commands
  21256. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21257. ;; Org still relies on `comment-dwim', but cannot trust
  21258. ;; `comment-only-p'. So, `comment-region-function' and
  21259. ;; `uncomment-region-function' both point
  21260. ;; to`org-comment-or-uncomment-region'. Eventually,
  21261. ;; `org-insert-comment' takes care of insertion of comments at the
  21262. ;; beginning of line.
  21263. ;; `org-setup-comments-handling' install comments related variables
  21264. ;; during `org-mode' initialization.
  21265. (defun org-setup-comments-handling ()
  21266. (interactive)
  21267. (setq-local comment-use-syntax nil)
  21268. (setq-local comment-start "# ")
  21269. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21270. (setq-local comment-insert-comment-function 'org-insert-comment)
  21271. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21272. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21273. (defun org-insert-comment ()
  21274. "Insert an empty comment above current line.
  21275. If the line is empty, insert comment at its beginning. When
  21276. point is within a source block, comment according to the related
  21277. major mode."
  21278. (if (let ((element (org-element-at-point)))
  21279. (and (eq (org-element-type element) 'src-block)
  21280. (< (save-excursion
  21281. (goto-char (org-element-property :post-affiliated element))
  21282. (line-end-position))
  21283. (point))
  21284. (> (save-excursion
  21285. (goto-char (org-element-property :end element))
  21286. (skip-chars-backward " \r\t\n")
  21287. (line-beginning-position))
  21288. (point))))
  21289. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21290. (beginning-of-line)
  21291. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21292. (open-line 1))
  21293. (org-indent-line)
  21294. (insert "# ")))
  21295. (defvar comment-empty-lines) ; From newcomment.el.
  21296. (defun org-comment-or-uncomment-region (beg end &rest _)
  21297. "Comment or uncomment each non-blank line in the region.
  21298. Uncomment each non-blank line between BEG and END if it only
  21299. contains commented lines. Otherwise, comment them. If region is
  21300. strictly within a source block, use appropriate comment syntax."
  21301. (if (let ((element (org-element-at-point)))
  21302. (and (eq (org-element-type element) 'src-block)
  21303. (< (save-excursion
  21304. (goto-char (org-element-property :post-affiliated element))
  21305. (line-end-position))
  21306. beg)
  21307. (>= (save-excursion
  21308. (goto-char (org-element-property :end element))
  21309. (skip-chars-backward " \r\t\n")
  21310. (line-beginning-position))
  21311. end)))
  21312. ;; Translate region boundaries for the Org buffer to the source
  21313. ;; buffer.
  21314. (let ((offset (- end beg)))
  21315. (save-excursion
  21316. (goto-char beg)
  21317. (org-babel-do-in-edit-buffer
  21318. (comment-or-uncomment-region (point) (+ offset (point))))))
  21319. (save-restriction
  21320. ;; Restrict region
  21321. (narrow-to-region (save-excursion (goto-char beg)
  21322. (skip-chars-forward " \r\t\n" end)
  21323. (line-beginning-position))
  21324. (save-excursion (goto-char end)
  21325. (skip-chars-backward " \r\t\n" beg)
  21326. (line-end-position)))
  21327. (let ((uncommentp
  21328. ;; UNCOMMENTP is non-nil when every non blank line between
  21329. ;; BEG and END is a comment.
  21330. (save-excursion
  21331. (goto-char (point-min))
  21332. (while (and (not (eobp))
  21333. (let ((element (org-element-at-point)))
  21334. (and (eq (org-element-type element) 'comment)
  21335. (goto-char (min (point-max)
  21336. (org-element-property
  21337. :end element)))))))
  21338. (eobp))))
  21339. (if uncommentp
  21340. ;; Only blank lines and comments in region: uncomment it.
  21341. (save-excursion
  21342. (goto-char (point-min))
  21343. (while (not (eobp))
  21344. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21345. (replace-match "" nil nil nil 1))
  21346. (forward-line)))
  21347. ;; Comment each line in region.
  21348. (let ((min-indent (point-max)))
  21349. ;; First find the minimum indentation across all lines.
  21350. (save-excursion
  21351. (goto-char (point-min))
  21352. (while (and (not (eobp)) (not (zerop min-indent)))
  21353. (unless (looking-at "[ \t]*$")
  21354. (setq min-indent (min min-indent (current-indentation))))
  21355. (forward-line)))
  21356. ;; Then loop over all lines.
  21357. (save-excursion
  21358. (goto-char (point-min))
  21359. (while (not (eobp))
  21360. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21361. ;; Don't get fooled by invisible text (e.g. link path)
  21362. ;; when moving to column MIN-INDENT.
  21363. (let ((buffer-invisibility-spec nil))
  21364. (org-move-to-column min-indent t))
  21365. (insert comment-start))
  21366. (forward-line)))))))))
  21367. (defun org-comment-dwim (_arg)
  21368. "Call `comment-dwim' within a source edit buffer if needed."
  21369. (interactive "*P")
  21370. (if (org-in-src-block-p)
  21371. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21372. (call-interactively 'comment-dwim)))
  21373. ;;; Timestamps API
  21374. ;; This section contains tools to operate on timestamp objects, as
  21375. ;; returned by, e.g. `org-element-context'.
  21376. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21377. "Encode TIMESTAMP object into Emacs internal time.
  21378. Use end of date range or time range when END is non-nil."
  21379. (apply #'encode-time
  21380. (cons 0
  21381. (mapcar
  21382. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21383. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21384. '(:minute-start :hour-start :day-start :month-start
  21385. :year-start))))))
  21386. (defun org-timestamp-has-time-p (timestamp)
  21387. "Non-nil when TIMESTAMP has a time specified."
  21388. (org-element-property :hour-start timestamp))
  21389. (defun org-timestamp-format (timestamp format &optional end utc)
  21390. "Format a TIMESTAMP object into a string.
  21391. FORMAT is a format specifier to be passed to
  21392. `format-time-string'.
  21393. When optional argument END is non-nil, use end of date-range or
  21394. time-range, if possible.
  21395. When optional argument UTC is non-nil, time will be expressed as
  21396. Universal Time."
  21397. (format-time-string
  21398. format (org-timestamp--to-internal-time timestamp end)
  21399. (and utc t)))
  21400. (defun org-timestamp-split-range (timestamp &optional end)
  21401. "Extract a TIMESTAMP object from a date or time range.
  21402. END, when non-nil, means extract the end of the range.
  21403. Otherwise, extract its start.
  21404. Return a new timestamp object."
  21405. (let ((type (org-element-property :type timestamp)))
  21406. (if (memq type '(active inactive diary)) timestamp
  21407. (let ((split-ts (org-element-copy timestamp)))
  21408. ;; Set new type.
  21409. (org-element-put-property
  21410. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21411. ;; Copy start properties over end properties if END is
  21412. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21413. (let ((p-alist '((:minute-start . :minute-end)
  21414. (:hour-start . :hour-end)
  21415. (:day-start . :day-end)
  21416. (:month-start . :month-end)
  21417. (:year-start . :year-end))))
  21418. (dolist (p-cell p-alist)
  21419. (org-element-put-property
  21420. split-ts
  21421. (funcall (if end #'car #'cdr) p-cell)
  21422. (org-element-property
  21423. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21424. ;; Eventually refresh `:raw-value'.
  21425. (org-element-put-property split-ts :raw-value nil)
  21426. (org-element-put-property
  21427. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21428. (defun org-timestamp-translate (timestamp &optional boundary)
  21429. "Translate TIMESTAMP object to custom format.
  21430. Format string is defined in `org-time-stamp-custom-formats',
  21431. which see.
  21432. When optional argument BOUNDARY is non-nil, it is either the
  21433. symbol `start' or `end'. In this case, only translate the
  21434. starting or ending part of TIMESTAMP if it is a date or time
  21435. range. Otherwise, translate both parts.
  21436. Return timestamp as-is if `org-display-custom-times' is nil or if
  21437. it has a `diary' type."
  21438. (let ((type (org-element-property :type timestamp)))
  21439. (if (or (not org-display-custom-times) (eq type 'diary))
  21440. (org-element-interpret-data timestamp)
  21441. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21442. org-time-stamp-custom-formats)))
  21443. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21444. (concat (org-timestamp-format timestamp fmt)
  21445. "--"
  21446. (org-timestamp-format timestamp fmt t))
  21447. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21448. ;;; Other stuff.
  21449. (defvar reftex-docstruct-symbol)
  21450. (defvar org--rds)
  21451. (defun org-reftex-citation ()
  21452. "Use reftex-citation to insert a citation into the buffer.
  21453. This looks for a line like
  21454. #+BIBLIOGRAPHY: foo plain option:-d
  21455. and derives from it that foo.bib is the bibliography file relevant
  21456. for this document. It then installs the necessary environment for RefTeX
  21457. to work in this buffer and calls `reftex-citation' to insert a citation
  21458. into the buffer.
  21459. Export of such citations to both LaTeX and HTML is handled by the contributed
  21460. package ox-bibtex by Taru Karttunen."
  21461. (interactive)
  21462. (let ((reftex-docstruct-symbol 'org--rds)
  21463. org--rds bib)
  21464. (org-with-wide-buffer
  21465. (let ((case-fold-search t)
  21466. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21467. (if (not (save-excursion
  21468. (or (re-search-forward re nil t)
  21469. (re-search-backward re nil t))))
  21470. (user-error "No bibliography defined in file")
  21471. (setq bib (concat (match-string 1) ".bib")
  21472. org--rds (list (list 'bib bib))))))
  21473. (call-interactively 'reftex-citation)))
  21474. ;;;; Functions extending outline functionality
  21475. (defun org-beginning-of-line (&optional n)
  21476. "Go to the beginning of the current visible line.
  21477. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21478. tags on the first attempt, and only move to after the tags when
  21479. the cursor is already beyond the end of the headline.
  21480. With argument N not nil or 1, move forward N - 1 lines first."
  21481. (interactive "^p")
  21482. (let ((origin (point))
  21483. (special (pcase org-special-ctrl-a/e
  21484. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21485. deactivate-mark)
  21486. ;; First move to a visible line.
  21487. (if (bound-and-true-p visual-line-mode)
  21488. (beginning-of-visual-line n)
  21489. (move-beginning-of-line n)
  21490. ;; `move-beginning-of-line' may leave point after invisible
  21491. ;; characters if line starts with such of these (e.g., with
  21492. ;; a link at column 0). Really move to the beginning of the
  21493. ;; current visible line.
  21494. (beginning-of-line))
  21495. (cond
  21496. ;; No special behavior. Point is already at the beginning of
  21497. ;; a line, logical or visual.
  21498. ((not special))
  21499. ;; `beginning-of-visual-line' left point before logical beginning
  21500. ;; of line: point is at the beginning of a visual line. Bail
  21501. ;; out.
  21502. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21503. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21504. ;; At a headline, special position is before the title, but
  21505. ;; after any TODO keyword or priority cookie.
  21506. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21507. (line-end-position)))
  21508. (bol (point)))
  21509. (if (eq special 'reversed)
  21510. (when (and (= origin bol) (eq last-command this-command))
  21511. (goto-char refpos))
  21512. (when (or (> origin refpos) (= origin bol))
  21513. (goto-char refpos)))))
  21514. ((and (looking-at org-list-full-item-re)
  21515. (memq (org-element-type (save-match-data (org-element-at-point)))
  21516. '(item plain-list)))
  21517. ;; Set special position at first white space character after
  21518. ;; bullet, and check-box, if any.
  21519. (let ((after-bullet
  21520. (let ((box (match-end 3)))
  21521. (cond ((not box) (match-end 1))
  21522. ((eq (char-after box) ?\s) (1+ box))
  21523. (t box)))))
  21524. (if (eq special 'reversed)
  21525. (when (and (= (point) origin) (eq last-command this-command))
  21526. (goto-char after-bullet))
  21527. (when (or (> origin after-bullet) (= (point) origin))
  21528. (goto-char after-bullet)))))
  21529. ;; No special context. Point is already at beginning of line.
  21530. (t nil))))
  21531. (defun org-end-of-line (&optional n)
  21532. "Go to the end of the line, but before ellipsis, if any.
  21533. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21534. tags on the first attempt, and only move to after the tags when
  21535. the cursor is already beyond the end of the headline.
  21536. With argument N not nil or 1, move forward N - 1 lines first."
  21537. (interactive "^p")
  21538. (let ((origin (point))
  21539. (special (pcase org-special-ctrl-a/e
  21540. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21541. deactivate-mark)
  21542. ;; First move to a visible line.
  21543. (if (bound-and-true-p visual-line-mode)
  21544. (beginning-of-visual-line n)
  21545. (move-beginning-of-line n))
  21546. (cond
  21547. ;; At a headline, with tags.
  21548. ((and special
  21549. (save-excursion
  21550. (beginning-of-line)
  21551. (let ((case-fold-search nil))
  21552. (looking-at org-complex-heading-regexp)))
  21553. (match-end 5))
  21554. (let ((tags (save-excursion
  21555. (goto-char (match-beginning 5))
  21556. (skip-chars-backward " \t")
  21557. (point)))
  21558. (visual-end (and (bound-and-true-p visual-line-mode)
  21559. (save-excursion
  21560. (end-of-visual-line)
  21561. (point)))))
  21562. ;; If `end-of-visual-line' brings us before end of line or
  21563. ;; even tags, i.e., the headline spans over multiple visual
  21564. ;; lines, move there.
  21565. (cond ((and visual-end
  21566. (< visual-end tags)
  21567. (<= origin visual-end))
  21568. (goto-char visual-end))
  21569. ((eq special 'reversed)
  21570. (if (and (= origin (line-end-position))
  21571. (eq this-command last-command))
  21572. (goto-char tags)
  21573. (end-of-line)))
  21574. (t
  21575. (if (or (< origin tags) (= origin (line-end-position)))
  21576. (goto-char tags)
  21577. (end-of-line))))))
  21578. ((bound-and-true-p visual-line-mode)
  21579. (let ((bol (line-beginning-position)))
  21580. (end-of-visual-line)
  21581. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21582. ;; end of a line, backtrack and use `end-of-line' instead.
  21583. (when (/= bol (line-beginning-position))
  21584. (goto-char bol)
  21585. (end-of-line))))
  21586. (t (end-of-line)))))
  21587. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21588. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21589. (defun org-backward-sentence (&optional _arg)
  21590. "Go to beginning of sentence, or beginning of table field.
  21591. This will call `backward-sentence' or `org-table-beginning-of-field',
  21592. depending on context."
  21593. (interactive)
  21594. (let* ((element (org-element-at-point))
  21595. (contents-begin (org-element-property :contents-begin element))
  21596. (table (org-element-lineage element '(table) t)))
  21597. (if (and table
  21598. (> (point) contents-begin)
  21599. (<= (point) (org-element-property :contents-end table)))
  21600. (call-interactively #'org-table-beginning-of-field)
  21601. (save-restriction
  21602. (when (and contents-begin
  21603. (< (point-min) contents-begin)
  21604. (> (point) contents-begin))
  21605. (narrow-to-region contents-begin
  21606. (org-element-property :contents-end element)))
  21607. (call-interactively #'backward-sentence)))))
  21608. (defun org-forward-sentence (&optional _arg)
  21609. "Go to end of sentence, or end of table field.
  21610. This will call `forward-sentence' or `org-table-end-of-field',
  21611. depending on context."
  21612. (interactive)
  21613. (let* ((element (org-element-at-point))
  21614. (contents-end (org-element-property :contents-end element))
  21615. (table (org-element-lineage element '(table) t)))
  21616. (if (and table
  21617. (>= (point) (org-element-property :contents-begin table))
  21618. (< (point) contents-end))
  21619. (call-interactively #'org-table-end-of-field)
  21620. (save-restriction
  21621. (when (and contents-end
  21622. (> (point-max) contents-end)
  21623. ;; Skip blank lines between elements.
  21624. (< (org-element-property :end element)
  21625. (save-excursion (goto-char contents-end)
  21626. (skip-chars-forward " \r\t\n"))))
  21627. (narrow-to-region (org-element-property :contents-begin element)
  21628. contents-end))
  21629. (call-interactively #'forward-sentence)))))
  21630. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21631. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21632. (defun org-kill-line (&optional _arg)
  21633. "Kill line, to tags or end of line."
  21634. (interactive)
  21635. (cond
  21636. ((or (not org-special-ctrl-k)
  21637. (bolp)
  21638. (not (org-at-heading-p)))
  21639. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21640. org-ctrl-k-protect-subtree
  21641. (or (eq org-ctrl-k-protect-subtree 'error)
  21642. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21643. (user-error "C-k aborted as it would kill a hidden subtree"))
  21644. (call-interactively
  21645. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21646. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21647. (kill-region (point) (match-beginning 1))
  21648. (org-set-tags nil t))
  21649. (t (kill-region (point) (point-at-eol)))))
  21650. (define-key org-mode-map "\C-k" 'org-kill-line)
  21651. (defun org-yank (&optional arg)
  21652. "Yank. If the kill is a subtree, treat it specially.
  21653. This command will look at the current kill and check if is a single
  21654. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21655. cursor is at the beginning of a line or after the stars of a currently
  21656. empty headline, then the yank is handled specially. How exactly depends
  21657. on the value of the following variables.
  21658. `org-yank-folded-subtrees'
  21659. By default, this variable is non-nil, which results in
  21660. subtree(s) being folded after insertion, except if doing so
  21661. would swallow text after the yanked text.
  21662. `org-yank-adjusted-subtrees'
  21663. When non-nil (the default value is nil), the subtree will be
  21664. promoted or demoted in order to fit into the local outline tree
  21665. structure, which means that the level will be adjusted so that it
  21666. becomes the smaller one of the two *visible* surrounding headings.
  21667. Any prefix to this command will cause `yank' to be called directly with
  21668. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21669. will just
  21670. plainly yank the text as it is.
  21671. \[1] The test checks if the first non-white line is a heading
  21672. and if there are no other headings with fewer stars."
  21673. (interactive "P")
  21674. (org-yank-generic 'yank arg))
  21675. (defun org-yank-generic (command arg)
  21676. "Perform some yank-like command.
  21677. This function implements the behavior described in the `org-yank'
  21678. documentation. However, it has been generalized to work for any
  21679. interactive command with similar behavior."
  21680. ;; pretend to be command COMMAND
  21681. (setq this-command command)
  21682. (if arg
  21683. (call-interactively command)
  21684. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21685. (and (org-kill-is-subtree-p)
  21686. (or (bolp)
  21687. (and (looking-at "[ \t]*$")
  21688. (string-match
  21689. "\\`\\*+\\'"
  21690. (buffer-substring (point-at-bol) (point)))))))
  21691. swallowp)
  21692. (cond
  21693. ((and subtreep org-yank-folded-subtrees)
  21694. (let ((beg (point))
  21695. end)
  21696. (if (and subtreep org-yank-adjusted-subtrees)
  21697. (org-paste-subtree nil nil 'for-yank)
  21698. (call-interactively command))
  21699. (setq end (point))
  21700. (goto-char beg)
  21701. (when (and (bolp) subtreep
  21702. (not (setq swallowp
  21703. (org-yank-folding-would-swallow-text beg end))))
  21704. (org-with-limited-levels
  21705. (or (looking-at org-outline-regexp)
  21706. (re-search-forward org-outline-regexp-bol end t))
  21707. (while (and (< (point) end) (looking-at org-outline-regexp))
  21708. (outline-hide-subtree)
  21709. (org-cycle-show-empty-lines 'folded)
  21710. (condition-case nil
  21711. (outline-forward-same-level 1)
  21712. (error (goto-char end))))))
  21713. (when swallowp
  21714. (message
  21715. "Inserted text not folded because that would swallow text"))
  21716. (goto-char end)
  21717. (skip-chars-forward " \t\n\r")
  21718. (beginning-of-line 1)
  21719. (push-mark beg 'nomsg)))
  21720. ((and subtreep org-yank-adjusted-subtrees)
  21721. (let ((beg (point-at-bol)))
  21722. (org-paste-subtree nil nil 'for-yank)
  21723. (push-mark beg 'nomsg)))
  21724. (t
  21725. (call-interactively command))))))
  21726. (defun org-yank-folding-would-swallow-text (beg end)
  21727. "Would hide-subtree at BEG swallow any text after END?"
  21728. (let (level)
  21729. (org-with-limited-levels
  21730. (save-excursion
  21731. (goto-char beg)
  21732. (when (or (looking-at org-outline-regexp)
  21733. (re-search-forward org-outline-regexp-bol end t))
  21734. (setq level (org-outline-level)))
  21735. (goto-char end)
  21736. (skip-chars-forward " \t\r\n\v\f")
  21737. (not (or (eobp)
  21738. (and (bolp) (looking-at-p org-outline-regexp)
  21739. (<= (org-outline-level) level))))))))
  21740. (define-key org-mode-map "\C-y" 'org-yank)
  21741. (defun org-truely-invisible-p ()
  21742. "Check if point is at a character currently not visible.
  21743. This version does not only check the character property, but also
  21744. `visible-mode'."
  21745. (unless (bound-and-true-p visible-mode)
  21746. (org-invisible-p)))
  21747. (defun org-invisible-p2 ()
  21748. "Check if point is at a character currently not visible.
  21749. If the point is at EOL (and not at the beginning of a buffer too),
  21750. move it back by one char before doing this check."
  21751. (save-excursion
  21752. (when (and (eolp) (not (bobp)))
  21753. (backward-char 1))
  21754. (org-invisible-p)))
  21755. (defun org-back-to-heading (&optional invisible-ok)
  21756. "Call `outline-back-to-heading', but provide a better error message."
  21757. (condition-case nil
  21758. (outline-back-to-heading invisible-ok)
  21759. (error (error "Before first headline at position %d in buffer %s"
  21760. (point) (current-buffer)))))
  21761. (defun org-before-first-heading-p ()
  21762. "Before first heading?"
  21763. (save-excursion
  21764. (end-of-line)
  21765. (null (re-search-backward org-outline-regexp-bol nil t))))
  21766. (defun org-at-heading-p (&optional ignored)
  21767. (outline-on-heading-p t))
  21768. (defun org-in-commented-heading-p (&optional no-inheritance)
  21769. "Non-nil if point is under a commented heading.
  21770. This function also checks ancestors of the current headline,
  21771. unless optional argument NO-INHERITANCE is non-nil."
  21772. (cond
  21773. ((org-before-first-heading-p) nil)
  21774. ((let ((headline (nth 4 (org-heading-components))))
  21775. (and headline
  21776. (let ((case-fold-search nil))
  21777. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21778. headline)))))
  21779. (no-inheritance nil)
  21780. (t
  21781. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21782. (defun org-at-comment-p nil
  21783. "Is cursor in a commented line?"
  21784. (save-excursion
  21785. (save-match-data
  21786. (beginning-of-line)
  21787. (looking-at "^[ \t]*# "))))
  21788. (defun org-at-drawer-p nil
  21789. "Is cursor at a drawer keyword?"
  21790. (save-excursion
  21791. (move-beginning-of-line 1)
  21792. (looking-at org-drawer-regexp)))
  21793. (defun org-at-block-p nil
  21794. "Is cursor at a block keyword?"
  21795. (save-excursion
  21796. (move-beginning-of-line 1)
  21797. (looking-at org-block-regexp)))
  21798. (defun org-point-at-end-of-empty-headline ()
  21799. "If point is at the end of an empty headline, return t, else nil.
  21800. If the heading only contains a TODO keyword, it is still still considered
  21801. empty."
  21802. (let ((case-fold-search nil))
  21803. (and (looking-at "[ \t]*$")
  21804. org-todo-line-regexp
  21805. (save-excursion
  21806. (beginning-of-line)
  21807. (looking-at org-todo-line-regexp)
  21808. (string= (match-string 3) "")))))
  21809. (defun org-at-heading-or-item-p ()
  21810. (or (org-at-heading-p) (org-at-item-p)))
  21811. (defun org-at-target-p ()
  21812. (or (org-in-regexp org-radio-target-regexp)
  21813. (org-in-regexp org-target-regexp)))
  21814. ;; Compatibility alias with Org versions < 7.8.03
  21815. (defalias 'org-on-target-p 'org-at-target-p)
  21816. (defun org-up-heading-all (arg)
  21817. "Move to the heading line of which the present line is a subheading.
  21818. This function considers both visible and invisible heading lines.
  21819. With argument, move up ARG levels."
  21820. (outline-up-heading arg t))
  21821. (defun org-up-heading-safe ()
  21822. "Move to the heading line of which the present line is a subheading.
  21823. This version will not throw an error. It will return the level of the
  21824. headline found, or nil if no higher level is found.
  21825. Also, this function will be a lot faster than `outline-up-heading',
  21826. because it relies on stars being the outline starters. This can really
  21827. make a significant difference in outlines with very many siblings."
  21828. (when (ignore-errors (org-back-to-heading t))
  21829. (let ((level-up (1- (funcall outline-level))))
  21830. (and (> level-up 0)
  21831. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21832. (funcall outline-level)))))
  21833. (defun org-first-sibling-p ()
  21834. "Is this heading the first child of its parents?"
  21835. (interactive)
  21836. (let ((re org-outline-regexp-bol)
  21837. level l)
  21838. (unless (org-at-heading-p t)
  21839. (user-error "Not at a heading"))
  21840. (setq level (funcall outline-level))
  21841. (save-excursion
  21842. (if (not (re-search-backward re nil t))
  21843. t
  21844. (setq l (funcall outline-level))
  21845. (< l level)))))
  21846. (defun org-goto-sibling (&optional previous)
  21847. "Goto the next sibling, even if it is invisible.
  21848. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21849. when a sibling was found. When none is found, return nil and don't
  21850. move point."
  21851. (let ((fun (if previous 're-search-backward 're-search-forward))
  21852. (pos (point))
  21853. (re org-outline-regexp-bol)
  21854. level l)
  21855. (when (ignore-errors (org-back-to-heading t))
  21856. (setq level (funcall outline-level))
  21857. (catch 'exit
  21858. (or previous (forward-char 1))
  21859. (while (funcall fun re nil t)
  21860. (setq l (funcall outline-level))
  21861. (when (< l level) (goto-char pos) (throw 'exit nil))
  21862. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21863. (goto-char pos)
  21864. nil))))
  21865. (defun org-show-siblings ()
  21866. "Show all siblings of the current headline."
  21867. (save-excursion
  21868. (while (org-goto-sibling) (org-flag-heading nil)))
  21869. (save-excursion
  21870. (while (org-goto-sibling 'previous)
  21871. (org-flag-heading nil))))
  21872. (defun org-goto-first-child ()
  21873. "Goto the first child, even if it is invisible.
  21874. Return t when a child was found. Otherwise don't move point and
  21875. return nil."
  21876. (let (level (pos (point)) (re org-outline-regexp-bol))
  21877. (when (ignore-errors (org-back-to-heading t))
  21878. (setq level (outline-level))
  21879. (forward-char 1)
  21880. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21881. (progn (goto-char (match-beginning 0)) t)
  21882. (goto-char pos) nil))))
  21883. (defun org-show-hidden-entry ()
  21884. "Show an entry where even the heading is hidden."
  21885. (save-excursion
  21886. (org-show-entry)))
  21887. (defun org-flag-heading (flag &optional entry)
  21888. "Flag the current heading. FLAG non-nil means make invisible.
  21889. When ENTRY is non-nil, show the entire entry."
  21890. (save-excursion
  21891. (org-back-to-heading t)
  21892. ;; Check if we should show the entire entry
  21893. (if entry
  21894. (progn
  21895. (org-show-entry)
  21896. (save-excursion
  21897. (and (outline-next-heading)
  21898. (org-flag-heading nil))))
  21899. (outline-flag-region (max (point-min) (1- (point)))
  21900. (save-excursion (outline-end-of-heading) (point))
  21901. flag))))
  21902. (defun org-get-next-sibling ()
  21903. "Move to next heading of the same level, and return point.
  21904. If there is no such heading, return nil.
  21905. This is like outline-next-sibling, but invisible headings are ok."
  21906. (let ((level (funcall outline-level)))
  21907. (outline-next-heading)
  21908. (while (and (not (eobp)) (> (funcall outline-level) level))
  21909. (outline-next-heading))
  21910. (unless (or (eobp) (< (funcall outline-level) level))
  21911. (point))))
  21912. (defun org-get-last-sibling ()
  21913. "Move to previous heading of the same level, and return point.
  21914. If there is no such heading, return nil."
  21915. (let ((opoint (point))
  21916. (level (funcall outline-level)))
  21917. (outline-previous-heading)
  21918. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21919. (while (and (> (funcall outline-level) level)
  21920. (not (bobp)))
  21921. (outline-previous-heading))
  21922. (unless (< (funcall outline-level) level)
  21923. (point)))))
  21924. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21925. "Goto to the end of a subtree."
  21926. ;; This contains an exact copy of the original function, but it uses
  21927. ;; `org-back-to-heading', to make it work also in invisible
  21928. ;; trees. And is uses an invisible-ok argument.
  21929. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21930. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21931. ;; with many children and grandchildren etc, this can be much faster
  21932. ;; than the outline version.
  21933. (org-back-to-heading invisible-ok)
  21934. (let ((first t)
  21935. (level (funcall outline-level)))
  21936. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21937. ;; A true heading (not a plain list item), in Org
  21938. ;; This means we can easily find the end by looking
  21939. ;; only for the right number of stars. Using a regexp to do
  21940. ;; this is so much faster than using a Lisp loop.
  21941. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21942. (forward-char 1)
  21943. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21944. ;; something else, do it the slow way
  21945. (while (and (not (eobp))
  21946. (or first (> (funcall outline-level) level)))
  21947. (setq first nil)
  21948. (outline-next-heading)))
  21949. (unless to-heading
  21950. (when (memq (preceding-char) '(?\n ?\^M))
  21951. ;; Go to end of line before heading
  21952. (forward-char -1)
  21953. (when (memq (preceding-char) '(?\n ?\^M))
  21954. ;; leave blank line before heading
  21955. (forward-char -1)))))
  21956. (point))
  21957. (defun org-end-of-meta-data (&optional full)
  21958. "Skip planning line and properties drawer in current entry.
  21959. When optional argument FULL is non-nil, also skip empty lines,
  21960. clocking lines and regular drawers at the beginning of the
  21961. entry."
  21962. (org-back-to-heading t)
  21963. (forward-line)
  21964. (when (looking-at-p org-planning-line-re) (forward-line))
  21965. (when (looking-at org-property-drawer-re)
  21966. (goto-char (match-end 0))
  21967. (forward-line))
  21968. (when (and full (not (org-at-heading-p)))
  21969. (catch 'exit
  21970. (let ((end (save-excursion (outline-next-heading) (point)))
  21971. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21972. (while (not (eobp))
  21973. (cond ((looking-at-p org-drawer-regexp)
  21974. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21975. (forward-line)
  21976. (throw 'exit t)))
  21977. ((looking-at-p re) (forward-line))
  21978. (t (throw 'exit t))))))))
  21979. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21980. "Move forward to the ARG'th subheading at same level as this one.
  21981. Stop at the first and last subheadings of a superior heading.
  21982. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21983. non-nil it will also look at invisible ones."
  21984. (interactive "p")
  21985. (let ((backward? (and arg (< arg 0))))
  21986. (if (org-before-first-heading-p)
  21987. (if backward? (goto-char (point-min)) (outline-next-heading))
  21988. (org-back-to-heading invisible-ok)
  21989. (unless backward? (end-of-line)) ;do not match current headline
  21990. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21991. (f (if backward? #'re-search-backward #'re-search-forward))
  21992. (count (if arg (abs arg) 1))
  21993. (result (point)))
  21994. (while (and (> count 0)
  21995. (funcall f org-outline-regexp-bol nil 'move))
  21996. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21997. (cond ((< l level) (setq count 0))
  21998. ((and (= l level)
  21999. (or invisible-ok
  22000. (not (org-invisible-p
  22001. (line-beginning-position)))))
  22002. (cl-decf count)
  22003. (when (= l level) (setq result (point)))))))
  22004. (goto-char result))
  22005. (beginning-of-line))))
  22006. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22007. "Move backward to the ARG'th subheading at same level as this one.
  22008. Stop at the first and last subheadings of a superior heading."
  22009. (interactive "p")
  22010. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22011. (defun org-next-visible-heading (arg)
  22012. "Move to the next visible heading.
  22013. This function wraps `outline-next-visible-heading' with
  22014. `org-with-limited-levels' in order to skip over inline tasks and
  22015. respect customization of `org-odd-levels-only'."
  22016. (interactive "p")
  22017. (org-with-limited-levels
  22018. (outline-next-visible-heading arg)))
  22019. (defun org-previous-visible-heading (arg)
  22020. "Move to the previous visible heading.
  22021. This function wraps `outline-previous-visible-heading' with
  22022. `org-with-limited-levels' in order to skip over inline tasks and
  22023. respect customization of `org-odd-levels-only'."
  22024. (interactive "p")
  22025. (org-with-limited-levels
  22026. (outline-previous-visible-heading arg)))
  22027. (defun org-next-block (arg &optional backward block-regexp)
  22028. "Jump to the next block.
  22029. With a prefix argument ARG, jump forward ARG many blocks.
  22030. When BACKWARD is non-nil, jump to the previous block.
  22031. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22032. Match data is set according to this regexp when the function
  22033. returns.
  22034. Return point at beginning of the opening line of found block.
  22035. Throw an error if no block is found."
  22036. (interactive "p")
  22037. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22038. (case-fold-search t)
  22039. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22040. (count (or arg 1))
  22041. (origin (point))
  22042. last-element)
  22043. (if backward (beginning-of-line) (end-of-line))
  22044. (while (and (> count 0) (funcall search-fn re nil t))
  22045. (let ((element (save-excursion
  22046. (goto-char (match-beginning 0))
  22047. (save-match-data (org-element-at-point)))))
  22048. (when (and (memq (org-element-type element)
  22049. '(center-block comment-block dynamic-block
  22050. example-block export-block quote-block
  22051. special-block src-block verse-block))
  22052. (<= (match-beginning 0)
  22053. (org-element-property :post-affiliated element)))
  22054. (setq last-element element)
  22055. (cl-decf count))))
  22056. (if (= count 0)
  22057. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22058. (save-match-data (org-show-context)))
  22059. (goto-char origin)
  22060. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22061. (defun org-previous-block (arg &optional block-regexp)
  22062. "Jump to the previous block.
  22063. With a prefix argument ARG, jump backward ARG many source blocks.
  22064. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22065. (interactive "p")
  22066. (org-next-block arg t block-regexp))
  22067. (defun org-forward-paragraph ()
  22068. "Move forward to beginning of next paragraph or equivalent.
  22069. The function moves point to the beginning of the next visible
  22070. structural element, which can be a paragraph, a table, a list
  22071. item, etc. It also provides some special moves for convenience:
  22072. - On an affiliated keyword, jump to the beginning of the
  22073. relative element.
  22074. - On an item or a footnote definition, move to the second
  22075. element inside, if any.
  22076. - On a table or a property drawer, jump after it.
  22077. - On a verse or source block, stop after blank lines."
  22078. (interactive)
  22079. (unless (eobp)
  22080. (let* ((deactivate-mark nil)
  22081. (element (org-element-at-point))
  22082. (type (org-element-type element))
  22083. (post-affiliated (org-element-property :post-affiliated element))
  22084. (contents-begin (org-element-property :contents-begin element))
  22085. (contents-end (org-element-property :contents-end element))
  22086. (end (let ((end (org-element-property :end element)) (parent element))
  22087. (while (and (setq parent (org-element-property :parent parent))
  22088. (= (org-element-property :contents-end parent) end))
  22089. (setq end (org-element-property :end parent)))
  22090. end)))
  22091. (cond ((not element)
  22092. (skip-chars-forward " \r\t\n")
  22093. (or (eobp) (beginning-of-line)))
  22094. ;; On affiliated keywords, move to element's beginning.
  22095. ((< (point) post-affiliated)
  22096. (goto-char post-affiliated))
  22097. ;; At a table row, move to the end of the table. Similarly,
  22098. ;; at a node property, move to the end of the property
  22099. ;; drawer.
  22100. ((memq type '(node-property table-row))
  22101. (goto-char (org-element-property
  22102. :end (org-element-property :parent element))))
  22103. ((memq type '(property-drawer table)) (goto-char end))
  22104. ;; Consider blank lines as separators in verse and source
  22105. ;; blocks to ease editing.
  22106. ((memq type '(src-block verse-block))
  22107. (when (eq type 'src-block)
  22108. (setq contents-end
  22109. (save-excursion (goto-char end)
  22110. (skip-chars-backward " \r\t\n")
  22111. (line-beginning-position))))
  22112. (beginning-of-line)
  22113. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22114. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22115. (goto-char end)
  22116. (skip-chars-forward " \r\t\n")
  22117. (if (= (point) contents-end) (goto-char end)
  22118. (beginning-of-line))))
  22119. ;; With no contents, just skip element.
  22120. ((not contents-begin) (goto-char end))
  22121. ;; If contents are invisible, skip the element altogether.
  22122. ((org-invisible-p (line-end-position))
  22123. (cl-case type
  22124. (headline
  22125. (org-with-limited-levels (outline-next-visible-heading 1)))
  22126. ;; At a plain list, make sure we move to the next item
  22127. ;; instead of skipping the whole list.
  22128. (plain-list (forward-char)
  22129. (org-forward-paragraph))
  22130. (otherwise (goto-char end))))
  22131. ((>= (point) contents-end) (goto-char end))
  22132. ((>= (point) contents-begin)
  22133. ;; This can only happen on paragraphs and plain lists.
  22134. (cl-case type
  22135. (paragraph (goto-char end))
  22136. ;; At a plain list, try to move to second element in
  22137. ;; first item, if possible.
  22138. (plain-list (end-of-line)
  22139. (org-forward-paragraph))))
  22140. ;; When contents start on the middle of a line (e.g. in
  22141. ;; items and footnote definitions), try to reach first
  22142. ;; element starting after current line.
  22143. ((> (line-end-position) contents-begin)
  22144. (end-of-line)
  22145. (org-forward-paragraph))
  22146. (t (goto-char contents-begin))))))
  22147. (defun org-backward-paragraph ()
  22148. "Move backward to start of previous paragraph or equivalent.
  22149. The function moves point to the beginning of the current
  22150. structural element, which can be a paragraph, a table, a list
  22151. item, etc., or to the beginning of the previous visible one if
  22152. point is already there. It also provides some special moves for
  22153. convenience:
  22154. - On an affiliated keyword, jump to the first one.
  22155. - On a table or a property drawer, move to its beginning.
  22156. - On a verse or source block, stop before blank lines."
  22157. (interactive)
  22158. (unless (bobp)
  22159. (let* ((deactivate-mark nil)
  22160. (element (org-element-at-point))
  22161. (type (org-element-type element))
  22162. (contents-begin (org-element-property :contents-begin element))
  22163. (contents-end (org-element-property :contents-end element))
  22164. (post-affiliated (org-element-property :post-affiliated element))
  22165. (begin (org-element-property :begin element)))
  22166. (cond
  22167. ((not element) (goto-char (point-min)))
  22168. ((= (point) begin)
  22169. (backward-char)
  22170. (org-backward-paragraph))
  22171. ((<= (point) post-affiliated) (goto-char begin))
  22172. ((memq type '(node-property table-row))
  22173. (goto-char (org-element-property
  22174. :post-affiliated (org-element-property :parent element))))
  22175. ((memq type '(property-drawer table)) (goto-char begin))
  22176. ((memq type '(src-block verse-block))
  22177. (when (eq type 'src-block)
  22178. (setq contents-begin
  22179. (save-excursion (goto-char begin) (forward-line) (point))))
  22180. (if (= (point) contents-begin) (goto-char post-affiliated)
  22181. ;; Inside a verse block, see blank lines as paragraph
  22182. ;; separators.
  22183. (let ((origin (point)))
  22184. (skip-chars-backward " \r\t\n" contents-begin)
  22185. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22186. (skip-chars-forward " \r\t\n" origin)
  22187. (if (= (point) origin) (goto-char contents-begin)
  22188. (beginning-of-line))))))
  22189. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22190. ((eq type 'paragraph)
  22191. (goto-char contents-begin)
  22192. ;; When at first paragraph in an item or a footnote definition,
  22193. ;; move directly to beginning of line.
  22194. (let ((parent-contents
  22195. (org-element-property
  22196. :contents-begin (org-element-property :parent element))))
  22197. (when (and parent-contents (= parent-contents contents-begin))
  22198. (beginning-of-line))))
  22199. ;; At the end of a greater element, move to the beginning of the
  22200. ;; last element within.
  22201. ((>= (point) contents-end)
  22202. (goto-char (1- contents-end))
  22203. (org-backward-paragraph))
  22204. (t (goto-char (or post-affiliated begin))))
  22205. ;; Ensure we never leave point invisible.
  22206. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  22207. (defun org-forward-element ()
  22208. "Move forward by one element.
  22209. Move to the next element at the same level, when possible."
  22210. (interactive)
  22211. (cond ((eobp) (user-error "Cannot move further down"))
  22212. ((org-with-limited-levels (org-at-heading-p))
  22213. (let ((origin (point)))
  22214. (goto-char (org-end-of-subtree nil t))
  22215. (unless (org-with-limited-levels (org-at-heading-p))
  22216. (goto-char origin)
  22217. (user-error "Cannot move further down"))))
  22218. (t
  22219. (let* ((elem (org-element-at-point))
  22220. (end (org-element-property :end elem))
  22221. (parent (org-element-property :parent elem)))
  22222. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22223. (goto-char (org-element-property :end parent)))
  22224. ((integer-or-marker-p end) (goto-char end))
  22225. (t (message "No element at point")))))))
  22226. (defun org-backward-element ()
  22227. "Move backward by one element.
  22228. Move to the previous element at the same level, when possible."
  22229. (interactive)
  22230. (cond ((bobp) (user-error "Cannot move further up"))
  22231. ((org-with-limited-levels (org-at-heading-p))
  22232. ;; At a headline, move to the previous one, if any, or stay
  22233. ;; here.
  22234. (let ((origin (point)))
  22235. (org-with-limited-levels (org-backward-heading-same-level 1))
  22236. ;; When current headline has no sibling above, move to its
  22237. ;; parent.
  22238. (when (= (point) origin)
  22239. (or (org-with-limited-levels (org-up-heading-safe))
  22240. (progn (goto-char origin)
  22241. (user-error "Cannot move further up"))))))
  22242. (t
  22243. (let* ((elem (org-element-at-point))
  22244. (beg (org-element-property :begin elem)))
  22245. (cond
  22246. ;; Move to beginning of current element if point isn't
  22247. ;; there already.
  22248. ((null beg) (message "No element at point"))
  22249. ((/= (point) beg) (goto-char beg))
  22250. (t (goto-char beg)
  22251. (skip-chars-backward " \r\t\n")
  22252. (unless (bobp)
  22253. (let ((prev (org-element-at-point)))
  22254. (goto-char (org-element-property :begin prev))
  22255. (while (and (setq prev (org-element-property :parent prev))
  22256. (<= (org-element-property :end prev) beg))
  22257. (goto-char (org-element-property :begin prev)))))))))))
  22258. (defun org-up-element ()
  22259. "Move to upper element."
  22260. (interactive)
  22261. (if (org-with-limited-levels (org-at-heading-p))
  22262. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22263. (let* ((elem (org-element-at-point))
  22264. (parent (org-element-property :parent elem)))
  22265. (if parent (goto-char (org-element-property :begin parent))
  22266. (if (org-with-limited-levels (org-before-first-heading-p))
  22267. (user-error "No surrounding element")
  22268. (org-with-limited-levels (org-back-to-heading)))))))
  22269. (defun org-down-element ()
  22270. "Move to inner element."
  22271. (interactive)
  22272. (let ((element (org-element-at-point)))
  22273. (cond
  22274. ((memq (org-element-type element) '(plain-list table))
  22275. (goto-char (org-element-property :contents-begin element))
  22276. (forward-char))
  22277. ((memq (org-element-type element) org-element-greater-elements)
  22278. ;; If contents are hidden, first disclose them.
  22279. (when (org-invisible-p (line-end-position)) (org-cycle))
  22280. (goto-char (or (org-element-property :contents-begin element)
  22281. (user-error "No content for this element"))))
  22282. (t (user-error "No inner element")))))
  22283. (defun org-drag-element-backward ()
  22284. "Move backward element at point."
  22285. (interactive)
  22286. (let ((elem (or (org-element-at-point)
  22287. (user-error "No element at point"))))
  22288. (if (eq (org-element-type elem) 'headline)
  22289. ;; Preserve point when moving a whole tree, even if point was
  22290. ;; on blank lines below the headline.
  22291. (let ((offset (skip-chars-backward " \t\n")))
  22292. (unwind-protect (org-move-subtree-up)
  22293. (forward-char (- offset))))
  22294. (let ((prev-elem
  22295. (save-excursion
  22296. (goto-char (org-element-property :begin elem))
  22297. (skip-chars-backward " \r\t\n")
  22298. (unless (bobp)
  22299. (let* ((beg (org-element-property :begin elem))
  22300. (prev (org-element-at-point))
  22301. (up prev))
  22302. (while (and (setq up (org-element-property :parent up))
  22303. (<= (org-element-property :end up) beg))
  22304. (setq prev up))
  22305. prev)))))
  22306. ;; Error out if no previous element or previous element is
  22307. ;; a parent of the current one.
  22308. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22309. (user-error "Cannot drag element backward")
  22310. (let ((pos (point)))
  22311. (org-element-swap-A-B prev-elem elem)
  22312. (goto-char (+ (org-element-property :begin prev-elem)
  22313. (- pos (org-element-property :begin elem))))))))))
  22314. (defun org-drag-element-forward ()
  22315. "Move forward element at point."
  22316. (interactive)
  22317. (let* ((pos (point))
  22318. (elem (or (org-element-at-point)
  22319. (user-error "No element at point"))))
  22320. (when (= (point-max) (org-element-property :end elem))
  22321. (user-error "Cannot drag element forward"))
  22322. (goto-char (org-element-property :end elem))
  22323. (let ((next-elem (org-element-at-point)))
  22324. (when (or (org-element-nested-p elem next-elem)
  22325. (and (eq (org-element-type next-elem) 'headline)
  22326. (not (eq (org-element-type elem) 'headline))))
  22327. (goto-char pos)
  22328. (user-error "Cannot drag element forward"))
  22329. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22330. ;; body's length (without final blanks) and by the length of
  22331. ;; blanks between ELEM and NEXT-ELEM.
  22332. (let ((size-next (- (save-excursion
  22333. (goto-char (org-element-property :end next-elem))
  22334. (skip-chars-backward " \r\t\n")
  22335. (forward-line)
  22336. ;; Small correction if buffer doesn't end
  22337. ;; with a newline character.
  22338. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22339. (org-element-property :begin next-elem)))
  22340. (size-blank (- (org-element-property :end elem)
  22341. (save-excursion
  22342. (goto-char (org-element-property :end elem))
  22343. (skip-chars-backward " \r\t\n")
  22344. (forward-line)
  22345. (point)))))
  22346. (org-element-swap-A-B elem next-elem)
  22347. (goto-char (+ pos size-next size-blank))))))
  22348. (defun org-drag-line-forward (arg)
  22349. "Drag the line at point ARG lines forward."
  22350. (interactive "p")
  22351. (dotimes (_ (abs arg))
  22352. (let ((c (current-column)))
  22353. (if (< 0 arg)
  22354. (progn
  22355. (beginning-of-line 2)
  22356. (transpose-lines 1)
  22357. (beginning-of-line 0))
  22358. (transpose-lines 1)
  22359. (beginning-of-line -1))
  22360. (org-move-to-column c))))
  22361. (defun org-drag-line-backward (arg)
  22362. "Drag the line at point ARG lines backward."
  22363. (interactive "p")
  22364. (org-drag-line-forward (- arg)))
  22365. (defun org-mark-element ()
  22366. "Put point at beginning of this element, mark at end.
  22367. Interactively, if this command is repeated or (in Transient Mark
  22368. mode) if the mark is active, it marks the next element after the
  22369. ones already marked."
  22370. (interactive)
  22371. (let (deactivate-mark)
  22372. (if (and (called-interactively-p 'any)
  22373. (or (and (eq last-command this-command) (mark t))
  22374. (and transient-mark-mode mark-active)))
  22375. (set-mark
  22376. (save-excursion
  22377. (goto-char (mark))
  22378. (goto-char (org-element-property :end (org-element-at-point)))))
  22379. (let ((element (org-element-at-point)))
  22380. (end-of-line)
  22381. (push-mark (org-element-property :end element) t t)
  22382. (goto-char (org-element-property :begin element))))))
  22383. (defun org-narrow-to-element ()
  22384. "Narrow buffer to current element."
  22385. (interactive)
  22386. (let ((elem (org-element-at-point)))
  22387. (cond
  22388. ((eq (car elem) 'headline)
  22389. (narrow-to-region
  22390. (org-element-property :begin elem)
  22391. (org-element-property :end elem)))
  22392. ((memq (car elem) org-element-greater-elements)
  22393. (narrow-to-region
  22394. (org-element-property :contents-begin elem)
  22395. (org-element-property :contents-end elem)))
  22396. (t
  22397. (narrow-to-region
  22398. (org-element-property :begin elem)
  22399. (org-element-property :end elem))))))
  22400. (defun org-transpose-element ()
  22401. "Transpose current and previous elements, keeping blank lines between.
  22402. Point is moved after both elements."
  22403. (interactive)
  22404. (org-skip-whitespace)
  22405. (let ((end (org-element-property :end (org-element-at-point))))
  22406. (org-drag-element-backward)
  22407. (goto-char end)))
  22408. (defun org-unindent-buffer ()
  22409. "Un-indent the visible part of the buffer.
  22410. Relative indentation (between items, inside blocks, etc.) isn't
  22411. modified."
  22412. (interactive)
  22413. (unless (eq major-mode 'org-mode)
  22414. (user-error "Cannot un-indent a buffer not in Org mode"))
  22415. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22416. (unindent-tree
  22417. (lambda (contents)
  22418. (dolist (element (reverse contents))
  22419. (if (memq (org-element-type element) '(headline section))
  22420. (funcall unindent-tree (org-element-contents element))
  22421. (save-excursion
  22422. (save-restriction
  22423. (narrow-to-region
  22424. (org-element-property :begin element)
  22425. (org-element-property :end element))
  22426. (org-do-remove-indentation))))))))
  22427. (funcall unindent-tree (org-element-contents parse-tree))))
  22428. (defun org-show-children (&optional level)
  22429. "Show all direct subheadings of this heading.
  22430. Prefix arg LEVEL is how many levels below the current level
  22431. should be shown. Default is enough to cause the following
  22432. heading to appear."
  22433. (interactive "p")
  22434. ;; If `orgstruct-mode' is active, use the slower version.
  22435. (if orgstruct-mode (call-interactively #'outline-show-children)
  22436. (save-excursion
  22437. (org-back-to-heading t)
  22438. (let* ((current-level (funcall outline-level))
  22439. (max-level (org-get-valid-level
  22440. current-level
  22441. (if level (prefix-numeric-value level) 1)))
  22442. (end (save-excursion (org-end-of-subtree t t)))
  22443. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22444. (past-first-child nil)
  22445. ;; Make sure to skip inlinetasks.
  22446. (re (format regexp-fmt
  22447. current-level
  22448. (cond
  22449. ((not (featurep 'org-inlinetask)) "")
  22450. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22451. 3))
  22452. (t (1- org-inlinetask-min-level))))))
  22453. ;; Display parent heading.
  22454. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22455. (forward-line)
  22456. ;; Display children. First child may be deeper than expected
  22457. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22458. ;; MAX-LEVEL accordingly.
  22459. (while (re-search-forward re end t)
  22460. (unless past-first-child
  22461. (setq re (format regexp-fmt
  22462. current-level
  22463. (max (funcall outline-level) max-level)))
  22464. (setq past-first-child t))
  22465. (outline-flag-region
  22466. (line-end-position 0) (line-end-position) nil))))))
  22467. (defun org-show-subtree ()
  22468. "Show everything after this heading at deeper levels."
  22469. (interactive)
  22470. (outline-flag-region
  22471. (point)
  22472. (save-excursion
  22473. (org-end-of-subtree t t))
  22474. nil))
  22475. (defun org-show-entry ()
  22476. "Show the body directly following this heading.
  22477. Show the heading too, if it is currently invisible."
  22478. (interactive)
  22479. (save-excursion
  22480. (ignore-errors
  22481. (org-back-to-heading t)
  22482. (outline-flag-region
  22483. (max (point-min) (1- (point)))
  22484. (save-excursion
  22485. (if (re-search-forward
  22486. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22487. (match-beginning 1)
  22488. (point-max)))
  22489. nil)
  22490. (org-cycle-hide-drawers 'children))))
  22491. (defun org-make-options-regexp (kwds &optional extra)
  22492. "Make a regular expression for keyword lines.
  22493. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22494. when non-nil, is a regexp matching keywords names."
  22495. (concat "^[ \t]*#\\+\\("
  22496. (regexp-opt kwds)
  22497. (and extra (concat (and kwds "\\|") extra))
  22498. "\\):[ \t]*\\(.*\\)"))
  22499. ;;;; Integration with and fixes for other packages
  22500. ;;; Imenu support
  22501. (defvar-local org-imenu-markers nil
  22502. "All markers currently used by Imenu.")
  22503. (defun org-imenu-new-marker (&optional pos)
  22504. "Return a new marker for use by Imenu, and remember the marker."
  22505. (let ((m (make-marker)))
  22506. (move-marker m (or pos (point)))
  22507. (push m org-imenu-markers)
  22508. m))
  22509. (defun org-imenu-get-tree ()
  22510. "Produce the index for Imenu."
  22511. (dolist (x org-imenu-markers) (move-marker x nil))
  22512. (setq org-imenu-markers nil)
  22513. (let* ((case-fold-search nil)
  22514. (n org-imenu-depth)
  22515. (re (concat "^" (org-get-limited-outline-regexp)))
  22516. (subs (make-vector (1+ n) nil))
  22517. (last-level 0)
  22518. m level head0 head)
  22519. (org-with-wide-buffer
  22520. (goto-char (point-max))
  22521. (while (re-search-backward re nil t)
  22522. (setq level (org-reduced-level (funcall outline-level)))
  22523. (when (and (<= level n)
  22524. (looking-at org-complex-heading-regexp)
  22525. (setq head0 (match-string-no-properties 4)))
  22526. (setq head (org-link-display-format head0)
  22527. m (org-imenu-new-marker))
  22528. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22529. (if (>= level last-level)
  22530. (push (cons head m) (aref subs level))
  22531. (push (cons head (aref subs (1+ level))) (aref subs level))
  22532. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22533. (setq last-level level))))
  22534. (aref subs 1)))
  22535. (eval-after-load "imenu"
  22536. '(progn
  22537. (add-hook 'imenu-after-jump-hook
  22538. (lambda ()
  22539. (when (derived-mode-p 'org-mode)
  22540. (org-show-context 'org-goto))))))
  22541. (defun org-link-display-format (s)
  22542. "Replace links in string S with their description.
  22543. If there is no description, use the link target."
  22544. (save-match-data
  22545. (replace-regexp-in-string
  22546. org-bracket-link-analytic-regexp
  22547. (lambda (m)
  22548. (if (match-end 5) (match-string 5 m)
  22549. (concat (match-string 1 m) (match-string 3 m))))
  22550. s nil t)))
  22551. (defun org-toggle-link-display ()
  22552. "Toggle the literal or descriptive display of links."
  22553. (interactive)
  22554. (if org-descriptive-links
  22555. (progn (org-remove-from-invisibility-spec '(org-link))
  22556. (org-restart-font-lock)
  22557. (setq org-descriptive-links nil))
  22558. (progn (add-to-invisibility-spec '(org-link))
  22559. (org-restart-font-lock)
  22560. (setq org-descriptive-links t))))
  22561. ;; Speedbar support
  22562. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22563. "Overlay marking the agenda restriction line in speedbar.")
  22564. (overlay-put org-speedbar-restriction-lock-overlay
  22565. 'face 'org-agenda-restriction-lock)
  22566. (overlay-put org-speedbar-restriction-lock-overlay
  22567. 'help-echo "Agendas are currently limited to this item.")
  22568. (delete-overlay org-speedbar-restriction-lock-overlay)
  22569. (defun org-speedbar-set-agenda-restriction ()
  22570. "Restrict future agenda commands to the location at point in speedbar.
  22571. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22572. (interactive)
  22573. (require 'org-agenda)
  22574. (let (p m tp np dir txt)
  22575. (cond
  22576. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22577. 'org-imenu t))
  22578. (setq m (get-text-property p 'org-imenu-marker))
  22579. (with-current-buffer (marker-buffer m)
  22580. (goto-char m)
  22581. (org-agenda-set-restriction-lock 'subtree)))
  22582. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22583. 'speedbar-function 'speedbar-find-file))
  22584. (setq tp (previous-single-property-change
  22585. (1+ p) 'speedbar-function)
  22586. np (next-single-property-change
  22587. tp 'speedbar-function)
  22588. dir (speedbar-line-directory)
  22589. txt (buffer-substring-no-properties (or tp (point-min))
  22590. (or np (point-max))))
  22591. (with-current-buffer (find-file-noselect
  22592. (let ((default-directory dir))
  22593. (expand-file-name txt)))
  22594. (unless (derived-mode-p 'org-mode)
  22595. (user-error "Cannot restrict to non-Org mode file"))
  22596. (org-agenda-set-restriction-lock 'file)))
  22597. (t (user-error "Don't know how to restrict Org mode agenda")))
  22598. (move-overlay org-speedbar-restriction-lock-overlay
  22599. (point-at-bol) (point-at-eol))
  22600. (setq current-prefix-arg nil)
  22601. (org-agenda-maybe-redo)))
  22602. (defvar speedbar-file-key-map)
  22603. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22604. (eval-after-load "speedbar"
  22605. '(progn
  22606. (speedbar-add-supported-extension ".org")
  22607. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22608. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22609. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22610. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22611. (add-hook 'speedbar-visiting-tag-hook
  22612. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22613. ;;; Fixes and Hacks for problems with other packages
  22614. (defun org--flyspell-object-check-p (element)
  22615. "Non-nil when Flyspell can check object at point.
  22616. ELEMENT is the element at point."
  22617. (let ((object (save-excursion
  22618. (when (looking-at-p "\\>") (backward-char))
  22619. (org-element-context element))))
  22620. (cl-case (org-element-type object)
  22621. ;; Prevent checks in links due to keybinding conflict with
  22622. ;; Flyspell.
  22623. ((code entity export-snippet inline-babel-call
  22624. inline-src-block line-break latex-fragment link macro
  22625. statistics-cookie target timestamp verbatim)
  22626. nil)
  22627. (footnote-reference
  22628. ;; Only in inline footnotes, within the definition.
  22629. (and (eq (org-element-property :type object) 'inline)
  22630. (< (save-excursion
  22631. (goto-char (org-element-property :begin object))
  22632. (search-forward ":" nil t 2))
  22633. (point))))
  22634. (otherwise t))))
  22635. (defun org-mode-flyspell-verify ()
  22636. "Function used for `flyspell-generic-check-word-predicate'."
  22637. (if (org-at-heading-p)
  22638. ;; At a headline or an inlinetask, check title only. This is
  22639. ;; faster than relying on `org-element-at-point'.
  22640. (and (save-excursion (beginning-of-line)
  22641. (and (let ((case-fold-search t))
  22642. (not (looking-at-p "\\*+ END[ \t]*$")))
  22643. (let ((case-fold-search nil))
  22644. (looking-at org-complex-heading-regexp))))
  22645. (match-beginning 4)
  22646. (>= (point) (match-beginning 4))
  22647. (or (not (match-beginning 5))
  22648. (< (point) (match-beginning 5))))
  22649. (let* ((element (org-element-at-point))
  22650. (post-affiliated (org-element-property :post-affiliated element)))
  22651. (cond
  22652. ;; Ignore checks in all affiliated keywords but captions.
  22653. ((< (point) post-affiliated)
  22654. (and (save-excursion
  22655. (beginning-of-line)
  22656. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22657. (> (point) (match-end 0))
  22658. (org--flyspell-object-check-p element)))
  22659. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22660. ((let ((log (org-log-into-drawer)))
  22661. (and log
  22662. (let ((drawer (org-element-lineage element '(drawer))))
  22663. (and drawer
  22664. (eq (compare-strings
  22665. log nil nil
  22666. (org-element-property :drawer-name drawer) nil nil t)
  22667. t)))))
  22668. nil)
  22669. (t
  22670. (cl-case (org-element-type element)
  22671. ((comment quote-section) t)
  22672. (comment-block
  22673. ;; Allow checks between block markers, not on them.
  22674. (and (> (line-beginning-position) post-affiliated)
  22675. (save-excursion
  22676. (end-of-line)
  22677. (skip-chars-forward " \r\t\n")
  22678. (< (point) (org-element-property :end element)))))
  22679. ;; Arbitrary list of keywords where checks are meaningful.
  22680. ;; Make sure point is on the value part of the element.
  22681. (keyword
  22682. (and (member (org-element-property :key element)
  22683. '("DESCRIPTION" "TITLE"))
  22684. (save-excursion
  22685. (search-backward ":" (line-beginning-position) t))))
  22686. ;; Check is globally allowed in paragraphs verse blocks and
  22687. ;; table rows (after affiliated keywords) but some objects
  22688. ;; must not be affected.
  22689. ((paragraph table-row verse-block)
  22690. (let ((cbeg (org-element-property :contents-begin element))
  22691. (cend (org-element-property :contents-end element)))
  22692. (and cbeg (>= (point) cbeg) (< (point) cend)
  22693. (org--flyspell-object-check-p element))))))))))
  22694. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22695. (defun org-remove-flyspell-overlays-in (beg end)
  22696. "Remove flyspell overlays in region."
  22697. (and (bound-and-true-p flyspell-mode)
  22698. (fboundp 'flyspell-delete-region-overlays)
  22699. (flyspell-delete-region-overlays beg end)))
  22700. (defvar flyspell-delayed-commands)
  22701. (eval-after-load "flyspell"
  22702. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22703. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22704. (eval-after-load "bookmark"
  22705. '(if (boundp 'bookmark-after-jump-hook)
  22706. ;; We can use the hook
  22707. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22708. ;; Hook not available, use advice
  22709. (defadvice bookmark-jump (after org-make-visible activate)
  22710. "Make the position visible."
  22711. (org-bookmark-jump-unhide))))
  22712. ;; Make sure saveplace shows the location if it was hidden
  22713. (eval-after-load "saveplace"
  22714. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22715. "Make the position visible."
  22716. (org-bookmark-jump-unhide)))
  22717. ;; Make sure ecb shows the location if it was hidden
  22718. (eval-after-load "ecb"
  22719. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22720. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22721. (when (derived-mode-p 'org-mode)
  22722. (org-show-context))))
  22723. (defun org-bookmark-jump-unhide ()
  22724. "Unhide the current position, to show the bookmark location."
  22725. (and (derived-mode-p 'org-mode)
  22726. (or (org-invisible-p)
  22727. (save-excursion (goto-char (max (point-min) (1- (point))))
  22728. (org-invisible-p)))
  22729. (org-show-context 'bookmark-jump)))
  22730. (defun org-mark-jump-unhide ()
  22731. "Make the point visible with `org-show-context' after jumping to the mark."
  22732. (when (and (derived-mode-p 'org-mode)
  22733. (org-invisible-p))
  22734. (org-show-context 'mark-goto)))
  22735. (eval-after-load "simple"
  22736. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22737. "Make the point visible with `org-show-context'."
  22738. (org-mark-jump-unhide)))
  22739. (eval-after-load "simple"
  22740. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22741. "Make the point visible with `org-show-context'."
  22742. (org-mark-jump-unhide)))
  22743. (eval-after-load "simple"
  22744. '(defadvice pop-global-mark (after org-make-visible activate)
  22745. "Make the point visible with `org-show-context'."
  22746. (org-mark-jump-unhide)))
  22747. ;; Make session.el ignore our circular variable
  22748. (defvar session-globals-exclude)
  22749. (eval-after-load "session"
  22750. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22751. ;;;; Finish up
  22752. (provide 'org)
  22753. (run-hooks 'org-load-hook)
  22754. ;;; org.el ends here